instance_id
stringlengths
17
39
repo
stringclasses
8 values
issue_id
stringlengths
14
34
pr_id
stringlengths
14
34
linking_methods
sequencelengths
1
3
base_commit
stringlengths
40
40
merge_commit
stringlengths
0
40
hints_text
sequencelengths
0
106
resolved_comments
sequencelengths
0
119
created_at
unknown
labeled_as
sequencelengths
0
7
problem_title
stringlengths
7
174
problem_statement
stringlengths
0
55.4k
gold_files
sequencelengths
0
10
gold_files_postpatch
sequencelengths
1
10
test_files
sequencelengths
0
60
gold_patch
stringlengths
220
5.83M
test_patch
stringlengths
386
194k
split_random
stringclasses
3 values
split_time
stringclasses
3 values
issue_start_time
timestamp[ns]
issue_created_at
unknown
issue_by_user
stringlengths
3
21
split_repo
stringclasses
3 values
iluwatar/java-design-patterns/955_959
iluwatar/java-design-patterns
iluwatar/java-design-patterns/955
iluwatar/java-design-patterns/959
[ "timestamp(timedelta=143575.0, similarity=0.8550195875763785)" ]
90ea4506caa653711f69fabb99ee7ac26c4ecce7
a6fdcd4a34802deb13e9301ec15089fb3f430b28
[ "Currently all the patterns belong to the unnamed module since they have not been modularized. The next step would be to add `module-info.java` to each of the patterns to make them real modules." ]
[]
"2019-10-06T09:25:19Z"
[ "info: help wanted", "type: support", "epic: design" ]
Java 11 support: Modules
This task is part of the Java 11 transition plan https://github.com/iluwatar/java-design-patterns/wiki/16.-Java-11-Transition Java 9 introduces the Java Platform Module System. How should it be utilized in this project? In this task we create a plan what kind of modules are going to be created. Would it be possible to start without modules i.e. let everything belong to the default 'unnamed' module? And then later on possibly create module per pattern. Links: https://blog.codefx.org/java/java-9-migration-guide/ https://www.baeldung.com/java-9-modularity
[ ".travis.yml", "exclude-pmd.properties", "naked-objects/dom/pom.xml", "naked-objects/integtests/pom.xml", "pom.xml" ]
[ ".travis.yml", "exclude-pmd.properties", "naked-objects/dom/pom.xml", "naked-objects/integtests/pom.xml", "pom.xml" ]
[]
diff --git a/.travis.yml b/.travis.yml index 58edddeb416e..474732c166b3 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,7 @@ language: java dist: trusty # Xenial build environment won't allow installation of Java 8 jdk: -- oraclejdk8 +- openjdk11 env: global: @@ -21,12 +21,6 @@ after_success: - mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent package sonar:sonar -Dsonar.host.url=https://sonarcloud.io -Dsonar.login=$SONAR_TOKEN - bash update-ghpages.sh -# use latest java version available instead of travis default -addons: - apt: - packages: - - oracle-java8-installer - notifications: email: - [email protected] diff --git a/exclude-pmd.properties b/exclude-pmd.properties index 5a4bb138834e..c49916ca964d 100644 --- a/exclude-pmd.properties +++ b/exclude-pmd.properties @@ -24,4 +24,4 @@ com.iluwatar.servicelayer.common.BaseEntity=UnusedPrivateField com.iluwatar.doublechecked.locking.App=EmptyStatementNotInLoop,EmptyWhileStmt com.iluwatar.doublechecked.locking.InventoryTest=EmptyStatementNotInLoop,EmptyWhileStmt -domainapp.dom.modules.simple.QSimpleObject=UnusedFormalParameter \ No newline at end of file +domainapp.dom.modules.simple.QSimpleObject=UnusedFormalParameter,UnusedImports \ No newline at end of file diff --git a/naked-objects/dom/pom.xml b/naked-objects/dom/pom.xml index 69365bd4b00a..83c18267c5a9 100644 --- a/naked-objects/dom/pom.xml +++ b/naked-objects/dom/pom.xml @@ -78,7 +78,7 @@ <activeByDefault>true</activeByDefault> </activation> <properties> - <datanucleus-maven-plugin.version>4.0.1</datanucleus-maven-plugin.version> + <datanucleus.version>5.2.1</datanucleus.version> </properties> <build> <pluginManagement> @@ -96,7 +96,7 @@ <pluginExecutionFilter> <groupId>org.datanucleus</groupId> <artifactId>datanucleus-maven-plugin</artifactId> - <versionRange>[${datanucleus-maven-plugin.version},)</versionRange> + <versionRange>[${datanucleus.version},)</versionRange> <goals> <goal>enhance</goal> </goals> @@ -115,12 +115,13 @@ <plugin> <groupId>org.datanucleus</groupId> <artifactId>datanucleus-maven-plugin</artifactId> - <version>${datanucleus-maven-plugin.version}</version> + <version>${datanucleus.version}</version> <configuration> + <log4jConfiguration>log4j.properties</log4jConfiguration> + <persistenceUnitName>simple</persistenceUnitName> + <api>JDO</api> <fork>false</fork> - <log4jConfiguration>${basedir}/log4j.properties</log4jConfiguration> <verbose>true</verbose> - <props>${basedir}/datanucleus.properties</props> </configuration> <executions> <execution> @@ -137,6 +138,7 @@ <dependency> <groupId>org.datanucleus</groupId> <artifactId>datanucleus-core</artifactId> + <version>${datanucleus.version}</version> </dependency> <dependency> <groupId>org.datanucleus</groupId> @@ -145,6 +147,7 @@ <dependency> <groupId>org.datanucleus</groupId> <artifactId>datanucleus-api-jdo</artifactId> + <version>${datanucleus.version}</version> </dependency> </dependencies> </profile> @@ -157,7 +160,7 @@ <plugin> <groupId>org.apache.isis.tool</groupId> <artifactId>isis-maven-plugin</artifactId> - <version>1.9.0-SNAPSHOT</version> + <version>${isis.version}</version> <configuration> <isisConfigDir>../webapp/src/main/webapp/WEB-INF</isisConfigDir> </configuration> @@ -165,7 +168,7 @@ <dependency> <groupId>org.apache.isis.example.application</groupId> <artifactId>simpleapp-dom</artifactId> - <version>1.9.0-SNAPSHOT</version> + <version>${isis.version}</version> </dependency> <!-- ... workaround to avoid conflict with plexus-default (not sure why exclusions in the isis-maven-plugin aren't sufficient, though ... --> diff --git a/naked-objects/integtests/pom.xml b/naked-objects/integtests/pom.xml index c4dd52dcf652..0d5940df556d 100644 --- a/naked-objects/integtests/pom.xml +++ b/naked-objects/integtests/pom.xml @@ -85,6 +85,11 @@ <scope>test</scope> </dependency> + <dependency> + <groupId>javax.annotation</groupId> + <artifactId>javax.annotation-api</artifactId> + </dependency> + <dependency> <groupId>org.hsqldb</groupId> <artifactId>hsqldb</artifactId> diff --git a/pom.xml b/pom.xml index 539da396b2d8..1feafbd559ce 100644 --- a/pom.xml +++ b/pom.xml @@ -56,7 +56,7 @@ <jackson.version>2.8.5</jackson.version> <pmd.version>3.12.0</pmd.version> <jaxb-api.version>2.3.0</jaxb-api.version> - <annotation-api.version>1.3.1</annotation-api.version> + <annotation-api.version>1.3.2</annotation-api.version> </properties> <modules> <module>abstract-factory</module> @@ -329,6 +329,11 @@ <artifactId>logback-core</artifactId> <version>${logback.version}</version> </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + <version>2.3.1</version> + </dependency> </dependencies> <build> @@ -370,8 +375,7 @@ <artifactId>maven-compiler-plugin</artifactId> <version>${compiler.version}</version> <configuration> - <source>1.8</source> - <target>1.8</target> + <release>11</release> </configuration> </plugin> <plugin>
null
test
train
2019-10-08T17:29:59
"2019-10-05T15:31:30Z"
iluwatar
train
iluwatar/java-design-patterns/933_960
iluwatar/java-design-patterns
iluwatar/java-design-patterns/933
iluwatar/java-design-patterns/960
[ "keyword_pr_to_issue", "timestamp(timedelta=188.0, similarity=0.9065034689810998)" ]
94ca25462667b15d2d4f7d5120c94a0733f53bf7
84c4b034a9f282a0d8739ef7bd4cd83813a7c454
[ "HI @iluwatar \r\nI would like to take this up", "Ok @hbothra15 ", "is this still work in progress or shall i pick up ? @hbothra15 @iluwatar ", "Ping @hbothra15 ", "@iluwatar Want to take this issue. Is there anything else we need to do apart from upgrading the concerned dependencies?", "@gaurav9822 update the dependencies and after that verify that build and tests still work", "@iluwatar I have raised a ticket on Spring JIRA.\r\nURL - https://jira.spring.io/projects/DATAJPA/issues/DATAJPA-1610?filter=allopenissues\r\n\r\nAlso, after discussing with Spring developers, they have told to upgrade spring-boot as well in order to support spring-data 1.11.", "Makes sense, those artifacts are probably dependent of each other. It's worth trying at least." ]
[ "What if the `topping` is not present? We should handle also the error case. Maybe throw the `CakeBakingException`?", "`findById` returns an `Optional`, probably we don't want to log that but its contents", "Returns an `Optional`.." ]
"2019-10-06T10:40:17Z"
[ "type: bug", "info: good first issue", "epic: build issue" ]
Github reports security vulnerabilities
![image](https://user-images.githubusercontent.com/582346/65894272-266ef300-e3b2-11e9-9f71-046923607de6.png) ![image](https://user-images.githubusercontent.com/582346/65894326-3dade080-e3b2-11e9-920b-b524d0edbfda.png)
[ "layers/pom.xml", "layers/src/main/java/com/iluwatar/layers/CakeBakingServiceImpl.java", "layers/src/main/resources/applicationContext.xml", "pom.xml", "repository/pom.xml", "repository/src/main/java/com/iluwatar/repository/App.java", "repository/src/main/java/com/iluwatar/repository/AppConfig.java", "repository/src/main/resources/applicationContext.xml" ]
[ "layers/pom.xml", "layers/src/main/java/com/iluwatar/layers/CakeBakingServiceImpl.java", "layers/src/main/resources/applicationContext.xml", "pom.xml", "repository/pom.xml", "repository/src/main/java/com/iluwatar/repository/App.java", "repository/src/main/java/com/iluwatar/repository/AppConfig.java", "repository/src/main/resources/applicationContext.xml" ]
[ "eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/AggregatorRouteTest.java", "eip-splitter/src/test/java/com/iluwatar/eip/splitter/routes/SplitterRouteTest.java", "eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/routes/WireTapRouteTest.java", "repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java", "repository/src/test/java/com/iluwatar/repository/AppConfigTest.java", "repository/src/test/java/com/iluwatar/repository/RepositoryTest.java" ]
diff --git a/layers/pom.xml b/layers/pom.xml index 8237c8f4f6e0..a6d3d17199f6 100644 --- a/layers/pom.xml +++ b/layers/pom.xml @@ -41,7 +41,11 @@ </dependency> <dependency> <groupId>org.hibernate</groupId> - <artifactId>hibernate-entitymanager</artifactId> + <artifactId>hibernate-core</artifactId> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> </dependency> <dependency> <groupId>commons-dbcp</groupId> diff --git a/layers/src/main/java/com/iluwatar/layers/CakeBakingServiceImpl.java b/layers/src/main/java/com/iluwatar/layers/CakeBakingServiceImpl.java index e8deee73a767..556a74c7afbf 100644 --- a/layers/src/main/java/com/iluwatar/layers/CakeBakingServiceImpl.java +++ b/layers/src/main/java/com/iluwatar/layers/CakeBakingServiceImpl.java @@ -72,18 +72,23 @@ public void bakeNewCake(CakeInfo cakeInfo) throws CakeBakingException { } } CakeToppingDao toppingBean = context.getBean(CakeToppingDao.class); - CakeTopping topping = toppingBean.findOne(matchingToppings.iterator().next().getId()); + Optional<CakeTopping> topping = toppingBean.findById(matchingToppings.iterator().next().getId()); CakeDao cakeBean = context.getBean(CakeDao.class); - Cake cake = new Cake(); - cake.setTopping(topping); - cake.setLayers(foundLayers); - cakeBean.save(cake); - topping.setCake(cake); - toppingBean.save(topping); - CakeLayerDao layerBean = context.getBean(CakeLayerDao.class); - for (CakeLayer layer : foundLayers) { - layer.setCake(cake); - layerBean.save(layer); + if (topping.isPresent()) { + Cake cake = new Cake(); + cake.setTopping(topping.get()); + cake.setLayers(foundLayers); + cakeBean.save(cake); + topping.get().setCake(cake); + toppingBean.save(topping.get()); + CakeLayerDao layerBean = context.getBean(CakeLayerDao.class); + for (CakeLayer layer : foundLayers) { + layer.setCake(cake); + layerBean.save(layer); + } + } else { + throw new CakeBakingException(String.format("Topping %s is not available", + cakeInfo.cakeToppingInfo.name)); } } diff --git a/layers/src/main/resources/applicationContext.xml b/layers/src/main/resources/applicationContext.xml index eca3670b0fbf..c149094c1fa3 100644 --- a/layers/src/main/resources/applicationContext.xml +++ b/layers/src/main/resources/applicationContext.xml @@ -50,7 +50,7 @@ <property name="dataSource" ref="dataSource" /> <property name="packagesToScan" value="com.iluwatar" /> <property name="persistenceProvider"> - <bean class="org.hibernate.ejb.HibernatePersistence" /> + <bean class="org.hibernate.jpa.HibernatePersistenceProvider" /> </property> <property name="jpaProperties"> <map> diff --git a/pom.xml b/pom.xml index acaaef6181c5..e0f64a534aef 100644 --- a/pom.xml +++ b/pom.xml @@ -28,10 +28,10 @@ <inceptionYear>2014</inceptionYear> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> - <hibernate.version>5.0.1.Final</hibernate.version> - <spring.version>4.2.4.RELEASE</spring.version> - <spring-boot.version>1.3.3.RELEASE</spring-boot.version> - <spring-data.version>1.9.2.RELEASE</spring-data.version> + <hibernate.version>5.2.18.Final</hibernate.version> + <spring.version>5.0.13.RELEASE</spring.version> + <spring-boot.version>2.0.9.RELEASE</spring-boot.version> + <spring-data.version>2.0.14.RELEASE</spring-data.version> <h2.version>1.4.190</h2.version> <junit.version>4.12</junit.version> <junit-jupiter.version>5.0.2</junit-jupiter.version> @@ -40,7 +40,7 @@ <compiler.version>3.8.1</compiler.version> <jacoco.version>0.8.4</jacoco.version> <commons-dbcp.version>1.4</commons-dbcp.version> - <camel.version>2.16.1</camel.version> + <camel.version>2.24.0</camel.version> <guava.version>19.0</guava.version> <mockito.version>1.10.19</mockito.version> <apache-httpcomponents.version>4.5.2</apache-httpcomponents.version> @@ -55,6 +55,7 @@ <aws-lambda-java-events.version>2.0.1</aws-lambda-java-events.version> <jackson.version>2.8.5</jackson.version> <pmd.version>3.12.0</pmd.version> + <log4j.version>1.2.17</log4j.version> <jaxb-api.version>2.3.0</jaxb-api.version> <annotation-api.version>1.3.1</annotation-api.version> </properties> @@ -191,11 +192,6 @@ <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> - <dependency> - <groupId>org.hibernate</groupId> - <artifactId>hibernate-entitymanager</artifactId> - <version>${hibernate.version}</version> - </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> @@ -300,6 +296,11 @@ <artifactId>mongo-java-driver</artifactId> <version>${mongo-java-driver.version}</version> </dependency> + <dependency> + <groupId>log4j</groupId> + <artifactId>log4j</artifactId> + <version>${log4j.version}</version> + </dependency> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> diff --git a/repository/pom.xml b/repository/pom.xml index 2ccdc9da7ba5..f0340f1260ef 100644 --- a/repository/pom.xml +++ b/repository/pom.xml @@ -44,7 +44,7 @@ </dependency> <dependency> <groupId>org.hibernate</groupId> - <artifactId>hibernate-entitymanager</artifactId> + <artifactId>hibernate-core</artifactId> </dependency> <dependency> <groupId>commons-dbcp</groupId> @@ -71,5 +71,9 @@ <groupId>javax.annotation</groupId> <artifactId>javax.annotation-api</artifactId> </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-test</artifactId> + </dependency> </dependencies> </project> diff --git a/repository/src/main/java/com/iluwatar/repository/App.java b/repository/src/main/java/com/iluwatar/repository/App.java index d96b4351ea38..c4a885380064 100644 --- a/repository/src/main/java/com/iluwatar/repository/App.java +++ b/repository/src/main/java/com/iluwatar/repository/App.java @@ -23,6 +23,7 @@ package com.iluwatar.repository; import java.util.List; +import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -84,17 +85,17 @@ public static void main(String[] args) { nasta.setSurname("Spotakova"); repository.save(nasta); - LOGGER.info("Find by id 2: {}", repository.findOne(2L)); + LOGGER.info("Find by id 2: {}", repository.findById(2L).get()); // Remove record from Person - repository.delete(2L); + repository.deleteById(2L); // count records LOGGER.info("Count Person records: {}", repository.count()); // find by name - Person p = repository.findOne(new PersonSpecifications.NameEqualSpec("John")); - LOGGER.info("Find by John is {}", p); + Optional<Person> p = repository.findOne(new PersonSpecifications.NameEqualSpec("John")); + LOGGER.info("Find by John is {}", p.get()); // find by age persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40)); diff --git a/repository/src/main/java/com/iluwatar/repository/AppConfig.java b/repository/src/main/java/com/iluwatar/repository/AppConfig.java index c5ccb7d00002..584c09037be7 100644 --- a/repository/src/main/java/com/iluwatar/repository/AppConfig.java +++ b/repository/src/main/java/com/iluwatar/repository/AppConfig.java @@ -24,6 +24,7 @@ import java.sql.SQLException; import java.util.List; +import java.util.Optional; import java.util.Properties; import javax.sql.DataSource; @@ -32,6 +33,7 @@ import org.hibernate.jpa.HibernatePersistenceProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.boot.SpringBootConfiguration; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @@ -44,6 +46,7 @@ * */ @EnableJpaRepositories +@SpringBootConfiguration public class AppConfig { private static final Logger LOGGER = LoggerFactory.getLogger(AppConfig.class); @@ -60,7 +63,7 @@ public DataSource dataSource() { basicDataSource.setUrl("jdbc:h2:~/databases/person"); basicDataSource.setUsername("sa"); basicDataSource.setPassword("sa"); - return (DataSource) basicDataSource; + return basicDataSource; } /** @@ -134,17 +137,17 @@ public static void main(String[] args) { nasta.setSurname("Spotakova"); repository.save(nasta); - LOGGER.info("Find by id 2: {}", repository.findOne(2L)); + LOGGER.info("Find by id 2: {}", repository.findById(2L).get()); // Remove record from Person - repository.delete(2L); + repository.deleteById(2L); // count records LOGGER.info("Count Person records: {}", repository.count()); // find by name - Person p = repository.findOne(new PersonSpecifications.NameEqualSpec("John")); - LOGGER.info("Find by John is {}", p); + Optional<Person> p = repository.findOne(new PersonSpecifications.NameEqualSpec("John")); + LOGGER.info("Find by John is {}", p.get()); // find by age persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40)); diff --git a/repository/src/main/resources/applicationContext.xml b/repository/src/main/resources/applicationContext.xml index 26d6cb3f4dc3..b27bb4c85f73 100644 --- a/repository/src/main/resources/applicationContext.xml +++ b/repository/src/main/resources/applicationContext.xml @@ -49,7 +49,7 @@ <property name="dataSource" ref="dataSource" /> <property name="packagesToScan" value="com.iluwatar" /> <property name="persistenceProvider"> - <bean class="org.hibernate.ejb.HibernatePersistence" /> + <bean class="org.hibernate.jpa.HibernatePersistenceProvider" /> </property> <property name="jpaProperties"> <map>
diff --git a/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/AggregatorRouteTest.java b/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/AggregatorRouteTest.java index 2c7d207d6f53..2b831e01958b 100644 --- a/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/AggregatorRouteTest.java +++ b/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/AggregatorRouteTest.java @@ -28,7 +28,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.ComponentScan; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; @@ -44,7 +44,7 @@ * </p> */ @ExtendWith(SpringExtension.class) -@SpringApplicationConfiguration(classes = AggregatorRouteTest.class) +@SpringBootTest(classes = AggregatorRouteTest.class) @ActiveProfiles("test") @EnableAutoConfiguration @ComponentScan diff --git a/eip-splitter/src/test/java/com/iluwatar/eip/splitter/routes/SplitterRouteTest.java b/eip-splitter/src/test/java/com/iluwatar/eip/splitter/routes/SplitterRouteTest.java index 9257a4410186..334b77da03c8 100644 --- a/eip-splitter/src/test/java/com/iluwatar/eip/splitter/routes/SplitterRouteTest.java +++ b/eip-splitter/src/test/java/com/iluwatar/eip/splitter/routes/SplitterRouteTest.java @@ -28,7 +28,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.ComponentScan; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; @@ -42,7 +42,7 @@ * </p> */ @ExtendWith(SpringExtension.class) -@SpringApplicationConfiguration(classes = SplitterRouteTest.class) +@SpringBootTest(classes = SplitterRouteTest.class) @ActiveProfiles("test") @EnableAutoConfiguration @ComponentScan diff --git a/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/routes/WireTapRouteTest.java b/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/routes/WireTapRouteTest.java index 449f86208258..bb433f350238 100644 --- a/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/routes/WireTapRouteTest.java +++ b/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/routes/WireTapRouteTest.java @@ -29,7 +29,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.ComponentScan; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; @@ -45,7 +45,7 @@ * </p> */ @ExtendWith(SpringExtension.class) -@SpringApplicationConfiguration(classes = WireTapRouteTest.class) +@SpringBootTest(classes = WireTapRouteTest.class) @ActiveProfiles("test") @EnableAutoConfiguration @ComponentScan diff --git a/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java b/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java index 4cfb6e022f51..8d7e1d94b797 100644 --- a/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java +++ b/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java @@ -28,6 +28,7 @@ import java.util.Arrays; import java.util.List; +import java.util.Optional; import javax.annotation.Resource; @@ -35,9 +36,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.test.context.ContextConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; -import org.springframework.test.context.support.AnnotationConfigContextLoader; import com.google.common.collect.Lists; @@ -47,7 +47,7 @@ * */ @ExtendWith(SpringExtension.class) -@ContextConfiguration(classes = { AppConfig.class }, loader = AnnotationConfigContextLoader.class) +@SpringBootTest(classes = { AppConfig.class }) public class AnnotationBasedRepositoryTest { @Resource @@ -66,7 +66,7 @@ public class AnnotationBasedRepositoryTest { @BeforeEach public void setup() { - repository.save(persons); + repository.saveAll(persons); } @Test @@ -119,8 +119,8 @@ public void testFindAllByAgeBetweenSpec() { @Test public void testFindOneByNameEqualSpec() { - Person actual = repository.findOne(new PersonSpecifications.NameEqualSpec("Terry")); - assertEquals(terry, actual); + Optional<Person> actual = repository.findOne(new PersonSpecifications.NameEqualSpec("Terry")); + assertEquals(terry, actual.get()); } @AfterEach diff --git a/repository/src/test/java/com/iluwatar/repository/AppConfigTest.java b/repository/src/test/java/com/iluwatar/repository/AppConfigTest.java index 3fb1b427b232..1839a2523e6c 100644 --- a/repository/src/test/java/com/iluwatar/repository/AppConfigTest.java +++ b/repository/src/test/java/com/iluwatar/repository/AppConfigTest.java @@ -25,9 +25,8 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; -import org.springframework.test.context.support.AnnotationConfigContextLoader; import org.springframework.transaction.annotation.Transactional; import javax.sql.DataSource; @@ -42,7 +41,7 @@ * */ @ExtendWith(SpringExtension.class) -@ContextConfiguration(classes = { AppConfig.class }, loader = AnnotationConfigContextLoader.class) +@SpringBootTest(classes = { AppConfig.class }) public class AppConfigTest { @Autowired diff --git a/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java b/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java index 5b4b8e80c055..dc976cbe72d3 100644 --- a/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java +++ b/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java @@ -28,6 +28,7 @@ import java.util.Arrays; import java.util.List; +import java.util.Optional; import javax.annotation.Resource; @@ -35,7 +36,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.test.context.ContextConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; import com.google.common.collect.Lists; @@ -45,7 +46,7 @@ * by {@link org.springframework.data.jpa.domain.Specification} are also test. */ @ExtendWith(SpringExtension.class) -@ContextConfiguration(locations = { "classpath:applicationContext.xml" }) +@SpringBootTest(properties = { "locations=classpath:applicationContext.xml" }) public class RepositoryTest { @Resource @@ -64,7 +65,7 @@ public class RepositoryTest { @BeforeEach public void setup() { - repository.save(persons); + repository.saveAll(persons); } @Test @@ -115,8 +116,8 @@ public void testFindAllByAgeBetweenSpec() { @Test public void testFindOneByNameEqualSpec() { - Person actual = repository.findOne(new PersonSpecifications.NameEqualSpec("Terry")); - assertEquals(terry, actual); + Optional<Person> actual = repository.findOne(new PersonSpecifications.NameEqualSpec("Terry")); + assertEquals(terry, actual.get()); } @AfterEach
test
train
2019-10-06T18:06:39
"2019-09-30T15:44:26Z"
iluwatar
train
iluwatar/java-design-patterns/496_967
iluwatar/java-design-patterns
iluwatar/java-design-patterns/496
iluwatar/java-design-patterns/967
[ "timestamp(timedelta=100.0, similarity=0.8719039795684427)" ]
94ca25462667b15d2d4f7d5120c94a0733f53bf7
f903d7e9a9379c79742ecc61a3901bdbe2a0a318
[ "Working on it\n", "Ok @ghost-60 \n", "@ghost-60 are you still working on this?", "Sorry.... not yet\n\nOn Feb 12, 2017 05:02, \"Ilkka Seppälä\" <[email protected]> wrote:\n\n> @ghost-60 <https://github.com/ghost-60> are you still working on this?\n>\n> —\n> You are receiving this because you were mentioned.\n> Reply to this email directly, view it on GitHub\n> <https://github.com/iluwatar/java-design-patterns/issues/496#issuecomment-279183789>,\n> or mute the thread\n> <https://github.com/notifications/unsubscribe-auth/AUIdn6FWVcnwQchUgMgDBSqwfm9wtyCjks5rbkT5gaJpZM4KF-qy>\n> .\n>\n", "My question, do you still want to keep the issue or can someone else take it?", "Someone else can take it. Sorry.\n\nOn Feb 13, 2017 20:41, \"Ilkka Seppälä\" <[email protected]> wrote:\n\n> My question, do you still want to keep the issue or can someone else take\n> it?\n>\n> —\n> You are receiving this because you were mentioned.\n> Reply to this email directly, view it on GitHub\n> <https://github.com/iluwatar/java-design-patterns/issues/496#issuecomment-279418778>,\n> or mute the thread\n> <https://github.com/notifications/unsubscribe-auth/AUIdn8sorgk2-Hk4nq3Xt1TndOtAXUFqks5rcHKEgaJpZM4KF-qy>\n> .\n>\n", "It's ok @ghost-60. This issue is free for taking again.", "can I take it? ", "Sure @urielatzmon go ahead", "@urielatzmon are you still implementing this?", "Hello. Can I take on this issue and make a PR? ", "Ok @jjjimenez100 ", "If this is inactive, I'd love to take this up", "Yes, it seems so. Please go ahead @havanagrawal ", "The issue is free", "Hi. I'll continue working on this one (for real now). Just forked the repository. Will have you pinged when the PR's up. \r\n\r\nThanks!", "@jjjimenez100 ok the second time's a charm, or how it goes :smirk: " ]
[ "We can leave this chapter if there are no aliases", "We can link to https://java-design-patterns.com/principles/#single-responsibility-principle" ]
"2019-10-06T17:12:55Z"
[ "epic: pattern" ]
Pipeline pattern
https://msdn.microsoft.com/en-us/library/ff963548.aspx
[ "pom.xml" ]
[ "pipeline/README.md", "pipeline/pom.xml", "pipeline/src/main/java/com.iluwatar.pipeline/App.java", "pipeline/src/main/java/com.iluwatar.pipeline/ConvertToCharArrayHandler.java", "pipeline/src/main/java/com.iluwatar.pipeline/Handler.java", "pipeline/src/main/java/com.iluwatar.pipeline/Pipeline.java", "pipeline/src/main/java/com.iluwatar.pipeline/RemoveAlphabetsHandler.java", "pipeline/src/main/java/com.iluwatar.pipeline/RemoveDigitsHandler.java", "pom.xml" ]
[ "pipeline/src/test/java/com.iluwatar.pipeline/AppTest.java", "pipeline/src/test/java/com.iluwatar.pipeline/PipelineTest.java" ]
diff --git a/pipeline/README.md b/pipeline/README.md new file mode 100644 index 000000000000..e990affd62c7 --- /dev/null +++ b/pipeline/README.md @@ -0,0 +1,37 @@ +--- +layout: pattern +title: Pipeline +folder: pipeline +permalink: /patterns/pipeline/ +categories: Behavioral +tags: + - Java + - Functional + - Difficulty-Intermediate +--- + +## Intent +Allows processing of data in a series of stages by giving in an initial input and passing the processed output to be used by the next stages. + +## Applicability +Use the Pipeline pattern when you want to + +* execute individual stages that yields a final value +* add readability to complex sequence of operations by providing a fluent builder as an interface +* improve testability of code since stages will most likely be doing a single thing, complying to the [Single Responsibility Principle (SRP)](https://java-design-patterns.com/principles/#single-responsibility-principle) + +## Typical Use Case + +* implement stages and execute them in an ordered manner + +## Real world examples + +* [java.util.Stream](https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html) +* [Maven Build Lifecycle](http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html) +* [Functional Java](https://github.com/functionaljava/functionaljava) + +## Credits + +* [The Pipeline Pattern — for fun and profit](https://medium.com/@aaronweatherall/the-pipeline-pattern-for-fun-and-profit-9b5f43a98130) +* [The Pipeline design pattern (in Java)](https://medium.com/@deepakbapat/the-pipeline-design-pattern-in-java-831d9ce2fe21) +* [Pipelines | Microsoft Docs](https://docs.microsoft.com/en-us/previous-versions/msp-n-p/ff963548(v=pandp.10)) \ No newline at end of file diff --git a/pipeline/pom.xml b/pipeline/pom.xml new file mode 100644 index 000000000000..7ad60d5620e4 --- /dev/null +++ b/pipeline/pom.xml @@ -0,0 +1,47 @@ +<?xml version="1.0"?> +<!-- + + The MIT License + Copyright (c) 2014-2016 Ilkka Seppälä + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + +--> +<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>com.iluwatar</groupId> + <artifactId>java-design-patterns</artifactId> + <version>1.22.0-SNAPSHOT</version> + </parent> + <artifactId>pipeline</artifactId> + <dependencies> + <dependency> + <groupId>org.junit.jupiter</groupId> + <artifactId>junit-jupiter-engine</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-core</artifactId> + <scope>test</scope> + </dependency> + </dependencies> +</project> diff --git a/pipeline/src/main/java/com.iluwatar.pipeline/App.java b/pipeline/src/main/java/com.iluwatar.pipeline/App.java new file mode 100644 index 000000000000..7efa2ecca003 --- /dev/null +++ b/pipeline/src/main/java/com.iluwatar.pipeline/App.java @@ -0,0 +1,66 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.pipeline; + +/** + * The Pipeline pattern uses ordered stages to process a sequence of input values. + * Each implemented task is represented by a stage of the pipeline. You can think of + * pipelines as similar to assembly lines in a factory, where each item in the assembly + * line is constructed in stages. The partially assembled item is passed from one assembly + * stage to another. The outputs of the assembly line occur in the same order as that of the + * inputs. + * + * Classes used in this example are suffixed with "Handlers", and synonymously refers to the + * "stage". + */ +public class App { + /** + * Specify the initial input type for the first stage handler and the expected output type + * of the last stage handler as type parameters for Pipeline. Use the fluent builder by + * calling addHandler to add more stage handlers on the pipeline. + */ + public static void main(String[] args) { + /* + Suppose we wanted to pass through a String to a series of filtering stages and convert it + as a char array on the last stage. + + - Stage handler 1 (pipe): Removing the alphabets, accepts a String input and returns the + processed String output. This will be used by the next handler as its input. + + - Stage handler 2 (pipe): Removing the digits, accepts a String input and returns the + processed String output. This shall also be used by the last handler we have. + + - Stage handler 3 (pipe): Converting the String input to a char array handler. We would + be returning a different type in here since that is what's specified by the requirement. + This means that at any stages along the pipeline, the handler can return any type of data + as long as it fulfills the requirements for the next handler's input. + + Suppose we wanted to add another handler after ConvertToCharArrayHandler. That handler + then is expected to receive an input of char[] array since that is the type being returned + by the previous handler, ConvertToCharArrayHandler. + */ + new Pipeline<>(new RemoveAlphabetsHandler()) + .addHandler(new RemoveDigitsHandler()) + .addHandler(new ConvertToCharArrayHandler()); + } +} diff --git a/pipeline/src/main/java/com.iluwatar.pipeline/ConvertToCharArrayHandler.java b/pipeline/src/main/java/com.iluwatar.pipeline/ConvertToCharArrayHandler.java new file mode 100644 index 000000000000..b69241914980 --- /dev/null +++ b/pipeline/src/main/java/com.iluwatar.pipeline/ConvertToCharArrayHandler.java @@ -0,0 +1,45 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * <p> + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * <p> + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * <p> + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.pipeline; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Arrays; + +/** + * Stage handler that converts an input String to its char[] array counterpart. + */ +class ConvertToCharArrayHandler implements Handler<String, char[]> { + + private final Logger logger = LoggerFactory.getLogger(ConvertToCharArrayHandler.class); + + @Override + public char[] process(String input) { + char[] characters = input.toCharArray(); + logger.info(String.format("Current handler: %s, input is %s of type %s, output is %s, of type %s", + ConvertToCharArrayHandler.class, input, String.class, Arrays.toString(characters), Character[].class)); + + return characters; + } +} diff --git a/pipeline/src/main/java/com.iluwatar.pipeline/Handler.java b/pipeline/src/main/java/com.iluwatar.pipeline/Handler.java new file mode 100644 index 000000000000..7d2bc0db7f59 --- /dev/null +++ b/pipeline/src/main/java/com.iluwatar.pipeline/Handler.java @@ -0,0 +1,32 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.pipeline; + +/** + * Forms a contract to all stage handlers to accept a certain type of input and return a processed output. + * @param <I> the input type of the handler + * @param <O> the processed output type of the handler + */ +interface Handler<I, O> { + O process(I input); +} \ No newline at end of file diff --git a/pipeline/src/main/java/com.iluwatar.pipeline/Pipeline.java b/pipeline/src/main/java/com.iluwatar.pipeline/Pipeline.java new file mode 100644 index 000000000000..8e231bbc4d09 --- /dev/null +++ b/pipeline/src/main/java/com.iluwatar.pipeline/Pipeline.java @@ -0,0 +1,46 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.pipeline; + +/** + * Main Pipeline class that initially sets the current handler. Processed output + * of the initial handler is then passed as the input to the next stage handlers. + * @param <I> the type of the input for the first stage handler + * @param <O> the final stage handler's output type + */ +class Pipeline<I, O> { + + private final Handler<I, O> currentHandler; + + Pipeline(Handler<I, O> currentHandler) { + this.currentHandler = currentHandler; + } + + <K> Pipeline<I, K> addHandler(Handler<O, K> newHandler) { + return new Pipeline<>(input -> newHandler.process(currentHandler.process(input))); + } + + O execute(I input) { + return currentHandler.process(input); + } +} \ No newline at end of file diff --git a/pipeline/src/main/java/com.iluwatar.pipeline/RemoveAlphabetsHandler.java b/pipeline/src/main/java/com.iluwatar.pipeline/RemoveAlphabetsHandler.java new file mode 100644 index 000000000000..2085052742fa --- /dev/null +++ b/pipeline/src/main/java/com.iluwatar.pipeline/RemoveAlphabetsHandler.java @@ -0,0 +1,54 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.pipeline; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Stage handler that returns a new instance of String without the alphabet characters of the input string. + */ +class RemoveAlphabetsHandler implements Handler<String, String> { + + private final Logger logger = LoggerFactory.getLogger(RemoveAlphabetsHandler.class); + + @Override + public String process(String input) { + StringBuilder inputWithoutAlphabets = new StringBuilder(); + + for (int index = 0; index < input.length(); index++) { + char currentCharacter = input.charAt(index); + if (Character.isAlphabetic(currentCharacter)) { + continue; + } + + inputWithoutAlphabets.append(currentCharacter); + } + + String inputWithoutAlphabetsStr = inputWithoutAlphabets.toString(); + logger.info(String.format("Current handler: %s, input is %s of type %s, output is %s, of type %s", + RemoveAlphabetsHandler.class, input, String.class, inputWithoutAlphabetsStr, String.class)); + + return inputWithoutAlphabetsStr; + } +} \ No newline at end of file diff --git a/pipeline/src/main/java/com.iluwatar.pipeline/RemoveDigitsHandler.java b/pipeline/src/main/java/com.iluwatar.pipeline/RemoveDigitsHandler.java new file mode 100644 index 000000000000..e0c0aa6a87b2 --- /dev/null +++ b/pipeline/src/main/java/com.iluwatar.pipeline/RemoveDigitsHandler.java @@ -0,0 +1,54 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.pipeline; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Stage handler that returns a new instance of String without the digit characters of the input string. + */ +class RemoveDigitsHandler implements Handler<String, String> { + + private final Logger logger = LoggerFactory.getLogger(RemoveDigitsHandler.class); + + @Override + public String process(String input) { + StringBuilder inputWithoutDigits = new StringBuilder(); + + for (int index = 0; index < input.length(); index++) { + char currentCharacter = input.charAt(index); + if (Character.isDigit(currentCharacter)) { + continue; + } + + inputWithoutDigits.append(currentCharacter); + } + + String inputWithoutDigitsStr = inputWithoutDigits.toString(); + logger.info(String.format("Current handler: %s, input is %s of type %s, output is %s, of type %s", + RemoveDigitsHandler.class, input, String.class, inputWithoutDigitsStr, String.class)); + + return inputWithoutDigitsStr; + } +} \ No newline at end of file diff --git a/pom.xml b/pom.xml index f1a586eb8b34..325a2ff00025 100644 --- a/pom.xml +++ b/pom.xml @@ -94,6 +94,7 @@ <module>property</module> <module>intercepting-filter</module> <module>producer-consumer</module> + <module>pipeline</module> <module>poison-pill</module> <module>reader-writer-lock</module> <module>lazy-loading</module>
diff --git a/pipeline/src/test/java/com.iluwatar.pipeline/AppTest.java b/pipeline/src/test/java/com.iluwatar.pipeline/AppTest.java new file mode 100644 index 000000000000..79524575c13c --- /dev/null +++ b/pipeline/src/test/java/com.iluwatar.pipeline/AppTest.java @@ -0,0 +1,37 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * <p> + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * <p> + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * <p> + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.pipeline; + +import org.junit.jupiter.api.Test; + +/** + * Application Test + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/pipeline/src/test/java/com.iluwatar.pipeline/PipelineTest.java b/pipeline/src/test/java/com.iluwatar.pipeline/PipelineTest.java new file mode 100644 index 000000000000..1a2676e25d05 --- /dev/null +++ b/pipeline/src/test/java/com.iluwatar.pipeline/PipelineTest.java @@ -0,0 +1,45 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * <p> + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * <p> + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * <p> + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.pipeline; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; + +/** + * Test for {@link Pipeline} + */ +public class PipelineTest { + + @Test + public void testAddHandlersToPipeline() { + Pipeline<String, char[]> filters = new Pipeline<>(new RemoveAlphabetsHandler()) + .addHandler(new RemoveDigitsHandler()) + .addHandler(new ConvertToCharArrayHandler()); + + assertArrayEquals( + new char[] {'#', '!', '(', '&', '%', '#', '!'}, + filters.execute("#H!E(L&L0O%THE3R#34E!") + ); + } +}
test
train
2019-10-06T18:06:39
"2016-09-25T19:20:32Z"
iluwatar
train
iluwatar/java-design-patterns/838_968
iluwatar/java-design-patterns
iluwatar/java-design-patterns/838
iluwatar/java-design-patterns/968
[ "keyword_pr_to_issue" ]
94ca25462667b15d2d4f7d5120c94a0733f53bf7
f5455f9887f2613ef2b8ca16eb594d6a962196d8
[ "I would like to try my hand at resolving this issue", "Ok @Kevinyl3, the issue is yours", "I have checked through all the dependencies in all the pom.xml's\r\n\r\n- logback-classic: This dependency is already at version 1.2.3 \r\n- slf4j-api: This dependency is already at version 1.7.30\r\n- httpclient: I cannot find this dependency in the pom.xml of the whole project, nor in any of the individual pom.xml for each module\r\n\r\nOverall it seems that the dependencies listed in this issue have either all already been upgraded past their buggy versions, or have been removed from the project altogether. This issue may be able to marked as resolved as it is.", "Thanks for checking! I too think that we are now able to close this issue.\r\n\r\n@all-contributors please add @Kevinyl3 for review", "@iluwatar \n\nI've put up [a pull request](https://github.com/iluwatar/java-design-patterns/pull/1926) to add @Kevinyl3! :tada:" ]
[]
"2019-10-07T02:05:13Z"
[ "type: bug", "epic: build issue" ]
Buggy dependencies
Hi, there! We are a research team working on third-party library analysis. We have found that some widely-used third-party libraries in your project have major/critical bugs, which will degrade the quality of your project. We highly recommend you to update those libraries to new versions. We have attached the buggy third-party libraries and corresponding jira issue links below for you to have more detailed information. 1 org.apache.httpcomponents httpclient (pom in maven central) version: 4.5.1 Jira issues: Add convenience methods to fluent API class Request affectsVersions:4.5.1 https://issues.apache.org/jira/projects/HTTPCLIENT/issues/HTTPCLIENT-1696?filter=allopenissues GET request should support body affectsVersions:4.5.1 https://issues.apache.org/jira/projects/HTTPCLIENT/issues/HTTPCLIENT-1703?filter=allopenissues Delete obsolete clone method affectsVersions:4.5.1 https://issues.apache.org/jira/projects/HTTPCLIENT/issues/HTTPCLIENT-1709?filter=allopenissues NTLMEngineImpl.Type1Message not thread safe but declared as a constant affectsVersions:4.5.1 https://issues.apache.org/jira/projects/HTTPCLIENT/issues/HTTPCLIENT-1715?filter=allopenissues HttpClient 4.5.1 may perform multiple requests on the same connection despite having "Connection: close" header. affectsVersions:4.5.1 https://issues.apache.org/jira/projects/HTTPCLIENT/issues/HTTPCLIENT-1723?filter=allopenissues The deprecated SSLSocketFactory does not contain the SNI fix found in the SSLConnectionSocketFactory class affectsVersions:4.4.1;4.5.1 https://issues.apache.org/jira/projects/HTTPCLIENT/issues/HTTPCLIENT-1726?filter=allopenissues org.apache.http.impl.client.AbstractHttpClient#createClientConnectionManager Does not account for context class loader affectsVersions:4.4.1;4.5;4.5.1;4.5.2 https://issues.apache.org/jira/projects/HTTPCLIENT/issues/HTTPCLIENT-1727?filter=allopenissues Malformed path not handled well affectsVersions:4.5.1 https://issues.apache.org/jira/projects/HTTPCLIENT/issues/HTTPCLIENT-1803?filter=allopenissues NTLM authentication error: Unexpected state: MSG_TYPE3_GENERATED affectsVersions:4.5.1 https://issues.apache.org/jira/projects/HTTPCLIENT/issues/HTTPCLIENT-1882?filter=allopenissues 2 org.apache.httpcomponents httpclient (pom.xml) version: 4.5.2 Jira issues: org.apache.http.impl.client.AbstractHttpClient#createClientConnectionManager Does not account for context class loader affectsVersions:4.4.1;4.5;4.5.1;4.5.2 https://issues.apache.org/jira/projects/HTTPCLIENT/issues/HTTPCLIENT-1727?filter=allopenissues Memory Leak in OSGi support affectsVersions:4.4.1;4.5.2 https://issues.apache.org/jira/projects/HTTPCLIENT/issues/HTTPCLIENT-1749?filter=allopenissues SystemDefaultRoutePlanner: Possible null pointer dereference affectsVersions:4.5.2 https://issues.apache.org/jira/projects/HTTPCLIENT/issues/HTTPCLIENT-1766?filter=allopenissues Null pointer dereference in EofSensorInputStream and ResponseEntityProxy affectsVersions:4.5.2 https://issues.apache.org/jira/projects/HTTPCLIENT/issues/HTTPCLIENT-1767?filter=allopenissues [OSGi] WeakList needs to support "clear" method affectsVersions:4.5.2;5.0 Alpha1 https://issues.apache.org/jira/projects/HTTPCLIENT/issues/HTTPCLIENT-1772?filter=allopenissues [OSGi] HttpProxyConfigurationActivator does not unregister HttpClientBuilderFactory affectsVersions:4.5.2 https://issues.apache.org/jira/projects/HTTPCLIENT/issues/HTTPCLIENT-1773?filter=allopenissues Why is Retry around Redirect and not the other way round affectsVersions:4.5.2 https://issues.apache.org/jira/projects/HTTPCLIENT/issues/HTTPCLIENT-1800?filter=allopenissues 3 org.slf4j slf4j-api (pom.xml) version: 1.7.21 Jira issues: Cannot re-initialize the SimpleLogger anymore. affectsVersions:1.7.21 https://jira.qos.ch/projects/SLF4J/issues/SLF4J-370?filter=allopenissues Marker lost in EventRecodingLogger affectsVersions:1.7.21 https://jira.qos.ch/projects/SLF4J/issues/SLF4J-379?filter=allopenissues Support for JCL 1.2 affectsVersions:1.7.21 https://jira.qos.ch/projects/SLF4J/issues/SLF4J-383?filter=allopenissues 4 ch.qos.logback logback-classic (pom.xml) version: 1.1.7 Jira issues: SMTPAppender configuration error since Logback 1.1.7 affectsVersions:1.1.7 https://jira.qos.ch/projects/LOGBACK/issues/LOGBACK-1158?filter=allopenissues Don't swallow Errors affectsVersions:1.1.6;1.1.7 https://jira.qos.ch/projects/LOGBACK/issues/LOGBACK-1159?filter=allopenissues Incorrect "contains multiple setters for the same property" error output for bridge methods affectsVersions:1.1.7 https://jira.qos.ch/projects/LOGBACK/issues/LOGBACK-1164?filter=allopenissues MDCFilter crashes with NPE when value is not set affectsVersions:1.1.7 https://jira.qos.ch/projects/LOGBACK/issues/LOGBACK-1165?filter=allopenissues totalSizeCap not work as expected affectsVersions:1.1.7 https://jira.qos.ch/projects/LOGBACK/issues/LOGBACK-1166?filter=allopenissues Log file handle/descriptor not closed/released after WAR file redeploy affectsVersions:1.1.6;1.1.7 https://jira.qos.ch/projects/LOGBACK/issues/LOGBACK-1170?filter=allopenissues FilenamePattern used to TimeBasedArchiveRemover is limited for 999 files affectsVersions:1.1.7 https://jira.qos.ch/projects/LOGBACK/issues/LOGBACK-1175?filter=allopenissues SizeAndTimeBasedFNATP should not start in the absence of maxFileSize property affectsVersions:1.1.7 https://jira.qos.ch/projects/LOGBACK/issues/LOGBACK-1176?filter=allopenissues RollingFileAppender throws UnsupportedOperationEx after elapsed period affectsVersions:1.1.7 https://jira.qos.ch/projects/LOGBACK/issues/LOGBACK-1181?filter=allopenissues scanPeriod attribute is required by logback-classic for auto-reload to work affectsVersions:1.1.7 https://jira.qos.ch/projects/LOGBACK/issues/LOGBACK-1194?filter=allopenissues RollingFileAppender generating a large numbers of .tmp files affectsVersions:1.1.7 https://jira.qos.ch/projects/LOGBACK/issues/LOGBACK-1238?filter=allopenissues Allow leading zeros in %i pattern affectsVersions:1.1.7 https://jira.qos.ch/projects/LOGBACK/issues/LOGBACK-1248?filter=allopenissues Sincerely~ FDU Software Engineering Lab Jan 7th,2019
[ "pom.xml" ]
[ "pom.xml" ]
[]
diff --git a/pom.xml b/pom.xml index acaaef6181c5..539da396b2d8 100644 --- a/pom.xml +++ b/pom.xml @@ -43,12 +43,12 @@ <camel.version>2.16.1</camel.version> <guava.version>19.0</guava.version> <mockito.version>1.10.19</mockito.version> - <apache-httpcomponents.version>4.5.2</apache-httpcomponents.version> + <apache-httpcomponents.version>4.5.10</apache-httpcomponents.version> <htmlunit.version>2.22</htmlunit.version> <guice.version>4.0</guice.version> <mongo-java-driver.version>3.3.0</mongo-java-driver.version> - <slf4j.version>1.7.21</slf4j.version> - <logback.version>1.1.7</logback.version> + <slf4j.version>1.7.28</slf4j.version> + <logback.version>1.2.3</logback.version> <aws-lambda-core.version>1.1.0</aws-lambda-core.version> <aws-java-sdk-dynamodb.version>1.11.289</aws-java-sdk-dynamodb.version> <aws-lambda-log4j.version>1.0.0</aws-lambda-log4j.version>
null
test
train
2019-10-06T18:06:39
"2019-01-13T18:03:43Z"
iluwatar
train
iluwatar/java-design-patterns/549_971
iluwatar/java-design-patterns
iluwatar/java-design-patterns/549
iluwatar/java-design-patterns/971
[ "keyword_pr_to_issue" ]
55b0341c8dc28ab84412d535bee9ecbb461fa081
1d4a7681e2d8699457c557fbab3d69d5f8aa105b
[ "Can't we consider \r\n\r\n` try (CloseableHttpClient httpClient = HttpClients.createDefault()) {\r\n HttpGet httpGet = new HttpGet(\"http://localhost:51515/information\");\r\n try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) {\r\n response = EntityUtils.toString(httpResponse.getEntity());\r\n }\r\n } catch (IOException e) {\r\n LOGGER.error(\"Exception caught.\", e);\r\n }`\r\n\r\nin com.iluwatar.aggregator.microservices.ProductInformationClientImpl as example of fallback strategy ([https://blogs.oracle.com/developers/getting-started-with-microservices-part-three](url))?\r\nOr do i not understand the task?", "Has this issue been resolved?", "@ddunig2 I don't see a PR against this. If you want to resolve, you can go ahead.", "Hi, I am raising a PR for this, where ClientProtocolException is caught and the error log statements are updated.", "https://github.com/iluwatar/java-design-patterns/pull/958", "Exception handling was improved, but the original issue still remains unsolved", "Under investigation by @jarpit96 ", "@iluwatar @ddunig2 To implement fallback pattern in Aggregator Service, is returning default literals/constants sufficient ?", "I would probably display an error message to the user in case one of the microservices does not respond or some other fault occurs", "#971", "I have added fall backs in Aggregator Service when other microservices fail. Default error messages (Product Title and Inventory) are returned to the user." ]
[ "`ProductInventoryClientImpl` does not return null but 0 when exception occurs. Perhaps returning null would be the correct way, so the change should be implemented in the client.." ]
"2019-10-07T20:35:04Z"
[ "type: enhancement", "info: good first issue", "epic: code quality" ]
"Aggregator microservices" design pattern doesn't show exception handling
"Aggregator microservices" design pattern doesn't show how exception handling would be done if the one or multiple services used are down and how client calling the aggregator microservice would cope in this situation.
[ "aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Aggregator.java", "aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClient.java", "aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java" ]
[ "aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Aggregator.java", "aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClient.java", "aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java" ]
[]
diff --git a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Aggregator.java b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Aggregator.java index e96ac9d43c2c..dbed50fc6610 100644 --- a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Aggregator.java +++ b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Aggregator.java @@ -51,9 +51,23 @@ public class Aggregator { */ @RequestMapping(path = "/product", method = RequestMethod.GET) public Product getProduct() { + var product = new Product(); - product.setTitle(informationClient.getProductTitle()); - product.setProductInventories(inventoryClient.getProductInventories()); + String productTitle = informationClient.getProductTitle(); + Integer productInventory = inventoryClient.getProductInventories(); + + if (productTitle != null) { + product.setTitle(productTitle); + } else { + product.setTitle("Error: Fetching Product Title Failed"); //Fallback to error message + } + + if (productInventory != null) { + product.setProductInventories(productInventory); + } else { + product.setProductInventories(-1); //Fallback to default error inventory + } + return product; } diff --git a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClient.java b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClient.java index ed325be0070f..22369350a203 100644 --- a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClient.java +++ b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClient.java @@ -28,5 +28,5 @@ */ public interface ProductInventoryClient { - int getProductInventories(); + Integer getProductInventories(); } diff --git a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java index c43fe84c61ca..fcd824de7aca 100644 --- a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java +++ b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java @@ -42,8 +42,8 @@ public class ProductInventoryClientImpl implements ProductInventoryClient { private static final Logger LOGGER = LoggerFactory.getLogger(ProductInventoryClientImpl.class); @Override - public int getProductInventories() { - var response = "0"; + public Integer getProductInventories() { + var response = ""; var request = HttpRequest.newBuilder().GET().uri(URI.create("http://localhost:51516/inventories")).build(); var client = HttpClient.newHttpClient(); @@ -55,6 +55,10 @@ public int getProductInventories() { } catch (InterruptedException ie) { LOGGER.error("InterruptedException Occurred", ie); } - return Integer.parseInt(response); + if("".equalsIgnoreCase(response)) { + return null; + } else { + return Integer.parseInt(response); + } } }
null
train
train
2019-10-31T19:01:39
"2017-03-26T17:51:56Z"
neerajmahajan
train
iluwatar/java-design-patterns/973_975
iluwatar/java-design-patterns
iluwatar/java-design-patterns/973
iluwatar/java-design-patterns/975
[ "timestamp(timedelta=7881.0, similarity=0.869720833449218)" ]
71f26c3e59f45d0e62b7137a75705a522d43cdec
e36bbbb22bad5e24c15ea2d185309033580f2ba8
[ "Can I try this out?", "Go ahead @JasonSarwar ", "See `.travis.yml` in https://github.com/iluwatar/java-design-patterns/pull/959", "Set Travis to build on both openjdk8 and openjdk 11 in commits https://github.com/iluwatar/java-design-patterns/commit/795b6be17d270e93ccfc871fa4976f052c33a181 and https://github.com/iluwatar/java-design-patterns/commit/71f26c3e59f45d0e62b7137a75705a522d43cdec", "I was a little late on the draw. Sorry about that!" ]
[]
"2019-10-10T12:57:41Z"
[ "info: good first issue", "epic: build issue" ]
Java 11 support: Update Travis to build on JDK 11
This task is part of the Java 11 transition plan https://github.com/iluwatar/java-design-patterns/wiki/16.-Java-11-Transition The purpose is to update the Travis CI build to use JDK 11, instead of the old JDK 8.
[ "cqrs/pom.xml", "eip-aggregator/pom.xml", "eip-splitter/pom.xml", "eip-wire-tap/pom.xml", "naked-objects/dom/pom.xml", "naked-objects/integtests/pom.xml", "pom.xml", "service-layer/pom.xml", "trampoline/pom.xml" ]
[ "cqrs/pom.xml", "eip-aggregator/pom.xml", "eip-splitter/pom.xml", "eip-wire-tap/pom.xml", "naked-objects/dom/exclude-pmd.properties", "naked-objects/dom/pom.xml", "naked-objects/integtests/pom.xml", "pom.xml", "service-layer/pom.xml", "trampoline/pom.xml" ]
[]
diff --git a/cqrs/pom.xml b/cqrs/pom.xml index beb195473ced..fc89a93b7c79 100644 --- a/cqrs/pom.xml +++ b/cqrs/pom.xml @@ -39,4 +39,25 @@ <artifactId>hibernate-core</artifactId> </dependency> </dependencies> + <profiles> + <profile> + <id>jdk11-deps</id> + <activation> + <jdk>[11,)</jdk> + </activation> + <dependencies> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + <scope>test</scope> + <version>2.1.17</version> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + <scope>test</scope> + </dependency> + </dependencies> + </profile> + </profiles> </project> diff --git a/eip-aggregator/pom.xml b/eip-aggregator/pom.xml index f56ae78deb73..39270f02097e 100644 --- a/eip-aggregator/pom.xml +++ b/eip-aggregator/pom.xml @@ -70,4 +70,24 @@ </dependency> </dependencies> + + <profiles> + <profile> + <id>jdk11-deps</id> + <activation> + <jdk>[11,)</jdk> + </activation> + <dependencies> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + </dependency> + </dependencies> + </profile> + </profiles> + </project> diff --git a/eip-splitter/pom.xml b/eip-splitter/pom.xml index 2bc3eec8402b..7319f651939c 100644 --- a/eip-splitter/pom.xml +++ b/eip-splitter/pom.xml @@ -70,4 +70,25 @@ </dependency> </dependencies> + + <profiles> + <profile> + <id>jdk11-deps</id> + <activation> + <jdk>[11,)</jdk> + </activation> + <dependencies> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + </dependency> + </dependencies> + </profile> + </profiles> + + </project> diff --git a/eip-wire-tap/pom.xml b/eip-wire-tap/pom.xml index efca8d3c4cfb..a9d30924204a 100644 --- a/eip-wire-tap/pom.xml +++ b/eip-wire-tap/pom.xml @@ -70,4 +70,23 @@ </dependency> </dependencies> + + <profiles> + <profile> + <id>jdk11-deps</id> + <activation> + <jdk>[11,)</jdk> + </activation> + <dependencies> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + </dependency> + </dependencies> + </profile> + </profiles> </project> diff --git a/naked-objects/dom/exclude-pmd.properties b/naked-objects/dom/exclude-pmd.properties new file mode 100644 index 000000000000..bda3929accc6 --- /dev/null +++ b/naked-objects/dom/exclude-pmd.properties @@ -0,0 +1,24 @@ +# +# The MIT License +# Copyright (c) 2014-2016 Ilkka Seppälä +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# + +domainapp.dom.modules.simple.QSimpleObject=UnusedFormalParameter \ No newline at end of file diff --git a/naked-objects/dom/pom.xml b/naked-objects/dom/pom.xml index 69365bd4b00a..039afc373727 100644 --- a/naked-objects/dom/pom.xml +++ b/naked-objects/dom/pom.xml @@ -78,7 +78,7 @@ <activeByDefault>true</activeByDefault> </activation> <properties> - <datanucleus-maven-plugin.version>4.0.1</datanucleus-maven-plugin.version> + <datanucleus-maven-plugin.version>5.2.1</datanucleus-maven-plugin.version> </properties> <build> <pluginManagement> diff --git a/naked-objects/integtests/pom.xml b/naked-objects/integtests/pom.xml index c4dd52dcf652..f12f4ae1e368 100644 --- a/naked-objects/integtests/pom.xml +++ b/naked-objects/integtests/pom.xml @@ -122,6 +122,20 @@ </repository> </repositories> --> + <profiles> + <profile> + <id>jdk11-deps</id> + <activation> + <jdk>[11,)</jdk> + </activation> + <dependencies> + <dependency> + <groupId>javax.annotation</groupId> + <artifactId>javax.annotation-api</artifactId> + </dependency> + </dependencies> + </profile> + </profiles> </project> diff --git a/pom.xml b/pom.xml index d812d27c4c54..efeee185c788 100644 --- a/pom.xml +++ b/pom.xml @@ -56,7 +56,8 @@ <jackson.version>2.8.5</jackson.version> <pmd.version>3.12.0</pmd.version> <log4j.version>1.2.17</log4j.version> - <jaxb-api.version>2.3.0</jaxb-api.version> + <jaxb-api.version>2.3.1</jaxb-api.version> + <jaxb-impl.version>2.3.2</jaxb-impl.version> <annotation-api.version>1.3.1</annotation-api.version> </properties> <modules> @@ -314,6 +315,11 @@ <artifactId>javax.annotation-api</artifactId> <version>${annotation-api.version}</version> </dependency> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + <version>${jaxb-impl.version}</version> + </dependency> </dependencies> </dependencyManagement> @@ -494,4 +500,27 @@ </plugins> </reporting> + <profiles> + <profile> + <id>jdk11-dep-management</id> + <activation> + <jdk>[11,)</jdk> + </activation> + <dependencyManagement> + <dependencies> + <dependency> + <groupId>org.javassist</groupId> + <artifactId>javassist</artifactId> + <version>3.25.0-GA</version> + </dependency> + <dependency> + <groupId>javax.annotation</groupId> + <artifactId>javax.annotation-api</artifactId> + <version>1.3.2</version> + </dependency> + </dependencies> + </dependencyManagement> + </profile> + </profiles> + </project> diff --git a/service-layer/pom.xml b/service-layer/pom.xml index 403a896a4613..4edd950740a8 100644 --- a/service-layer/pom.xml +++ b/service-layer/pom.xml @@ -52,4 +52,22 @@ <scope>test</scope> </dependency> </dependencies> + <profiles> + <profile> + <id>jdk11-deps</id> + <activation> + <jdk>[11,)</jdk> + </activation> + <dependencies> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + </dependency> + </dependencies> + </profile> + </profiles> </project> diff --git a/trampoline/pom.xml b/trampoline/pom.xml index 1e019ef31297..86726a1186bc 100644 --- a/trampoline/pom.xml +++ b/trampoline/pom.xml @@ -51,7 +51,7 @@ <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> - <version>1.16.18</version> + <version>1.18.10</version> </dependency>
null
train
train
2019-10-11T18:37:28
"2019-10-08T15:06:02Z"
iluwatar
train
iluwatar/java-design-patterns/948_975
iluwatar/java-design-patterns
iluwatar/java-design-patterns/948
iluwatar/java-design-patterns/975
[ "timestamp(timedelta=83635.0, similarity=0.8724987719835455)" ]
71f26c3e59f45d0e62b7137a75705a522d43cdec
e36bbbb22bad5e24c15ea2d185309033580f2ba8
[ "Lets give it a try..", "Ok @perwramdemark ", "@iluwatar would it be possible to setup CI build with JDK11?", "Added issue https://github.com/iluwatar/java-design-patterns/issues/973 where this is resolved", "Build with JDK11 from current master branch (commit 90ea4506caa653711f69fabb99ee7ac26c4ecce7) produces the following output.\r\n\r\n![image](https://user-images.githubusercontent.com/582346/66600101-6fdaf180-ebad-11e9-894c-79c277a725a3.png)\r\n\r\nThe modules that are failing\r\n- service-layer\r\n- naked-objects\r\n- repository\r\n- layers\r\n- cqrs\r\n- eip-wire-tap\r\n- eip-splitter\r\n- eip-aggregator\r\n- trampoline\r\n\r\nFull build output in the attachment \r\n[output.txt](https://github.com/iluwatar/java-design-patterns/files/3714293/output.txt)\r\n", "Let's continue from here in other issues", "See https://github.com/iluwatar/java-design-patterns/issues/976\r\n@perwramdemark will you work on that?" ]
[]
"2019-10-10T12:57:41Z"
[ "epic: build issue" ]
Java 11 support: Run the build on JDK 11
This task is part of the Java 11 transition plan https://github.com/iluwatar/java-design-patterns/wiki/16.-Java-11-Transition In this task we run the regular build entirely on the newer JDK 11 in a way that lets us gather all errors instead of stopping the build to the first failure (see https://blog.codefx.org/java/planning-your-java-9-update/). Report the list of errors under this issue.
[ "cqrs/pom.xml", "eip-aggregator/pom.xml", "eip-splitter/pom.xml", "eip-wire-tap/pom.xml", "naked-objects/dom/pom.xml", "naked-objects/integtests/pom.xml", "pom.xml", "service-layer/pom.xml", "trampoline/pom.xml" ]
[ "cqrs/pom.xml", "eip-aggregator/pom.xml", "eip-splitter/pom.xml", "eip-wire-tap/pom.xml", "naked-objects/dom/exclude-pmd.properties", "naked-objects/dom/pom.xml", "naked-objects/integtests/pom.xml", "pom.xml", "service-layer/pom.xml", "trampoline/pom.xml" ]
[]
diff --git a/cqrs/pom.xml b/cqrs/pom.xml index beb195473ced..fc89a93b7c79 100644 --- a/cqrs/pom.xml +++ b/cqrs/pom.xml @@ -39,4 +39,25 @@ <artifactId>hibernate-core</artifactId> </dependency> </dependencies> + <profiles> + <profile> + <id>jdk11-deps</id> + <activation> + <jdk>[11,)</jdk> + </activation> + <dependencies> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + <scope>test</scope> + <version>2.1.17</version> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + <scope>test</scope> + </dependency> + </dependencies> + </profile> + </profiles> </project> diff --git a/eip-aggregator/pom.xml b/eip-aggregator/pom.xml index f56ae78deb73..39270f02097e 100644 --- a/eip-aggregator/pom.xml +++ b/eip-aggregator/pom.xml @@ -70,4 +70,24 @@ </dependency> </dependencies> + + <profiles> + <profile> + <id>jdk11-deps</id> + <activation> + <jdk>[11,)</jdk> + </activation> + <dependencies> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + </dependency> + </dependencies> + </profile> + </profiles> + </project> diff --git a/eip-splitter/pom.xml b/eip-splitter/pom.xml index 2bc3eec8402b..7319f651939c 100644 --- a/eip-splitter/pom.xml +++ b/eip-splitter/pom.xml @@ -70,4 +70,25 @@ </dependency> </dependencies> + + <profiles> + <profile> + <id>jdk11-deps</id> + <activation> + <jdk>[11,)</jdk> + </activation> + <dependencies> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + </dependency> + </dependencies> + </profile> + </profiles> + + </project> diff --git a/eip-wire-tap/pom.xml b/eip-wire-tap/pom.xml index efca8d3c4cfb..a9d30924204a 100644 --- a/eip-wire-tap/pom.xml +++ b/eip-wire-tap/pom.xml @@ -70,4 +70,23 @@ </dependency> </dependencies> + + <profiles> + <profile> + <id>jdk11-deps</id> + <activation> + <jdk>[11,)</jdk> + </activation> + <dependencies> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + </dependency> + </dependencies> + </profile> + </profiles> </project> diff --git a/naked-objects/dom/exclude-pmd.properties b/naked-objects/dom/exclude-pmd.properties new file mode 100644 index 000000000000..bda3929accc6 --- /dev/null +++ b/naked-objects/dom/exclude-pmd.properties @@ -0,0 +1,24 @@ +# +# The MIT License +# Copyright (c) 2014-2016 Ilkka Seppälä +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# + +domainapp.dom.modules.simple.QSimpleObject=UnusedFormalParameter \ No newline at end of file diff --git a/naked-objects/dom/pom.xml b/naked-objects/dom/pom.xml index 69365bd4b00a..039afc373727 100644 --- a/naked-objects/dom/pom.xml +++ b/naked-objects/dom/pom.xml @@ -78,7 +78,7 @@ <activeByDefault>true</activeByDefault> </activation> <properties> - <datanucleus-maven-plugin.version>4.0.1</datanucleus-maven-plugin.version> + <datanucleus-maven-plugin.version>5.2.1</datanucleus-maven-plugin.version> </properties> <build> <pluginManagement> diff --git a/naked-objects/integtests/pom.xml b/naked-objects/integtests/pom.xml index c4dd52dcf652..f12f4ae1e368 100644 --- a/naked-objects/integtests/pom.xml +++ b/naked-objects/integtests/pom.xml @@ -122,6 +122,20 @@ </repository> </repositories> --> + <profiles> + <profile> + <id>jdk11-deps</id> + <activation> + <jdk>[11,)</jdk> + </activation> + <dependencies> + <dependency> + <groupId>javax.annotation</groupId> + <artifactId>javax.annotation-api</artifactId> + </dependency> + </dependencies> + </profile> + </profiles> </project> diff --git a/pom.xml b/pom.xml index d812d27c4c54..efeee185c788 100644 --- a/pom.xml +++ b/pom.xml @@ -56,7 +56,8 @@ <jackson.version>2.8.5</jackson.version> <pmd.version>3.12.0</pmd.version> <log4j.version>1.2.17</log4j.version> - <jaxb-api.version>2.3.0</jaxb-api.version> + <jaxb-api.version>2.3.1</jaxb-api.version> + <jaxb-impl.version>2.3.2</jaxb-impl.version> <annotation-api.version>1.3.1</annotation-api.version> </properties> <modules> @@ -314,6 +315,11 @@ <artifactId>javax.annotation-api</artifactId> <version>${annotation-api.version}</version> </dependency> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + <version>${jaxb-impl.version}</version> + </dependency> </dependencies> </dependencyManagement> @@ -494,4 +500,27 @@ </plugins> </reporting> + <profiles> + <profile> + <id>jdk11-dep-management</id> + <activation> + <jdk>[11,)</jdk> + </activation> + <dependencyManagement> + <dependencies> + <dependency> + <groupId>org.javassist</groupId> + <artifactId>javassist</artifactId> + <version>3.25.0-GA</version> + </dependency> + <dependency> + <groupId>javax.annotation</groupId> + <artifactId>javax.annotation-api</artifactId> + <version>1.3.2</version> + </dependency> + </dependencies> + </dependencyManagement> + </profile> + </profiles> + </project> diff --git a/service-layer/pom.xml b/service-layer/pom.xml index 403a896a4613..4edd950740a8 100644 --- a/service-layer/pom.xml +++ b/service-layer/pom.xml @@ -52,4 +52,22 @@ <scope>test</scope> </dependency> </dependencies> + <profiles> + <profile> + <id>jdk11-deps</id> + <activation> + <jdk>[11,)</jdk> + </activation> + <dependencies> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + </dependency> + </dependencies> + </profile> + </profiles> </project> diff --git a/trampoline/pom.xml b/trampoline/pom.xml index 1e019ef31297..86726a1186bc 100644 --- a/trampoline/pom.xml +++ b/trampoline/pom.xml @@ -51,7 +51,7 @@ <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> - <version>1.16.18</version> + <version>1.18.10</version> </dependency>
null
train
train
2019-10-11T18:37:28
"2019-10-04T05:30:43Z"
iluwatar
train
iluwatar/java-design-patterns/977_979
iluwatar/java-design-patterns
iluwatar/java-design-patterns/977
iluwatar/java-design-patterns/979
[ "timestamp(timedelta=79.0, similarity=0.9455374395355424)" ]
e36bbbb22bad5e24c15ea2d185309033580f2ba8
fcc1c0a27cbf92f07d4a2d9164598c883da74416
[ "Hello.\r\nCan I claim this? :)", "Sure @Shumyk I'll assign it to you" ]
[]
"2019-10-11T19:30:07Z"
[ "info: good first issue", "epic: build issue", "epic: dependencies" ]
Remove maven-pmd-plugin from project
We are using SonarCloud for static source code analysis so maven-pmd-plugin is included really for no particular reason. Let's remove it from the project.
[ "exclude-pmd.properties", "pom.xml" ]
[ "pom.xml" ]
[]
diff --git a/exclude-pmd.properties b/exclude-pmd.properties deleted file mode 100644 index 5a4bb138834e..000000000000 --- a/exclude-pmd.properties +++ /dev/null @@ -1,27 +0,0 @@ -# -# The MIT License -# Copyright (c) 2014-2016 Ilkka Seppälä -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -# - -com.iluwatar.servicelayer.common.BaseEntity=UnusedPrivateField -com.iluwatar.doublechecked.locking.App=EmptyStatementNotInLoop,EmptyWhileStmt -com.iluwatar.doublechecked.locking.InventoryTest=EmptyStatementNotInLoop,EmptyWhileStmt -domainapp.dom.modules.simple.QSimpleObject=UnusedFormalParameter \ No newline at end of file diff --git a/pom.xml b/pom.xml index d812d27c4c54..bb3e31d300fb 100644 --- a/pom.xml +++ b/pom.xml @@ -54,7 +54,6 @@ <aws-lambda-log4j.version>1.0.0</aws-lambda-log4j.version> <aws-lambda-java-events.version>2.0.1</aws-lambda-java-events.version> <jackson.version>2.8.5</jackson.version> - <pmd.version>3.12.0</pmd.version> <log4j.version>1.2.17</log4j.version> <jaxb-api.version>2.3.0</jaxb-api.version> <annotation-api.version>1.3.1</annotation-api.version> @@ -434,26 +433,6 @@ </execution> </executions> </plugin> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-pmd-plugin</artifactId> - <version>${pmd.version}</version> - <configuration> - <failOnViolation>true</failOnViolation> - <failurePriority>5</failurePriority> - <printFailingErrors>true</printFailingErrors> - </configuration> - <executions> - <execution> - <goals> - <goal>check</goal> - </goals> - <configuration> - <excludeFromFailureFile>exclude-pmd.properties</excludeFromFailureFile> - </configuration> - </execution> - </executions> - </plugin> <plugin> <groupId>com.mycila</groupId> @@ -481,11 +460,6 @@ <reporting> <plugins> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-pmd-plugin</artifactId> - <version>${pmd.version}</version> - </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jxr-plugin</artifactId>
null
val
train
2019-10-11T20:55:48
"2019-10-11T17:24:02Z"
iluwatar
train
iluwatar/java-design-patterns/964_980
iluwatar/java-design-patterns
iluwatar/java-design-patterns/964
iluwatar/java-design-patterns/980
[ "timestamp(timedelta=37400.0, similarity=0.878957276479159)" ]
e36bbbb22bad5e24c15ea2d185309033580f2ba8
6faec9901a2380800aa50af538c8669539997176
[ "Also see if https://github.com/iluwatar/java-design-patterns/issues/838 can be closed after the dependency update", "This issue can be closed as we are already JDK11 compliant" ]
[]
"2019-10-11T19:50:31Z"
[ "info: help wanted", "resolution: won't fix", "epic: dependencies" ]
Java 11 support: Upgrade dependencies
This task is part of the Java 11 transition plan https://github.com/iluwatar/java-design-patterns/wiki/16.-Java-11-Transition Upgrade project dependencies so that they support Java 11. Most of the dependencies can be found in main `pom.xml` dependencyManagement section. Links: https://www.infoq.com/articles/upgrading-java-8-to-12/ and https://winterbe.com/posts/2018/08/29/migrate-maven-projects-to-java-11-jigsaw/
[ ".travis.yml", "cqrs/pom.xml", "eip-aggregator/pom.xml", "eip-splitter/pom.xml", "eip-wire-tap/pom.xml", "naked-objects/dom/pom.xml", "naked-objects/integtests/pom.xml", "pom.xml", "service-layer/pom.xml" ]
[ ".travis.yml", "cqrs/pom.xml", "eip-aggregator/pom.xml", "eip-splitter/pom.xml", "eip-wire-tap/pom.xml", "naked-objects/dom/pom.xml", "naked-objects/integtests/pom.xml", "pom.xml", "service-layer/pom.xml" ]
[]
diff --git a/.travis.yml b/.travis.yml index 84b031fadcc1..45323dcfd457 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,6 @@ language: java dist: xenial jdk: -- openjdk8 - openjdk11 env: diff --git a/cqrs/pom.xml b/cqrs/pom.xml index fc89a93b7c79..9c9458505aba 100644 --- a/cqrs/pom.xml +++ b/cqrs/pom.xml @@ -38,26 +38,18 @@ <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> </dependency> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + <scope>test</scope> + <version>2.1.17</version> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + <scope>test</scope> + </dependency> + </dependencies> - <profiles> - <profile> - <id>jdk11-deps</id> - <activation> - <jdk>[11,)</jdk> - </activation> - <dependencies> - <dependency> - <groupId>com.sun.xml.bind</groupId> - <artifactId>jaxb-impl</artifactId> - <scope>test</scope> - <version>2.1.17</version> - </dependency> - <dependency> - <groupId>javax.xml.bind</groupId> - <artifactId>jaxb-api</artifactId> - <scope>test</scope> - </dependency> - </dependencies> - </profile> - </profiles> + </project> diff --git a/eip-aggregator/pom.xml b/eip-aggregator/pom.xml index 39270f02097e..6a5e32845cfc 100644 --- a/eip-aggregator/pom.xml +++ b/eip-aggregator/pom.xml @@ -47,6 +47,15 @@ <version>${camel.version}</version> </dependency> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + </dependency> + <!-- Testing --> <dependency> <groupId>com.github.sbrannen</groupId> @@ -71,23 +80,4 @@ </dependencies> - <profiles> - <profile> - <id>jdk11-deps</id> - <activation> - <jdk>[11,)</jdk> - </activation> - <dependencies> - <dependency> - <groupId>com.sun.xml.bind</groupId> - <artifactId>jaxb-impl</artifactId> - </dependency> - <dependency> - <groupId>javax.xml.bind</groupId> - <artifactId>jaxb-api</artifactId> - </dependency> - </dependencies> - </profile> - </profiles> - </project> diff --git a/eip-splitter/pom.xml b/eip-splitter/pom.xml index 7319f651939c..9769d08034a7 100644 --- a/eip-splitter/pom.xml +++ b/eip-splitter/pom.xml @@ -47,6 +47,16 @@ <version>${camel.version}</version> </dependency> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + </dependency> + + <!-- Testing --> <dependency> <groupId>com.github.sbrannen</groupId> @@ -71,24 +81,4 @@ </dependencies> - <profiles> - <profile> - <id>jdk11-deps</id> - <activation> - <jdk>[11,)</jdk> - </activation> - <dependencies> - <dependency> - <groupId>com.sun.xml.bind</groupId> - <artifactId>jaxb-impl</artifactId> - </dependency> - <dependency> - <groupId>javax.xml.bind</groupId> - <artifactId>jaxb-api</artifactId> - </dependency> - </dependencies> - </profile> - </profiles> - - </project> diff --git a/eip-wire-tap/pom.xml b/eip-wire-tap/pom.xml index a9d30924204a..c96063418c46 100644 --- a/eip-wire-tap/pom.xml +++ b/eip-wire-tap/pom.xml @@ -47,6 +47,16 @@ <version>${camel.version}</version> </dependency> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + </dependency> + + <!-- Testing --> <dependency> <groupId>com.github.sbrannen</groupId> @@ -71,22 +81,4 @@ </dependencies> - <profiles> - <profile> - <id>jdk11-deps</id> - <activation> - <jdk>[11,)</jdk> - </activation> - <dependencies> - <dependency> - <groupId>com.sun.xml.bind</groupId> - <artifactId>jaxb-impl</artifactId> - </dependency> - <dependency> - <groupId>javax.xml.bind</groupId> - <artifactId>jaxb-api</artifactId> - </dependency> - </dependencies> - </profile> - </profiles> </project> diff --git a/naked-objects/dom/pom.xml b/naked-objects/dom/pom.xml index 039afc373727..e816c76bbd78 100644 --- a/naked-objects/dom/pom.xml +++ b/naked-objects/dom/pom.xml @@ -36,6 +36,17 @@ </excludes> </resource> </resources> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-compiler-plugin</artifactId> + <version>${compiler.version}</version> + <configuration> + <source>8</source> + <target>8</target> + </configuration> + </plugin> + </plugins> </build> <dependencies> diff --git a/naked-objects/integtests/pom.xml b/naked-objects/integtests/pom.xml index f12f4ae1e368..7365a71a9acb 100644 --- a/naked-objects/integtests/pom.xml +++ b/naked-objects/integtests/pom.xml @@ -90,6 +90,11 @@ <artifactId>hsqldb</artifactId> </dependency> + <dependency> + <groupId>javax.annotation</groupId> + <artifactId>javax.annotation-api</artifactId> + </dependency> + <!-- uncomment to enable enhanced cucumber-jvm reporting http://www.masterthought.net/section/cucumber-reporting @@ -122,20 +127,5 @@ </repository> </repositories> --> - <profiles> - <profile> - <id>jdk11-deps</id> - <activation> - <jdk>[11,)</jdk> - </activation> - <dependencies> - <dependency> - <groupId>javax.annotation</groupId> - <artifactId>javax.annotation-api</artifactId> - </dependency> - </dependencies> - </profile> - </profiles> - </project> diff --git a/pom.xml b/pom.xml index efeee185c788..b3756e1c06fb 100644 --- a/pom.xml +++ b/pom.xml @@ -58,7 +58,7 @@ <log4j.version>1.2.17</log4j.version> <jaxb-api.version>2.3.1</jaxb-api.version> <jaxb-impl.version>2.3.2</jaxb-impl.version> - <annotation-api.version>1.3.1</annotation-api.version> + <annotation-api.version>1.3.2</annotation-api.version> </properties> <modules> <module>abstract-factory</module> @@ -320,6 +320,11 @@ <artifactId>jaxb-impl</artifactId> <version>${jaxb-impl.version}</version> </dependency> + <dependency> + <groupId>org.javassist</groupId> + <artifactId>javassist</artifactId> + <version>3.25.0-GA</version> + </dependency> </dependencies> </dependencyManagement> @@ -380,8 +385,8 @@ <artifactId>maven-compiler-plugin</artifactId> <version>${compiler.version}</version> <configuration> - <source>1.8</source> - <target>1.8</target> + <source>11</source> + <target>11</target> </configuration> </plugin> <plugin> @@ -500,27 +505,4 @@ </plugins> </reporting> - <profiles> - <profile> - <id>jdk11-dep-management</id> - <activation> - <jdk>[11,)</jdk> - </activation> - <dependencyManagement> - <dependencies> - <dependency> - <groupId>org.javassist</groupId> - <artifactId>javassist</artifactId> - <version>3.25.0-GA</version> - </dependency> - <dependency> - <groupId>javax.annotation</groupId> - <artifactId>javax.annotation-api</artifactId> - <version>1.3.2</version> - </dependency> - </dependencies> - </dependencyManagement> - </profile> - </profiles> - </project> diff --git a/service-layer/pom.xml b/service-layer/pom.xml index 4edd950740a8..057a701341a7 100644 --- a/service-layer/pom.xml +++ b/service-layer/pom.xml @@ -41,6 +41,14 @@ <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </dependency> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> @@ -52,22 +60,5 @@ <scope>test</scope> </dependency> </dependencies> - <profiles> - <profile> - <id>jdk11-deps</id> - <activation> - <jdk>[11,)</jdk> - </activation> - <dependencies> - <dependency> - <groupId>com.sun.xml.bind</groupId> - <artifactId>jaxb-impl</artifactId> - </dependency> - <dependency> - <groupId>javax.xml.bind</groupId> - <artifactId>jaxb-api</artifactId> - </dependency> - </dependencies> - </profile> - </profiles> + </project>
null
val
train
2019-10-11T20:55:48
"2019-10-06T16:22:26Z"
iluwatar
train
iluwatar/java-design-patterns/976_980
iluwatar/java-design-patterns
iluwatar/java-design-patterns/976
iluwatar/java-design-patterns/980
[ "timestamp(timedelta=887.0, similarity=0.8643342372704113)" ]
e36bbbb22bad5e24c15ea2d185309033580f2ba8
6faec9901a2380800aa50af538c8669539997176
[ "@lbroman @perwramdemark working on this?", "PR #975 should take care of this. Building through the project now, will push the PR in a few minutes.", "Sorry, wrong issue I was editing. Reopened.", "In my PR #980 I have left language source and target at 8 for the naked-objects/dom module. This is because java 11 bytecode breaks the datanucleus enhancer, even if they claim that 5.2 should support java 11 bytecode.\r\nI have tried fiddling with the datanucleus dependency versions because the module uses datanucleus core 5 and apis from 4 so I thought that might be the problem. However, bumping up the versions breaks other stuff as they seem to have moved around some classes between 4 and 5.", "I created follow-up task https://github.com/iluwatar/java-design-patterns/issues/983 about the datanucleus issue you described @lbroman. As such I think this issue can be closed. Many thanks for the hard work you've done so far :+1: " ]
[]
"2019-10-11T19:50:31Z"
[ "epic: build issue", "epic: dependencies" ]
Java 11 support: Build with JDK11
This task is part of the Java 11 transition plan https://github.com/iluwatar/java-design-patterns/wiki/16.-Java-11-Transition Configure Maven plugins to use Java 11 and verify that build works using JDK11 (see https://winterbe.com/posts/2018/08/29/migrate-maven-projects-to-java-11-jigsaw/ and https://www.baeldung.com/maven-java-version)
[ ".travis.yml", "cqrs/pom.xml", "eip-aggregator/pom.xml", "eip-splitter/pom.xml", "eip-wire-tap/pom.xml", "naked-objects/dom/pom.xml", "naked-objects/integtests/pom.xml", "pom.xml", "service-layer/pom.xml" ]
[ ".travis.yml", "cqrs/pom.xml", "eip-aggregator/pom.xml", "eip-splitter/pom.xml", "eip-wire-tap/pom.xml", "naked-objects/dom/pom.xml", "naked-objects/integtests/pom.xml", "pom.xml", "service-layer/pom.xml" ]
[]
diff --git a/.travis.yml b/.travis.yml index 84b031fadcc1..45323dcfd457 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,6 @@ language: java dist: xenial jdk: -- openjdk8 - openjdk11 env: diff --git a/cqrs/pom.xml b/cqrs/pom.xml index fc89a93b7c79..9c9458505aba 100644 --- a/cqrs/pom.xml +++ b/cqrs/pom.xml @@ -38,26 +38,18 @@ <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> </dependency> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + <scope>test</scope> + <version>2.1.17</version> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + <scope>test</scope> + </dependency> + </dependencies> - <profiles> - <profile> - <id>jdk11-deps</id> - <activation> - <jdk>[11,)</jdk> - </activation> - <dependencies> - <dependency> - <groupId>com.sun.xml.bind</groupId> - <artifactId>jaxb-impl</artifactId> - <scope>test</scope> - <version>2.1.17</version> - </dependency> - <dependency> - <groupId>javax.xml.bind</groupId> - <artifactId>jaxb-api</artifactId> - <scope>test</scope> - </dependency> - </dependencies> - </profile> - </profiles> + </project> diff --git a/eip-aggregator/pom.xml b/eip-aggregator/pom.xml index 39270f02097e..6a5e32845cfc 100644 --- a/eip-aggregator/pom.xml +++ b/eip-aggregator/pom.xml @@ -47,6 +47,15 @@ <version>${camel.version}</version> </dependency> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + </dependency> + <!-- Testing --> <dependency> <groupId>com.github.sbrannen</groupId> @@ -71,23 +80,4 @@ </dependencies> - <profiles> - <profile> - <id>jdk11-deps</id> - <activation> - <jdk>[11,)</jdk> - </activation> - <dependencies> - <dependency> - <groupId>com.sun.xml.bind</groupId> - <artifactId>jaxb-impl</artifactId> - </dependency> - <dependency> - <groupId>javax.xml.bind</groupId> - <artifactId>jaxb-api</artifactId> - </dependency> - </dependencies> - </profile> - </profiles> - </project> diff --git a/eip-splitter/pom.xml b/eip-splitter/pom.xml index 7319f651939c..9769d08034a7 100644 --- a/eip-splitter/pom.xml +++ b/eip-splitter/pom.xml @@ -47,6 +47,16 @@ <version>${camel.version}</version> </dependency> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + </dependency> + + <!-- Testing --> <dependency> <groupId>com.github.sbrannen</groupId> @@ -71,24 +81,4 @@ </dependencies> - <profiles> - <profile> - <id>jdk11-deps</id> - <activation> - <jdk>[11,)</jdk> - </activation> - <dependencies> - <dependency> - <groupId>com.sun.xml.bind</groupId> - <artifactId>jaxb-impl</artifactId> - </dependency> - <dependency> - <groupId>javax.xml.bind</groupId> - <artifactId>jaxb-api</artifactId> - </dependency> - </dependencies> - </profile> - </profiles> - - </project> diff --git a/eip-wire-tap/pom.xml b/eip-wire-tap/pom.xml index a9d30924204a..c96063418c46 100644 --- a/eip-wire-tap/pom.xml +++ b/eip-wire-tap/pom.xml @@ -47,6 +47,16 @@ <version>${camel.version}</version> </dependency> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + </dependency> + + <!-- Testing --> <dependency> <groupId>com.github.sbrannen</groupId> @@ -71,22 +81,4 @@ </dependencies> - <profiles> - <profile> - <id>jdk11-deps</id> - <activation> - <jdk>[11,)</jdk> - </activation> - <dependencies> - <dependency> - <groupId>com.sun.xml.bind</groupId> - <artifactId>jaxb-impl</artifactId> - </dependency> - <dependency> - <groupId>javax.xml.bind</groupId> - <artifactId>jaxb-api</artifactId> - </dependency> - </dependencies> - </profile> - </profiles> </project> diff --git a/naked-objects/dom/pom.xml b/naked-objects/dom/pom.xml index 039afc373727..e816c76bbd78 100644 --- a/naked-objects/dom/pom.xml +++ b/naked-objects/dom/pom.xml @@ -36,6 +36,17 @@ </excludes> </resource> </resources> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-compiler-plugin</artifactId> + <version>${compiler.version}</version> + <configuration> + <source>8</source> + <target>8</target> + </configuration> + </plugin> + </plugins> </build> <dependencies> diff --git a/naked-objects/integtests/pom.xml b/naked-objects/integtests/pom.xml index f12f4ae1e368..7365a71a9acb 100644 --- a/naked-objects/integtests/pom.xml +++ b/naked-objects/integtests/pom.xml @@ -90,6 +90,11 @@ <artifactId>hsqldb</artifactId> </dependency> + <dependency> + <groupId>javax.annotation</groupId> + <artifactId>javax.annotation-api</artifactId> + </dependency> + <!-- uncomment to enable enhanced cucumber-jvm reporting http://www.masterthought.net/section/cucumber-reporting @@ -122,20 +127,5 @@ </repository> </repositories> --> - <profiles> - <profile> - <id>jdk11-deps</id> - <activation> - <jdk>[11,)</jdk> - </activation> - <dependencies> - <dependency> - <groupId>javax.annotation</groupId> - <artifactId>javax.annotation-api</artifactId> - </dependency> - </dependencies> - </profile> - </profiles> - </project> diff --git a/pom.xml b/pom.xml index efeee185c788..b3756e1c06fb 100644 --- a/pom.xml +++ b/pom.xml @@ -58,7 +58,7 @@ <log4j.version>1.2.17</log4j.version> <jaxb-api.version>2.3.1</jaxb-api.version> <jaxb-impl.version>2.3.2</jaxb-impl.version> - <annotation-api.version>1.3.1</annotation-api.version> + <annotation-api.version>1.3.2</annotation-api.version> </properties> <modules> <module>abstract-factory</module> @@ -320,6 +320,11 @@ <artifactId>jaxb-impl</artifactId> <version>${jaxb-impl.version}</version> </dependency> + <dependency> + <groupId>org.javassist</groupId> + <artifactId>javassist</artifactId> + <version>3.25.0-GA</version> + </dependency> </dependencies> </dependencyManagement> @@ -380,8 +385,8 @@ <artifactId>maven-compiler-plugin</artifactId> <version>${compiler.version}</version> <configuration> - <source>1.8</source> - <target>1.8</target> + <source>11</source> + <target>11</target> </configuration> </plugin> <plugin> @@ -500,27 +505,4 @@ </plugins> </reporting> - <profiles> - <profile> - <id>jdk11-dep-management</id> - <activation> - <jdk>[11,)</jdk> - </activation> - <dependencyManagement> - <dependencies> - <dependency> - <groupId>org.javassist</groupId> - <artifactId>javassist</artifactId> - <version>3.25.0-GA</version> - </dependency> - <dependency> - <groupId>javax.annotation</groupId> - <artifactId>javax.annotation-api</artifactId> - <version>1.3.2</version> - </dependency> - </dependencies> - </dependencyManagement> - </profile> - </profiles> - </project> diff --git a/service-layer/pom.xml b/service-layer/pom.xml index 4edd950740a8..057a701341a7 100644 --- a/service-layer/pom.xml +++ b/service-layer/pom.xml @@ -41,6 +41,14 @@ <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </dependency> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> @@ -52,22 +60,5 @@ <scope>test</scope> </dependency> </dependencies> - <profiles> - <profile> - <id>jdk11-deps</id> - <activation> - <jdk>[11,)</jdk> - </activation> - <dependencies> - <dependency> - <groupId>com.sun.xml.bind</groupId> - <artifactId>jaxb-impl</artifactId> - </dependency> - <dependency> - <groupId>javax.xml.bind</groupId> - <artifactId>jaxb-api</artifactId> - </dependency> - </dependencies> - </profile> - </profiles> + </project>
null
train
train
2019-10-11T20:55:48
"2019-10-10T19:50:26Z"
iluwatar
train
iluwatar/java-design-patterns/950_980
iluwatar/java-design-patterns
iluwatar/java-design-patterns/950
iluwatar/java-design-patterns/980
[ "timestamp(timedelta=90918.0, similarity=0.8647862011261235)" ]
e36bbbb22bad5e24c15ea2d185309033580f2ba8
6faec9901a2380800aa50af538c8669539997176
[ "E.g. `/usr/lib/jvm/java-11-openjdk-amd64/bin/jdeps -jdkinternals async-method-invocation/target/async-method-invocation-1.22.0-SNAPSHOT.jar`", "Get the list of jars to be inspected\r\n`find -name \"*-1.22.0-SNAPSHOT.jar\" > list.txt`\r\n\r\nCheck the jars with the following scritpt\r\n```\r\n#!/bin/bash\r\n\r\nset -x\r\n\r\ncat list.txt | while read line\r\ndo\r\n /usr/lib/jvm/java-11-openjdk-amd64/bin/jdeps -jdkinternals \"${line}\"\r\ndone\r\n```\r\n\r\nNo violations were found in the check.\r\n" ]
[]
"2019-10-11T19:50:31Z"
[ "epic: build issue" ]
Java 11 support: JDeps
This task is part of the Java 11 transition plan https://github.com/iluwatar/java-design-patterns/wiki/16.-Java-11-Transition There’s a tool, JDeps, that’s part of the JDK 11 that you can run with a flag of -jdkinternals to check to see if a set of classes is using something it shouldn’t. Run JDeps on the project and its dependencies (see https://blog.codefx.org/tools/jdeps-tutorial-analyze-java-project-dependencies/) and report findings under this issue.
[ ".travis.yml", "cqrs/pom.xml", "eip-aggregator/pom.xml", "eip-splitter/pom.xml", "eip-wire-tap/pom.xml", "naked-objects/dom/pom.xml", "naked-objects/integtests/pom.xml", "pom.xml", "service-layer/pom.xml" ]
[ ".travis.yml", "cqrs/pom.xml", "eip-aggregator/pom.xml", "eip-splitter/pom.xml", "eip-wire-tap/pom.xml", "naked-objects/dom/pom.xml", "naked-objects/integtests/pom.xml", "pom.xml", "service-layer/pom.xml" ]
[]
diff --git a/.travis.yml b/.travis.yml index 84b031fadcc1..45323dcfd457 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,6 @@ language: java dist: xenial jdk: -- openjdk8 - openjdk11 env: diff --git a/cqrs/pom.xml b/cqrs/pom.xml index fc89a93b7c79..9c9458505aba 100644 --- a/cqrs/pom.xml +++ b/cqrs/pom.xml @@ -38,26 +38,18 @@ <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> </dependency> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + <scope>test</scope> + <version>2.1.17</version> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + <scope>test</scope> + </dependency> + </dependencies> - <profiles> - <profile> - <id>jdk11-deps</id> - <activation> - <jdk>[11,)</jdk> - </activation> - <dependencies> - <dependency> - <groupId>com.sun.xml.bind</groupId> - <artifactId>jaxb-impl</artifactId> - <scope>test</scope> - <version>2.1.17</version> - </dependency> - <dependency> - <groupId>javax.xml.bind</groupId> - <artifactId>jaxb-api</artifactId> - <scope>test</scope> - </dependency> - </dependencies> - </profile> - </profiles> + </project> diff --git a/eip-aggregator/pom.xml b/eip-aggregator/pom.xml index 39270f02097e..6a5e32845cfc 100644 --- a/eip-aggregator/pom.xml +++ b/eip-aggregator/pom.xml @@ -47,6 +47,15 @@ <version>${camel.version}</version> </dependency> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + </dependency> + <!-- Testing --> <dependency> <groupId>com.github.sbrannen</groupId> @@ -71,23 +80,4 @@ </dependencies> - <profiles> - <profile> - <id>jdk11-deps</id> - <activation> - <jdk>[11,)</jdk> - </activation> - <dependencies> - <dependency> - <groupId>com.sun.xml.bind</groupId> - <artifactId>jaxb-impl</artifactId> - </dependency> - <dependency> - <groupId>javax.xml.bind</groupId> - <artifactId>jaxb-api</artifactId> - </dependency> - </dependencies> - </profile> - </profiles> - </project> diff --git a/eip-splitter/pom.xml b/eip-splitter/pom.xml index 7319f651939c..9769d08034a7 100644 --- a/eip-splitter/pom.xml +++ b/eip-splitter/pom.xml @@ -47,6 +47,16 @@ <version>${camel.version}</version> </dependency> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + </dependency> + + <!-- Testing --> <dependency> <groupId>com.github.sbrannen</groupId> @@ -71,24 +81,4 @@ </dependencies> - <profiles> - <profile> - <id>jdk11-deps</id> - <activation> - <jdk>[11,)</jdk> - </activation> - <dependencies> - <dependency> - <groupId>com.sun.xml.bind</groupId> - <artifactId>jaxb-impl</artifactId> - </dependency> - <dependency> - <groupId>javax.xml.bind</groupId> - <artifactId>jaxb-api</artifactId> - </dependency> - </dependencies> - </profile> - </profiles> - - </project> diff --git a/eip-wire-tap/pom.xml b/eip-wire-tap/pom.xml index a9d30924204a..c96063418c46 100644 --- a/eip-wire-tap/pom.xml +++ b/eip-wire-tap/pom.xml @@ -47,6 +47,16 @@ <version>${camel.version}</version> </dependency> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + </dependency> + + <!-- Testing --> <dependency> <groupId>com.github.sbrannen</groupId> @@ -71,22 +81,4 @@ </dependencies> - <profiles> - <profile> - <id>jdk11-deps</id> - <activation> - <jdk>[11,)</jdk> - </activation> - <dependencies> - <dependency> - <groupId>com.sun.xml.bind</groupId> - <artifactId>jaxb-impl</artifactId> - </dependency> - <dependency> - <groupId>javax.xml.bind</groupId> - <artifactId>jaxb-api</artifactId> - </dependency> - </dependencies> - </profile> - </profiles> </project> diff --git a/naked-objects/dom/pom.xml b/naked-objects/dom/pom.xml index 039afc373727..e816c76bbd78 100644 --- a/naked-objects/dom/pom.xml +++ b/naked-objects/dom/pom.xml @@ -36,6 +36,17 @@ </excludes> </resource> </resources> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-compiler-plugin</artifactId> + <version>${compiler.version}</version> + <configuration> + <source>8</source> + <target>8</target> + </configuration> + </plugin> + </plugins> </build> <dependencies> diff --git a/naked-objects/integtests/pom.xml b/naked-objects/integtests/pom.xml index f12f4ae1e368..7365a71a9acb 100644 --- a/naked-objects/integtests/pom.xml +++ b/naked-objects/integtests/pom.xml @@ -90,6 +90,11 @@ <artifactId>hsqldb</artifactId> </dependency> + <dependency> + <groupId>javax.annotation</groupId> + <artifactId>javax.annotation-api</artifactId> + </dependency> + <!-- uncomment to enable enhanced cucumber-jvm reporting http://www.masterthought.net/section/cucumber-reporting @@ -122,20 +127,5 @@ </repository> </repositories> --> - <profiles> - <profile> - <id>jdk11-deps</id> - <activation> - <jdk>[11,)</jdk> - </activation> - <dependencies> - <dependency> - <groupId>javax.annotation</groupId> - <artifactId>javax.annotation-api</artifactId> - </dependency> - </dependencies> - </profile> - </profiles> - </project> diff --git a/pom.xml b/pom.xml index efeee185c788..b3756e1c06fb 100644 --- a/pom.xml +++ b/pom.xml @@ -58,7 +58,7 @@ <log4j.version>1.2.17</log4j.version> <jaxb-api.version>2.3.1</jaxb-api.version> <jaxb-impl.version>2.3.2</jaxb-impl.version> - <annotation-api.version>1.3.1</annotation-api.version> + <annotation-api.version>1.3.2</annotation-api.version> </properties> <modules> <module>abstract-factory</module> @@ -320,6 +320,11 @@ <artifactId>jaxb-impl</artifactId> <version>${jaxb-impl.version}</version> </dependency> + <dependency> + <groupId>org.javassist</groupId> + <artifactId>javassist</artifactId> + <version>3.25.0-GA</version> + </dependency> </dependencies> </dependencyManagement> @@ -380,8 +385,8 @@ <artifactId>maven-compiler-plugin</artifactId> <version>${compiler.version}</version> <configuration> - <source>1.8</source> - <target>1.8</target> + <source>11</source> + <target>11</target> </configuration> </plugin> <plugin> @@ -500,27 +505,4 @@ </plugins> </reporting> - <profiles> - <profile> - <id>jdk11-dep-management</id> - <activation> - <jdk>[11,)</jdk> - </activation> - <dependencyManagement> - <dependencies> - <dependency> - <groupId>org.javassist</groupId> - <artifactId>javassist</artifactId> - <version>3.25.0-GA</version> - </dependency> - <dependency> - <groupId>javax.annotation</groupId> - <artifactId>javax.annotation-api</artifactId> - <version>1.3.2</version> - </dependency> - </dependencies> - </dependencyManagement> - </profile> - </profiles> - </project> diff --git a/service-layer/pom.xml b/service-layer/pom.xml index 4edd950740a8..057a701341a7 100644 --- a/service-layer/pom.xml +++ b/service-layer/pom.xml @@ -41,6 +41,14 @@ <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </dependency> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> @@ -52,22 +60,5 @@ <scope>test</scope> </dependency> </dependencies> - <profiles> - <profile> - <id>jdk11-deps</id> - <activation> - <jdk>[11,)</jdk> - </activation> - <dependencies> - <dependency> - <groupId>com.sun.xml.bind</groupId> - <artifactId>jaxb-impl</artifactId> - </dependency> - <dependency> - <groupId>javax.xml.bind</groupId> - <artifactId>jaxb-api</artifactId> - </dependency> - </dependencies> - </profile> - </profiles> + </project>
null
test
train
2019-10-11T20:55:48
"2019-10-04T05:44:04Z"
iluwatar
train
iluwatar/java-design-patterns/949_980
iluwatar/java-design-patterns
iluwatar/java-design-patterns/949
iluwatar/java-design-patterns/980
[ "timestamp(timedelta=30765.0, similarity=0.870099769949494)" ]
e36bbbb22bad5e24c15ea2d185309033580f2ba8
6faec9901a2380800aa50af538c8669539997176
[ "No need to do this anymore since we have already transitioned to JDK11" ]
[]
"2019-10-11T19:50:31Z"
[ "info: help wanted", "resolution: won't fix", "epic: build issue" ]
Java 11 support: Run the project against Java 11 runtime
This task is part of the Java 11 transition plan https://github.com/iluwatar/java-design-patterns/wiki/16.-Java-11-Transition Build the project using the old JDK 8, but try to run some of the pattern examples we have against a newer Java 11 runtime (see https://blog.codefx.org/java/planning-your-java-9-update/). Record the errors under this issue.
[ ".travis.yml", "cqrs/pom.xml", "eip-aggregator/pom.xml", "eip-splitter/pom.xml", "eip-wire-tap/pom.xml", "naked-objects/dom/pom.xml", "naked-objects/integtests/pom.xml", "pom.xml", "service-layer/pom.xml" ]
[ ".travis.yml", "cqrs/pom.xml", "eip-aggregator/pom.xml", "eip-splitter/pom.xml", "eip-wire-tap/pom.xml", "naked-objects/dom/pom.xml", "naked-objects/integtests/pom.xml", "pom.xml", "service-layer/pom.xml" ]
[]
diff --git a/.travis.yml b/.travis.yml index 84b031fadcc1..45323dcfd457 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,6 @@ language: java dist: xenial jdk: -- openjdk8 - openjdk11 env: diff --git a/cqrs/pom.xml b/cqrs/pom.xml index fc89a93b7c79..9c9458505aba 100644 --- a/cqrs/pom.xml +++ b/cqrs/pom.xml @@ -38,26 +38,18 @@ <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> </dependency> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + <scope>test</scope> + <version>2.1.17</version> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + <scope>test</scope> + </dependency> + </dependencies> - <profiles> - <profile> - <id>jdk11-deps</id> - <activation> - <jdk>[11,)</jdk> - </activation> - <dependencies> - <dependency> - <groupId>com.sun.xml.bind</groupId> - <artifactId>jaxb-impl</artifactId> - <scope>test</scope> - <version>2.1.17</version> - </dependency> - <dependency> - <groupId>javax.xml.bind</groupId> - <artifactId>jaxb-api</artifactId> - <scope>test</scope> - </dependency> - </dependencies> - </profile> - </profiles> + </project> diff --git a/eip-aggregator/pom.xml b/eip-aggregator/pom.xml index 39270f02097e..6a5e32845cfc 100644 --- a/eip-aggregator/pom.xml +++ b/eip-aggregator/pom.xml @@ -47,6 +47,15 @@ <version>${camel.version}</version> </dependency> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + </dependency> + <!-- Testing --> <dependency> <groupId>com.github.sbrannen</groupId> @@ -71,23 +80,4 @@ </dependencies> - <profiles> - <profile> - <id>jdk11-deps</id> - <activation> - <jdk>[11,)</jdk> - </activation> - <dependencies> - <dependency> - <groupId>com.sun.xml.bind</groupId> - <artifactId>jaxb-impl</artifactId> - </dependency> - <dependency> - <groupId>javax.xml.bind</groupId> - <artifactId>jaxb-api</artifactId> - </dependency> - </dependencies> - </profile> - </profiles> - </project> diff --git a/eip-splitter/pom.xml b/eip-splitter/pom.xml index 7319f651939c..9769d08034a7 100644 --- a/eip-splitter/pom.xml +++ b/eip-splitter/pom.xml @@ -47,6 +47,16 @@ <version>${camel.version}</version> </dependency> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + </dependency> + + <!-- Testing --> <dependency> <groupId>com.github.sbrannen</groupId> @@ -71,24 +81,4 @@ </dependencies> - <profiles> - <profile> - <id>jdk11-deps</id> - <activation> - <jdk>[11,)</jdk> - </activation> - <dependencies> - <dependency> - <groupId>com.sun.xml.bind</groupId> - <artifactId>jaxb-impl</artifactId> - </dependency> - <dependency> - <groupId>javax.xml.bind</groupId> - <artifactId>jaxb-api</artifactId> - </dependency> - </dependencies> - </profile> - </profiles> - - </project> diff --git a/eip-wire-tap/pom.xml b/eip-wire-tap/pom.xml index a9d30924204a..c96063418c46 100644 --- a/eip-wire-tap/pom.xml +++ b/eip-wire-tap/pom.xml @@ -47,6 +47,16 @@ <version>${camel.version}</version> </dependency> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + </dependency> + + <!-- Testing --> <dependency> <groupId>com.github.sbrannen</groupId> @@ -71,22 +81,4 @@ </dependencies> - <profiles> - <profile> - <id>jdk11-deps</id> - <activation> - <jdk>[11,)</jdk> - </activation> - <dependencies> - <dependency> - <groupId>com.sun.xml.bind</groupId> - <artifactId>jaxb-impl</artifactId> - </dependency> - <dependency> - <groupId>javax.xml.bind</groupId> - <artifactId>jaxb-api</artifactId> - </dependency> - </dependencies> - </profile> - </profiles> </project> diff --git a/naked-objects/dom/pom.xml b/naked-objects/dom/pom.xml index 039afc373727..e816c76bbd78 100644 --- a/naked-objects/dom/pom.xml +++ b/naked-objects/dom/pom.xml @@ -36,6 +36,17 @@ </excludes> </resource> </resources> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-compiler-plugin</artifactId> + <version>${compiler.version}</version> + <configuration> + <source>8</source> + <target>8</target> + </configuration> + </plugin> + </plugins> </build> <dependencies> diff --git a/naked-objects/integtests/pom.xml b/naked-objects/integtests/pom.xml index f12f4ae1e368..7365a71a9acb 100644 --- a/naked-objects/integtests/pom.xml +++ b/naked-objects/integtests/pom.xml @@ -90,6 +90,11 @@ <artifactId>hsqldb</artifactId> </dependency> + <dependency> + <groupId>javax.annotation</groupId> + <artifactId>javax.annotation-api</artifactId> + </dependency> + <!-- uncomment to enable enhanced cucumber-jvm reporting http://www.masterthought.net/section/cucumber-reporting @@ -122,20 +127,5 @@ </repository> </repositories> --> - <profiles> - <profile> - <id>jdk11-deps</id> - <activation> - <jdk>[11,)</jdk> - </activation> - <dependencies> - <dependency> - <groupId>javax.annotation</groupId> - <artifactId>javax.annotation-api</artifactId> - </dependency> - </dependencies> - </profile> - </profiles> - </project> diff --git a/pom.xml b/pom.xml index efeee185c788..b3756e1c06fb 100644 --- a/pom.xml +++ b/pom.xml @@ -58,7 +58,7 @@ <log4j.version>1.2.17</log4j.version> <jaxb-api.version>2.3.1</jaxb-api.version> <jaxb-impl.version>2.3.2</jaxb-impl.version> - <annotation-api.version>1.3.1</annotation-api.version> + <annotation-api.version>1.3.2</annotation-api.version> </properties> <modules> <module>abstract-factory</module> @@ -320,6 +320,11 @@ <artifactId>jaxb-impl</artifactId> <version>${jaxb-impl.version}</version> </dependency> + <dependency> + <groupId>org.javassist</groupId> + <artifactId>javassist</artifactId> + <version>3.25.0-GA</version> + </dependency> </dependencies> </dependencyManagement> @@ -380,8 +385,8 @@ <artifactId>maven-compiler-plugin</artifactId> <version>${compiler.version}</version> <configuration> - <source>1.8</source> - <target>1.8</target> + <source>11</source> + <target>11</target> </configuration> </plugin> <plugin> @@ -500,27 +505,4 @@ </plugins> </reporting> - <profiles> - <profile> - <id>jdk11-dep-management</id> - <activation> - <jdk>[11,)</jdk> - </activation> - <dependencyManagement> - <dependencies> - <dependency> - <groupId>org.javassist</groupId> - <artifactId>javassist</artifactId> - <version>3.25.0-GA</version> - </dependency> - <dependency> - <groupId>javax.annotation</groupId> - <artifactId>javax.annotation-api</artifactId> - <version>1.3.2</version> - </dependency> - </dependencies> - </dependencyManagement> - </profile> - </profiles> - </project> diff --git a/service-layer/pom.xml b/service-layer/pom.xml index 4edd950740a8..057a701341a7 100644 --- a/service-layer/pom.xml +++ b/service-layer/pom.xml @@ -41,6 +41,14 @@ <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </dependency> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> @@ -52,22 +60,5 @@ <scope>test</scope> </dependency> </dependencies> - <profiles> - <profile> - <id>jdk11-deps</id> - <activation> - <jdk>[11,)</jdk> - </activation> - <dependencies> - <dependency> - <groupId>com.sun.xml.bind</groupId> - <artifactId>jaxb-impl</artifactId> - </dependency> - <dependency> - <groupId>javax.xml.bind</groupId> - <artifactId>jaxb-api</artifactId> - </dependency> - </dependencies> - </profile> - </profiles> + </project>
null
train
train
2019-10-11T20:55:48
"2019-10-04T05:35:26Z"
iluwatar
train
iluwatar/java-design-patterns/413_986
iluwatar/java-design-patterns
iluwatar/java-design-patterns/413
iluwatar/java-design-patterns/986
[ "timestamp(timedelta=64.0, similarity=0.8955927821338747)" ]
088bb764f35ec5d37e58ef1eb66bfce80378db5d
7e698a90dd7664e119ec0b082883ea48dc12ae2e
[ "From the implementation, CircuitBreaker-State Pattern is a great pattern\ncompound to use for our implementation. The state pattern is to map\ndifferent state of the CircuitBreaker. I love this pattern.\n\nOn Thu, Mar 31, 2016 at 6:30 AM, Narendra Pathai [email protected]\nwrote:\n\n> http://martinfowler.com/bliki/CircuitBreaker.html\n> \n> The basic idea behind the circuit breaker is very simple. You wrap a\n> protected function call in a circuit breaker object, which monitors for\n> failures. Once the failures reach a certain threshold, the circuit breaker\n> trips, and all further calls to the circuit breaker return with an error,\n> without the protected call being made at all. Usually you'll also want some\n> kind of monitor alert if the circuit breaker trips.\n> \n> A production ready implementation of pattern can be found here.\n> \n> https://github.com/Comcast/jrugged/blob/master/jrugged-core/src/main/java/org/fishwife/jrugged/CircuitBreaker.java\n> \n> —\n> You are receiving this because you are subscribed to this thread.\n> Reply to this email directly or view it on GitHub\n> https://github.com/iluwatar/java-design-patterns/issues/413\n", "@geniusgeek Yes we used this pattern for years in production but didnt know its name. Found it today while exploring cloud patterns. We had implemented it without official name n now i am going to refactor our production code to use it.\n", "http://techblog.netflix.com/2011/12/making-netflix-api-more-resilient.html\n", "https://msdn.microsoft.com/en-us/library/dn589784.aspx\n", "http://www.hascode.com/2017/02/resilient-architecture-circuit-breakers-for-java-hystrix-vert-x-javaslang-and-failsafe-examples/ (link contributed by @rinormaloku)", "Hi .. can I work on this one ?", "Ok @MohitNarula ", "Issue is free", "Hi, wondering if I could take this issue up since it's free? Would love to contribute to this awesome repository 😄 ", "Wonderful @PalAditya, please go ahead. Looking forward to your pull request." ]
[ "The plugins are already defined in parent pom.xml and not needed here", "You can use local-variable type inference here (var)", "Use final where member variables don't change", "Use local-variable type inference (var)", "Could it be constant? Looks a bit cryptic", "The calculation here is hard to understand. We need at least comment there.", "Also in tests var can be used extensively" ]
"2019-10-12T14:37:04Z"
[ "epic: pattern" ]
Circuit Breaker pattern
http://martinfowler.com/bliki/CircuitBreaker.html The basic idea behind the circuit breaker is very simple. You wrap a protected function call in a circuit breaker object, which monitors for failures. Once the failures reach a certain threshold, the circuit breaker trips, and all further calls to the circuit breaker return with an error, without the protected call being made at all. Usually you'll also want some kind of monitor alert if the circuit breaker trips. A production ready implementation of pattern can be found here. https://github.com/Comcast/jrugged/blob/master/jrugged-core/src/main/java/org/fishwife/jrugged/CircuitBreaker.java
[ "pom.xml" ]
[ "circuit-breaker/README.md", "circuit-breaker/pom.xml", "circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/App.java", "circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/CircuitBreaker.java", "circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DelayedService.java", "circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/MonitoringService.java", "circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/State.java", "pom.xml" ]
[ "circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/CircuitBreakerTest.java", "circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/DelayedServiceTest.java", "circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/MonitoringServiceTest.java" ]
diff --git a/circuit-breaker/README.md b/circuit-breaker/README.md new file mode 100644 index 000000000000..db75ca58c0d0 --- /dev/null +++ b/circuit-breaker/README.md @@ -0,0 +1,188 @@ +--- +layout: pattern +title: CircuitBreaker +folder: circuit-breaker +permalink: /patterns/circuit-breaker/ +categories: Other +tags: + - Java + - Performance + - Difficulty-Intermediate +--- + +## Intent + +Handle costly remote *procedure/service* calls in such a way that the failure of a **single** service/component cannot bring the whole application down, and we can reconnect to the service as soon as possible. + +## Explanation + +Real world example + +> Imagine a Web App that has both local (example: files and images) and remote (example: database entries) to serve. The database might not be responding due to a variety of reasons, so if the application keeps trying to read from the database using multiple threads/processes, soon all of them will hang and our entire web application will crash. We should be able to detect this situation and show the user an appropriate message so that he/she can explore other parts of the app unaffected by the database failure without any problem. + +In plain words + +> Allows us to save resources when we know a remote service failed. Useful when all parts of our application are highly decoupled from each other, and failure of one component doesn't mean the other parts will stop working. + +Wikipedia says + +> **Circuit breaker** is a design pattern used in modern software development. It is used to detect failures and encapsulates the logic of preventing a failure from constantly recurring, during maintenance, temporary external system failure or unexpected system difficulties. + +So, how does this all come together? + +## Programmatic Example +With the above example in mind we will imitate the functionality in a simple manner. We have two services: A *monitoring service* which will mimic the web app and will make both **local** and **remote** calls. + +The service architecture is as follows: + +![alt text](./etc/ServiceDiagram.PNG "Service Diagram") + +In terms of code, the End user application is: + +```java +public class App { + + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + + public static void main(String[] args) { + var obj = new MonitoringService(); + var circuitBreaker = new CircuitBreaker(3000, 1, 2000 * 1000 * 1000); + var serverStartTime = System.nanoTime(); + while (true) { + LOGGER.info(obj.localResourceResponse()); + LOGGER.info(obj.remoteResourceResponse(circuitBreaker, serverStartTime)); + LOGGER.info(circuitBreaker.getState()); + try { + Thread.sleep(5 * 1000); + } catch (InterruptedException e) { + LOGGER.error(e.getMessage()); + } + } + } +} +``` + +The monitoring service is: + +``` java +public class MonitoringService { + + public String localResourceResponse() { + return "Local Service is working"; + } + + public String remoteResourceResponse(CircuitBreaker circuitBreaker, long serverStartTime) { + try { + return circuitBreaker.call("delayedService", serverStartTime); + } catch (Exception e) { + return e.getMessage(); + } + } +} +``` +As it can be seen, it does the call to get local resources directly, but it wraps the call to remote (costly) service in a circuit breaker object, which prevents faults as follows: + +```java +public class CircuitBreaker { + private final long timeout; + private final long retryTimePeriod; + long lastFailureTime; + int failureCount; + private final int failureThreshold; + private State state; + private final long futureTime = 1000 * 1000 * 1000 * 1000; + + CircuitBreaker(long timeout, int failureThreshold, long retryTimePeriod) { + this.state = State.CLOSED; + this.failureThreshold = failureThreshold; + this.timeout = timeout; + this.retryTimePeriod = retryTimePeriod; + this.lastFailureTime = System.nanoTime() + futureTime; + this.failureCount = 0; + } + + private void reset() { + this.failureCount = 0; + this.lastFailureTime = System.nanoTime() + futureTime; + this.state = State.CLOSED; + } + + private void recordFailure() { + failureCount = failureCount + 1; + this.lastFailureTime = System.nanoTime(); + } + + protected void setState() { + if (failureCount > failureThreshold) { + if ((System.nanoTime() - lastFailureTime) > retryTimePeriod) { + state = State.HALF_OPEN; + } else { + state = State.OPEN; + } + } else { + state = State.CLOSED; + } + } + + public String getState() { + return state.name(); + } + + public void setStateForBypass(State state) { + this.state = state; + } + + public String call(String serviceToCall, long serverStartTime) throws Exception { + setState(); + if (state == State.OPEN) { + return "This is stale response from API"; + } else { + if (serviceToCall.equals("delayedService")) { + var delayedService = new DelayedService(20); + var response = delayedService.response(serverStartTime); + if (response.split(" ")[3].equals("working")) { + reset(); + return response; + } else { + recordFailure(); + throw new Exception("Remote service not responding"); + } + } else { + throw new Exception("Unknown Service Name"); + } + } + } +} +``` + +How does the above pattern prevent failures? Let's understand via this finite state machine implemented by it. + +![alt text](./etc/StateDiagram.PNG "State Diagram") + +- We initialize the Circuit Breaker object with certain parameters: **timeout**, **failureThreshold** and **retryTimePeriod** which help determine how resilient the API is. +- Initially, we are in the **closed** state and the remote call to API happens. +- Every time the call succeeds, we reset the state to as it was in the beginning. +- If the number of failures cross a certain threshold, we move to the **open** state, which acts just like an open circuit and prevents remote service calls from being made, thus saving resources. (Here, we return the response called ```stale response from API```) +- Once we exceed the retry timeout period, we move to the **half-open** state and make another call to the remote service again to check if the service is working so that we can serve fresh content. A *failure* sets it back to **open** state and another attempt is made after retry timeout period, while a *success* sets it to **closed** state so that everything starts working normally again. + + +## Applicability +Use the Circuit Breaker pattern when + +- Building a fault-tolerant application where failure of some services shouldn't bring the entire application down. +- Building an continuously incremental/continuous delivery application, as some of it's components can be upgraded without shutting it down entirely. + +## Related Patterns + +- [Retry Pattern](https://github.com/iluwatar/java-design-patterns/tree/master/retry) + +## Real world examples +* [Spring Circuit Breaker module](https://spring.io/guides/gs/circuit-breaker) +* [Netflix Hystrix API](https://github.com/Netflix/Hystrix) + +## Credits + +* [Understanding Circuit Breaker Pattern](https://itnext.io/understand-circuitbreaker-design-pattern-with-simple-practical-example-92a752615b42) +* [Martin Fowler on Circuit Breaker](https://martinfowler.com/bliki/CircuitBreaker.html) +* [Fault tolerance in a high volume, distributed system](https://medium.com/netflix-techblog/fault-tolerance-in-a-high-volume-distributed-system-91ab4faae74a) +* [Microsoft docs](https://docs.microsoft.com/en-us/azure/architecture/patterns/circuit-breaker) diff --git a/circuit-breaker/pom.xml b/circuit-breaker/pom.xml new file mode 100644 index 000000000000..b6587b061f7a --- /dev/null +++ b/circuit-breaker/pom.xml @@ -0,0 +1,40 @@ +<!-- + + The MIT License + Copyright (c) 2014 Ilkka Seppälä + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + +--> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>com.iluwatar</groupId> + <artifactId>java-design-patterns</artifactId> + <version>1.22.0-SNAPSHOT</version> + </parent> + <artifactId>circuit-breaker</artifactId> + <dependencies> + <dependency> + <groupId>org.junit.jupiter</groupId> + <artifactId>junit-jupiter-engine</artifactId> + <scope>test</scope> + </dependency> + </dependencies> +</project> diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/App.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/App.java new file mode 100644 index 000000000000..d1d361b16063 --- /dev/null +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/App.java @@ -0,0 +1,86 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.circuitbreaker; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * <p> + * The intention of the Circuit Builder pattern is to handle remote failures + * robustly, which is to mean that if a service is dependant on n number of + * other services, and m of them fail, we should be able to recover from that + * failure by ensuring that the user can still use the services that are actually + * functional, and resources are not tied up by uselessly by the services which + * are not working. However, we should also be able to detect when any of the m + * failing services become operational again, so that we can use it + * </p> + * <p> + * In this example, the circuit breaker pattern is demonstrated by using two services: + * {@link MonitoringService} and {@link DelayedService}. The monitoring service + * is responsible for calling two services: a local service and a remote service {@link DelayedService} + * , and by using the circuit breaker construction we ensure that if the call to + * remote service is going to fail, we are going to save our resources and not make the + * function call at all, by wrapping our call to the remote service in the circuit + * breaker object. + * </p> + * <p> + * This works as follows: The {@link CircuitBreaker} object can be in one of three + * states: <b>Open</b>, <b>Closed</b> and <b>Half-Open</b>, which represents the real + * world circuits. If the state is closed (initial), we assume everything is alright + * and perform the function call. However, every time the call fails, we note it + * and once it crosses a threshold, we set the state to Open, preventing any further + * calls to the remote server. Then, after a certain retry period (during which we + * expect thee service to recover), we make another call to the remote server and + * this state is called the Half-Open state, where it stays till the service is down, + * and once it recovers, it goes back to the closed state and the cycle continues. + * </p> + */ +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) { + //Create an object of monitoring service which makes both local and remote calls + var obj = new MonitoringService(); + //Set the circuit Breaker parameters + var circuitBreaker = new CircuitBreaker(3000, 1, 2000 * 1000 * 1000); + var serverStartTime = System.nanoTime(); + while (true) { + LOGGER.info(obj.localResourceResponse()); + LOGGER.info(obj.remoteResourceResponse(circuitBreaker, serverStartTime)); + LOGGER.info(circuitBreaker.getState()); + try { + Thread.sleep(5 * 1000); + } catch (InterruptedException e) { + LOGGER.error(e.getMessage()); + } + } + } +} diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/CircuitBreaker.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/CircuitBreaker.java new file mode 100644 index 000000000000..ad014f9fdae0 --- /dev/null +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/CircuitBreaker.java @@ -0,0 +1,128 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.circuitbreaker; + +/** + * The circuit breaker class with all configurations + */ +public class CircuitBreaker { + private final long timeout; + private final long retryTimePeriod; + long lastFailureTime; + int failureCount; + private final int failureThreshold; + private State state; + private final long futureTime = 1000 * 1000 * 1000 * 1000; + + /** + * Constructor to create an instance of Circuit Breaker + * @param timeout Timeout for the API request. Not necessary for this simple example + * @param failureThreshold Number of failures we receive from the depended service before changing state to 'OPEN' + * @param retryTimePeriod Time period after which a new request is made to remote service for status check. + */ + CircuitBreaker(long timeout, int failureThreshold, long retryTimePeriod) { + // We start in a closed state hoping that everything is fine + this.state = State.CLOSED; + this.failureThreshold = failureThreshold; + // Timeout for the API request. Used to break the calls made to remote resource if it exceeds the limit + this.timeout = timeout; + this.retryTimePeriod = retryTimePeriod; + //An absurd amount of time in future which basically indicates the last failure never happened + this.lastFailureTime = System.nanoTime() + futureTime; + this.failureCount = 0; + } + + //Reset everything to defaults + private void reset() { + this.failureCount = 0; + this.lastFailureTime = System.nanoTime() + futureTime; + this.state = State.CLOSED; + } + + private void recordFailure() { + failureCount = failureCount + 1; + this.lastFailureTime = System.nanoTime(); + } + + protected void setState() { + if (failureCount > failureThreshold) { //Then something is wrong with remote service + if ((System.nanoTime() - lastFailureTime) > retryTimePeriod) { + //We have waited long enough and should try checking if service is up + state = State.HALF_OPEN; + } else { + //Service would still probably be down + state = State.OPEN; + } + } else { + //Everything is working fine + state = State.CLOSED; + } + } + + public String getState() { + return state.name(); + } + + /** + * Break the circuit beforehand if it is known service is down + * Or connect the circuit manually if service comes online before expected + * @param state State at which circuit is in + */ + public void setStateForBypass(State state) { + this.state = state; + } + + /** + * @param serviceToCall The name of the service in String. Can be changed to data URLs in case of web applications + * @param serverStartTime Time at which actual server was started which makes calls to this service + * @return Value from the remote resource, stale response or a custom exception + */ + public String call(String serviceToCall, long serverStartTime) throws Exception { + setState(); + if (state == State.OPEN) { + // return cached response if no the circuit is in OPEN state + return "This is stale response from API"; + } else { + // Make the API request if the circuit is not OPEN + if (serviceToCall.equals("delayedService")) { + var delayedService = new DelayedService(20); + var response = delayedService.response(serverStartTime); + //In a real application, this would be run in a thread and the timeout + //parameter of the circuit breaker would be utilized to know if service + //is working. Here, we simulate that based on server response itself + if (response.split(" ")[3].equals("working")) { + // Yay!! the API responded fine. Let's reset everything. + reset(); + return response; + } else { + // Uh-oh!! the call still failed. Let's update that in our records. + recordFailure(); + throw new Exception("Remote service not responding"); + } + } else { + throw new Exception("Unknown Service Name"); + } + } + } +} \ No newline at end of file diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DelayedService.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DelayedService.java new file mode 100644 index 000000000000..33217b8e721b --- /dev/null +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DelayedService.java @@ -0,0 +1,61 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.circuitbreaker; + +/** +* This simulates the remote service +* It responds only after a certain timeout period (default set to 20 seconds) +*/ +public class DelayedService { + private final int delay; + + /** + * Constructor to create an instance of DelayedService, which is down for first few seconds + * @param delay the delay after which service would behave properly, in seconds + */ + public DelayedService(int delay) { + this.delay = delay; + } + + public DelayedService() { + this.delay = 60; + } + + /** + * @param serverStartTime Time at which actual server was started which makes calls to this service + * @return The state of the service + */ + public String response(long serverStartTime) { + var currentTime = System.nanoTime(); + //Since currentTime and serverStartTime are both in nanoseconds, we convert it to + //seconds by diving by 10e9 and ensure floating point division by multiplying it + //with 1.0 first. We then check if it is greater or less than specified delay and then + //send the reply + if ((currentTime - serverStartTime) * 1.0 / (1000 * 1000 * 1000) < delay) { + //Can use Thread.sleep() here to block and simulate a hung server + return "Delayed service is down"; + } else { + return "Delayed service is working"; + } + } +} diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/MonitoringService.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/MonitoringService.java new file mode 100644 index 000000000000..e301ff3ca52b --- /dev/null +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/MonitoringService.java @@ -0,0 +1,50 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.circuitbreaker; + +/** + * The service class which makes local and remote calls + * Uses {@link CircuitBreaker} object to ensure remote calls don't use up resources + */ +public class MonitoringService { + + //Assumption: Local service won't fail, no need to wrap it in a circuit breaker logic + public String localResourceResponse() { + return "Local Service is working"; + } + + /** + * Try to get result from remote server + * @param circuitBreaker The circuitBreaker object with all parameters + * @param serverStartTime Time at which actual server was started which makes calls to this service + * @return result from the remote response or exception raised by it. + */ + public String remoteResourceResponse(CircuitBreaker circuitBreaker, long serverStartTime) { + try { + return circuitBreaker.call("delayedService", serverStartTime); + } catch (Exception e) { + return e.getMessage(); + } + } +} \ No newline at end of file diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/State.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/State.java new file mode 100644 index 000000000000..87982153ccd0 --- /dev/null +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/State.java @@ -0,0 +1,33 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.circuitbreaker; + +/** + * Enumeration for states the circuit breaker could be in + */ +public enum State { + CLOSED, + OPEN, + HALF_OPEN +} \ No newline at end of file diff --git a/pom.xml b/pom.xml index 50e7c7de5439..9e61e716b864 100644 --- a/pom.xml +++ b/pom.xml @@ -181,6 +181,7 @@ <module>bytecode</module> <module>leader-election</module> <module>data-locality</module> + <module>circuit-breaker</module> </modules>
diff --git a/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/CircuitBreakerTest.java b/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/CircuitBreakerTest.java new file mode 100644 index 000000000000..5780e9355c58 --- /dev/null +++ b/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/CircuitBreakerTest.java @@ -0,0 +1,80 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.circuitbreaker; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + +/** + * + * Circuit Breaker test + * + */ +public class CircuitBreakerTest { + + //long timeout, int failureThreshold, long retryTimePeriod + @Test + public void testSetState() { + var circuitBreaker = new CircuitBreaker(1,1,100); + //Right now, failureCount<failureThreshold, so state should be closed + assertEquals(circuitBreaker.getState(), "CLOSED"); + circuitBreaker.failureCount = 4; + circuitBreaker.lastFailureTime = System.nanoTime(); + circuitBreaker.setState(); + //Since failureCount>failureThreshold, and lastFailureTime is nearly equal to current time, + //state should be half-open + assertEquals(circuitBreaker.getState(), "HALF_OPEN"); + //Since failureCount>failureThreshold, and lastFailureTime is much lesser current time, + //state should be open + circuitBreaker.lastFailureTime = System.nanoTime() - 1000 * 1000 * 1000 * 1000; + circuitBreaker.setState(); + assertEquals(circuitBreaker.getState(), "OPEN"); + //Now set it back again to closed to test idempotency + circuitBreaker.failureCount = 0; + circuitBreaker.setState(); + assertEquals(circuitBreaker.getState(), "CLOSED"); + } + + @Test + public void testSetStateForBypass() { + var circuitBreaker = new CircuitBreaker(1,1,100); + //Right now, failureCount<failureThreshold, so state should be closed + //Bypass it and set it to open + circuitBreaker.setStateForBypass(State.OPEN); + assertEquals(circuitBreaker.getState(), "OPEN"); + } + + @Test + public void testApiResponses() { + var circuitBreaker = new CircuitBreaker(1,1,100); + try { + //Call with the paramater start_time set to huge amount of time in past so that service + //replies with "Ok". Also, state is CLOSED in start + var response = circuitBreaker.call("delayedService", System.nanoTime() - 60 * 1000 * 1000 * 1000); + assertEquals(response, "Delayed service is working"); + } catch (Exception e) { + System.out.println(e.getMessage()); + } + } +} diff --git a/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/DelayedServiceTest.java b/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/DelayedServiceTest.java new file mode 100644 index 000000000000..7b9c33795144 --- /dev/null +++ b/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/DelayedServiceTest.java @@ -0,0 +1,42 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.circuitbreaker; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + +/** + * + * Monitoring Service test + * + */ +public class DelayedServiceTest { + + //Improves code coverage + @Test + public void testDefaultConstructor() { + var obj = new DelayedService(); + assertEquals(obj.response(System.nanoTime()), "Delayed service is down"); + } +} diff --git a/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/MonitoringServiceTest.java b/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/MonitoringServiceTest.java new file mode 100644 index 000000000000..280da63e5e91 --- /dev/null +++ b/circuit-breaker/src/test/java/com/iluwatar/circuitbreaker/MonitoringServiceTest.java @@ -0,0 +1,63 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.circuitbreaker; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + +/** + * + * Monitoring Service test + * + */ +public class MonitoringServiceTest { + + //long timeout, int failureThreshold, long retryTimePeriod + @Test + public void testLocalResponse() { + var monitoringService = new MonitoringService(); + var response = monitoringService.localResourceResponse(); + assertEquals(response, "Local Service is working"); + } + + @Test + public void testRemoteResponse() { + var monitoringService = new MonitoringService(); + var circuitBreaker = new CircuitBreaker(1,1,100); + //Set time in past to make the server work + var serverStartTime = System.nanoTime() / 10; + var response = monitoringService.remoteResourceResponse(circuitBreaker, serverStartTime); + assertEquals(response, "Delayed service is working"); + } + + @Test + public void testRemoteResponse2() { + MonitoringService monitoringService = new MonitoringService(); + CircuitBreaker circuitBreaker = new CircuitBreaker(1,1,100); + //Set time as current time as initially server fails + long serverStartTime = System.nanoTime(); + String response = monitoringService.remoteResourceResponse(circuitBreaker, serverStartTime); + assertEquals(response, "Remote service not responding"); + } +}
test
train
2019-10-14T19:25:35
"2016-03-31T10:29:51Z"
npathai
train
iluwatar/java-design-patterns/988_992
iluwatar/java-design-patterns
iluwatar/java-design-patterns/988
iluwatar/java-design-patterns/992
[ "timestamp(timedelta=81254.0, similarity=0.846215572962624)" ]
9ebbc421dd96b84c50808ca8ac4a520042e73b8f
7de53f9853d575c7a341eefeac77949e6d660349
[ "I'd be interested in looking into this, can I go ahead and try?", "Ok @oconnelc ", "Which version of JDK should I compile against? Should I use Oracle or Openjdk? ", "We have just switched to openjdk11" ]
[]
"2019-10-12T19:34:43Z"
[ "type: enhancement", "info: good first issue", "epic: dependencies", "epic: architecture", "type: refactoring" ]
Java 11 support: HttpClient
This task is part of the Java 11 transition plan https://github.com/iluwatar/java-design-patterns/wiki/16.-Java-11-Transition Patterns Aggregator Microservices and API Gateway are currently using Apache HttpClient in their implementation. Java 11 provides its own HttpClient and we should switch to that instead to get rid of unnecessary external dependencies. Links: https://winterbe.com/posts/2018/09/24/java-11-tutorial/#http-client
[ "aggregator-microservices/aggregator-service/pom.xml", "aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClientImpl.java", "aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java", "api-gateway/api-gateway-service/pom.xml", "api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClientImpl.java", "api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClientImpl.java", "pom.xml" ]
[ "aggregator-microservices/aggregator-service/pom.xml", "aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClientImpl.java", "aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java", "api-gateway/api-gateway-service/pom.xml", "api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClientImpl.java", "api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClientImpl.java", "pom.xml" ]
[]
diff --git a/aggregator-microservices/aggregator-service/pom.xml b/aggregator-microservices/aggregator-service/pom.xml index 6ad8c3c8c5a4..f1ea05a6ec4d 100644 --- a/aggregator-microservices/aggregator-service/pom.xml +++ b/aggregator-microservices/aggregator-service/pom.xml @@ -53,10 +53,6 @@ <artifactId>mockito-core</artifactId> <scope>test</scope> </dependency> - <dependency> - <groupId>org.apache.httpcomponents</groupId> - <artifactId>httpclient</artifactId> - </dependency> </dependencies> <build> diff --git a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClientImpl.java b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClientImpl.java index 131fbf8695cd..c731a695d2a3 100644 --- a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClientImpl.java +++ b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInformationClientImpl.java @@ -22,18 +22,16 @@ */ package com.iluwatar.aggregator.microservices; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.util.EntityUtils; +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import java.io.IOException; - /** * An adapter to communicate with information micro-service. */ @@ -45,16 +43,17 @@ public class ProductInformationClientImpl implements ProductInformationClient { @Override public String getProductTitle() { String response = null; - try (CloseableHttpClient httpClient = HttpClients.createDefault()) { - HttpGet httpGet = new HttpGet("http://localhost:51515/information"); - try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) { - response = EntityUtils.toString(httpResponse.getEntity()); - } - } catch (ClientProtocolException cpe) { - LOGGER.error("ClientProtocolException Occured", cpe); + HttpRequest request = + HttpRequest.newBuilder().GET().uri(URI.create("http://localhost:51515/information")).build(); + HttpClient client = HttpClient.newHttpClient(); + try { + HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString()); + response = httpResponse.body(); } catch (IOException ioe) { - LOGGER.error("IOException Occurred", ioe); - } + LOGGER.error("IOException Occurred", ioe); + } catch (InterruptedException ie) { + LOGGER.error("InterruptedException Occurred", ie); + } return response; } } diff --git a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java index 780dccb78e20..7e855fffe149 100644 --- a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java +++ b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java @@ -22,39 +22,39 @@ */ package com.iluwatar.aggregator.microservices; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.util.EntityUtils; +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import java.io.IOException; - /** * An adapter to communicate with inventory micro-service. */ @Component public class ProductInventoryClientImpl implements ProductInventoryClient { - private static final Logger LOGGER = LoggerFactory.getLogger(ProductInventoryClientImpl.class); + private static final Logger LOGGER = LoggerFactory.getLogger(ProductInventoryClientImpl.class); - @Override - public int getProductInventories() { - String response = "0"; - try (CloseableHttpClient httpClient = HttpClients.createDefault()) { - HttpGet httpGet = new HttpGet("http://localhost:51516/inventories"); - try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) { - response = EntityUtils.toString(httpResponse.getEntity()); - } - } catch (ClientProtocolException cpe) { - LOGGER.error("ClientProtocolException Occured", cpe); - } catch (IOException ioe) { - LOGGER.error("IOException Occurred", ioe); - } - return Integer.parseInt(response); - } + @Override + public int getProductInventories() { + String response = "0"; + + HttpRequest request = + HttpRequest.newBuilder().GET().uri(URI.create("http://localhost:51516/inventories")).build(); + HttpClient client = HttpClient.newHttpClient(); + try { + HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString()); + response = httpResponse.body(); + } catch (IOException ioe) { + LOGGER.error("IOException Occurred", ioe); + } catch (InterruptedException ie) { + LOGGER.error("InterruptedException Occurred", ie); + } + return Integer.parseInt(response); + } } diff --git a/api-gateway/api-gateway-service/pom.xml b/api-gateway/api-gateway-service/pom.xml index 44a8bde37923..fdea5c2a4993 100644 --- a/api-gateway/api-gateway-service/pom.xml +++ b/api-gateway/api-gateway-service/pom.xml @@ -39,10 +39,6 @@ <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> </dependency> - <dependency> - <groupId>org.apache.httpcomponents</groupId> - <artifactId>httpclient</artifactId> - </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> diff --git a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClientImpl.java b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClientImpl.java index ebabfe839b69..63dd270e965f 100644 --- a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClientImpl.java +++ b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClientImpl.java @@ -22,35 +22,42 @@ */ package com.iluwatar.api.gateway; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.util.EntityUtils; -import org.springframework.stereotype.Component; - import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.net.http.HttpResponse.BodyHandlers; + +import org.springframework.stereotype.Component; /** * An adapter to communicate with the Image microservice */ @Component public class ImageClientImpl implements ImageClient { - /** - * Makes a simple HTTP Get request to the Image microservice - * @return The path to the image - */ - @Override - public String getImagePath() { - String response = null; - try (CloseableHttpClient httpClient = HttpClients.createDefault()) { - HttpGet httpGet = new HttpGet("http://localhost:50005/image-path"); - try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) { - response = EntityUtils.toString(httpResponse.getEntity()); - } - } catch (IOException e) { - e.printStackTrace(); - } - return response; - } + /** + * Makes a simple HTTP Get request to the Image microservice + * @return The path to the image + */ + @Override + public String getImagePath() { + String response = null; + + HttpClient httpClient = + HttpClient.newHttpClient(); + HttpRequest httpGet = + HttpRequest.newBuilder().GET().uri(URI.create("http://localhost:50005/image-path")).build(); + + try { + HttpResponse<String> httpResponse = httpClient.send(httpGet, BodyHandlers.ofString()); + response = httpResponse.body(); + } catch (IOException e) { + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + return response; + } } diff --git a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClientImpl.java b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClientImpl.java index 87f44761c649..e8ef38bff3b2 100644 --- a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClientImpl.java +++ b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClientImpl.java @@ -22,35 +22,43 @@ */ package com.iluwatar.api.gateway; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.util.EntityUtils; -import org.springframework.stereotype.Component; - import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.net.http.HttpResponse.BodyHandlers; + +import org.springframework.stereotype.Component; /** * An adapter to communicate with the Price microservice */ @Component public class PriceClientImpl implements PriceClient { - /** - * Makes a simple HTTP Get request to the Price microservice - * @return The price of the product - */ - @Override - public String getPrice() { - String response = null; - try (CloseableHttpClient httpClient = HttpClients.createDefault()) { - HttpGet httpGet = new HttpGet("http://localhost:50006/price"); - try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) { - response = EntityUtils.toString(httpResponse.getEntity()); - } - } catch (IOException e) { - e.printStackTrace(); - } - return response; - } + /** + * Makes a simple HTTP Get request to the Price microservice + * @return The price of the product + */ + @Override + public String getPrice() { + + String response = null; + + HttpClient httpClient = + HttpClient.newHttpClient(); + HttpRequest httpGet = + HttpRequest.newBuilder().GET().uri(URI.create("http://localhost:50006/price")).build(); + + try { + HttpResponse<String> httpResponse = httpClient.send(httpGet, BodyHandlers.ofString()); + response = httpResponse.body(); + } catch (IOException e) { + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + return response; + } } diff --git a/pom.xml b/pom.xml index 9b4672fb3b6e..80b0b3e706e8 100644 --- a/pom.xml +++ b/pom.xml @@ -43,7 +43,6 @@ <camel.version>2.24.0</camel.version> <guava.version>19.0</guava.version> <mockito.version>1.10.19</mockito.version> - <apache-httpcomponents.version>4.5.10</apache-httpcomponents.version> <htmlunit.version>2.22</htmlunit.version> <guice.version>4.0</guice.version> <mongo-java-driver.version>3.3.0</mongo-java-driver.version> @@ -212,11 +211,6 @@ <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> - <dependency> - <groupId>org.apache.httpcomponents</groupId> - <artifactId>httpclient</artifactId> - <version>${apache-httpcomponents.version}</version> - </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId>
null
test
train
2019-10-12T19:05:54
"2019-10-12T15:19:26Z"
iluwatar
train
iluwatar/java-design-patterns/996_997
iluwatar/java-design-patterns
iluwatar/java-design-patterns/996
iluwatar/java-design-patterns/997
[ "timestamp(timedelta=0.0, similarity=0.8628434739492639)", "keyword_pr_to_issue" ]
9ebbc421dd96b84c50808ca8ac4a520042e73b8f
72b174619fa8f936bff553ef19e741f4a11efb6c
[ "![image](https://user-images.githubusercontent.com/582346/66716496-fcb4c380-edd6-11e9-9d2b-91395c546dab.png)\r\n" ]
[]
"2019-10-13T14:26:59Z"
[ "type: bug", "epic: build issue" ]
Sonar analysis in master branch is failing
![image](https://user-images.githubusercontent.com/582346/66716392-f7a34480-edd5-11e9-9dbe-efcc02fa7d24.png)
[ ".sonarcloud.properties", ".travis.yml", "pom.xml" ]
[ ".travis.yml", "pom.xml" ]
[]
diff --git a/.sonarcloud.properties b/.sonarcloud.properties deleted file mode 100644 index c6b26bf5df8b..000000000000 --- a/.sonarcloud.properties +++ /dev/null @@ -1,38 +0,0 @@ -# -# The MIT License -# Copyright © 2014-2019 Ilkka Seppälä -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -# - -# Path to sources -#sonar.sources=. -#sonar.exclusions= -#sonar.inclusions= - -# Path to tests -#sonar.tests= -#sonar.test.exclusions= -#sonar.test.inclusions= - -# Source encoding -#sonar.sourceEncoding=UTF-8 - -# Exclusions for copy-paste detection -#sonar.cpd.exclusions= diff --git a/.travis.yml b/.travis.yml index 45323dcfd457..6cd971428327 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,23 +1,27 @@ language: java -dist: xenial +dist: bionic jdk: - openjdk11 +sudo: required env: global: - GH_REF: github.com/iluwatar/java-design-patterns.git - secure: LxTDuNS/rBWIvKkaEqr79ImZAe48mCdoYCF41coxNXgNoippo4GIBArknqtv+XvdkiuRZ1yGyj6pn8GU33c/yn+krddTUkVCwTbVatbalW5jhQjDbHYym/JcxaK9ZS/3JTeGcWrBgiPqHEEDhCf26vPZsXoMSeVCEORVKTp1BSg= - - secure: "eoWlW9GyTJY04P8K3pxayXwU9/hmptQg/LfirispQkV9YvmziCfSzXnatnBhNfud98sCzY8BScXnb+OWLTnjLKpId4rtEqb0aJ40Jc32cUKzgzFAUn7cNcDAbUIfyPAGVqyQqfj/11wYSADwWMMOPlW97ExUtoyiH2WenXuRHso=" services: - xvfb -# default install command is just "mvn install -DskipTests=true -Dmaven.javadoc.skip=true -B -V" -install: -- mvn install -DskipTests=true -Dmaven.javadoc.skip=true -B -V -e +addons: + sonarcloud: + organization: "iluwatar" + token: + secure: "FpHwMYPMkdWU6CeIB7+O3qIeIM4vJMp47UjkKK53f0w0s6tPZofZZkab+gcL2TqKSil7sFVB/AQXU1cUubflRszwcLbNsc8H2yFehD79o0o0Mqd1Dd5ip/q0KQbHkkln+InFlVLfvrLB4Xd4mlQVxbGhqpULBhXjKzFzQlRFcuU=" +script: + # the following command line builds the project, runs the tests with coverage and then execute the SonarCloud analysis + - mvn clean verify sonar:sonar -Dsonar.projectKey=iluwatar_java-design-patterns after_success: -- mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent package sonar:sonar -Dsonar.host.url=https://sonarcloud.io -Dsonar.login=$SONAR_TOKEN - bash update-ghpages.sh notifications: @@ -29,5 +33,3 @@ notifications: on_success: change # options: [always|never|change] default: always on_failure: always # options: [always|never|change] default: always on_start: never # options: [always|never|change] default: always - -sudo: required diff --git a/pom.xml b/pom.xml index 4ed357181a12..d6cd3a6e60c3 100644 --- a/pom.xml +++ b/pom.xml @@ -353,37 +353,6 @@ <build> <pluginManagement> <plugins> - <!-- This plugin's configuration is used to store Eclipse m2e settings - only. It has no influence on the Maven build itself. TODO: Remove when the - m2e plugin can correctly bind to Maven lifecycle --> - <plugin> - <groupId>org.eclipse.m2e</groupId> - <artifactId>lifecycle-mapping</artifactId> - <version>1.0.0</version> - <configuration> - <lifecycleMappingMetadata> - <pluginExecutions> - <pluginExecution> - <pluginExecutionFilter> - <groupId>org.jacoco</groupId> - <artifactId> - jacoco-maven-plugin - </artifactId> - <versionRange> - [0.6.2,) - </versionRange> - <goals> - <goal>prepare-agent</goal> - </goals> - </pluginExecutionFilter> - <action> - <ignore/> - </action> - </pluginExecution> - </pluginExecutions> - </lifecycleMappingMetadata> - </configuration> - </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> @@ -410,20 +379,6 @@ </pluginManagement> <plugins> - <plugin> - <groupId>org.jacoco</groupId> - <artifactId>jacoco-maven-plugin</artifactId> - <version>${jacoco.version}</version> - <executions> - <execution> - <id>prepare-agent</id> - <goals> - <goal>prepare-agent</goal> - </goals> - </execution> - </executions> - </plugin> - <!--checkstyle plug-in. checking against googles styles see config at checkstyle.xml --> @@ -471,6 +426,27 @@ </execution> </executions> </plugin> + + <plugin> + <groupId>org.jacoco</groupId> + <artifactId>jacoco-maven-plugin</artifactId> + <version>${jacoco.version}</version> + <executions> + <execution> + <id>prepare-agent</id> + <goals> + <goal>prepare-agent</goal> + </goals> + </execution> + <execution> + <id>report</id> + <goals> + <goal>report</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> </build>
null
val
train
2019-10-12T19:05:54
"2019-10-13T13:31:58Z"
iluwatar
train
iluwatar/java-design-patterns/554_998
iluwatar/java-design-patterns
iluwatar/java-design-patterns/554
iluwatar/java-design-patterns/998
[ "timestamp(timedelta=100.0, similarity=0.9294577700353882)" ]
7e698a90dd7664e119ec0b082883ea48dc12ae2e
a5646b63c19455051fb49fd5a455a28159708d49
[ "Hello @iluwatar I would like to take this pattern. Thanks!", "Ok @szokekristof ", "@szokekristof are you still implementing this?", "The task is free to take", "@iluwatar May I pick up this issue?", "Sure go ahead @Azureyjt " ]
[ "New dependencies should be introduced in parent pom.xml, and then referenced in submodule. See for example the junit dependency above.", "You can use Java's local variable type inference (var) in code like this. Please check it elsewhere too.", "typo there", "typo there", "Fixed in commit 87c55b338aa0e32b9e736c708e0a1b562ca576a0", "Fixed in commit 87c55b338aa0e32b9e736c708e0a1b562ca576a0", "Fixed in eca54c4460b3683c8e65f68409ef6e158bf53b61", "Fixed in a627f17a72df44cf99d83a41fb261c93911d20cd\r\n\r\n@iluwatar Thanks for your suggestion. Since I do not have much experience on using var, could you kindly review my change again to see if it is ok? Thanks. " ]
"2019-10-13T15:20:49Z"
[ "epic: pattern", "type: feature" ]
Subclass Sandbox pattern
http://gameprogrammingpatterns.com/subclass-sandbox.html
[ "pom.xml" ]
[ "pom.xml", "subclass-sandbox/README.md", "subclass-sandbox/pom.xml", "subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/App.java", "subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/GroundDive.java", "subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/SkyLaunch.java", "subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/Superpower.java" ]
[ "subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/AppTest.java", "subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/GroundDiveTest.java", "subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/SkyLaunchTest.java" ]
diff --git a/pom.xml b/pom.xml index 9e61e716b864..36d501a92054 100644 --- a/pom.xml +++ b/pom.xml @@ -61,6 +61,7 @@ <jaxb-api.version>2.3.1</jaxb-api.version> <jaxb-impl.version>2.3.2</jaxb-impl.version> <annotation-api.version>1.3.2</annotation-api.version> + <system-rules.version>1.19.0</system-rules.version> </properties> <modules> <module>abstract-factory</module> @@ -181,8 +182,8 @@ <module>bytecode</module> <module>leader-election</module> <module>data-locality</module> + <module>subclass-sandbox</module> <module>circuit-breaker</module> - </modules> <repositories> @@ -323,6 +324,12 @@ <artifactId>javassist</artifactId> <version>3.25.0-GA</version> </dependency> + <dependency> + <groupId>com.github.stefanbirkner</groupId> + <artifactId>system-rules</artifactId> + <version>${system-rules.version}</version> + <scope>test</scope> + </dependency> </dependencies> </dependencyManagement> diff --git a/subclass-sandbox/README.md b/subclass-sandbox/README.md new file mode 100644 index 000000000000..674991f0895c --- /dev/null +++ b/subclass-sandbox/README.md @@ -0,0 +1,29 @@ + +--- +layout: pattern +title: Subclass Sandbox +folder: subclass-sandbox +permalink: /patterns/subclass-sandbox/ +categories: Other +tags: + - Java + - Difficulty-Beginner +--- + +## Intent +The subclass sandbox pattern describes a basic idea, while not having a lot of detailed mechanics. You will need the pattern when you have several similar subclasses. If you have to make a tiny change, then change the base class, while all subclasses shouldn't have to be touched. So the base class has to be able to provide all of the operations a derived class needs to perform. + +## Applicability +The Subclass Sandbox pattern is a very simple, common pattern lurking in lots of codebases, even outside of games. If you have a non-virtual protected method laying around, you’re probably already using something like this. Subclass Sandbox is a good fit when: + +- You have a base class with a number of derived classes. + +- The base class is able to provide all of the operations that a derived class may need to perform. + +- There is behavioral overlap in the subclasses and you want to make it easier to share code between them. + +- You want to minimize coupling between those derived classes and the rest of the program. + +## Credits + +* [Game Programming Patterns - Subclass Sandbox]([http://gameprogrammingpatterns.com/subclass-sandbox.html](http://gameprogrammingpatterns.com/subclass-sandbox.html)) \ No newline at end of file diff --git a/subclass-sandbox/pom.xml b/subclass-sandbox/pom.xml new file mode 100644 index 000000000000..8016ba471ed0 --- /dev/null +++ b/subclass-sandbox/pom.xml @@ -0,0 +1,49 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + + The MIT License + Copyright ? 2014 Ilkka Sepp?l? + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + +--> +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <parent> + <artifactId>java-design-patterns</artifactId> + <groupId>com.iluwatar</groupId> + <version>1.22.0-SNAPSHOT</version> + </parent> + <modelVersion>4.0.0</modelVersion> + + <artifactId>subclass-sandbox</artifactId> + + <dependencies> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + </dependency> + <dependency> + <groupId>com.github.stefanbirkner</groupId> + <artifactId>system-rules</artifactId> + </dependency> + </dependencies> + +</project> \ No newline at end of file diff --git a/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/App.java b/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/App.java new file mode 100644 index 000000000000..2e1f41c056c4 --- /dev/null +++ b/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/App.java @@ -0,0 +1,53 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * <p> + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * <p> + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * <p> + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.subclasssandbox; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The subclass sandbox pattern describes a basic idea, while not having a lot + * of detailed mechanics. You will need the pattern when you have several similar + * subclasses. If you have to make a tiny change, then change the base class, + * while all subclasses shouldn't have to be touched. So the base class has to be + * able to provide all of the operations a derived class needs to perform. + */ +public class App { + + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + + /** + * Entry point of the main program. + * @param args Program runtime arguments. + */ + public static void main(String[] args) { + LOGGER.info("Use superpower: sky launch"); + var skyLaunch = new SkyLaunch(); + skyLaunch.activate(); + LOGGER.info("Use superpower: ground dive"); + var groundDive = new GroundDive(); + groundDive.activate(); + } + +} diff --git a/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/GroundDive.java b/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/GroundDive.java new file mode 100644 index 000000000000..f284e125fba7 --- /dev/null +++ b/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/GroundDive.java @@ -0,0 +1,44 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * <p> + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * <p> + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * <p> + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.subclasssandbox; + +import org.slf4j.LoggerFactory; + +/** + * GroundDive superpower. + */ +public class GroundDive extends Superpower { + + public GroundDive() { + super(); + logger = LoggerFactory.getLogger(GroundDive.class); + } + + @Override + protected void activate() { + move(0, 0, -20); + playSound("GROUNDDIVE_SOUND", 5); + spawnParticles("GROUNDDIVE_PARTICLE", 20); + } +} diff --git a/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/SkyLaunch.java b/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/SkyLaunch.java new file mode 100644 index 000000000000..16c94bd0ca57 --- /dev/null +++ b/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/SkyLaunch.java @@ -0,0 +1,44 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * <p> + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * <p> + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * <p> + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.subclasssandbox; + +import org.slf4j.LoggerFactory; + +/** + * SkyLaunch superpower. + */ +public class SkyLaunch extends Superpower { + + public SkyLaunch() { + super(); + logger = LoggerFactory.getLogger(SkyLaunch.class); + } + + @Override + protected void activate() { + move(0, 0, 20); + playSound("SKYLAUNCH_SOUND", 1); + spawnParticles("SKYLAUNCH_PARTICLE", 100); + } +} diff --git a/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/Superpower.java b/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/Superpower.java new file mode 100644 index 000000000000..d4875d586d62 --- /dev/null +++ b/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/Superpower.java @@ -0,0 +1,69 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * <p> + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * <p> + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * <p> + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.subclasssandbox; + +import org.slf4j.Logger; + +/** + * Superpower abstract class. In this class the basic operations of all types of + * superpowers are provided as protected methods. + */ +public abstract class Superpower { + + protected Logger logger; + + /** + * Subclass of superpower should implement this sandbox method by calling the + * methods provided in this super class. + */ + protected abstract void activate(); + + /** + * Move to (x, y, z). + * @param x X coordinate. + * @param y Y coordinate. + * @param z Z coordinate. + */ + protected void move(double x, double y, double z) { + logger.info("Move to ( " + x + ", " + y + ", " + z + " )"); + } + + /** + * Play sound effect for the superpower. + * @param soundName Sound name. + * @param volumn Value of volumn. + */ + protected void playSound(String soundName, int volumn) { + logger.info("Play " + soundName + " with volumn " + volumn); + } + + /** + * Spawn particles for the superpower. + * @param particleType Particle type. + * @param count Count of particles to be spawned. + */ + protected void spawnParticles(String particleType, int count) { + logger.info("Spawn " + count + " particle with type " + particleType); + } +}
diff --git a/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/AppTest.java b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/AppTest.java new file mode 100644 index 000000000000..207c71ef9ef0 --- /dev/null +++ b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * <p> + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * <p> + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * <p> + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.subclasssandbox; + +import org.junit.Test; + +/** + * App unit tests. + */ +public class AppTest { + + @Test + public void testMain() { + String[] args = {}; + App.main(args); + } +} diff --git a/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/GroundDiveTest.java b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/GroundDiveTest.java new file mode 100644 index 000000000000..7b4645742376 --- /dev/null +++ b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/GroundDiveTest.java @@ -0,0 +1,92 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * <p> + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * <p> + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * <p> + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.subclasssandbox; + +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.junit.contrib.java.lang.system.SystemOutRule; + +/** + * GroundDive unit tests. + */ +public class GroundDiveTest { + + @Rule + public SystemOutRule log = new SystemOutRule().enableLog(); + + @Test + public void testMove() { + log.clearLog(); + var groundDive = new GroundDive(); + groundDive.move(1.0, 1.0, 1.0); + var outputLog = getLogContent(log.getLog()); + var expectedLog = "Move to ( 1.0, 1.0, 1.0 )"; + Assert.assertEquals(outputLog, expectedLog); + } + + @Test + public void testPlaySound() { + log.clearLog(); + var groundDive = new GroundDive(); + groundDive.playSound("SOUND_NAME", 1); + var outputLog = getLogContent(log.getLog()); + var expectedLog = "Play SOUND_NAME with volumn 1"; + Assert.assertEquals(outputLog, expectedLog); + } + + @Test + public void testSpawnParticles() { + log.clearLog(); + var groundDive = new GroundDive(); + groundDive.spawnParticles("PARTICLE_TYPE", 100); + final var outputLog = getLogContent(log.getLog()); + final var expectedLog = "Spawn 100 particle with type PARTICLE_TYPE"; + Assert.assertEquals(outputLog, expectedLog); + } + + @Test + public void testActivate() { + log.clearLog(); + var groundDive = new GroundDive(); + groundDive.activate();; + String[] logs = log.getLog().split("\n"); + final var expectedSize = 3; + final var log1 = logs[0].split("-")[1].trim() + " -" + logs[0].split("-")[2].trim(); + final var expectedLog1 = "Move to ( 0.0, 0.0, -20.0 )"; + final var log2 = getLogContent(logs[1]); + final var expectedLog2 = "Play GROUNDDIVE_SOUND with volumn 5"; + final var log3 = getLogContent(logs[2]); + final var expectedLog3 = "Spawn 20 particle with type GROUNDDIVE_PARTICLE"; + Assert.assertEquals(logs.length, expectedSize); + Assert.assertEquals(log1, expectedLog1); + Assert.assertEquals(log2, expectedLog2); + Assert.assertEquals(log3, expectedLog3); + } + + private String getLogContent(String log) { + return log.split("-")[1].trim(); + } + +} diff --git a/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/SkyLaunchTest.java b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/SkyLaunchTest.java new file mode 100644 index 000000000000..5ba84c0b55cc --- /dev/null +++ b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/SkyLaunchTest.java @@ -0,0 +1,91 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * <p> + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * <p> + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * <p> + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.subclasssandbox; + +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.junit.contrib.java.lang.system.SystemOutRule; + +/** + * SkyLaunch unit tests. + */ +public class SkyLaunchTest { + + @Rule + public SystemOutRule log = new SystemOutRule().enableLog(); + + @Test + public void testMove() { + log.clearLog(); + var skyLaunch = new SkyLaunch(); + skyLaunch.move(1.0, 1.0, 1.0); + var outputLog = getLogContent(log.getLog()); + var expectedLog = "Move to ( 1.0, 1.0, 1.0 )"; + Assert.assertEquals(outputLog, expectedLog); + } + + @Test + public void testPlaySound() { + log.clearLog(); + var skyLaunch = new SkyLaunch(); + skyLaunch.playSound("SOUND_NAME", 1); + var outputLog = getLogContent(log.getLog()); + var expectedLog = "Play SOUND_NAME with volumn 1"; + Assert.assertEquals(outputLog, expectedLog); + } + + @Test + public void testSpawnParticles() { + log.clearLog(); + var skyLaunch = new SkyLaunch(); + skyLaunch.spawnParticles("PARTICLE_TYPE", 100); + var outputLog = getLogContent(log.getLog()); + var expectedLog = "Spawn 100 particle with type PARTICLE_TYPE"; + Assert.assertEquals(outputLog, expectedLog); + } + + @Test + public void testActivate() { + log.clearLog(); + var skyLaunch = new SkyLaunch(); + skyLaunch.activate();; + String[] logs = log.getLog().split("\n"); + final var expectedSize = 3; + final var log1 = getLogContent(logs[0]); + final var expectedLog1 = "Move to ( 0.0, 0.0, 20.0 )"; + final var log2 = getLogContent(logs[1]); + final var expectedLog2 = "Play SKYLAUNCH_SOUND with volumn 1"; + final var log3 = getLogContent(logs[2]); + final var expectedLog3 = "Spawn 100 particle with type SKYLAUNCH_PARTICLE"; + Assert.assertEquals(logs.length, expectedSize); + Assert.assertEquals(log1, expectedLog1); + Assert.assertEquals(log2, expectedLog2); + Assert.assertEquals(log3, expectedLog3); + } + + private String getLogContent(String log) { + return log.split("-")[1].trim(); + } +}
train
train
2019-10-14T20:32:19
"2017-04-01T08:54:15Z"
iluwatar
train
iluwatar/java-design-patterns/1001_1008
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1001
iluwatar/java-design-patterns/1008
[ "keyword_pr_to_issue" ]
7e698a90dd7664e119ec0b082883ea48dc12ae2e
27c131c2cb850a92b5b346b24dce20eae91cc84f
[ "Fixed intermittent issue #1001", "Didn't see @afflato already took this, sorry!" ]
[]
"2019-10-14T20:41:48Z"
[ "type: bug", "info: good first issue", "epic: build issue" ]
Intermittent test failure in Spatial Partition pattern
![image](https://user-images.githubusercontent.com/582346/66769142-09134c00-eebd-11e9-9a90-e694dac91be5.png)
[ "spatial-partition/src/main/java/com/iluwatar/spatialpartition/Rect.java" ]
[ "spatial-partition/src/main/java/com/iluwatar/spatialpartition/Rect.java" ]
[]
diff --git a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Rect.java b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Rect.java index 3d2f01d77d3d..71d4eda5bfa7 100644 --- a/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Rect.java +++ b/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Rect.java @@ -28,14 +28,14 @@ */ public class Rect { - int x; - int y; - int width; - int height; + double x; + double y; + double width; + double height; //(x,y) - centre of rectangle - Rect(int x, int y, int width, int height) { + Rect(double x, double y, double width, double height) { this.x = x; this.y = y; this.width = width;
null
test
train
2019-10-14T20:32:19
"2019-10-14T16:59:14Z"
iluwatar
train
iluwatar/java-design-patterns/1007_1015
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1007
iluwatar/java-design-patterns/1015
[ "keyword_pr_to_issue" ]
a5646b63c19455051fb49fd5a455a28159708d49
880b234d8fa328619e2505650849fec4c319d9fa
[ "I got this at work today as well, and we solved it with the above suggested solution. I can prepare a PR for it if noone else already did it?", "Sure @lbroman, PR is welcome", "Instead of inserting `junit-platform-commons` in each of the ~120 module poms a better fix would be to just update JUnit 5 to the most current version...", "Does this fix the problem?\r\n\r\nI suggested in my PR (not visible here) that a better aproach might also be to upgrade the last junit 4 projects to jupiter and then pull the jupiter dependencies up to the root pom.", "Yes it does, because JUnit 5.5.2 transitively pulls junit-platform-commons 1.5.2:\r\n\r\n![jupiter-5 5 2](https://user-images.githubusercontent.com/110982/66992341-f5890080-f0c9-11e9-8756-edc81336beab.PNG)\r\n", "Tried updating to 5.5.2 and it broke the maven build, current version dates back to 2017...\r\njunit-platform-commons is in the current dependency tree also, but 1.0.2.\r\n\r\nAlso noticed I cannot reproduce this issue on Eclipse EE but only on Eclipse Java, so is problably eclipse edition related. Will test this by managing the junit-platforms-commons version instead and see what that might bring.", "Updating to 5.5.2 works for me. In addition `junit-jupiter-api` have to be added in the parent pom because `spring-boot-dependencies` imports and old version of this. \r\n\r\nNow the tests run on the command line as well as from eclipse. I'll submit a pull request.\r\n\r\n![command line](https://user-images.githubusercontent.com/110982/67011635-4ad80880-f0f0-11e9-948c-3e28e1cecfbe.PNG)\r\n\r\n![eclipse](https://user-images.githubusercontent.com/110982/67011770-7eb32e00-f0f0-11e9-8d03-dbd78f76f7f5.png)\r\n\r\n\r\nA future improvement may be to remove all `junit-jupiter-*` dependencies and replace them by the aggregator dependency [`junit-jupiter`](https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter/5.5.2) which was introduces with 5.4.0.", "Another option is to switch to TestNG.", "java.lang.BootstrapMethodError: java.lang.NoClassDefFoundError: org/junit/platform/engine/EngineDiscoveryListener\r\n\tat org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder.getLauncherDiscoveryListener(LauncherDiscoveryRequestBuilder.java:241)\r\n\tat org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder.build(LauncherDiscoveryRequestBuilder.java:235)\r\n\tat org.eclipse.jdt.internal.junit5.runner.JUnit5TestLoader.createUnfilteredTest(JUnit5TestLoader.java:75)\r\n\tat org.eclipse.jdt.internal.junit5.runner.JUnit5TestLoader.createTest(JUnit5TestLoader.java:66)\r\n\tat org.eclipse.jdt.internal.junit5.runner.JUnit5TestLoader.loadTests(JUnit5TestLoader.java:53)\r\n\tat org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:526)\r\n\tat org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)\r\n\tat org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)\r\n\tat org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)\r\nCaused by: java.lang.NoClassDefFoundError: org/junit/platform/engine/EngineDiscoveryListener\r\n\tat java.lang.ClassLoader.defineClass1(Native Method)\r\n\tat java.lang.ClassLoader.defineClass(Unknown Source)\r\n\tat java.security.SecureClassLoader.defineClass(Unknown Source)\r\n\tat java.net.URLClassLoader.defineClass(Unknown Source)\r\n\tat java.net.URLClassLoader.access$100(Unknown Source)\r\n\tat java.net.URLClassLoader$1.run(Unknown Source)\r\n\tat java.net.URLClassLoader$1.run(Unknown Source)\r\n\tat java.security.AccessController.doPrivileged(Native Method)\r\n\tat java.net.URLClassLoader.findClass(Unknown Source)\r\n\tat java.lang.ClassLoader.loadClass(Unknown Source)\r\n\tat sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)\r\n\tat java.lang.ClassLoader.loadClass(Unknown Source)\r\n\t... 9 more\r\nCaused by: java.lang.ClassNotFoundException: org.junit.platform.engine.EngineDiscoveryListener\r\n\tat java.net.URLClassLoader.findClass(Unknown Source)\r\n\tat java.lang.ClassLoader.loadClass(Unknown Source)\r\n\tat sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)\r\n\tat java.lang.ClassLoader.loadClass(Unknown Source)\r\n\t... 21 more\r\n" ]
[]
"2019-10-17T13:23:12Z"
[ "type: bug", "info: good first issue", "epic: build issue", "epic: ide issue", "epic: dependencies" ]
JUnit5 test are not able to run in Eclipse
Steps to recreate: 1. In Eclipse, select a unit test to run by right-clicking and selecting: "Run Configurations." Select a JUnit execution and ensure that the JUnit5 runner is selected: ![image](https://user-images.githubusercontent.com/1112973/66777789-ecb0e880-ee97-11e9-9bf2-ace877c11bd2.png) 1. Click the Run button. 1. The following error is shown: ![image](https://user-images.githubusercontent.com/1112973/66777844-179b3c80-ee98-11e9-8090-22953a3950f5.png) and the following stack trace is displayed: ``` java.lang.NoClassDefFoundError: org/junit/platform/commons/PreconditionViolationException at org.eclipse.jdt.internal.junit5.runner.JUnit5TestLoader.createUnfilteredTest(JUnit5TestLoader.java:75) at org.eclipse.jdt.internal.junit5.runner.JUnit5TestLoader.createTest(JUnit5TestLoader.java:66) at org.eclipse.jdt.internal.junit5.runner.JUnit5TestLoader.loadTests(JUnit5TestLoader.java:53) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:525) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209) Caused by: java.lang.ClassNotFoundException: org.junit.platform.commons.PreconditionViolationException at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583) at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521) ... 7 more ``` Workaround: Run the mvn test on the command line and the tests will execute. According to the following Stackoverflow: https://stackoverflow.com/questions/57040675/java-lang-noclassdeffounderror-org-junit-platform-commons-preconditionviolation adding the following dependency to the project will fix. (I've tried with the example project and it seems to work). ``` <dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-commons</artifactId> <version>1.5.2</version> </dependency> ```
[ "pom.xml" ]
[ "pom.xml" ]
[]
diff --git a/pom.xml b/pom.xml index 020c784c62fd..22dedc14a59e 100644 --- a/pom.xml +++ b/pom.xml @@ -39,7 +39,7 @@ <spring-data.version>2.0.14.RELEASE</spring-data.version> <h2.version>1.4.190</h2.version> <junit.version>4.12</junit.version> - <junit-jupiter.version>5.0.2</junit-jupiter.version> + <junit-jupiter.version>5.5.2</junit-jupiter.version> <junit-vintage.version>${junit.version}.2</junit-vintage.version> <sping-test-junit5.version>1.0.2</sping-test-junit5.version> <compiler.version>3.8.1</compiler.version> @@ -242,6 +242,12 @@ <version>${junit.version}</version> <scope>test</scope> </dependency> + <dependency> + <groupId>org.junit.jupiter</groupId> + <artifactId>junit-jupiter-api</artifactId> + <version>${junit-jupiter.version}</version> + <scope>test</scope> + </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId>
null
train
train
2019-10-16T17:21:06
"2019-10-14T19:36:18Z"
oconnelc
train
iluwatar/java-design-patterns/1011_1017
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1011
iluwatar/java-design-patterns/1017
[ "keyword_issue_to_pr" ]
880b234d8fa328619e2505650849fec4c319d9fa
c308ca09e5018aecd9ee409d6fdddb0d18d3a3de
[ "I would like to take a look, if no one else is interested.", "I just submitted #1017 to address. ", "Ok @oconnelc " ]
[]
"2019-10-18T00:03:50Z"
[ "type: bug", "info: good first issue", "epic: code quality" ]
SonarCloud reports vulnerabilities
The project is using SonarCloud static code analysis. The latest results are showing that it has found several blocker level vulnerabilities. In this task those are fixed or marked as false positives. To mark false positives, `SuppressWarnings` annotation should be used in code as explained in the linked documentation. Links: [Blocker and critical severity vulnerabilities in SonarCloud](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL&types=VULNERABILITY) [Sonar false positives](https://docs.sonarqube.org/latest/analysis/languages/java/#JavaFAQ-HowtoremoveFalse-Positiveissues)
[ "aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Aggregator.java", "api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ApiGateway.java", "naked-objects/webapp/src/main/webapp/about/index.html" ]
[ "aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Aggregator.java", "api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ApiGateway.java", "naked-objects/webapp/src/main/webapp/about/index.html" ]
[]
diff --git a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Aggregator.java b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Aggregator.java index cd30afc4807c..ccbe6f2fe68c 100644 --- a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Aggregator.java +++ b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Aggregator.java @@ -22,11 +22,12 @@ */ package com.iluwatar.aggregator.microservices; +import javax.annotation.Resource; + import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; -import javax.annotation.Resource; - /** * The aggregator aggregates calls on various micro-services, collects * data and further publishes them under a REST endpoint. @@ -47,7 +48,7 @@ public class Aggregator { * * @return a Product. */ - @RequestMapping("/product") + @RequestMapping(path = "/product", method = RequestMethod.GET) public Product getProduct() { Product product = new Product(); product.setTitle(informationClient.getProductTitle()); diff --git a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ApiGateway.java b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ApiGateway.java index cbabad1e6ff6..dc4249c6eb3d 100644 --- a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ApiGateway.java +++ b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ApiGateway.java @@ -23,6 +23,7 @@ package com.iluwatar.api.gateway; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; @@ -43,7 +44,7 @@ public class ApiGateway { * Retrieves product information that desktop clients need * @return Product information for clients on a desktop */ - @RequestMapping("/desktop") + @RequestMapping(path = "/desktop", method = RequestMethod.GET) public DesktopProduct getProductDesktop() { DesktopProduct desktopProduct = new DesktopProduct(); desktopProduct.setImagePath(imageClient.getImagePath()); @@ -55,7 +56,7 @@ public DesktopProduct getProductDesktop() { * Retrieves product information that mobile clients need * @return Product information for clients on a mobile device */ - @RequestMapping("/mobile") + @RequestMapping(path = "/mobile", method = RequestMethod.GET) public MobileProduct getProductMobile() { MobileProduct mobileProduct = new MobileProduct(); mobileProduct.setPrice(priceClient.getPrice()); diff --git a/naked-objects/webapp/src/main/webapp/about/index.html b/naked-objects/webapp/src/main/webapp/about/index.html index 176bfc13a3f6..e929c5b6da33 100644 --- a/naked-objects/webapp/src/main/webapp/about/index.html +++ b/naked-objects/webapp/src/main/webapp/about/index.html @@ -82,12 +82,12 @@ <p> This app has been generated using Apache Isis' - <a href="http://isis.apache.org/intro/getting-started/simple%61pp-archetype.html" target="_blank">SimpleApp</a> archetype, + <a href="http://isis.apache.org/intro/getting-started/simple%61pp-archetype.html" target="_blank" rel="noopener noreferrer">SimpleApp</a> archetype, to create a purposefully minimal application that nevertheless includes fixture data, integration tests and BDD specs. <br/> <br/> - The app itself consists of a single domain class, <a href="https://github.com/apache/isis/blob/master/example/application/simple%61pp/dom/src/main/java/dom/simple/SimpleObject.java" target="_blank"><tt>SimpleObject</tt></a>, - along with an equally simple (factory/repository) domain service, <a href="https://github.com/apache/isis/blob/master/example/application/simple%61pp/dom/src/main/java/dom/simple/SimpleObjects.java" target="_blank"><tt>SimpleObjects</tt></a>. + The app itself consists of a single domain class, <a href="https://github.com/apache/isis/blob/master/example/application/simple%61pp/dom/src/main/java/dom/simple/SimpleObject.java" target="_blank" rel="noopener noreferrer"><tt>SimpleObject</tt></a>, + along with an equally simple (factory/repository) domain service, <a href="https://github.com/apache/isis/blob/master/example/application/simple%61pp/dom/src/main/java/dom/simple/SimpleObjects.java" target="_blank" rel="noopener noreferrer"><tt>SimpleObjects</tt></a>. </p> <p>To access the app:</p> @@ -98,8 +98,8 @@ </p> <p> provides accesses to a generic UI for end-users, - Isis' <a href="http://isis.apache.org/components/viewers/wicket/about.html" target="_blank">Wicket Viewer</a>. - As its name suggests, this viewer is built on top of <a href="http://wicket.apache.org" target="_blank">Apache Wicket</a>&trade;. + Isis' <a href="http://isis.apache.org/components/viewers/wicket/about.html" target="_blank" rel="noopener noreferrer">Wicket Viewer</a>. + As its name suggests, this viewer is built on top of <a href="http://wicket.apache.org" target="_blank" rel="noopener noreferrer">Apache Wicket</a>&trade;. </p> </li> <li> @@ -118,7 +118,7 @@ <p> The default user/password is <b><i>sven/pass</i></b> (as configured in the - <a href="https://github.com/apache/isis/blob/master/example/application/simple%61pp/webapp/src/main/webapp/WEB-INF/shiro.ini" target="_blank">shiro.ini</a> file). + <a href="https://github.com/apache/isis/blob/master/example/application/simple%61pp/webapp/src/main/webapp/WEB-INF/shiro.ini" target="_blank" rel="noopener noreferrer">shiro.ini</a> file). </p> </div>
null
test
train
2019-10-17T20:00:32
"2019-10-15T17:51:01Z"
iluwatar
train
iluwatar/java-design-patterns/1016_1018
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1016
iluwatar/java-design-patterns/1018
[ "timestamp(timedelta=0.0, similarity=0.8630280494323783)", "keyword_pr_to_issue" ]
2982db456db68f5a1e30eb7f53bea1dac054f974
0c60a95d8f0da0275db6b16f685444db96fe1837
[ "Why does the `maven-checkstyle-plugin` in the root pom use an execution? As a consequence running `mvn checkstyle:checkstyle-aggregate` on the command line doesn't use this configuration...", "I think the source of the configuration has been the instructions on the plugin's web site https://maven.apache.org/plugins/maven-checkstyle-plugin/usage.html, see \"Checking for Violations as Part of the Build\"", "OK if this is intentional then the switch to google_checks.xml should be easy. I'll submit a pull request.", "Ok @kaiwinter " ]
[]
"2019-10-18T11:13:28Z"
[ "info: good first issue", "epic: ide issue", "type: refactoring", "epic: code quality" ]
Checkstyle should use google_checks.xml
At the moment maven-checkstyle-plugin in main pom.xml has been configured to use custom rules defined in checkstyle.xml. However there shouldn't be many modifications compared to the builtin google_checks.xml and it would be beneficial to start using this so that own rules wouldn't have to be maintained.
[ "checkstyle.xml", "pom.xml" ]
[ "pom.xml" ]
[]
diff --git a/checkstyle.xml b/checkstyle.xml deleted file mode 100644 index d66281f178c6..000000000000 --- a/checkstyle.xml +++ /dev/null @@ -1,197 +0,0 @@ -<?xml version="1.0"?> -<!-- - - The MIT License - Copyright © 2014-2019 Ilkka Seppälä - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ---> -<!DOCTYPE module PUBLIC - "-//Puppy Crawl//DTD Check Configuration 1.3//EN" - "http://www.puppycrawl.com/dtds/configuration_1_3.dtd"> - -<!-- - - Source = https://github.com/checkstyle/checkstyle/tree/master/src/main/resources - - Checkstyle configurartion that checks the Google coding conventions from: - - - Google Java Style - https://google-styleguide.googlecode.com/svn-history/r130/trunk/javaguide.html - - Checkstyle is very configurable. Be sure to read the documentation at - http://checkstyle.sf.net (or in your downloaded distribution). - - Most Checks are configurable, be sure to consult the documentation. - - To completely disable a check, just comment it out or delete it from the file. - - Authors: Max Vetrenko, Ruslan Diachenko, Roman Ivanov. - - --> - -<module name="Checker"> - <property name="charset" value="UTF-8"/> - - <property name="fileExtensions" value="java, xml, properties"/> - - <property name="severity" value="error"/> - - <!-- Checks for whitespace --> - <!-- See http://checkstyle.sf.net/config_whitespace.html --> - <module name="FileTabCharacter"> - <property name="eachLine" value="true"/> - </module> - - <module name="TreeWalker"> - <module name="OuterTypeFilename"/> - <module name="IllegalTokenText"> - <property name="tokens" value="STRING_LITERAL, CHAR_LITERAL"/> - <property name="format" - value="\\u00(08|09|0(a|A)|0(c|C)|0(d|D)|22|27|5(C|c))|\\(0(10|11|12|14|15|42|47)|134)"/> - <property name="message" value="Avoid using corresponding octal or Unicode escape."/> - </module> - <module name="AvoidEscapedUnicodeCharacters"> - <property name="allowEscapesForControlCharacters" value="true"/> - <property name="allowByTailComment" value="true"/> - <property name="allowNonPrintableEscapes" value="true"/> - </module> - <module name="LineLength"> - <property name="max" value="120"/> - <property name="ignorePattern" value="^package.*|^import.*|a href|href|http://|https://|ftp://"/> - </module> - <module name="OneTopLevelClass"/> - <module name="NoLineWrap"/> - <module name="EmptyBlock"> - <property name="option" value="TEXT"/> - <property name="tokens" - value="LITERAL_TRY, LITERAL_CATCH, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE, LITERAL_SWITCH"/> - </module> - <module name="NeedBraces"/> - <module name="LeftCurly"/> - <module name="RightCurly"/> - <module name="RightCurly"> - <property name="option" value="alone"/> - <property name="tokens" - value="CLASS_DEF, METHOD_DEF, CTOR_DEF, LITERAL_FOR, LITERAL_WHILE, LITERAL_DO, STATIC_INIT, INSTANCE_INIT"/> - </module> - <module name="WhitespaceAround"> - <property name="allowEmptyConstructors" value="true"/> - <property name="allowEmptyMethods" value="true"/> - <property name="allowEmptyTypes" value="true"/> - <property name="allowEmptyLoops" value="true"/> - <message key="ws.notFollowed" - value="WhitespaceAround: ''{0}'' is not followed by whitespace."/> - <message key="ws.notPreceded" - value="WhitespaceAround: ''{0}'' is not preceded with whitespace."/> - </module> - <module name="OneStatementPerLine"/> - <module name="MultipleVariableDeclarations"/> - <module name="ArrayTypeStyle"/> - <module name="MissingSwitchDefault"/> - <module name="FallThrough"/> - <module name="UpperEll"/> - <module name="ModifierOrder"/> - <module name="SeparatorWrap"> - <property name="tokens" value="DOT"/> - <property name="option" value="nl"/> - </module> - <module name="SeparatorWrap"> - <property name="tokens" value="COMMA"/> - <property name="option" value="EOL"/> - </module> - - <!-- Checks for Naming Conventions. --> - <!-- See http://checkstyle.sf.net/config_naming.html --> - <module name="ConstantName"/> - <module name="LocalFinalVariableName"/> - <module name="LocalVariableName"/> - <module name="MemberName"/> - <module name="MethodName"/> - <module name="PackageName"/> - <module name="ParameterName"/> - <module name="StaticVariableName"/> - <module name="TypeName"/> - - <module name="NoFinalizer"/> - <module name="GenericWhitespace"> - <message key="ws.followed" - value="GenericWhitespace ''{0}'' is followed by whitespace."/> - <message key="ws.preceded" - value="GenericWhitespace ''{0}'' is preceded with whitespace."/> - <message key="ws.illegalFollow" - value="GenericWhitespace ''{0}'' should followed by whitespace."/> - <message key="ws.notPreceded" - value="GenericWhitespace ''{0}'' is not preceded with whitespace."/> - </module> - <module name="Indentation"> - <property name="basicOffset" value="2"/> - <property name="braceAdjustment" value="0"/> - <property name="caseIndent" value="2"/> - <property name="throwsIndent" value="4"/> - <property name="lineWrappingIndentation" value="4"/> - <property name="arrayInitIndent" value="2"/> - </module> - <module name="AbbreviationAsWordInName"> - <property name="ignoreFinal" value="false"/> - <property name="allowedAbbreviationLength" value="1"/> - </module> - <module name="OverloadMethodsDeclarationOrder"/> - <module name="MethodParamPad"/> - <module name="OperatorWrap"> - <property name="option" value="NL"/> - <property name="tokens" - value="BAND, BOR, BSR, BXOR, DIV, EQUAL, GE, GT, LAND, LE, LITERAL_INSTANCEOF, LOR, LT, MINUS, MOD, NOT_EQUAL, PLUS, QUESTION, SL, SR, STAR "/> - </module> - <module name="AnnotationLocation"> - <property name="tokens" value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF"/> - </module> - <module name="AnnotationLocation"> - <property name="tokens" value="VARIABLE_DEF"/> - <property name="allowSamelineMultipleAnnotations" value="true"/> - </module> - <module name="NonEmptyAtclauseDescription"/> - <module name="JavadocTagContinuationIndentation"/> - <module name="AtclauseOrder"> - <property name="tagOrder" value="@param, @return, @throws, @deprecated"/> - <property name="target" value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF, VARIABLE_DEF"/> - </module> - <module name="JavadocMethod"> - <property name="scope" value="public"/> - <property name="allowMissingParamTags" value="true"/> - <property name="allowMissingThrowsTags" value="true"/> - <property name="allowMissingReturnTag" value="true"/> - <property name="minLineCount" value="2"/> - <property name="allowedAnnotations" value="Override, Test, Before, After, Parameters, Given, When, BeforeClass, AfterClass, Parameterized, ParameterizedTest, BeforeAll, BeforeEach"/> - <property name="allowThrowsTagsForSubclasses" value="true"/> - </module> - <module name="JavadocType"> - <property name="scope" value="public"/> - <property name="allowUnknownTags" value="true"/> - </module> - <module name="MethodName"> - <property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9_]*$"/> - <message key="name.invalidPattern" - value="Method name ''{0}'' must match pattern ''{1}''."/> - </module> - <module name="SingleLineJavadoc"/> - </module> - -</module> diff --git a/pom.xml b/pom.xml index 22dedc14a59e..0ef4890ca065 100644 --- a/pom.xml +++ b/pom.xml @@ -395,11 +395,10 @@ </goals> <phase>validate</phase> <configuration> - <configLocation>checkstyle.xml</configLocation> + <configLocation>google_checks.xml</configLocation> <suppressionsLocation>checkstyle-suppressions.xml</suppressionsLocation> <encoding>UTF-8</encoding> - <consoleOutput>true</consoleOutput> - <failsOnError>true</failsOnError> + <failOnViolation>true</failOnViolation> <includeTestSourceDirectory>true</includeTestSourceDirectory> </configuration> </execution>
null
val
train
2019-10-18T22:09:27
"2019-10-17T17:57:14Z"
iluwatar
train
iluwatar/java-design-patterns/1010_1023
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1010
iluwatar/java-design-patterns/1023
[ "timestamp(timedelta=1432.0, similarity=0.8563808740103421)" ]
f671f03d13966c9c5b3b65625224912336db86dd
82f9a6c2323b412036965fc51e5ec155b6cf7741
[ "I started taking a look at these errors and I think the first one will be a false positive. Specifically the rule: \"Loops should not be infinite\" in the file \"api-gateway/.../java/com/iluwatar/api/gateway/ApiGateway.java\" Based on the documentation in the above link, it seems like there are two options:\r\n\r\n1. Add the following annotation: \r\n`@SuppressWarnings(\"squid:S2189\")`\r\nbut this causes a Java compile warning that the squid:S2189 is not a valid warning. \r\n1. Mark the issue in the SonarCloud: I think this is probably what we should do, but I didn't want to act until this was discussed. ", "Hmm where do you see the error after adding the annotation? Is it in the Maven output or IDE? Tried that with Maven but did not get any warnings.", "I was seeing it on the IDE. (I keep stumbling on the Eclipse annoyances).\nIf it's not showing up in Maven, I'll just leave it as is.\n\nOn Fri, Oct 18, 2019, 15:27 Ilkka Seppälä <[email protected]> wrote:\n\n> Hmm where do you see the error after adding the annotation? Is it in the\n> Maven output or IDE? Tried that with Maven but did not get any warnings.\n>\n> —\n> You are receiving this because you were assigned.\n> Reply to this email directly, view it on GitHub\n> <https://github.com/iluwatar/java-design-patterns/issues/1010?email_source=notifications&email_token=AAIPXDJQWZL3VOFKABBSPFDQPIE3PA5CNFSM4JA74VX2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEBVT6KY#issuecomment-543899435>,\n> or unsubscribe\n> <https://github.com/notifications/unsubscribe-auth/AAIPXDOIZNQYS3KET7TOGDLQPIE3PANCNFSM4JA74VXQ>\n> .\n>\n", "Ok, let's try to proceed with `SuppressWarnings`", "It turns out the warning is a setting in Eclipse. Selecting Window->Preferences and navigating to the Java compiler options and changing the value of: \r\n`Unhandled Token in @SuppressWarnings` to ignore. By default this is warn.\r\n![image](https://user-images.githubusercontent.com/1112973/67146172-7117b880-f256-11e9-857e-14e31bd7e0c1.png)\r\n\r\n", "I just pushed #1020 to address. ", "The latest scan shows two critical issues left. See the screenshot:\r\n\r\n![image](https://user-images.githubusercontent.com/582346/67150293-6f81db00-f2be-11e9-84b3-4ce1c3b96310.png)\r\n", "That's weird. I know I made those changes. I'll make sure they weren't\nmissed in the commit.\n\nOn Sat, Oct 19, 2019, 15:22 Ilkka Seppälä <[email protected]> wrote:\n\n> The latest scan shows two critical issues left. See the screenshot:\n>\n> [image: image]\n> <https://user-images.githubusercontent.com/582346/67150293-6f81db00-f2be-11e9-84b3-4ce1c3b96310.png>\n>\n> —\n> You are receiving this because you were assigned.\n> Reply to this email directly, view it on GitHub\n> <https://github.com/iluwatar/java-design-patterns/issues/1010?email_source=notifications&email_token=AAIPXDIR7FTHU74PQWZWNFDQPNM73A5CNFSM4JA74VX2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEBX2YXA#issuecomment-544189532>,\n> or unsubscribe\n> <https://github.com/notifications/unsubscribe-auth/AAIPXDKPVAIB6KTEWNZNFHDQPNM73ANCNFSM4JA74VXQ>\n> .\n>\n" ]
[]
"2019-10-19T21:10:08Z"
[ "type: bug", "info: good first issue", "type: refactoring", "epic: code quality" ]
SonarCloud reports bugs
The project is using SonarCloud static code analysis. The latest results are showing that it has found several blocker and critical severity bugs. In this task those are fixed or marked as false positives. To mark false positives, `SuppressWarnings` annotation should be used in code as explained in the linked documentation. Links: [Blocker and critical severity bugs in SonarCloud](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL&types=BUG) [Sonar false positives](https://docs.sonarqube.org/latest/analysis/languages/java/#JavaFAQ-HowtoremoveFalse-Positiveissues)
[ "hexagonal/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java", "typeobjectpattern/src/main/java/com/iluwatar/typeobject/CellPool.java" ]
[ "hexagonal/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java", "typeobjectpattern/src/main/java/com/iluwatar/typeobject/CellPool.java" ]
[]
diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java index bc4e963e1808..29a9d3233889 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java @@ -102,8 +102,7 @@ public static void submitTickets(LotteryService lotteryService, int numTickets) } private static PlayerDetails getRandomPlayerDetails() { - Random random = new Random(); - int idx = random.nextInt(PLAYERS.size()); + int idx = RANDOM.nextInt(PLAYERS.size()); return PLAYERS.get(idx); } } diff --git a/typeobjectpattern/src/main/java/com/iluwatar/typeobject/CellPool.java b/typeobjectpattern/src/main/java/com/iluwatar/typeobject/CellPool.java index e04cce4f018a..6014da0cf1ce 100644 --- a/typeobjectpattern/src/main/java/com/iluwatar/typeobject/CellPool.java +++ b/typeobjectpattern/src/main/java/com/iluwatar/typeobject/CellPool.java @@ -71,8 +71,7 @@ Cell getNewCell() { } void addNewCell(Cell c) { - Random rand = new Random(); - c.candy = randomCode[rand.nextInt(randomCode.length)]; //changing candytype to new + c.candy = randomCode[RANDOM.nextInt(randomCode.length)]; //changing candytype to new this.pool.add(c); pointer++; }
null
test
train
2019-10-19T21:14:01
"2019-10-15T17:46:38Z"
iluwatar
train
iluwatar/java-design-patterns/1009_1030
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1009
iluwatar/java-design-patterns/1030
[ "timestamp(timedelta=67.0, similarity=0.8773917989038774)" ]
acaa6cdc62b92e874357f02239dd8f51dc155f6b
1cb1bdcb5778f911f67af70068f4d304f9094097
[ "@jjjimenez100 yes I think we should clean up. Can you point out some example where this redeclaration occurs?", "Looking at the parent pom, we already have the `mockito-core` dependency specified in [here](https://github.com/iluwatar/java-design-patterns/blob/master/pom.xml#L276).\r\n\r\nSome of the child poms like [this](https://github.com/iluwatar/java-design-patterns/blob/master/decorator/pom.xml#L43) and [this](https://github.com/iluwatar/java-design-patterns/blob/master/observer/pom.xml#L48) seem to redeclare the same dependency (Same goes for the jupiter engine ones)\r\n", "I think that example is just how Maven's dependency management works (see https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Dependency_Management)", "Can I take this issue?", "Ok @akrystian ", "I found two probably not needed dependencies:\r\n- `spring-boot-dependencies` \r\n- `javassist`\r\n\r\nI can try remove it." ]
[]
"2019-10-24T17:22:08Z"
[ "info: good first issue", "epic: dependencies", "type: refactoring" ]
Redundant dependency declarations on child poms
I've noticed that there are redeclaration of dependencies (e.g: junit 5 engine/mockito) on our modules. I don't think we'll be needing those since they are already specified on the parent pom. Might be a good idea to have an issue that will do cleanups on child poms. Wdyt? @iluwatar
[ "cqrs/pom.xml", "eip-aggregator/pom.xml", "eip-splitter/pom.xml", "eip-wire-tap/pom.xml", "trampoline/pom.xml" ]
[ "cqrs/pom.xml", "eip-aggregator/pom.xml", "eip-splitter/pom.xml", "eip-wire-tap/pom.xml", "trampoline/pom.xml" ]
[]
diff --git a/cqrs/pom.xml b/cqrs/pom.xml index b3afda05c226..feab9d1acacb 100644 --- a/cqrs/pom.xml +++ b/cqrs/pom.xml @@ -50,8 +50,8 @@ <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-impl</artifactId> - <scope>test</scope> <version>2.1.17</version> + <scope>test</scope> </dependency> <dependency> <groupId>javax.xml.bind</groupId> diff --git a/eip-aggregator/pom.xml b/eip-aggregator/pom.xml index 3410b4504379..e4b96d0aa75d 100644 --- a/eip-aggregator/pom.xml +++ b/eip-aggregator/pom.xml @@ -43,7 +43,6 @@ <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-core</artifactId> - <version>${camel.version}</version> </dependency> <dependency> diff --git a/eip-splitter/pom.xml b/eip-splitter/pom.xml index 906a43d22a27..6aef2dc09953 100644 --- a/eip-splitter/pom.xml +++ b/eip-splitter/pom.xml @@ -43,7 +43,6 @@ <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-core</artifactId> - <version>${camel.version}</version> </dependency> <dependency> diff --git a/eip-wire-tap/pom.xml b/eip-wire-tap/pom.xml index f44bbd232979..ae896f0d0399 100644 --- a/eip-wire-tap/pom.xml +++ b/eip-wire-tap/pom.xml @@ -43,7 +43,6 @@ <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-core</artifactId> - <version>${camel.version}</version> </dependency> <dependency> diff --git a/trampoline/pom.xml b/trampoline/pom.xml index a0f25fc39b56..99ef231ef534 100644 --- a/trampoline/pom.xml +++ b/trampoline/pom.xml @@ -38,7 +38,6 @@ <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> - <version>4.12</version> <scope>test</scope> </dependency>
null
train
train
2019-10-23T16:25:45
"2019-10-15T12:43:42Z"
jjjimenez100
train
iluwatar/java-design-patterns/1037_1045
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1037
iluwatar/java-design-patterns/1045
[ "timestamp(timedelta=0.0, similarity=0.897763655876506)" ]
fadad43f8b85daabc06f87fb55784a4aac9c2a54
5d47488fe9165374821d2c3d3c0bf84a421cf110
[]
[]
"2019-10-26T17:18:14Z"
[ "type: bug", "info: help wanted", "info: good first issue", "epic: build issue" ]
Error when building from submodule directories
When running `mvn clean install` from project's submodules, the following error message is outputted ``` Failed to execute goal com.mycila:license-maven-plugin:3.0:format (install-format) on project adapter: Resource license-plugin-header-style.xml not found in file system, classpath or URL: no protocol: license-plugin-header-style.xml ``` Building from the submodules should work as well as building from the multimodule root.
[ "pom.xml" ]
[ "pom.xml" ]
[]
diff --git a/pom.xml b/pom.xml index b6c1b4472a88..1bcf73b8b4d5 100644 --- a/pom.xml +++ b/pom.xml @@ -406,6 +406,31 @@ </executions> </plugin> + <!-- Resolves ${projectRoot} to the project root directory. + Used by the license-maven-plugin to find the correct location of + license-plugin-header-style.xml when built from a submodule directory. --> + <plugin> + <groupId>org.commonjava.maven.plugins</groupId> + <artifactId>directory-maven-plugin</artifactId> + <version>0.3.1</version> + <executions> + <execution> + <id>directories</id> + <goals> + <goal>directory-of</goal> + </goals> + <phase>initialize</phase> + <configuration> + <property>projectRoot</property> + <project> + <groupId>com.iluwatar</groupId> + <artifactId>java-design-patterns</artifactId> + </project> + </configuration> + </execution> + </executions> + </plugin> + <plugin> <groupId>com.mycila</groupId> <artifactId>license-maven-plugin</artifactId> @@ -417,7 +442,7 @@ </properties> <skipExistingHeaders>true</skipExistingHeaders> <headerDefinitions> - <headerDefinition>license-plugin-header-style.xml</headerDefinition> + <headerDefinition>${projectRoot}${file.separator}license-plugin-header-style.xml</headerDefinition> </headerDefinitions> <mapping> <java>SLASHSTAR_CUSTOM_STYLE</java>
null
val
train
2019-10-26T17:58:56
"2019-10-26T06:17:57Z"
iluwatar
train
iluwatar/java-design-patterns/1161_1214
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1161
iluwatar/java-design-patterns/1214
[ "timestamp(timedelta=0.0, similarity=0.886218809180579)", "keyword_pr_to_issue" ]
be1c0b81433ab4965be95f76c072c49908ca1378
751b3b945206bed390730f780070a73f5fe2d500
[ "Thanks for reporting @karthikmucheli. Would you like to create a pull request for that?" ]
[]
"2020-03-27T02:22:05Z"
[ "type: bug", "info: help wanted", "epic: web site", "info: good first issue" ]
Aggregator Microservices
Credits link in Aggregator Microservices is responded with a blank page. The current link is http://blog.arungupta.me/microservice-design-patterns/
[ "aggregator-microservices/README.md" ]
[ "aggregator-microservices/README.md" ]
[]
diff --git a/aggregator-microservices/README.md b/aggregator-microservices/README.md index 4d64178a66a5..74a411fc5cfb 100644 --- a/aggregator-microservices/README.md +++ b/aggregator-microservices/README.md @@ -27,4 +27,4 @@ Use the Aggregator Microservices pattern when you need a unified API for various ## Credits -* [Microservice Design Patterns](http://blog.arungupta.me/microservice-design-patterns/) +* [Microservice Design Patterns](http://web.archive.org/web/20190705163602/http://blog.arungupta.me/microservice-design-patterns/)
null
train
train
2020-03-26T20:14:44
"2020-01-21T03:01:22Z"
karthikmucheli
train
iluwatar/java-design-patterns/1218_1221
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1218
iluwatar/java-design-patterns/1221
[ "timestamp(timedelta=327.0, similarity=0.8903223199668275)" ]
751b3b945206bed390730f780070a73f5fe2d500
1c26bd741615e73579e5b70fdc84d96ca23c69e8
[ "hi im a beginner. can u elaborate more? so what should be done?", "For me it sounds just like a different name for Given-When-Then.\r\nhttps://en.wikipedia.org/wiki/Given-When-Then", "> For me it sounds just like a different name for Given-When-Then.\r\n> https://en.wikipedia.org/wiki/Given-When-Then\r\n\r\nI think you are right. You can also look at it as a reformulation of the Four-Phase Test pattern.\r\nhttps://martinfowler.com/bliki/GivenWhenThen.html", "@iluwatar , I'd like to take this", "Ok @npczwh " ]
[ "We don't have an existing tag yet, but I would propose to use `Testing` here. Then we need to amend file https://github.com/iluwatar/java-design-patterns-web/blob/master/_data/tags.yml. See https://github.com/iluwatar/java-design-patterns/wiki/07.-Categories-and-Tags.", "Changed in 882b569" ]
"2020-04-14T14:15:35Z"
[ "epic: pattern", "info: good first issue", "type: feature" ]
Arrange, Act, Assert pattern
AAA is a way to structure your unit tests so they're easier to read, maintain, and enhance. Reference: https://blog.ncrunch.net/post/arrange-act-assert-aaa-testing.aspx
[ "pom.xml" ]
[ "arrange-act-assert/README.md", "arrange-act-assert/etc/arrange-act-assert.urm.puml", "arrange-act-assert/pom.xml", "arrange-act-assert/src/main/java/com/iluwatar/arrangeactassert/Cash.java", "pom.xml" ]
[ "arrange-act-assert/src/test/java/com/iluwatar/arrangeactassert/CashAAATest.java", "arrange-act-assert/src/test/java/com/iluwatar/arrangeactassert/CashAntiAAATest.java" ]
diff --git a/arrange-act-assert/README.md b/arrange-act-assert/README.md new file mode 100644 index 000000000000..02b7ee8b7398 --- /dev/null +++ b/arrange-act-assert/README.md @@ -0,0 +1,30 @@ +--- +layout: pattern +title: Arrange/Act/Assert +folder: arrange-act-assert +permalink: /patterns/arrange-act-assert/ +categories: Idiom +tags: + - Testing +--- + +## Also known as +Given/When/Then + +## Intent +The Arrange/Act/Assert (AAA) is a pattern for organizing unit tests. +It breaks tests down into three clear and distinct steps: +1. Arrange: Perform the setup and initialization required for the test. +2. Act: Take action(s) required for the test. +3. Assert: Verify the outcome(s) of the test. + +## Applicability +Use Arrange/Act/Assert pattern when + +* you need to structure your unit tests so they're easier to read, maintain, and enhance. + +## Credits + +* [Arrange, Act, Assert: What is AAA Testing?](https://blog.ncrunch.net/post/arrange-act-assert-aaa-testing.aspx) +* [Bill Wake: 3A – Arrange, Act, Assert](https://xp123.com/articles/3a-arrange-act-assert/) +* [Martin Fowler: GivenWhenThen](https://martinfowler.com/bliki/GivenWhenThen.html) diff --git a/arrange-act-assert/etc/arrange-act-assert.urm.puml b/arrange-act-assert/etc/arrange-act-assert.urm.puml new file mode 100644 index 000000000000..4b22d2a4e4bb --- /dev/null +++ b/arrange-act-assert/etc/arrange-act-assert.urm.puml @@ -0,0 +1,11 @@ +@startuml +package com.iluwatar.arrangeactassert { + class Cash { + - amount : int + ~ Cash(amount : int) + ~ count() : int + ~ minus(subtrahend : int) : boolean + ~ plus(addend : int) + } +} +@enduml \ No newline at end of file diff --git a/arrange-act-assert/pom.xml b/arrange-act-assert/pom.xml new file mode 100644 index 000000000000..bb0387e7a6aa --- /dev/null +++ b/arrange-act-assert/pom.xml @@ -0,0 +1,44 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + + The MIT License + Copyright © 2014-2019 Ilkka Seppälä + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + +--> +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <parent> + <artifactId>java-design-patterns</artifactId> + <groupId>com.iluwatar</groupId> + <version>1.23.0-SNAPSHOT</version> + </parent> + <modelVersion>4.0.0</modelVersion> + + <artifactId>arrange-act-assert</artifactId> + <dependencies> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <scope>test</scope> + </dependency> + </dependencies> +</project> \ No newline at end of file diff --git a/arrange-act-assert/src/main/java/com/iluwatar/arrangeactassert/Cash.java b/arrange-act-assert/src/main/java/com/iluwatar/arrangeactassert/Cash.java new file mode 100644 index 000000000000..71269359ea58 --- /dev/null +++ b/arrange-act-assert/src/main/java/com/iluwatar/arrangeactassert/Cash.java @@ -0,0 +1,57 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.arrangeactassert; + +/** + * Arrange/Act/Assert (AAA) is a unit test pattern. In this simple example, we have a ({@link Cash}) + * object for plus, minus and counting amount. + */ +public class Cash { + + private int amount; + + Cash(int amount) { + this.amount = amount; + } + + //plus + void plus(int addend) { + amount += addend; + } + + //minus + boolean minus(int subtrahend) { + if (amount >= subtrahend) { + amount -= subtrahend; + return true; + } else { + return false; + } + } + + //count + int count() { + return amount; + } +} diff --git a/pom.xml b/pom.xml index b81cfe8d483e..97deda70313b 100644 --- a/pom.xml +++ b/pom.xml @@ -184,6 +184,7 @@ <module>combinator</module> <module>update-method</module> <module>leader-followers</module> + <module>arrange-act-assert</module> </modules> <repositories>
diff --git a/arrange-act-assert/src/test/java/com/iluwatar/arrangeactassert/CashAAATest.java b/arrange-act-assert/src/test/java/com/iluwatar/arrangeactassert/CashAAATest.java new file mode 100644 index 000000000000..d7841843db37 --- /dev/null +++ b/arrange-act-assert/src/test/java/com/iluwatar/arrangeactassert/CashAAATest.java @@ -0,0 +1,99 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.arrangeactassert; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +/** + * Arrange/Act/Assert (AAA) is a pattern for organizing unit tests. It is a way to structure your + * tests so they're easier to read, maintain and enhance. + * + * <p>It breaks tests down into three clear and distinct steps: + * <p>1. Arrange: Perform the setup and initialization required for the test. + * <p>2. Act: Take action(s) required for the test. + * <p>3. Assert: Verify the outcome(s) of the test. + * + * <p>This pattern has several significant benefits. It creates a clear separation between a test's + * setup, operations, and results. This structure makes the code easier to read and understand. If + * you place the steps in order and format your code to separate them, you can scan a test and + * quickly comprehend what it does. + * + * <p>It also enforces a certain degree of discipline when you write your tests. You have to think + * clearly about the three steps your test will perform. But it makes tests more natural to write at + * the same time since you already have an outline. + * + * <p>In ({@link CashAAATest}) we have four test methods. Each of them has only one reason to + * change and one reason to fail. In a large and complicated code base, tests that honor the single + * responsibility principle are much easier to troubleshoot. + */ +public class CashAAATest { + + @Test + public void testPlus() { + //Arrange + var cash = new Cash(3); + //Act + cash.plus(4); + //Assert + assertEquals(cash.count(), 7); + } + + @Test + public void testMinus() { + //Arrange + var cash = new Cash(8); + //Act + var result = cash.minus(5); + //Assert + assertTrue(result); + assertEquals(cash.count(), 3); + } + + @Test + public void testInsufficientMinus() { + //Arrange + var cash = new Cash(1); + //Act + var result = cash.minus(6); + //Assert + assertFalse(result); + assertEquals(cash.count(), 1); + } + + @Test + public void testUpdate() { + //Arrange + var cash = new Cash(5); + //Act + cash.plus(6); + var result = cash.minus(3); + //Assert + assertTrue(result); + assertEquals(cash.count(), 8); + } +} diff --git a/arrange-act-assert/src/test/java/com/iluwatar/arrangeactassert/CashAntiAAATest.java b/arrange-act-assert/src/test/java/com/iluwatar/arrangeactassert/CashAntiAAATest.java new file mode 100644 index 000000000000..3f8c33d5ea95 --- /dev/null +++ b/arrange-act-assert/src/test/java/com/iluwatar/arrangeactassert/CashAntiAAATest.java @@ -0,0 +1,59 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.arrangeactassert; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +/** + * ({@link CashAAATest}) is an anti-example of AAA pattern. This test is functionally correct, but + * with the addition of new feature, it needs refactoring. There are an awful lot of steps in that + * test method, but it verifies the class' important behavior in just eleven lines. It violates the + * single responsibility principle. If this test method failed after a small code change, it might + * take some digging to discover why. + */ +public class CashAntiAAATest { + + @Test + public void testCash() { + //initialize + var cash = new Cash(3); + //test plus + cash.plus(4); + assertEquals(cash.count(), 7); + //test minus + cash = new Cash(8); + assertTrue(cash.minus(5)); + assertEquals(cash.count(), 3); + assertFalse(cash.minus(6)); + assertEquals(cash.count(), 3); + //test update + cash.plus(5); + assertTrue(cash.minus(5)); + assertEquals(cash.count(), 3); + } +}
train
train
2020-03-28T19:26:37
"2020-03-31T16:33:40Z"
iluwatar
train
iluwatar/java-design-patterns/1339_1342
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1339
iluwatar/java-design-patterns/1342
[ "keyword_pr_to_issue", "timestamp(timedelta=31.0, similarity=0.9313792829300822)" ]
4b88214baef78c362806311d88f96bebb0cd4d21
54c0b1725c522666e7dbdcb973719cefb7a9daed
[]
[]
"2020-07-26T20:59:59Z"
[ "type: bug", "info: help wanted", "epic: pattern" ]
Service Layer logging broken
At the moment the Service Layer pattern example does not produce log output at all.
[ "service-layer/src/main/resources/logback.xml" ]
[ "service-layer/src/main/resources/logback.xml" ]
[]
diff --git a/service-layer/src/main/resources/logback.xml b/service-layer/src/main/resources/logback.xml index 47fe422366d8..e6678aff2e8f 100644 --- a/service-layer/src/main/resources/logback.xml +++ b/service-layer/src/main/resources/logback.xml @@ -43,6 +43,7 @@ <logger name="com.iluwatar" additivity="false"> <level value="DEBUG"/> <appender-ref ref="FILE"/> + <appender-ref ref="STDOUT"/> </logger> <logger name="org.hibernate" additivity="false">
null
val
train
2020-07-26T21:47:33
"2020-07-26T16:24:07Z"
iluwatar
train
iluwatar/java-design-patterns/1324_1472
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1324
iluwatar/java-design-patterns/1472
[ "timestamp(timedelta=204.0, similarity=0.854523537744862)" ]
9ff5b9e7c09277cc51c3b26224608c699b457156
97285d37244fd0d524b6e9d9aa8dae48f1fa0cc3
[ "Yes, I agree that would be the typical scenario and in this case it would suit the example fine.\r\n", "@ravening let's leave the issue open if somebody wants to implement it", "@iluwatar I can work on it if you are ok with it.\r\nShould I write separate classes/interfaces or rewrite the existing abstract classes with interfaces?", "I think you can modify the existing" ]
[]
"2020-08-03T14:57:32Z"
[ "epic: pattern", "type: enhancement", "info: good first issue" ]
Inheritence in Command pattern
I see that the `Command` is a class instead of `interface` and all the target actions extends this class. Typically `Command` should be interface and the targets should implement the interface. So should we rewrite the command pattern to implement interface rather than using inheritance?
[ "command/README.md", "command/etc/command.urm.puml", "command/src/main/java/com/iluwatar/command/Command.java", "command/src/main/java/com/iluwatar/command/InvisibilitySpell.java", "command/src/main/java/com/iluwatar/command/ShrinkSpell.java" ]
[ "command/README.md", "command/etc/command.urm.puml", "command/src/main/java/com/iluwatar/command/Command.java", "command/src/main/java/com/iluwatar/command/InvisibilitySpell.java", "command/src/main/java/com/iluwatar/command/ShrinkSpell.java" ]
[]
diff --git a/command/README.md b/command/README.md index fc0a11d9ffe8..b763cf4dd1c5 100644 --- a/command/README.md +++ b/command/README.md @@ -75,19 +75,18 @@ public class Wizard { Next we present the spell hierarchy. ```java -public abstract class Command { +public interface Command { - public abstract void execute(Target target); + void execute(Target target); - public abstract void undo(); + void undo(); - public abstract void redo(); + void redo(); - @Override - public abstract String toString(); + String toString(); } -public class InvisibilitySpell extends Command { +public class InvisibilitySpell implements Command { private Target target; @@ -117,7 +116,7 @@ public class InvisibilitySpell extends Command { } } -public class ShrinkSpell extends Command { +public class ShrinkSpell implements Command { private Size oldSize; private Target target; diff --git a/command/etc/command.urm.puml b/command/etc/command.urm.puml index a8b773418ee3..c9c172226fa3 100644 --- a/command/etc/command.urm.puml +++ b/command/etc/command.urm.puml @@ -4,7 +4,7 @@ package com.iluwatar.command { + App() + main(args : String[]) {static} } - abstract class Command { + interface Command { + Command() + execute(Target) {abstract} + redo() {abstract} @@ -77,7 +77,7 @@ ShrinkSpell --> "-oldSize" Size InvisibilitySpell --> "-target" Target ShrinkSpell --> "-target" Target Target --> "-visibility" Visibility -Goblin --|> Target -InvisibilitySpell --|> Command -ShrinkSpell --|> Command -@enduml \ No newline at end of file +Goblin --|> Target +InvisibilitySpell ..|> Command +ShrinkSpell ..|> Command +@enduml diff --git a/command/src/main/java/com/iluwatar/command/Command.java b/command/src/main/java/com/iluwatar/command/Command.java index 85deff74efd8..83010f1604d0 100644 --- a/command/src/main/java/com/iluwatar/command/Command.java +++ b/command/src/main/java/com/iluwatar/command/Command.java @@ -26,15 +26,12 @@ /** * Interface for Commands. */ -public abstract class Command { +public interface Command { + void execute(Target target); - public abstract void execute(Target target); + void undo(); - public abstract void undo(); - - public abstract void redo(); - - @Override - public abstract String toString(); + void redo(); + String toString(); } diff --git a/command/src/main/java/com/iluwatar/command/InvisibilitySpell.java b/command/src/main/java/com/iluwatar/command/InvisibilitySpell.java index 3e0f7bbf4fef..33e053cc2e3b 100644 --- a/command/src/main/java/com/iluwatar/command/InvisibilitySpell.java +++ b/command/src/main/java/com/iluwatar/command/InvisibilitySpell.java @@ -26,7 +26,7 @@ /** * InvisibilitySpell is a concrete command. */ -public class InvisibilitySpell extends Command { +public class InvisibilitySpell implements Command { private Target target; diff --git a/command/src/main/java/com/iluwatar/command/ShrinkSpell.java b/command/src/main/java/com/iluwatar/command/ShrinkSpell.java index 87497bb7bed8..3f21fc7c1fc7 100644 --- a/command/src/main/java/com/iluwatar/command/ShrinkSpell.java +++ b/command/src/main/java/com/iluwatar/command/ShrinkSpell.java @@ -26,7 +26,7 @@ /** * ShrinkSpell is a concrete command. */ -public class ShrinkSpell extends Command { +public class ShrinkSpell implements Command { private Size oldSize; private Target target;
null
train
train
2020-08-03T15:49:46
"2020-07-21T15:33:23Z"
ravening
train
iluwatar/java-design-patterns/1338_1485
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1338
iluwatar/java-design-patterns/1485
[ "timestamp(timedelta=60.0, similarity=0.9630152057325821)" ]
1e90d0d645e637cb716b1f3f40d259345fd8bf9d
2c6f1832b0d328240e270dc0051d4c9e1af682ee
[ "I can work on it, if you would like it to assign it to me?", "Thanks @amit1307 please go ahead", "Hey, I was trying to start on this one but might need some more info if that's okay.\r\n\r\nMy understanding of this issue is that we don't have any logger configured for `api-gateway` but after it seems like there is nothing logged at all by any modules under `api-gateway`. So is the requirement here is to add logger as well as the logs or just the logger? Could you please clarify that?", "True, there's only a couple of `e.printStackTrace()` currently. I think it would be good to add some basic logging in addition to adding the library. Just so that it's easy to follow the general steps from the output.", "Sure, thanks for the info. I should get back in 1-2 days with something.", "Hey, have raised the PR to add some logs. Please let me know if you have any feedback on the change." ]
[]
"2020-08-09T13:37:03Z"
[ "type: bug", "epic: pattern", "info: good first issue" ]
Logging in API Gateway
At the moment api-gateway pattern does not use a proper logger as in other examples. In this issue we fix that.
[ "api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClientImpl.java", "api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClientImpl.java", "api-gateway/image-microservice/src/main/java/com/iluwatar/image/microservice/ImageController.java", "api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceController.java" ]
[ "api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClientImpl.java", "api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClientImpl.java", "api-gateway/image-microservice/src/main/java/com/iluwatar/image/microservice/ImageController.java", "api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceController.java" ]
[]
diff --git a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClientImpl.java b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClientImpl.java index 52dd065ffc35..6fea815fc86d 100644 --- a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClientImpl.java +++ b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/ImageClientImpl.java @@ -23,11 +23,16 @@ package com.iluwatar.api.gateway; +import static org.slf4j.LoggerFactory.getLogger; + import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; +import java.net.http.HttpResponse; import java.net.http.HttpResponse.BodyHandlers; + +import org.slf4j.Logger; import org.springframework.stereotype.Component; /** @@ -35,6 +40,8 @@ */ @Component public class ImageClientImpl implements ImageClient { + private static final Logger LOGGER = getLogger(ImageClientImpl.class); + /** * Makes a simple HTTP Get request to the Image microservice. * @@ -49,12 +56,26 @@ public String getImagePath() { .build(); try { + LOGGER.info("Sending request to fetch image path"); var httpResponse = httpClient.send(httpGet, BodyHandlers.ofString()); + logResponse(httpResponse); return httpResponse.body(); } catch (IOException | InterruptedException e) { - e.printStackTrace(); + LOGGER.error("Failure occurred while getting image path", e); } return null; } + + private void logResponse(HttpResponse<String> httpResponse) { + if (isSuccessResponse(httpResponse.statusCode())) { + LOGGER.info("Image path received successfully"); + } else { + LOGGER.warn("Image path request failed"); + } + } + + private boolean isSuccessResponse(int responseCode) { + return responseCode >= 200 && responseCode <= 299; + } } diff --git a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClientImpl.java b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClientImpl.java index 0dc44a51bced..f773d0d54c7a 100644 --- a/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClientImpl.java +++ b/api-gateway/api-gateway-service/src/main/java/com/iluwatar/api/gateway/PriceClientImpl.java @@ -23,18 +23,26 @@ package com.iluwatar.api.gateway; +import static org.slf4j.LoggerFactory.getLogger; + import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; +import java.net.http.HttpResponse; import java.net.http.HttpResponse.BodyHandlers; + +import org.slf4j.Logger; import org.springframework.stereotype.Component; + /** * An adapter to communicate with the Price microservice. */ @Component public class PriceClientImpl implements PriceClient { + private static final Logger LOGGER = getLogger(PriceClientImpl.class); + /** * Makes a simple HTTP Get request to the Price microservice. * @@ -49,12 +57,26 @@ public String getPrice() { .build(); try { + LOGGER.info("Sending request to fetch price info"); var httpResponse = httpClient.send(httpGet, BodyHandlers.ofString()); + logResponse(httpResponse); return httpResponse.body(); } catch (IOException | InterruptedException e) { - e.printStackTrace(); + LOGGER.error("Failure occurred while getting price info", e); } return null; } + + private void logResponse(HttpResponse<String> httpResponse) { + if (isSuccessResponse(httpResponse.statusCode())) { + LOGGER.info("Price info received successfully"); + } else { + LOGGER.warn("Price info request failed"); + } + } + + private boolean isSuccessResponse(int responseCode) { + return responseCode >= 200 && responseCode <= 299; + } } diff --git a/api-gateway/image-microservice/src/main/java/com/iluwatar/image/microservice/ImageController.java b/api-gateway/image-microservice/src/main/java/com/iluwatar/image/microservice/ImageController.java index b1f6dd3f7eb6..a96ef4f413a7 100644 --- a/api-gateway/image-microservice/src/main/java/com/iluwatar/image/microservice/ImageController.java +++ b/api-gateway/image-microservice/src/main/java/com/iluwatar/image/microservice/ImageController.java @@ -23,15 +23,20 @@ package com.iluwatar.image.microservice; +import static org.slf4j.LoggerFactory.getLogger; + +import org.slf4j.Logger; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; + /** * Exposes the Image microservice's endpoints. */ @RestController public class ImageController { + private static final Logger LOGGER = getLogger(ImageController.class); /** * An endpoint for a user to retrieve an image path. @@ -40,6 +45,7 @@ public class ImageController { */ @RequestMapping(value = "/image-path", method = RequestMethod.GET) public String getImagePath() { + LOGGER.info("Successfully found image path"); return "/product-image.png"; } } diff --git a/api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceController.java b/api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceController.java index cf2f5eb4f83b..dbcd59952945 100644 --- a/api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceController.java +++ b/api-gateway/price-microservice/src/main/java/com/iluwatar/price/microservice/PriceController.java @@ -23,15 +23,20 @@ package com.iluwatar.price.microservice; +import static org.slf4j.LoggerFactory.getLogger; + +import org.slf4j.Logger; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; + /** * Exposes the Price microservice's endpoints. */ @RestController public class PriceController { + private static final Logger LOGGER = getLogger(PriceController.class); /** * An endpoint for a user to retrieve a product's price. @@ -40,6 +45,7 @@ public class PriceController { */ @RequestMapping(value = "/price", method = RequestMethod.GET) public String getPrice() { + LOGGER.info("Successfully found price info"); return "20"; } }
null
train
train
2020-08-08T21:44:51
"2020-07-26T13:00:00Z"
iluwatar
train
iluwatar/java-design-patterns/1500_1505
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1500
iluwatar/java-design-patterns/1505
[ "keyword_issue_to_pr", "connected" ]
6d83ceba285fb2a62119f6169d8041ec05c196c4
15d795bf8a92c65cbb42a5889a351e317729c031
[ "I'd like to take this issue. Thank you in advance.", "Yes @ToxicDreamz, go ahead ☺️ ", "Half way through upgrading, one test case seems to be causing an issue, within the **Serverless** module, in specific the **`SavePersonApiHandlerTest#handleRequestSavePersonException()`** method. I do not have any knowledge of the AWS library, which is why I chose not to mess around with it. \r\n\r\nInitially the DynamoDBMapper was being Mocked with Mockito, and was causing issues once the tests were upgraded to JUnit 5 stating that the class could not be mocked, but as stated in the official Mockito guidelines, a type **should not be mocked if it doesn't belong to you**. See attached link below for details.\r\n\r\nhttps://github.com/mockito/mockito/wiki/How-to-write-good-tests#dont-mock-a-type-you-dont-own\r\n\r\n### Suggestion.\r\nA new issue should be opened to address that certain test case, as of now the test case is commented out and marked with a **_TODO_**\r\n\r\n\r\n### Displayed Error\r\n\r\n```\r\n> \r\n> Caused by: com.amazonaws.SdkClientException: Unable to find a region via the region provider chain. Must provide an explicit region in the builder or setup environment to supply a region.\r\n> \tat com.amazonaws.client.builder.AwsClientBuilder.setRegion(AwsClientBuilder.java:371)\r\n> \tat com.amazonaws.client.builder.AwsClientBuilder.configureMutableProperties(AwsClientBuilder.java:337)\r\n> \tat com.amazonaws.client.builder.AwsSyncClientBuilder.build(AwsSyncClientBuilder.java:46)\r\n> \tat com.iluwatar.serverless.baas.api.SavePersonApiHandlerTest.<clinit>(SavePersonApiHandlerTest.java:58)\r\n> \t... 53 more\r\n```\r\n\r\nError after supplying region`\r\n\r\n```\r\n> com.amazonaws.SdkClientException: Unable to load AWS credentials from any provider in the chain\r\n> \r\n> \tat com.amazonaws.auth.AWSCredentialsProviderChain.getCredentials(AWSCredentialsProviderChain.java:131)\r\n> \tat com.amazonaws.http.AmazonHttpClient$RequestExecutor.getCredentialsFromContext(AmazonHttpClient.java:1164)\r\n> \tat com.amazonaws.http.AmazonHttpClient$RequestExecutor.runBeforeRequestHandlers(AmazonHttpClient.java:762)\r\n> \tat com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:724)\r\n> \tat com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:717)\r\n> \tat com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:699)\r\n> \tat com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:667)\r\n> \tat com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:649)\r\n> \tat com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:513)\r\n> \tat com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.doInvoke(AmazonDynamoDBClient.java:3082)\r\n> \tat com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.invoke(AmazonDynamoDBClient.java:3058)\r\n> \tat com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.executePutItem(AmazonDynamoDBClient.java:2119)\r\n> \tat com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.putItem(AmazonDynamoDBClient.java:2094)\r\n> \tat com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper$SaveObjectHandler.doPutItem(DynamoDBMapper.java:883)\r\n> \tat com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper$1.executeLowLevelRequest(DynamoDBMapper.java:536)\r\n> \tat com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper$SaveObjectHandler.execute(DynamoDBMapper.java:733)\r\n> \tat com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.save(DynamoDBMapper.java:623)\r\n> \tat com.amazonaws.services.dynamodbv2.datamodeling.AbstractDynamoDBMapper.save(AbstractDynamoDBMapper.java:123)\r\n> \tat com.iluwatar.serverless.baas.api.SavePersonApiHandler.handleRequest(SavePersonApiHandler.java:50)\r\n> \tat com.iluwatar.serverless.baas.api.SavePersonApiHandlerTest.handleRequestSavePersonSuccessful(SavePersonApiHandlerTest.java:76)\r\n> \tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n> \tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n> \tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n> \tat java.base/java.lang.reflect.Method.invoke(Method.java:567)\r\n> \tat org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:675)\r\n> \tat org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)\r\n> \tat org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:125)\r\n> \tat org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:132)\r\n> \tat org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:124)\r\n> \tat org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:74)\r\n> \tat org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)\r\n> \tat org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)\r\n> \tat org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:104)\r\n> \tat org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:62)\r\n> \tat org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:43)\r\n> \tat org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:35)\r\n> \tat org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)\r\n> \tat org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)\r\n> \tat org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:202)\r\n> \tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\r\n> \tat org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:198)\r\n> \tat org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)\r\n> \tat org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:69)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)\r\n> \tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)\r\n> \tat org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)\r\n> \tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)\r\n> \tat java.base/java.util.ArrayList.forEach(ArrayList.java:1507)\r\n> \tat org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)\r\n> \tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)\r\n> \tat org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)\r\n> \tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)\r\n> \tat java.base/java.util.ArrayList.forEach(ArrayList.java:1507)\r\n> \tat org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)\r\n> \tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)\r\n> \tat org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)\r\n> \tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)\r\n> \tat org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)\r\n> \tat org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)\r\n> \tat org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)\r\n> \tat org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)\r\n> \tat org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)\r\n> \tat org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)\r\n> \tat org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)\r\n> \tat org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)\r\n> \tat com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)\r\n> \tat com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)\r\n> \tat com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)\r\n> \tat com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)\r\n\r\n```\r\n\r\n", "Overall the serverless module needs to be looked at, more tests are causing the same issues due to them not being able to be mocked.", "@ToxicDreamz FYI: I created #1505 which removes the dependency of `subclass-sandbox` to Rule, which is a JUnit 4 only feature.", "@stefanbirkner Okay, thank you for the heads up. I'll wait for @iluwatar to merge that PR, until I continue with that module.", "It's merged now", "Using JUnit 5 in Trampoline module. PR #1529 created.", "I want to work on this issue if its is still unassigned .", "Ok @sgarg5794 ", "I'm working on updating all the modules to JUnit5 right now. @ohbus ", "Sure @charlesfinley you're good to go!", "> Sure @charlesfinley you're good to go!\r\n\r\nSorry I opened a new PR for this - #1668 ", "@charlesfinley no need to be sorry for 😄 It is easier for us to review code in smaller chunks and this helps a lot 💯 \r\n\r\nThank you so much for your help!", "> @charlesfinley no need to be sorry for 😄 It is easier for us to review code in smaller chunks and this helps a lot 💯\r\n> \r\n> Thank you so much for your help!\r\n\r\nThis issue should probably be closed since the PR was merged and we have 2 new issues identifying the only modules lacking JUnit5. ", "@charlesfinley great work!\r\n\r\nWe will close this issue for sure.", "This issue has been partially addressed using #1542 and #1668 thanks to @charlesfinley \r\n\r\nTests from two modules [**serverless**](https://github.com/iluwatar/java-design-patterns/tree/master/serverless) and [**naked-objects**](https://github.com/iluwatar/java-design-patterns/tree/master/naked-objects) are not being executed.\r\n\r\nRespective issues have been opened for resolving the tests in favour of these two modules.\r\n- [ ] #1667\r\n- [ ] #1669\r\n\r\nResolving these two issues should close this [current issue](https://github.com/iluwatar/java-design-patterns/issues/1500)", "@iluwatar let me know how can I help with this, I am confused about the status of the what has been resolved and what is pending.", "Thanks for asking @anuragagarwal561994. I think the only remaining issue is that naked objects pattern still uses JUnit 4. Resolving this is covered by issues https://github.com/iluwatar/java-design-patterns/issues/1669 and https://github.com/iluwatar/java-design-patterns/issues/1683. I think we should close this task." ]
[]
"2020-08-24T21:18:02Z"
[ "info: help wanted", "epic: build issue", "epic: dependencies", "type: refactoring" ]
Use the same JUnit version everywhere
At the moment there are some modules that are still using JUnit 4. Most of the codebase uses JUnit 5, but even with that there are different versions. For example `unit-of-work` and `partial-response` declare their own versions. In this ticket let's try to apply the same version of JUnit 5 everywhere upgrading from JUnit 4 where needed. ## This issue has been partially addressed using #1542 and #1668 Tests from two modules [**serverless**](https://github.com/iluwatar/java-design-patterns/tree/master/serverless) and [**naked-objects**](https://github.com/iluwatar/java-design-patterns/tree/master/naked-objects) are not being executed. Respective issues have been opened for resolving the tests in favour of these two modules. - [x] #1667 against [**serverless**](https://github.com/iluwatar/java-design-patterns/tree/master/serverless) - [ ] #1669 against [**naked-objects**](https://github.com/iluwatar/java-design-patterns/tree/master/naked-objects) Resolving these two issues should close this [current issue](https://github.com/iluwatar/java-design-patterns/issues/1500)
[ "pom.xml", "subclass-sandbox/pom.xml" ]
[ "pom.xml", "subclass-sandbox/pom.xml" ]
[ "subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/GroundDiveTest.java", "subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/SkyLaunchTest.java" ]
diff --git a/pom.xml b/pom.xml index 1275ce115c83..3b7ad35686b6 100644 --- a/pom.xml +++ b/pom.xml @@ -52,7 +52,7 @@ <jaxb-api.version>2.3.1</jaxb-api.version> <jaxb-impl.version>2.3.2</jaxb-impl.version> <annotation-api.version>1.3.2</annotation-api.version> - <system-rules.version>1.19.0</system-rules.version> + <system-lambda.version>1.1.0</system-lambda.version> <urm.version>2.0.0</urm.version> <mockito-junit-jupiter.version>3.5.0</mockito-junit-jupiter.version> <!-- SonarCloud --> @@ -338,8 +338,8 @@ </dependency> <dependency> <groupId>com.github.stefanbirkner</groupId> - <artifactId>system-rules</artifactId> - <version>${system-rules.version}</version> + <artifactId>system-lambda</artifactId> + <version>${system-lambda.version}</version> <scope>test</scope> </dependency> </dependencies> diff --git a/subclass-sandbox/pom.xml b/subclass-sandbox/pom.xml index ac718291e2a4..a912ada3fdeb 100644 --- a/subclass-sandbox/pom.xml +++ b/subclass-sandbox/pom.xml @@ -42,7 +42,7 @@ </dependency> <dependency> <groupId>com.github.stefanbirkner</groupId> - <artifactId>system-rules</artifactId> + <artifactId>system-lambda</artifactId> </dependency> <dependency> <groupId>org.junit.jupiter</groupId>
diff --git a/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/GroundDiveTest.java b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/GroundDiveTest.java index 97e2ac67d16f..3b379946c6f0 100644 --- a/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/GroundDiveTest.java +++ b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/GroundDiveTest.java @@ -23,55 +23,48 @@ package com.iluwatar.subclasssandbox; +import com.github.stefanbirkner.systemlambda.Statement; import org.junit.Assert; -import org.junit.Rule; import org.junit.Test; -import org.junit.contrib.java.lang.system.SystemOutRule; + +import static com.github.stefanbirkner.systemlambda.SystemLambda.tapSystemOutNormalized; /** * GroundDive unit tests. */ public class GroundDiveTest { - @Rule - public SystemOutRule log = new SystemOutRule().enableLog(); - @Test - public void testMove() { - log.clearLog(); + public void testMove() throws Exception { var groundDive = new GroundDive(); groundDive.move(1.0, 1.0, 1.0); - var outputLog = getLogContent(log.getLog()); + var outputLog = getLogContent(() -> groundDive.move(1.0, 1.0, 1.0)); var expectedLog = "Move to ( 1.0, 1.0, 1.0 )"; Assert.assertEquals(outputLog, expectedLog); } @Test - public void testPlaySound() { - log.clearLog(); + public void testPlaySound() throws Exception { var groundDive = new GroundDive(); - groundDive.playSound("SOUND_NAME", 1); - var outputLog = getLogContent(log.getLog()); + var outputLog = getLogContent(() -> groundDive.playSound("SOUND_NAME", 1)); var expectedLog = "Play SOUND_NAME with volumn 1"; Assert.assertEquals(outputLog, expectedLog); } @Test - public void testSpawnParticles() { - log.clearLog(); + public void testSpawnParticles() throws Exception { var groundDive = new GroundDive(); - groundDive.spawnParticles("PARTICLE_TYPE", 100); - final var outputLog = getLogContent(log.getLog()); + final var outputLog = getLogContent( + () -> groundDive.spawnParticles("PARTICLE_TYPE", 100)); final var expectedLog = "Spawn 100 particle with type PARTICLE_TYPE"; Assert.assertEquals(outputLog, expectedLog); } @Test - public void testActivate() { - log.clearLog(); + public void testActivate() throws Exception { var groundDive = new GroundDive(); - groundDive.activate(); - var logs = log.getLog().split("\n"); + var logs = tapSystemOutNormalized(groundDive::activate) + .split("\n"); final var expectedSize = 3; final var log1 = logs[0].split("-")[1].trim() + " -" + logs[0].split("-")[2].trim(); final var expectedLog1 = "Move to ( 0.0, 0.0, -20.0 )"; @@ -85,6 +78,11 @@ public void testActivate() { Assert.assertEquals(log3, expectedLog3); } + private String getLogContent(Statement statement) throws Exception { + var log = tapSystemOutNormalized(statement); + return getLogContent(log); + } + private String getLogContent(String log) { return log.split("-")[1].trim(); } diff --git a/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/SkyLaunchTest.java b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/SkyLaunchTest.java index e192737f6320..d285e6c7ddb2 100644 --- a/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/SkyLaunchTest.java +++ b/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/SkyLaunchTest.java @@ -23,55 +23,47 @@ package com.iluwatar.subclasssandbox; +import com.github.stefanbirkner.systemlambda.Statement; import org.junit.Assert; -import org.junit.Rule; import org.junit.Test; -import org.junit.contrib.java.lang.system.SystemOutRule; + +import static com.github.stefanbirkner.systemlambda.SystemLambda.tapSystemOutNormalized; /** * SkyLaunch unit tests. */ public class SkyLaunchTest { - @Rule - public SystemOutRule log = new SystemOutRule().enableLog(); - @Test - public void testMove() { - log.clearLog(); + public void testMove() throws Exception { var skyLaunch = new SkyLaunch(); - skyLaunch.move(1.0, 1.0, 1.0); - var outputLog = getLogContent(log.getLog()); + var outputLog = getLogContent(() -> skyLaunch.move(1.0, 1.0, 1.0)); var expectedLog = "Move to ( 1.0, 1.0, 1.0 )"; Assert.assertEquals(outputLog, expectedLog); } @Test - public void testPlaySound() { - log.clearLog(); + public void testPlaySound() throws Exception { var skyLaunch = new SkyLaunch(); - skyLaunch.playSound("SOUND_NAME", 1); - var outputLog = getLogContent(log.getLog()); + var outputLog = getLogContent(() -> skyLaunch.playSound("SOUND_NAME", 1)); var expectedLog = "Play SOUND_NAME with volumn 1"; Assert.assertEquals(outputLog, expectedLog); } @Test - public void testSpawnParticles() { - log.clearLog(); + public void testSpawnParticles() throws Exception { var skyLaunch = new SkyLaunch(); - skyLaunch.spawnParticles("PARTICLE_TYPE", 100); - var outputLog = getLogContent(log.getLog()); + var outputLog = getLogContent( + () -> skyLaunch.spawnParticles("PARTICLE_TYPE", 100)); var expectedLog = "Spawn 100 particle with type PARTICLE_TYPE"; Assert.assertEquals(outputLog, expectedLog); } @Test - public void testActivate() { - log.clearLog(); + public void testActivate() throws Exception { var skyLaunch = new SkyLaunch(); - skyLaunch.activate(); - var logs = log.getLog().split("\n"); + var logs = tapSystemOutNormalized(skyLaunch::activate) + .split("\n"); final var expectedSize = 3; final var log1 = getLogContent(logs[0]); final var expectedLog1 = "Move to ( 0.0, 0.0, 20.0 )"; @@ -85,6 +77,11 @@ public void testActivate() { Assert.assertEquals(log3, expectedLog3); } + private String getLogContent(Statement statement) throws Exception { + var log = tapSystemOutNormalized(statement); + return getLogContent(log); + } + private String getLogContent(String log) { return log.split("-")[1].trim(); }
train
train
2020-08-23T17:53:57
"2020-08-21T14:32:50Z"
iluwatar
train
iluwatar/java-design-patterns/1486_1507
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1486
iluwatar/java-design-patterns/1507
[ "timestamp(timedelta=86.0, similarity=0.927805650729066)" ]
9dd46d7b4a4329d07956b263dd627272e25db707
9b464e0be1a54f26bd50508d619f294d2147fa8d
[ "I can look into it if you can assign it to me please.", "Ok @amit1307 ", "@amit1307 Can we get an update on the status of this issue?", "Hey, sorry I was out of the town for few days and came back this week. Just catching up the stuff. I should get back with some progress soon. Hope that's fine." ]
[]
"2020-08-25T23:11:06Z"
[ "type: enhancement", "epic: dependencies" ]
Upgrade mockito
The current version declared in the main `pom.xml` is very old: ``` <mockito.version>1.10.19</mockito.version> ``` Let's try to upgrade it to a newer version in this task.
[ "pom.xml" ]
[ "pom.xml" ]
[]
diff --git a/pom.xml b/pom.xml index 56b95520435e..6d779700f9f5 100644 --- a/pom.xml +++ b/pom.xml @@ -39,7 +39,7 @@ <commons-dbcp.version>1.4</commons-dbcp.version> <camel.version>2.24.0</camel.version> <guava.version>19.0</guava.version> - <mockito.version>1.10.19</mockito.version> + <mockito.version>3.5.6</mockito.version> <htmlunit.version>2.22</htmlunit.version> <guice.version>4.0</guice.version> <mongo-java-driver.version>3.12.1</mongo-java-driver.version> @@ -206,6 +206,18 @@ <dependencyManagement> <dependencies> + <dependency> + <groupId>net.bytebuddy</groupId> + <artifactId>byte-buddy</artifactId> + <version>1.9.7</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>net.bytebuddy</groupId> + <artifactId>byte-buddy-agent</artifactId> + <version>1.9.7</version> + <scope>test</scope> + </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId>
null
test
train
2020-08-25T20:42:42
"2020-08-09T14:58:02Z"
iluwatar
train
iluwatar/java-design-patterns/1313_1522
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1313
iluwatar/java-design-patterns/1522
[ "timestamp(timedelta=213.0, similarity=0.8767148070795346)" ]
ef326ee77e03077714f38df36f92ffa58ebaffa9
ebc0e8b3cd79ce644c927ad0a64dd0539d6da4e3
[ "May I take this up and implement this pattern?", "Sure @swarajsaaj, go ahead!" ]
[ "In a sense it's architectural, but I would put it under `Structural` since this the scope is so small.", "Please add explanation for term `SPI` here, since it may not be familiar to everybody.", "Naming, I would suggest `DomesticTaxCalculator`", "Naming, `ForeignTaxCalculator` maybe?", "```suggestion\r\n public void testTaxCalculation(){\r\n```", "```suggestion\r\n public void testTaxCalculation(){\r\n```", "I think we can add https://en.wikipedia.org/wiki/Service_provider_interface link as well?", "Renamed\r\n", "Fixed in another commit.", "\r\n\r\nFixed in another commit.\r\n", "Added the definition and link to wikipedia for better understanding" ]
"2020-09-09T21:32:18Z"
[ "epic: pattern", "type: feature" ]
Separated Interface pattern
https://www.youtube.com/watch?v=d3k-hOA7k2Y
[ "pom.xml" ]
[ "pom.xml", "separated-interface/README.md", "separated-interface/etc/separated-interface.urm.puml", "separated-interface/pom.xml", "separated-interface/src/main/java/com/iluwatar/separatedinterface/App.java", "separated-interface/src/main/java/com/iluwatar/separatedinterface/invoice/InvoiceGenerator.java", "separated-interface/src/main/java/com/iluwatar/separatedinterface/invoice/TaxCalculator.java", "separated-interface/src/main/java/com/iluwatar/separatedinterface/taxes/DomesticTaxCalculator.java", "separated-interface/src/main/java/com/iluwatar/separatedinterface/taxes/ForeignTaxCalculator.java" ]
[ "separated-interface/src/test/java/com/iluwatar/separatedinterface/AppTest.java", "separated-interface/src/test/java/com/iluwatar/separatedinterface/invoice/InvoiceGeneratorTest.java", "separated-interface/src/test/java/com/iluwatar/separatedinterface/taxes/DomesticTaxCalculatorTest.java", "separated-interface/src/test/java/com/iluwatar/separatedinterface/taxes/ForeignTaxCalculatorTest.java" ]
diff --git a/pom.xml b/pom.xml index da3084ab2c51..1026685881db 100644 --- a/pom.xml +++ b/pom.xml @@ -196,6 +196,7 @@ <module>transaction-script</module> <module>filterer</module> <module>factory</module> + <module>separated-interface</module> </modules> <repositories> diff --git a/separated-interface/README.md b/separated-interface/README.md new file mode 100644 index 000000000000..ca7a12e44d95 --- /dev/null +++ b/separated-interface/README.md @@ -0,0 +1,119 @@ +--- +layout: pattern +title: Separated Interface +folder: separated-interface +permalink: /patterns/separated-interface/ +categories: Structural +tags: + - Decoupling +--- + + +## Intent +Separate the interface definition and implementation in different packages. This allows the client to be completely unaware of the implementation. + +## Explanation + +Real world example + +> An Invoice generator may be created with ability to use different Tax calculators that may be added in the invoice depending upon type of purchase, region etc. + +In plain words + +> Separated interface pattern encourages to keep the implementations of an interface decoupled from the client and its definition, so the client is not dependent on the implementation. + +A client code may abstract some specific functionality to an interface, and define the definition of the interface as an SPI ([Service Programming Interface](https://en.wikipedia.org/wiki/Service_provider_interface) is an API intended and open to be implemented or extended by a third party). Another package may implement this interface definition with a concrete logic, which will be injected into the client code at runtime (with a third class, injecting the implementation in the client) or at compile time (using Plugin pattern with some configurable file). + +**Programmatic Example** + +**Client** An Invoice generator class accepts the cost of the product and calculates the total amount payable inclusive of tax + +```java +public class InvoiceGenerator { + + private final TaxCalculator taxCalculator; + + private final double amount; + + public InvoiceGenerator(double amount, TaxCalculator taxCalculator) { + this.amount = amount; + this.taxCalculator = taxCalculator; + } + + public double getAmountWithTax() { + return amount + taxCalculator.calculate(amount); + } + +} +``` +The tax calculation logic is delegated to the ```TaxCalculator``` interface + +```java + +public interface TaxCalculator { + + double calculate(double amount); + +} + +``` + +**Implementation package** +In another package (which the client is completely unaware of) there exist multiple implementations of the ```TaxCalculator``` interface +```ForeignTaxCalculator``` which levies 60% tax for international products. +```java +public class ForeignTaxCalculator implements TaxCalculator { + + public static final double TAX_PERCENTAGE = 60; + + @Override + public double calculate(double amount) { + return amount * TAX_PERCENTAGE / 100.0; + } + +} +``` + +```DomesticTaxCalculator``` which levies 20% tax for international products. +```java +public class DomesticTaxCalculator implements TaxCalculator { + + public static final double TAX_PERCENTAGE = 20; + + @Override + public double calculate(double amount) { + return amount * TAX_PERCENTAGE / 100.0; + } + +} +``` + +These both implementations are instantiated and injected in the client class by the ```App.java``` class + +```java + var internationalProductInvoice = new InvoiceGenerator(PRODUCT_COST, new ForeignTaxCalculator()); + + LOGGER.info("Foreign Tax applied: {}", "" + internationalProductInvoice.getAmountWithTax()); + + var domesticProductInvoice = new InvoiceGenerator(PRODUCT_COST, new DomesticTaxCalculator()); + + LOGGER.info("Domestic Tax applied: {}", "" + domesticProductInvoice.getAmountWithTax()); +``` + +## Class diagram +![alt text](./etc/class_diagram.png "Separated Interface") + +## Applicability +Use the Separated interface pattern when + +* You are developing a framework package, and your framework needs to call some application code through interfaces. +* You have separate packages implementing the functionalities which may be plugged in your client code at runtime or compile-time. +* Your code resides in a layer that is not allowed to call the interface implementation layer by rule. For example, a domain layer needs to call a data mapper. + +## Tutorial + +* [Separated Interface Tutorial](https://www.youtube.com/watch?v=d3k-hOA7k2Y) + +## Credits + +* [Martin Fowler](https://www.martinfowler.com/eaaCatalog/separatedInterface.html) diff --git a/separated-interface/etc/separated-interface.urm.puml b/separated-interface/etc/separated-interface.urm.puml new file mode 100644 index 000000000000..eab2ad60c98e --- /dev/null +++ b/separated-interface/etc/separated-interface.urm.puml @@ -0,0 +1,36 @@ +@startuml +package com.iluwatar.separatedinterface { + class App { + - LOGGER : Logger {static} + + PRODUCT_COST : double {static} + + App() + + main(args : String[]) {static} + } +} +package com.iluwatar.separatedinterface.taxes { + class DomesticTaxCalculator { + + TAX_PERCENTAGE : double {static} + + DomesticTaxCalculator() + + calculate(amount : double) : double + } + class ForeignTaxCalculator { + + TAX_PERCENTAGE : double {static} + + ForeignTaxCalculator() + + calculate(amount : double) : double + } +} +package com.iluwatar.separatedinterface.invoice { + class InvoiceGenerator { + - amount : double + - taxCalculator : TaxCalculator + + InvoiceGenerator(amount : double, taxCalculator : TaxCalculator) + + getAmountWithTax() : double + } + interface TaxCalculator { + + calculate(double) : double {abstract} + } +} +InvoiceGenerator --> "-taxCalculator" TaxCalculator +DomesticTaxCalculator ..|> TaxCalculator +ForeignTaxCalculator ..|> TaxCalculator +@enduml \ No newline at end of file diff --git a/separated-interface/pom.xml b/separated-interface/pom.xml new file mode 100644 index 000000000000..da7584a93b6e --- /dev/null +++ b/separated-interface/pom.xml @@ -0,0 +1,71 @@ +<?xml version="1.0"?> +<!-- + + The MIT License + Copyright © 2014-2019 Ilkka Seppälä + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + +--> +<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>com.iluwatar</groupId> + <artifactId>java-design-patterns</artifactId> + <version>1.24.0-SNAPSHOT</version> + </parent> + <artifactId>separated-interface</artifactId> + <dependencies> + <dependency> + <groupId>org.junit.jupiter</groupId> + <artifactId>junit-jupiter-engine</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.junit.jupiter</groupId> + <artifactId>junit-jupiter-params</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-core</artifactId> + <scope>test</scope> + </dependency> + </dependencies> + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-assembly-plugin</artifactId> + <executions> + <execution> + <configuration> + <archive> + <manifest> + <mainClass>com.iluwatar.separatedinterface.App</mainClass> + </manifest> + </archive> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> +</project> diff --git a/separated-interface/src/main/java/com/iluwatar/separatedinterface/App.java b/separated-interface/src/main/java/com/iluwatar/separatedinterface/App.java new file mode 100644 index 000000000000..1951e738b77d --- /dev/null +++ b/separated-interface/src/main/java/com/iluwatar/separatedinterface/App.java @@ -0,0 +1,62 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.separatedinterface; + +import com.iluwatar.separatedinterface.invoice.InvoiceGenerator; +import com.iluwatar.separatedinterface.taxes.DomesticTaxCalculator; +import com.iluwatar.separatedinterface.taxes.ForeignTaxCalculator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * <p>The Separated Interface pattern encourages to separate the interface definition and + * implementation in different packages. This allows the client to be completely unaware of the + * implementation.</p> + * + * <p>In this class the {@link InvoiceGenerator} class is injected with different instances of + * {@link com.iluwatar.separatedinterface.invoice.TaxCalculator} implementations located in separate + * packages, to receive different responses for both of the implementations.</p> + */ +public class App { + + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + + public static final double PRODUCT_COST = 50.0; + + /** + * Program entry point. + * + * @param args command line args + */ + public static void main(String[] args) { + //Create the invoice generator with product cost as 50 and foreign product tax + var internationalProductInvoice = new InvoiceGenerator(PRODUCT_COST, + new ForeignTaxCalculator()); + LOGGER.info("Foreign Tax applied: {}", "" + internationalProductInvoice.getAmountWithTax()); + + //Create the invoice generator with product cost as 50 and domestic product tax + var domesticProductInvoice = new InvoiceGenerator(PRODUCT_COST, new DomesticTaxCalculator()); + LOGGER.info("Domestic Tax applied: {}", "" + domesticProductInvoice.getAmountWithTax()); + } +} diff --git a/separated-interface/src/main/java/com/iluwatar/separatedinterface/invoice/InvoiceGenerator.java b/separated-interface/src/main/java/com/iluwatar/separatedinterface/invoice/InvoiceGenerator.java new file mode 100644 index 000000000000..c17ed5ac55e3 --- /dev/null +++ b/separated-interface/src/main/java/com/iluwatar/separatedinterface/invoice/InvoiceGenerator.java @@ -0,0 +1,51 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.separatedinterface.invoice; + +/** + * InvoiceGenerator class generates an invoice, accepting the product cost and calculating the total + * price payable inclusive tax (calculated by {@link TaxCalculator}). + */ +public class InvoiceGenerator { + + /** + * The TaxCalculator interface to calculate the payable tax. + */ + private final TaxCalculator taxCalculator; + + /** + * The base product amount without tax. + */ + private final double amount; + + public InvoiceGenerator(double amount, TaxCalculator taxCalculator) { + this.amount = amount; + this.taxCalculator = taxCalculator; + } + + public double getAmountWithTax() { + return amount + taxCalculator.calculate(amount); + } + +} \ No newline at end of file diff --git a/separated-interface/src/main/java/com/iluwatar/separatedinterface/invoice/TaxCalculator.java b/separated-interface/src/main/java/com/iluwatar/separatedinterface/invoice/TaxCalculator.java new file mode 100644 index 000000000000..aa4b81a84995 --- /dev/null +++ b/separated-interface/src/main/java/com/iluwatar/separatedinterface/invoice/TaxCalculator.java @@ -0,0 +1,30 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.separatedinterface.invoice; + +public interface TaxCalculator { + + double calculate(double amount); + +} diff --git a/separated-interface/src/main/java/com/iluwatar/separatedinterface/taxes/DomesticTaxCalculator.java b/separated-interface/src/main/java/com/iluwatar/separatedinterface/taxes/DomesticTaxCalculator.java new file mode 100644 index 000000000000..788afb90ab85 --- /dev/null +++ b/separated-interface/src/main/java/com/iluwatar/separatedinterface/taxes/DomesticTaxCalculator.java @@ -0,0 +1,40 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.separatedinterface.taxes; + +import com.iluwatar.separatedinterface.invoice.TaxCalculator; + +/** + * TaxCalculator for Domestic goods with 20% tax. + */ +public class DomesticTaxCalculator implements TaxCalculator { + + public static final double TAX_PERCENTAGE = 20; + + @Override + public double calculate(double amount) { + return amount * TAX_PERCENTAGE / 100.0; + } + +} diff --git a/separated-interface/src/main/java/com/iluwatar/separatedinterface/taxes/ForeignTaxCalculator.java b/separated-interface/src/main/java/com/iluwatar/separatedinterface/taxes/ForeignTaxCalculator.java new file mode 100644 index 000000000000..c2b12e2f5637 --- /dev/null +++ b/separated-interface/src/main/java/com/iluwatar/separatedinterface/taxes/ForeignTaxCalculator.java @@ -0,0 +1,40 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.separatedinterface.taxes; + +import com.iluwatar.separatedinterface.invoice.TaxCalculator; + +/** + * TaxCalculator for foreign goods with 60% tax. + */ +public class ForeignTaxCalculator implements TaxCalculator { + + public static final double TAX_PERCENTAGE = 60; + + @Override + public double calculate(double amount) { + return amount * TAX_PERCENTAGE / 100.0; + } + +}
diff --git a/separated-interface/src/test/java/com/iluwatar/separatedinterface/AppTest.java b/separated-interface/src/test/java/com/iluwatar/separatedinterface/AppTest.java new file mode 100644 index 000000000000..4114f9bb73d0 --- /dev/null +++ b/separated-interface/src/test/java/com/iluwatar/separatedinterface/AppTest.java @@ -0,0 +1,41 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.separatedinterface; + +import org.junit.jupiter.api.Test; + +import com.iluwatar.separatedinterface.App; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +/** + * Application test. + */ +class AppTest { + + @Test + void shouldExecuteWithoutException() { + assertDoesNotThrow(() -> App.main(new String[]{})); + } +} diff --git a/separated-interface/src/test/java/com/iluwatar/separatedinterface/invoice/InvoiceGeneratorTest.java b/separated-interface/src/test/java/com/iluwatar/separatedinterface/invoice/InvoiceGeneratorTest.java new file mode 100644 index 000000000000..ac75d3b70c69 --- /dev/null +++ b/separated-interface/src/test/java/com/iluwatar/separatedinterface/invoice/InvoiceGeneratorTest.java @@ -0,0 +1,48 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.separatedinterface.invoice; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import static org.mockito.Mockito.*; + +public class InvoiceGeneratorTest { + + private InvoiceGenerator target; + + @Test + public void testGenerateTax() { + var productCost = 50.0; + var tax = 10.0; + TaxCalculator taxCalculatorMock = mock(TaxCalculator.class); + doReturn(tax).when(taxCalculatorMock).calculate(productCost); + + target = new InvoiceGenerator(productCost, taxCalculatorMock); + + Assertions.assertEquals(target.getAmountWithTax(), productCost + tax); + verify(taxCalculatorMock, times(1)).calculate(productCost); + } + +} diff --git a/separated-interface/src/test/java/com/iluwatar/separatedinterface/taxes/DomesticTaxCalculatorTest.java b/separated-interface/src/test/java/com/iluwatar/separatedinterface/taxes/DomesticTaxCalculatorTest.java new file mode 100644 index 000000000000..dac3ec2d6a28 --- /dev/null +++ b/separated-interface/src/test/java/com/iluwatar/separatedinterface/taxes/DomesticTaxCalculatorTest.java @@ -0,0 +1,41 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.separatedinterface.taxes; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class DomesticTaxCalculatorTest { + + private DomesticTaxCalculator target; + + @Test + public void testTaxCalculation(){ + target = new DomesticTaxCalculator(); + + var tax=target.calculate(100.0); + Assertions.assertEquals(tax,20.0); + } + +} diff --git a/separated-interface/src/test/java/com/iluwatar/separatedinterface/taxes/ForeignTaxCalculatorTest.java b/separated-interface/src/test/java/com/iluwatar/separatedinterface/taxes/ForeignTaxCalculatorTest.java new file mode 100644 index 000000000000..22526b6dfc13 --- /dev/null +++ b/separated-interface/src/test/java/com/iluwatar/separatedinterface/taxes/ForeignTaxCalculatorTest.java @@ -0,0 +1,41 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.separatedinterface.taxes; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class ForeignTaxCalculatorTest { + + private ForeignTaxCalculator target; + + @Test + public void testTaxCalculation(){ + target = new ForeignTaxCalculator(); + + var tax=target.calculate(100.0); + Assertions.assertEquals(tax,60.0); + } + +}
train
train
2020-09-06T18:56:07
"2020-07-07T18:04:05Z"
iluwatar
train
iluwatar/java-design-patterns/1500_1529
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1500
iluwatar/java-design-patterns/1529
[ "connected" ]
a125879d15e82af50b757baa9f7d81efbd1c3235
f0067828058d87352bcc7a072a53837b47f235b8
[ "I'd like to take this issue. Thank you in advance.", "Yes @ToxicDreamz, go ahead ☺️ ", "Half way through upgrading, one test case seems to be causing an issue, within the **Serverless** module, in specific the **`SavePersonApiHandlerTest#handleRequestSavePersonException()`** method. I do not have any knowledge of the AWS library, which is why I chose not to mess around with it. \r\n\r\nInitially the DynamoDBMapper was being Mocked with Mockito, and was causing issues once the tests were upgraded to JUnit 5 stating that the class could not be mocked, but as stated in the official Mockito guidelines, a type **should not be mocked if it doesn't belong to you**. See attached link below for details.\r\n\r\nhttps://github.com/mockito/mockito/wiki/How-to-write-good-tests#dont-mock-a-type-you-dont-own\r\n\r\n### Suggestion.\r\nA new issue should be opened to address that certain test case, as of now the test case is commented out and marked with a **_TODO_**\r\n\r\n\r\n### Displayed Error\r\n\r\n```\r\n> \r\n> Caused by: com.amazonaws.SdkClientException: Unable to find a region via the region provider chain. Must provide an explicit region in the builder or setup environment to supply a region.\r\n> \tat com.amazonaws.client.builder.AwsClientBuilder.setRegion(AwsClientBuilder.java:371)\r\n> \tat com.amazonaws.client.builder.AwsClientBuilder.configureMutableProperties(AwsClientBuilder.java:337)\r\n> \tat com.amazonaws.client.builder.AwsSyncClientBuilder.build(AwsSyncClientBuilder.java:46)\r\n> \tat com.iluwatar.serverless.baas.api.SavePersonApiHandlerTest.<clinit>(SavePersonApiHandlerTest.java:58)\r\n> \t... 53 more\r\n```\r\n\r\nError after supplying region`\r\n\r\n```\r\n> com.amazonaws.SdkClientException: Unable to load AWS credentials from any provider in the chain\r\n> \r\n> \tat com.amazonaws.auth.AWSCredentialsProviderChain.getCredentials(AWSCredentialsProviderChain.java:131)\r\n> \tat com.amazonaws.http.AmazonHttpClient$RequestExecutor.getCredentialsFromContext(AmazonHttpClient.java:1164)\r\n> \tat com.amazonaws.http.AmazonHttpClient$RequestExecutor.runBeforeRequestHandlers(AmazonHttpClient.java:762)\r\n> \tat com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:724)\r\n> \tat com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:717)\r\n> \tat com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:699)\r\n> \tat com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:667)\r\n> \tat com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:649)\r\n> \tat com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:513)\r\n> \tat com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.doInvoke(AmazonDynamoDBClient.java:3082)\r\n> \tat com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.invoke(AmazonDynamoDBClient.java:3058)\r\n> \tat com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.executePutItem(AmazonDynamoDBClient.java:2119)\r\n> \tat com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.putItem(AmazonDynamoDBClient.java:2094)\r\n> \tat com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper$SaveObjectHandler.doPutItem(DynamoDBMapper.java:883)\r\n> \tat com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper$1.executeLowLevelRequest(DynamoDBMapper.java:536)\r\n> \tat com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper$SaveObjectHandler.execute(DynamoDBMapper.java:733)\r\n> \tat com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.save(DynamoDBMapper.java:623)\r\n> \tat com.amazonaws.services.dynamodbv2.datamodeling.AbstractDynamoDBMapper.save(AbstractDynamoDBMapper.java:123)\r\n> \tat com.iluwatar.serverless.baas.api.SavePersonApiHandler.handleRequest(SavePersonApiHandler.java:50)\r\n> \tat com.iluwatar.serverless.baas.api.SavePersonApiHandlerTest.handleRequestSavePersonSuccessful(SavePersonApiHandlerTest.java:76)\r\n> \tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n> \tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n> \tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n> \tat java.base/java.lang.reflect.Method.invoke(Method.java:567)\r\n> \tat org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:675)\r\n> \tat org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)\r\n> \tat org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:125)\r\n> \tat org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:132)\r\n> \tat org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:124)\r\n> \tat org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:74)\r\n> \tat org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)\r\n> \tat org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)\r\n> \tat org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:104)\r\n> \tat org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:62)\r\n> \tat org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:43)\r\n> \tat org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:35)\r\n> \tat org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)\r\n> \tat org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)\r\n> \tat org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:202)\r\n> \tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\r\n> \tat org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:198)\r\n> \tat org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)\r\n> \tat org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:69)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)\r\n> \tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)\r\n> \tat org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)\r\n> \tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)\r\n> \tat java.base/java.util.ArrayList.forEach(ArrayList.java:1507)\r\n> \tat org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)\r\n> \tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)\r\n> \tat org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)\r\n> \tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)\r\n> \tat java.base/java.util.ArrayList.forEach(ArrayList.java:1507)\r\n> \tat org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)\r\n> \tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)\r\n> \tat org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)\r\n> \tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)\r\n> \tat org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)\r\n> \tat org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)\r\n> \tat org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)\r\n> \tat org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)\r\n> \tat org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)\r\n> \tat org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)\r\n> \tat org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)\r\n> \tat org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)\r\n> \tat com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)\r\n> \tat com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)\r\n> \tat com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)\r\n> \tat com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)\r\n\r\n```\r\n\r\n", "Overall the serverless module needs to be looked at, more tests are causing the same issues due to them not being able to be mocked.", "@ToxicDreamz FYI: I created #1505 which removes the dependency of `subclass-sandbox` to Rule, which is a JUnit 4 only feature.", "@stefanbirkner Okay, thank you for the heads up. I'll wait for @iluwatar to merge that PR, until I continue with that module.", "It's merged now", "Using JUnit 5 in Trampoline module. PR #1529 created.", "I want to work on this issue if its is still unassigned .", "Ok @sgarg5794 ", "I'm working on updating all the modules to JUnit5 right now. @ohbus ", "Sure @charlesfinley you're good to go!", "> Sure @charlesfinley you're good to go!\r\n\r\nSorry I opened a new PR for this - #1668 ", "@charlesfinley no need to be sorry for 😄 It is easier for us to review code in smaller chunks and this helps a lot 💯 \r\n\r\nThank you so much for your help!", "> @charlesfinley no need to be sorry for 😄 It is easier for us to review code in smaller chunks and this helps a lot 💯\r\n> \r\n> Thank you so much for your help!\r\n\r\nThis issue should probably be closed since the PR was merged and we have 2 new issues identifying the only modules lacking JUnit5. ", "@charlesfinley great work!\r\n\r\nWe will close this issue for sure.", "This issue has been partially addressed using #1542 and #1668 thanks to @charlesfinley \r\n\r\nTests from two modules [**serverless**](https://github.com/iluwatar/java-design-patterns/tree/master/serverless) and [**naked-objects**](https://github.com/iluwatar/java-design-patterns/tree/master/naked-objects) are not being executed.\r\n\r\nRespective issues have been opened for resolving the tests in favour of these two modules.\r\n- [ ] #1667\r\n- [ ] #1669\r\n\r\nResolving these two issues should close this [current issue](https://github.com/iluwatar/java-design-patterns/issues/1500)", "@iluwatar let me know how can I help with this, I am confused about the status of the what has been resolved and what is pending.", "Thanks for asking @anuragagarwal561994. I think the only remaining issue is that naked objects pattern still uses JUnit 4. Resolving this is covered by issues https://github.com/iluwatar/java-design-patterns/issues/1669 and https://github.com/iluwatar/java-design-patterns/issues/1683. I think we should close this task." ]
[]
"2020-09-27T13:31:51Z"
[ "info: help wanted", "epic: build issue", "epic: dependencies", "type: refactoring" ]
Use the same JUnit version everywhere
At the moment there are some modules that are still using JUnit 4. Most of the codebase uses JUnit 5, but even with that there are different versions. For example `unit-of-work` and `partial-response` declare their own versions. In this ticket let's try to apply the same version of JUnit 5 everywhere upgrading from JUnit 4 where needed. ## This issue has been partially addressed using #1542 and #1668 Tests from two modules [**serverless**](https://github.com/iluwatar/java-design-patterns/tree/master/serverless) and [**naked-objects**](https://github.com/iluwatar/java-design-patterns/tree/master/naked-objects) are not being executed. Respective issues have been opened for resolving the tests in favour of these two modules. - [x] #1667 against [**serverless**](https://github.com/iluwatar/java-design-patterns/tree/master/serverless) - [ ] #1669 against [**naked-objects**](https://github.com/iluwatar/java-design-patterns/tree/master/naked-objects) Resolving these two issues should close this [current issue](https://github.com/iluwatar/java-design-patterns/issues/1500)
[ "trampoline/pom.xml", "trampoline/src/main/java/com/iluwatar/trampoline/Trampoline.java" ]
[ "trampoline/pom.xml", "trampoline/src/main/java/com/iluwatar/trampoline/Trampoline.java" ]
[ "trampoline/src/test/java/com/iluwatar/trampoline/TrampolineAppTest.java" ]
diff --git a/trampoline/pom.xml b/trampoline/pom.xml index fff117bf8a72..d78236473725 100644 --- a/trampoline/pom.xml +++ b/trampoline/pom.xml @@ -35,11 +35,6 @@ </parent> <artifactId>trampoline</artifactId> <dependencies> - <dependency> - <groupId>junit</groupId> - <artifactId>junit</artifactId> - <scope>test</scope> - </dependency> <dependency> <groupId>org.junit.jupiter</groupId> diff --git a/trampoline/src/main/java/com/iluwatar/trampoline/Trampoline.java b/trampoline/src/main/java/com/iluwatar/trampoline/Trampoline.java index 36ad73e3e961..16e34ff10e01 100644 --- a/trampoline/src/main/java/com/iluwatar/trampoline/Trampoline.java +++ b/trampoline/src/main/java/com/iluwatar/trampoline/Trampoline.java @@ -98,12 +98,12 @@ public T get() { return trampoline(this); } - T trampoline(final Trampoline<T> trampoline) { + private T trampoline(final Trampoline<T> trampoline) { return Stream.iterate(trampoline, Trampoline::jump) .filter(Trampoline::complete) .findFirst() .map(Trampoline::result) - .orElseThrow(); + .get(); } }; }
diff --git a/trampoline/src/test/java/com/iluwatar/trampoline/TrampolineAppTest.java b/trampoline/src/test/java/com/iluwatar/trampoline/TrampolineAppTest.java index c5d6571cdd51..664a95634f5c 100644 --- a/trampoline/src/test/java/com/iluwatar/trampoline/TrampolineAppTest.java +++ b/trampoline/src/test/java/com/iluwatar/trampoline/TrampolineAppTest.java @@ -23,10 +23,9 @@ package com.iluwatar.trampoline; -import static org.junit.Assert.assertEquals; - -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; /** * Test for trampoline pattern. @@ -37,7 +36,7 @@ public class TrampolineAppTest { @Test public void testTrampolineWithFactorialFunction() { long result = TrampolineApp.loop(10, 1).result(); - assertEquals("Be equal", 3628800, result); + assertEquals(3_628_800, result); } } \ No newline at end of file
test
train
2020-09-26T12:01:58
"2020-08-21T14:32:50Z"
iluwatar
train
iluwatar/java-design-patterns/1500_1542
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1500
iluwatar/java-design-patterns/1542
[ "keyword_issue_to_pr", "connected" ]
c3c90e2bd451cdd60947704d1250c8b245881199
903453229cb7d5996f4f52a5f5d88f34e6eb1d5a
[ "I'd like to take this issue. Thank you in advance.", "Yes @ToxicDreamz, go ahead ☺️ ", "Half way through upgrading, one test case seems to be causing an issue, within the **Serverless** module, in specific the **`SavePersonApiHandlerTest#handleRequestSavePersonException()`** method. I do not have any knowledge of the AWS library, which is why I chose not to mess around with it. \r\n\r\nInitially the DynamoDBMapper was being Mocked with Mockito, and was causing issues once the tests were upgraded to JUnit 5 stating that the class could not be mocked, but as stated in the official Mockito guidelines, a type **should not be mocked if it doesn't belong to you**. See attached link below for details.\r\n\r\nhttps://github.com/mockito/mockito/wiki/How-to-write-good-tests#dont-mock-a-type-you-dont-own\r\n\r\n### Suggestion.\r\nA new issue should be opened to address that certain test case, as of now the test case is commented out and marked with a **_TODO_**\r\n\r\n\r\n### Displayed Error\r\n\r\n```\r\n> \r\n> Caused by: com.amazonaws.SdkClientException: Unable to find a region via the region provider chain. Must provide an explicit region in the builder or setup environment to supply a region.\r\n> \tat com.amazonaws.client.builder.AwsClientBuilder.setRegion(AwsClientBuilder.java:371)\r\n> \tat com.amazonaws.client.builder.AwsClientBuilder.configureMutableProperties(AwsClientBuilder.java:337)\r\n> \tat com.amazonaws.client.builder.AwsSyncClientBuilder.build(AwsSyncClientBuilder.java:46)\r\n> \tat com.iluwatar.serverless.baas.api.SavePersonApiHandlerTest.<clinit>(SavePersonApiHandlerTest.java:58)\r\n> \t... 53 more\r\n```\r\n\r\nError after supplying region`\r\n\r\n```\r\n> com.amazonaws.SdkClientException: Unable to load AWS credentials from any provider in the chain\r\n> \r\n> \tat com.amazonaws.auth.AWSCredentialsProviderChain.getCredentials(AWSCredentialsProviderChain.java:131)\r\n> \tat com.amazonaws.http.AmazonHttpClient$RequestExecutor.getCredentialsFromContext(AmazonHttpClient.java:1164)\r\n> \tat com.amazonaws.http.AmazonHttpClient$RequestExecutor.runBeforeRequestHandlers(AmazonHttpClient.java:762)\r\n> \tat com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:724)\r\n> \tat com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:717)\r\n> \tat com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:699)\r\n> \tat com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:667)\r\n> \tat com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:649)\r\n> \tat com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:513)\r\n> \tat com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.doInvoke(AmazonDynamoDBClient.java:3082)\r\n> \tat com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.invoke(AmazonDynamoDBClient.java:3058)\r\n> \tat com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.executePutItem(AmazonDynamoDBClient.java:2119)\r\n> \tat com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.putItem(AmazonDynamoDBClient.java:2094)\r\n> \tat com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper$SaveObjectHandler.doPutItem(DynamoDBMapper.java:883)\r\n> \tat com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper$1.executeLowLevelRequest(DynamoDBMapper.java:536)\r\n> \tat com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper$SaveObjectHandler.execute(DynamoDBMapper.java:733)\r\n> \tat com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.save(DynamoDBMapper.java:623)\r\n> \tat com.amazonaws.services.dynamodbv2.datamodeling.AbstractDynamoDBMapper.save(AbstractDynamoDBMapper.java:123)\r\n> \tat com.iluwatar.serverless.baas.api.SavePersonApiHandler.handleRequest(SavePersonApiHandler.java:50)\r\n> \tat com.iluwatar.serverless.baas.api.SavePersonApiHandlerTest.handleRequestSavePersonSuccessful(SavePersonApiHandlerTest.java:76)\r\n> \tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n> \tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n> \tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n> \tat java.base/java.lang.reflect.Method.invoke(Method.java:567)\r\n> \tat org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:675)\r\n> \tat org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)\r\n> \tat org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:125)\r\n> \tat org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:132)\r\n> \tat org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:124)\r\n> \tat org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:74)\r\n> \tat org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)\r\n> \tat org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)\r\n> \tat org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:104)\r\n> \tat org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:62)\r\n> \tat org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:43)\r\n> \tat org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:35)\r\n> \tat org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)\r\n> \tat org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)\r\n> \tat org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:202)\r\n> \tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\r\n> \tat org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:198)\r\n> \tat org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)\r\n> \tat org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:69)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)\r\n> \tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)\r\n> \tat org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)\r\n> \tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)\r\n> \tat java.base/java.util.ArrayList.forEach(ArrayList.java:1507)\r\n> \tat org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)\r\n> \tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)\r\n> \tat org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)\r\n> \tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)\r\n> \tat java.base/java.util.ArrayList.forEach(ArrayList.java:1507)\r\n> \tat org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)\r\n> \tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)\r\n> \tat org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)\r\n> \tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)\r\n> \tat org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)\r\n> \tat org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)\r\n> \tat org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)\r\n> \tat org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)\r\n> \tat org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)\r\n> \tat org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)\r\n> \tat org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)\r\n> \tat org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)\r\n> \tat org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)\r\n> \tat com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)\r\n> \tat com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)\r\n> \tat com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)\r\n> \tat com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)\r\n\r\n```\r\n\r\n", "Overall the serverless module needs to be looked at, more tests are causing the same issues due to them not being able to be mocked.", "@ToxicDreamz FYI: I created #1505 which removes the dependency of `subclass-sandbox` to Rule, which is a JUnit 4 only feature.", "@stefanbirkner Okay, thank you for the heads up. I'll wait for @iluwatar to merge that PR, until I continue with that module.", "It's merged now", "Using JUnit 5 in Trampoline module. PR #1529 created.", "I want to work on this issue if its is still unassigned .", "Ok @sgarg5794 ", "I'm working on updating all the modules to JUnit5 right now. @ohbus ", "Sure @charlesfinley you're good to go!", "> Sure @charlesfinley you're good to go!\r\n\r\nSorry I opened a new PR for this - #1668 ", "@charlesfinley no need to be sorry for 😄 It is easier for us to review code in smaller chunks and this helps a lot 💯 \r\n\r\nThank you so much for your help!", "> @charlesfinley no need to be sorry for 😄 It is easier for us to review code in smaller chunks and this helps a lot 💯\r\n> \r\n> Thank you so much for your help!\r\n\r\nThis issue should probably be closed since the PR was merged and we have 2 new issues identifying the only modules lacking JUnit5. ", "@charlesfinley great work!\r\n\r\nWe will close this issue for sure.", "This issue has been partially addressed using #1542 and #1668 thanks to @charlesfinley \r\n\r\nTests from two modules [**serverless**](https://github.com/iluwatar/java-design-patterns/tree/master/serverless) and [**naked-objects**](https://github.com/iluwatar/java-design-patterns/tree/master/naked-objects) are not being executed.\r\n\r\nRespective issues have been opened for resolving the tests in favour of these two modules.\r\n- [ ] #1667\r\n- [ ] #1669\r\n\r\nResolving these two issues should close this [current issue](https://github.com/iluwatar/java-design-patterns/issues/1500)", "@iluwatar let me know how can I help with this, I am confused about the status of the what has been resolved and what is pending.", "Thanks for asking @anuragagarwal561994. I think the only remaining issue is that naked objects pattern still uses JUnit 4. Resolving this is covered by issues https://github.com/iluwatar/java-design-patterns/issues/1669 and https://github.com/iluwatar/java-design-patterns/issues/1683. I think we should close this task." ]
[ "Could you please describe this change a bit, why is it needed? This particular snippet is also part of the pattern's `README.md` (which is rendered on the https://java-design-patterns.com web site) so all the changes should be reflected there.", "@charlesfinley can you please clarify on this part as why we modified this access specifier to `private`\r\n\r\nWe would love to merge the code to master.", "Will update soon with explanation. Sorry for the delay. ", "@iluwatar @ohbus - Reverted the change. It's no longer required. ", "Please add an extra line here", "add an empty line here", "```suggestion\r\nimport static org.junit.jupiter.api.Assertions.assertTrue;\r\nimport static org.junit.jupiter.api.Assertions.assertFalse;\r\n```", "Fixed the star import. ", "You want an empty line after the method declaration and before the assertion? ", "Yes an empty line at the end of the file.", "Ah, duh. I need coffee. Updated!", "Done" ]
"2020-10-02T03:16:36Z"
[ "info: help wanted", "epic: build issue", "epic: dependencies", "type: refactoring" ]
Use the same JUnit version everywhere
At the moment there are some modules that are still using JUnit 4. Most of the codebase uses JUnit 5, but even with that there are different versions. For example `unit-of-work` and `partial-response` declare their own versions. In this ticket let's try to apply the same version of JUnit 5 everywhere upgrading from JUnit 4 where needed. ## This issue has been partially addressed using #1542 and #1668 Tests from two modules [**serverless**](https://github.com/iluwatar/java-design-patterns/tree/master/serverless) and [**naked-objects**](https://github.com/iluwatar/java-design-patterns/tree/master/naked-objects) are not being executed. Respective issues have been opened for resolving the tests in favour of these two modules. - [x] #1667 against [**serverless**](https://github.com/iluwatar/java-design-patterns/tree/master/serverless) - [ ] #1669 against [**naked-objects**](https://github.com/iluwatar/java-design-patterns/tree/master/naked-objects) Resolving these two issues should close this [current issue](https://github.com/iluwatar/java-design-patterns/issues/1500)
[ "pom.xml", "saga/pom.xml", "trampoline/src/main/java/com/iluwatar/trampoline/Trampoline.java", "update-method/pom.xml" ]
[ "pom.xml", "saga/pom.xml", "trampoline/src/main/java/com/iluwatar/trampoline/Trampoline.java", "update-method/pom.xml" ]
[ "saga/src/test/java/com/iluwatar/saga/choreography/SagaApplicationTest.java", "saga/src/test/java/com/iluwatar/saga/choreography/SagaChoreographyTest.java", "saga/src/test/java/com/iluwatar/saga/orchestration/SagaApplicationTest.java", "saga/src/test/java/com/iluwatar/saga/orchestration/SagaOrchestratorInternallyTest.java", "saga/src/test/java/com/iluwatar/saga/orchestration/SagaOrchestratorTest.java", "update-method/src/test/java/com/iluwatar/updatemethod/AppTest.java", "update-method/src/test/java/com/iluwatar/updatemethod/SkeletonTest.java", "update-method/src/test/java/com/iluwatar/updatemethod/StatueTest.java", "update-method/src/test/java/com/iluwatar/updatemethod/WorldTest.java" ]
diff --git a/pom.xml b/pom.xml index 48fa6fdcf801..8b00646c5e2b 100644 --- a/pom.xml +++ b/pom.xml @@ -41,8 +41,8 @@ <spring-data.version>2.0.14.RELEASE</spring-data.version> <h2.version>1.4.190</h2.version> <junit.version>4.12</junit.version> - <junit-jupiter.version>5.5.2</junit-jupiter.version> - <junit-vintage.version>${junit.version}.2</junit-vintage.version> + <junit-jupiter.version>5.7.1</junit-jupiter.version> + <junit-vintage.version>${junit-jupiter.version}</junit-vintage.version> <sping-test-junit5.version>1.0.2</sping-test-junit5.version> <compiler.version>3.8.1</compiler.version> <jacoco.version>0.8.6</jacoco.version> @@ -274,12 +274,6 @@ <artifactId>camel-stream</artifactId> <version>${camel.version}</version> </dependency> - <dependency> - <groupId>junit</groupId> - <artifactId>junit</artifactId> - <version>${junit.version}</version> - <scope>test</scope> - </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> diff --git a/saga/pom.xml b/saga/pom.xml index 07d327885258..80eb70f752ad 100644 --- a/saga/pom.xml +++ b/saga/pom.xml @@ -35,11 +35,6 @@ <artifactId>saga</artifactId> <dependencies> - <dependency> - <groupId>junit</groupId> - <artifactId>junit</artifactId> - <scope>test</scope> - </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> diff --git a/trampoline/src/main/java/com/iluwatar/trampoline/Trampoline.java b/trampoline/src/main/java/com/iluwatar/trampoline/Trampoline.java index b28a148039cb..1d2ea91d31a6 100644 --- a/trampoline/src/main/java/com/iluwatar/trampoline/Trampoline.java +++ b/trampoline/src/main/java/com/iluwatar/trampoline/Trampoline.java @@ -98,7 +98,7 @@ public T get() { return trampoline(this); } - private T trampoline(final Trampoline<T> trampoline) { + T trampoline(final Trampoline<T> trampoline) { return Stream.iterate(trampoline, Trampoline::jump) .filter(Trampoline::complete) .findFirst() diff --git a/update-method/pom.xml b/update-method/pom.xml index b49ab3c070b2..b70520a99898 100644 --- a/update-method/pom.xml +++ b/update-method/pom.xml @@ -35,10 +35,6 @@ <artifactId>update-method</artifactId> <dependencies> - <dependency> - <groupId>junit</groupId> - <artifactId>junit</artifactId> - </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId>
diff --git a/saga/src/test/java/com/iluwatar/saga/choreography/SagaApplicationTest.java b/saga/src/test/java/com/iluwatar/saga/choreography/SagaApplicationTest.java index 52b407b57294..67ac0f2fae1d 100644 --- a/saga/src/test/java/com/iluwatar/saga/choreography/SagaApplicationTest.java +++ b/saga/src/test/java/com/iluwatar/saga/choreography/SagaApplicationTest.java @@ -23,18 +23,19 @@ package com.iluwatar.saga.choreography; -import com.iluwatar.saga.orchestration.SagaApplication; -import org.junit.Test; - import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import com.iluwatar.saga.orchestration.SagaApplication; +import org.junit.jupiter.api.Test; + /*** * empty test */ -public class SagaApplicationTest { +class SagaApplicationTest { + @Test - public void shouldExecuteWithoutException() { + void shouldExecuteWithoutException() { assertDoesNotThrow(() -> SagaApplication.main(new String[]{})); } -} \ No newline at end of file +} diff --git a/saga/src/test/java/com/iluwatar/saga/choreography/SagaChoreographyTest.java b/saga/src/test/java/com/iluwatar/saga/choreography/SagaChoreographyTest.java index b1ddcf13f465..749a66ac5617 100644 --- a/saga/src/test/java/com/iluwatar/saga/choreography/SagaChoreographyTest.java +++ b/saga/src/test/java/com/iluwatar/saga/choreography/SagaChoreographyTest.java @@ -23,24 +23,25 @@ package com.iluwatar.saga.choreography; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * test to check choreography saga */ -public class SagaChoreographyTest { +class SagaChoreographyTest { @Test - public void executeTest() { + void executeTest() { var sd = serviceDiscovery(); var service = sd.findAny(); var badOrderSaga = service.execute(newSaga("bad_order")); var goodOrderSaga = service.execute(newSaga("good_order")); - Assert.assertEquals(badOrderSaga.getResult(), Saga.SagaResult.ROLLBACKED); - Assert.assertEquals(goodOrderSaga.getResult(), Saga.SagaResult.FINISHED); + assertEquals(Saga.SagaResult.ROLLBACKED, badOrderSaga.getResult()); + assertEquals(Saga.SagaResult.FINISHED, goodOrderSaga.getResult()); } private static Saga newSaga(Object value) { diff --git a/saga/src/test/java/com/iluwatar/saga/orchestration/SagaApplicationTest.java b/saga/src/test/java/com/iluwatar/saga/orchestration/SagaApplicationTest.java index 1ebb9de4428a..29a2f7eb60a8 100644 --- a/saga/src/test/java/com/iluwatar/saga/orchestration/SagaApplicationTest.java +++ b/saga/src/test/java/com/iluwatar/saga/orchestration/SagaApplicationTest.java @@ -23,15 +23,15 @@ package com.iluwatar.saga.orchestration; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * empty test */ -public class SagaApplicationTest { +class SagaApplicationTest { @Test - public void mainTest() { + void mainTest() { SagaApplication.main(new String[]{}); } -} \ No newline at end of file +} diff --git a/saga/src/test/java/com/iluwatar/saga/orchestration/SagaOrchestratorInternallyTest.java b/saga/src/test/java/com/iluwatar/saga/orchestration/SagaOrchestratorInternallyTest.java index 6a1a257df716..23635d1e6665 100644 --- a/saga/src/test/java/com/iluwatar/saga/orchestration/SagaOrchestratorInternallyTest.java +++ b/saga/src/test/java/com/iluwatar/saga/orchestration/SagaOrchestratorInternallyTest.java @@ -23,28 +23,30 @@ 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; -import org.junit.Assert; -import org.junit.Test; /** * test to test orchestration logic */ -public class SagaOrchestratorInternallyTest { +class SagaOrchestratorInternallyTest { private final List<String> records = new ArrayList<>(); @Test - public void executeTest() { + void executeTest() { var sagaOrchestrator = new SagaOrchestrator(newSaga(), serviceDiscovery()); var result = sagaOrchestrator.execute(1); - Assert.assertEquals(result, Result.ROLLBACK); - Assert.assertArrayEquals( - records.toArray(new String[]{}), - new String[]{"+1", "+2", "+3", "+4", "-4", "-3", "-2", "-1"}); + assertEquals(Result.ROLLBACK, result); + assertArrayEquals( + new String[]{"+1", "+2", "+3", "+4", "-4", "-3", "-2", "-1"}, + records.toArray(new String[]{})); } private static Saga newSaga() { diff --git a/saga/src/test/java/com/iluwatar/saga/orchestration/SagaOrchestratorTest.java b/saga/src/test/java/com/iluwatar/saga/orchestration/SagaOrchestratorTest.java index 7dd4c318059a..2a1da99810e4 100644 --- a/saga/src/test/java/com/iluwatar/saga/orchestration/SagaOrchestratorTest.java +++ b/saga/src/test/java/com/iluwatar/saga/orchestration/SagaOrchestratorTest.java @@ -23,22 +23,23 @@ package com.iluwatar.saga.orchestration; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * test to check general logic */ -public class SagaOrchestratorTest { +class SagaOrchestratorTest { @Test - public void execute() { + void execute() { SagaOrchestrator sagaOrchestrator = new SagaOrchestrator(newSaga(), serviceDiscovery()); Saga.Result badOrder = sagaOrchestrator.execute("bad_order"); Saga.Result crashedOrder = sagaOrchestrator.execute("crashed_order"); - Assert.assertEquals(badOrder, Saga.Result.ROLLBACK); - Assert.assertEquals(crashedOrder, Saga.Result.CRASHED); + assertEquals(Saga.Result.ROLLBACK, badOrder); + assertEquals(Saga.Result.CRASHED, crashedOrder); } private static Saga newSaga() { diff --git a/update-method/src/test/java/com/iluwatar/updatemethod/AppTest.java b/update-method/src/test/java/com/iluwatar/updatemethod/AppTest.java index 6158e74912bc..9c5c2a1e2bb2 100644 --- a/update-method/src/test/java/com/iluwatar/updatemethod/AppTest.java +++ b/update-method/src/test/java/com/iluwatar/updatemethod/AppTest.java @@ -23,14 +23,14 @@ package com.iluwatar.updatemethod; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -public class AppTest { +class AppTest { @Test - public void shouldExecuteApplicationWithoutException() { + void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } } diff --git a/update-method/src/test/java/com/iluwatar/updatemethod/SkeletonTest.java b/update-method/src/test/java/com/iluwatar/updatemethod/SkeletonTest.java index 2562180b8f56..a30dd26cb712 100644 --- a/update-method/src/test/java/com/iluwatar/updatemethod/SkeletonTest.java +++ b/update-method/src/test/java/com/iluwatar/updatemethod/SkeletonTest.java @@ -23,56 +23,60 @@ package com.iluwatar.updatemethod; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -public class SkeletonTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; - private Skeleton skeleton; - @Before - public void setup() { +class SkeletonTest { + + private static Skeleton skeleton; + + @BeforeAll + public static void setup() { skeleton = new Skeleton(1); } - @After - public void tearDown() { + @AfterAll + public static void tearDown() { skeleton = null; } @Test - public void testUpdateForPatrollingLeft() { + void testUpdateForPatrollingLeft() { skeleton.patrollingLeft = true; skeleton.setPosition(50); skeleton.update(); - Assert.assertEquals(49, skeleton.getPosition()); + assertEquals(49, skeleton.getPosition()); } @Test - public void testUpdateForPatrollingRight() { + void testUpdateForPatrollingRight() { skeleton.patrollingLeft = false; skeleton.setPosition(50); skeleton.update(); - Assert.assertEquals(51, skeleton.getPosition()); + assertEquals(51, skeleton.getPosition()); } @Test - public void testUpdateForReverseDirectionFromLeftToRight() { + void testUpdateForReverseDirectionFromLeftToRight() { skeleton.patrollingLeft = true; skeleton.setPosition(1); skeleton.update(); - Assert.assertEquals(0, skeleton.getPosition()); - Assert.assertEquals(false, skeleton.patrollingLeft); + assertEquals(0, skeleton.getPosition()); + assertFalse(skeleton.patrollingLeft); } @Test - public void testUpdateForReverseDirectionFromRightToLeft() { + void testUpdateForReverseDirectionFromRightToLeft() { skeleton.patrollingLeft = false; skeleton.setPosition(99); skeleton.update(); - Assert.assertEquals(100, skeleton.getPosition()); - Assert.assertEquals(true, skeleton.patrollingLeft); + assertEquals(100, skeleton.getPosition()); + assertTrue(skeleton.patrollingLeft); } } diff --git a/update-method/src/test/java/com/iluwatar/updatemethod/StatueTest.java b/update-method/src/test/java/com/iluwatar/updatemethod/StatueTest.java index eea6bbeb1278..3b28ffd5d3cb 100644 --- a/update-method/src/test/java/com/iluwatar/updatemethod/StatueTest.java +++ b/update-method/src/test/java/com/iluwatar/updatemethod/StatueTest.java @@ -23,36 +23,37 @@ package com.iluwatar.updatemethod; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -public class StatueTest { +import static org.junit.jupiter.api.Assertions.assertEquals; - private Statue statue; +class StatueTest { - @Before - public void setup() { + private static Statue statue; + + @BeforeAll + public static void setup() { statue = new Statue(1, 20); } - @After - public void tearDown() { + @AfterAll + public static void tearDown() { statue = null; } @Test - public void testUpdateForPendingShoot() { + void testUpdateForPendingShoot() { statue.frames = 10; statue.update(); - Assert.assertEquals(11, statue.frames); + assertEquals(11, statue.frames); } @Test - public void testUpdateForShooting() { + void testUpdateForShooting() { statue.frames = 19; statue.update(); - Assert.assertEquals(0, statue.frames); + assertEquals(0, statue.frames); } } diff --git a/update-method/src/test/java/com/iluwatar/updatemethod/WorldTest.java b/update-method/src/test/java/com/iluwatar/updatemethod/WorldTest.java index b8d95f140705..843c4a654d21 100644 --- a/update-method/src/test/java/com/iluwatar/updatemethod/WorldTest.java +++ b/update-method/src/test/java/com/iluwatar/updatemethod/WorldTest.java @@ -23,41 +23,44 @@ package com.iluwatar.updatemethod; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -public class WorldTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; - private World world; +class WorldTest { - @Before - public void setup() { + private static World world; + + @BeforeAll + public static void setup() { world = new World(); } - @After - public void tearDown() { + @AfterAll + public static void tearDown() { world = null; } @Test - public void testRun() { + void testRun() { world.run(); - Assert.assertEquals(true, world.isRunning); + assertTrue(world.isRunning); } @Test - public void testStop() { + void testStop() { world.stop(); - Assert.assertEquals(false, world.isRunning); + assertFalse(world.isRunning); } @Test - public void testAddEntity() { + void testAddEntity() { var entity = new Skeleton(1); world.addEntity(entity); - Assert.assertEquals(entity, world.entities.get(0)); + assertEquals(entity, world.entities.get(0)); } }
train
train
2021-03-01T15:50:34
"2020-08-21T14:32:50Z"
iluwatar
train
iluwatar/java-design-patterns/1310_1543
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1310
iluwatar/java-design-patterns/1543
[ "timestamp(timedelta=0.0, similarity=0.8966570528077739)", "keyword_pr_to_issue", "connected" ]
428cbc1027594794cc0aaab17be35e3cacb2b117
14c4710435e89218404086816682012eff023497
[ "Hi @iluwatar \r\nI would like to work on it.", "Ok @viveksb007 ", "Hi @iluwatar,\r\n\r\nI understood that Registry Pattern is similar to `Multiton` pattern, the only difference is no restrictions on numbers of objects.\r\nIn simple words, it stores <key, object> and there is no restriction on number of objects stored.\r\n\r\nSo I am thinking of creating a `CustomerRegistry` which will store customer objects (with `customerId` as key) and provide a global access to them. It requires adding/registering the customer object in the registry. For that I was thinking of creating a `CustomerFactory` which would create a `Customer` object and add it to registry. And anyone can get customer object by giving a `customerId` to registry. \r\n\r\nWanted to clarify is it good adding a `Factory` to create customer object as I don't want any knowledge of registry inside the `Customer` object and don't want to manually add customer object to registry.\r\n\r\nAny inputs would be helpful. \r\nThanks!!\r\n", "I've understood that typically Registry pattern is implemented with separated interface and implementation. Basically there's two methods in the registry object: One to add objects to the registry and another to query them. It's also good to demonstrate how testing is handled in the pattern. To your question whether Factory should be used or not, I would not create one. I think initializing the registry can be simply handled when the program starts i.e. calling something like `addCustomer` multiple times." ]
[ "Add an empty line after this", "Done" ]
"2020-10-02T14:34:12Z"
[ "epic: pattern", "type: feature" ]
Registry pattern
https://www.martinfowler.com/eaaCatalog/registry.html https://stackoverflow.com/questions/16744424/whats-the-difference-between-singleton-and-registry-design-pattern https://wiki.c2.com/?RegistryPattern
[ "pom.xml" ]
[ "pom.xml", "registry/README.md", "registry/etc/registry.urm.puml", "registry/pom.xml", "registry/src/main/java/com/iluwatar/registry/App.java", "registry/src/main/java/com/iluwatar/registry/Customer.java", "registry/src/main/java/com/iluwatar/registry/CustomerRegistry.java" ]
[ "registry/src/test/java/com/iluwatar/registry/CustomerRegistryTest.java" ]
diff --git a/pom.xml b/pom.xml index e7fd2e4b3f87..86cefa13386a 100644 --- a/pom.xml +++ b/pom.xml @@ -195,6 +195,7 @@ <module>strangler</module> <module>arrange-act-assert</module> <module>transaction-script</module> + <module>registry</module> <module>filterer</module> <module>factory</module> <module>separated-interface</module> diff --git a/registry/README.md b/registry/README.md new file mode 100644 index 000000000000..699c13318263 --- /dev/null +++ b/registry/README.md @@ -0,0 +1,86 @@ +--- +layout: pattern +title: Registry +folder: registry +permalink: /patterns/registry/ +categories: Creational +tags: + - Instantiation +--- + +## Intent +Stores the objects of a single class and provide a global point of access to them. +Similar to Multiton pattern, only difference is that in a registry there is no restriction on the number of objects. + +## Explanation + +In Plain Words + +> Registry is a well-known object that other objects can use to find common objects and services. + +**Programmatic Example** +Below is a `Customer` Class + +```java +public class Customer { + + private final String id; + private final String name; + + public Customer(String id, String name) { + this.id = id; + this.name = name; + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } + +} +``` + +This registry of the `Customer` objects is `CustomerRegistry` +```java +public final class CustomerRegistry { + + private static final CustomerRegistry instance = new CustomerRegistry(); + + public static CustomerRegistry getInstance() { + return instance; + } + + private final Map<String, Customer> customerMap; + + private CustomerRegistry() { + customerMap = new ConcurrentHashMap<>(); + } + + public Customer addCustomer(Customer customer) { + return customerMap.put(customer.getId(), customer); + } + + public Customer getCustomer(String id) { + return customerMap.get(id); + } + +} +``` + +## Class diagram +![Registry](./etc/registry.png) + +## Applicability +Use Registry pattern when + +* client wants reference of some object, so client can lookup for that object in the object's registry. + +## Consequences +Large number of bulky objects added to registry would result in a lot of memory consumption as objects in the registry are not garbage collected. + +## Credits +* https://www.martinfowler.com/eaaCatalog/registry.html +* https://wiki.c2.com/?RegistryPattern diff --git a/registry/etc/registry.urm.puml b/registry/etc/registry.urm.puml new file mode 100644 index 000000000000..77c6441fe688 --- /dev/null +++ b/registry/etc/registry.urm.puml @@ -0,0 +1,21 @@ +@startuml +package com.iluwatar.registry { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + } + class Customer { + - id : String + - name : String + + getId() : String + + getName() : String + + toString() : String + } + class CustomerRegistry { + + addCustomer(customer : Customer) + + getCustomer(id : String) + } +} +Customer --> "-addCustomer" CustomerRegistry +@enduml diff --git a/registry/pom.xml b/registry/pom.xml new file mode 100644 index 000000000000..852bcacfd73c --- /dev/null +++ b/registry/pom.xml @@ -0,0 +1,46 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>com.iluwatar</groupId> + <artifactId>java-design-patterns</artifactId> + <version>1.24.0-SNAPSHOT</version> + </parent> + <artifactId>registry</artifactId> + + <dependencies> + <dependency> + <groupId>org.junit.jupiter</groupId> + <artifactId>junit-jupiter-engine</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + </dependency> + </dependencies> + + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-assembly-plugin</artifactId> + <executions> + <execution> + <configuration> + <archive> + <manifest> + <mainClass>com.iluwatar.registry.App</mainClass> + </manifest> + </archive> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> + +</project> diff --git a/registry/src/main/java/com/iluwatar/registry/App.java b/registry/src/main/java/com/iluwatar/registry/App.java new file mode 100644 index 000000000000..a593ce5cc15b --- /dev/null +++ b/registry/src/main/java/com/iluwatar/registry/App.java @@ -0,0 +1,27 @@ +package com.iluwatar.registry; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +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) { + CustomerRegistry customerRegistry = CustomerRegistry.getInstance(); + var john = new Customer("1", "John"); + customerRegistry.addCustomer(john); + + var julia = new Customer("2", "Julia"); + customerRegistry.addCustomer(julia); + + LOGGER.info("John {}", customerRegistry.getCustomer("1")); + LOGGER.info("Julia {}", customerRegistry.getCustomer("2")); + } + +} diff --git a/registry/src/main/java/com/iluwatar/registry/Customer.java b/registry/src/main/java/com/iluwatar/registry/Customer.java new file mode 100644 index 000000000000..354999fdf2ce --- /dev/null +++ b/registry/src/main/java/com/iluwatar/registry/Customer.java @@ -0,0 +1,28 @@ +package com.iluwatar.registry; + +public class Customer { + + private final String id; + private final String name; + + public Customer(String id, String name) { + this.id = id; + this.name = name; + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } + + @Override + public String toString() { + return "Customer{" + + "id='" + id + '\'' + + ", name='" + name + '\'' + + '}'; + } +} diff --git a/registry/src/main/java/com/iluwatar/registry/CustomerRegistry.java b/registry/src/main/java/com/iluwatar/registry/CustomerRegistry.java new file mode 100644 index 000000000000..406d616c678c --- /dev/null +++ b/registry/src/main/java/com/iluwatar/registry/CustomerRegistry.java @@ -0,0 +1,28 @@ +package com.iluwatar.registry; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +public final class CustomerRegistry { + + private static final CustomerRegistry instance = new CustomerRegistry(); + + public static CustomerRegistry getInstance() { + return instance; + } + + private final Map<String, Customer> customerMap; + + private CustomerRegistry() { + customerMap = new ConcurrentHashMap<>(); + } + + public Customer addCustomer(Customer customer) { + return customerMap.put(customer.getId(), customer); + } + + public Customer getCustomer(String id) { + return customerMap.get(id); + } + +}
diff --git a/registry/src/test/java/com/iluwatar/registry/CustomerRegistryTest.java b/registry/src/test/java/com/iluwatar/registry/CustomerRegistryTest.java new file mode 100644 index 000000000000..2919390b9270 --- /dev/null +++ b/registry/src/test/java/com/iluwatar/registry/CustomerRegistryTest.java @@ -0,0 +1,44 @@ +package com.iluwatar.registry; + +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.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +public class CustomerRegistryTest { + + private static CustomerRegistry customerRegistry; + + @BeforeAll + public static void setUp() { + customerRegistry = CustomerRegistry.getInstance(); + } + + @Test + public void shouldBeAbleToAddAndQueryCustomerObjectFromRegistry() { + Customer john = new Customer("1", "john"); + Customer julia = new Customer("2", "julia"); + + customerRegistry.addCustomer(john); + customerRegistry.addCustomer(julia); + + Customer customerWithId1 = customerRegistry.getCustomer("1"); + assertNotNull(customerWithId1); + assertEquals("1", customerWithId1.getId()); + assertEquals("john", customerWithId1.getName()); + + Customer customerWithId2 = customerRegistry.getCustomer("2"); + assertNotNull(customerWithId2); + assertEquals("2", customerWithId2.getId()); + assertEquals("julia", customerWithId2.getName()); + } + + @Test + public void shouldReturnNullWhenQueriedCustomerIsNotInRegistry() { + Customer customerWithId5 = customerRegistry.getCustomer("5"); + assertNull(customerWithId5); + } + +}
train
train
2020-12-07T19:25:59
"2020-07-07T18:00:12Z"
iluwatar
train
iluwatar/java-design-patterns/1569_1570
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1569
iluwatar/java-design-patterns/1570
[ "timestamp(timedelta=0.0, similarity=0.8769966537858309)", "connected" ]
a94615ac54300326b8912a5a365418caed9306bd
5bc61c8c28e770f9b2805a3dc56bfde5fdbbc238
[ "@siavashsoleymani Please provide us some solid references to this pattern.", "Created follow-up ticket https://github.com/iluwatar/java-design-patterns/issues/1617" ]
[ "add an extra line", "add an extra line", "Done, thanks for your suggestions", "A suggestion. You can use Lombok packages from this repo which avoids all the boilerplate code", "agree with you @ravening " ]
"2020-10-16T12:37:42Z"
[ "epic: pattern", "type: enhancement" ]
Data transfer object pattern using Enums
I'm going to implement a DTO pattern using java Enums. In this way the code is going to be more **Type safe**, **Consistent Syntax**, **Consistent Semantics**, and more **Readable & Maintainable**.
[ "pom.xml" ]
[ "data-transfer-object-enum-impl/README.md", "data-transfer-object-enum-impl/etc/data-transfer-object-enum-impl.urm.puml", "data-transfer-object-enum-impl/pom.xml", "data-transfer-object-enum-impl/src/main/java/com/iluwatar/datatransferenum/App.java", "data-transfer-object-enum-impl/src/main/java/com/iluwatar/datatransferenum/Product.java", "data-transfer-object-enum-impl/src/main/java/com/iluwatar/datatransferenum/ProductDto.java", "data-transfer-object-enum-impl/src/main/java/com/iluwatar/datatransferenum/ProductResource.java", "pom.xml" ]
[ "data-transfer-object-enum-impl/src/test/java/com/iluwatar/datatransferenum/AppTest.java" ]
diff --git a/data-transfer-object-enum-impl/README.md b/data-transfer-object-enum-impl/README.md new file mode 100644 index 000000000000..7e6dbc365319 --- /dev/null +++ b/data-transfer-object-enum-impl/README.md @@ -0,0 +1,54 @@ +--- +layout: pattern +title: Data Transfer Object +folder: data-transfer-object +permalink: /patterns/data-transfer-object/ +categories: Architectural +tags: + - Performance +--- + +## Intent + +Pass data with multiple attributes in one shot from client to server, to avoid multiple calls to +remote server. + +## Explanation + +Real world example + +> We need to fetch information about customers from remote database. Instead of querying the +> attributes one at a time, we use DTOs to transfer all the relevant attributes in a single shot. + +In plain words + +> Using DTO relevant information can be fetched with a single backend query. + +Wikipedia says + +> In the field of programming a data transfer object (DTO) is an object that carries data between +> processes. The motivation for its use is that communication between processes is usually done +> resorting to remote interfaces (e.g. web services), where each call is an expensive operation. +> Because the majority of the cost of each call is related to the round-trip time between the client +> and the server, one way of reducing the number of calls is to use an object (the DTO) that +> aggregates the data that would have been transferred by the several calls, but that is served by +> one call only. + +## Class diagram + +![alt text](./etc/dto-enum-uml.png "data-transfer-object") + +## Applicability + +Use the Data Transfer Object pattern when: + +* The client is asking for multiple information. And the information is related. +* When you want to boost the performance to get resources. +* You want reduced number of remote calls. + +## Credits + +* [Design Pattern - Transfer Object Pattern](https://www.tutorialspoint.com/design_pattern/transfer_object_pattern.htm) +* [Data Transfer Object](https://msdn.microsoft.com/en-us/library/ff649585.aspx) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=f27d2644fbe5026ea448791a8ad09c94) +* [Patterns of Enterprise Application Architecture](https://www.amazon.com/gp/product/0321127420/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321127420&linkCode=as2&tag=javadesignpat-20&linkId=014237a67c9d46f384b35e10151956bd) diff --git a/data-transfer-object-enum-impl/etc/data-transfer-object-enum-impl.urm.puml b/data-transfer-object-enum-impl/etc/data-transfer-object-enum-impl.urm.puml new file mode 100644 index 000000000000..e6426c3928df --- /dev/null +++ b/data-transfer-object-enum-impl/etc/data-transfer-object-enum-impl.urm.puml @@ -0,0 +1,129 @@ +@startuml +package com.iluwatar.datatransferenum { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + } + class Product { + - cost : Double + - id : Long + - name : String + - price : Double + - supplier : String + + Product() + + getCost() : Double + + getId() : Long + + getName() : String + + getPrice() : Double + + getSupplier() : String + + setCost(cost : Double) : Product + + setId(id : Long) : Product + + setName(name : String) : Product + + setPrice(price : Double) : Product + + setSupplier(supplier : String) : Product + + toString() : String + } + enum ProductDTO { + + valueOf(name : String) : ProductDTO {static} + + values() : ProductDTO[] {static} + } + -interface Cost { + + getCost() : Double {abstract} + } + -interface Id { + + getId() : Long {abstract} + } + -interface Name { + + getName() : String {abstract} + } + -interface Price { + + getPrice() : Double {abstract} + } + enum Request { + + valueOf(name : String) : Request {static} + + values() : Request[] {static} + } + class Create { + - cost : Double + - name : String + - price : Double + - supplier : String + + Create() + + getCost() : Double + + getName() : String + + getPrice() : Double + + getSupplier() : String + + setCost(cost : Double) : Create + + setName(name : String) : Create + + setPrice(price : Double) : Create + + setSupplier(supplier : String) : Create + } + enum Response { + + valueOf(name : String) : Response {static} + + values() : Response[] {static} + } + class Private { + - cost : Double + - id : Long + - name : String + - price : Double + + Private() + + getCost() : Double + + getId() : Long + + getName() : String + + getPrice() : Double + + setCost(cost : Double) : Private + + setId(id : Long) : Private + + setName(name : String) : Private + + setPrice(price : Double) : Private + + toString() : String + } + class Public { + - id : Long + - name : String + - price : Double + + Public() + + getId() : Long + + getName() : String + + getPrice() : Double + + setId(id : Long) : Public + + setName(name : String) : Public + + setPrice(price : Double) : Public + + toString() : String + } + -interface Supplier { + + getSupplier() : String {abstract} + } + class ProductResource { + - products : List<Product> + + ProductResource(products : List<Product>) + + getAllProductsForAdmin() : List<Private> + + getAllProductsForCustomer() : List<Public> + + getProducts() : List<Product> + + save(createProductDTO : Create) + } +} +Create ..+ Request +Request ..+ ProductDTO +Private ..+ Response +Supplier ..+ ProductDTO +Name ..+ ProductDTO +ProductResource --> "-products" Product +Public ..+ Response +Id ..+ ProductDTO +Price ..+ ProductDTO +Response ..+ ProductDTO +Cost ..+ ProductDTO +Create ..|> Name +Create ..|> Price +Create ..|> Cost +Create ..|> Supplier +Private ..|> Id +Private ..|> Name +Private ..|> Price +Private ..|> Cost +Public ..|> Id +Public ..|> Name +Public ..|> Price +@enduml diff --git a/data-transfer-object-enum-impl/pom.xml b/data-transfer-object-enum-impl/pom.xml new file mode 100644 index 000000000000..74c8a3a6cf8b --- /dev/null +++ b/data-transfer-object-enum-impl/pom.xml @@ -0,0 +1,61 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + + The MIT License + Copyright © 2014-2019 Ilkka Seppälä + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + +--> +<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>com.iluwatar</groupId> + <artifactId>java-design-patterns</artifactId> + <version>1.24.0-SNAPSHOT</version> + </parent> + <artifactId>data-transfer-object-enum-impl</artifactId> + <dependencies> + <dependency> + <groupId>org.junit.jupiter</groupId> + <artifactId>junit-jupiter-engine</artifactId> + <scope>test</scope> + </dependency> + </dependencies> + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-assembly-plugin</artifactId> + <executions> + <execution> + <configuration> + <archive> + <manifest> + <mainClass>com.iluwatar.datatransferenum.App</mainClass> + </manifest> + </archive> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> +</project> diff --git a/data-transfer-object-enum-impl/src/main/java/com/iluwatar/datatransferenum/App.java b/data-transfer-object-enum-impl/src/main/java/com/iluwatar/datatransferenum/App.java new file mode 100644 index 000000000000..9c80d07cc461 --- /dev/null +++ b/data-transfer-object-enum-impl/src/main/java/com/iluwatar/datatransferenum/App.java @@ -0,0 +1,59 @@ +package com.iluwatar.datatransferenum; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The Data Transfer Object pattern is a design pattern in which an data transfer object is used to + * serve related information together to avoid multiple call for each piece of information. + * + * <p>In this example, ({@link App}) as as product details consumer i.e. client to + * request for product details to server. + * + * <p>productResource ({@link ProductResource}) act as server to serve product information. And + * The productDto ({@link ProductDto} is data transfer object to share product information. + */ +public class App { + + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + + /** + * Method as act client and request to server for details. + * + * @param args program argument. + */ + public static void main(String[] args) { + Product tv = + new Product().setId(1L).setName("TV").setSupplier("Sony").setPrice(1000D).setCost(1090D); + Product microwave = + new Product().setId(2L).setName("microwave").setSupplier("Delonghi").setPrice(1000D) + .setCost(1090D); + Product refrigerator = + new Product().setId(3L).setName("refrigerator").setSupplier("Botsch").setPrice(1000D) + .setCost(1090D); + Product airConditioner = + new Product().setId(4L).setName("airConditioner").setSupplier("LG").setPrice(1000D) + .setCost(1090D); + List<Product> products = + new ArrayList<>(Arrays.asList(tv, microwave, refrigerator, airConditioner)); + ProductResource productResource = new ProductResource(products); + + LOGGER.info("####### List of products including sensitive data just for admins: \n {}", + Arrays.toString(productResource.getAllProductsForAdmin().toArray())); + LOGGER.info("####### List of products for customers: \n {}", + Arrays.toString(productResource.getAllProductsForCustomer().toArray())); + + LOGGER.info("####### Going to save Sony PS5 ..."); + ProductDto.Request.Create createProductRequestDto = new ProductDto.Request.Create() + .setName("PS5") + .setCost(1000D) + .setPrice(1220D) + .setSupplier("Sony"); + productResource.save(createProductRequestDto); + LOGGER.info("####### List of products after adding PS5: {}", + Arrays.toString(productResource.getProducts().toArray())); + } +} diff --git a/data-transfer-object-enum-impl/src/main/java/com/iluwatar/datatransferenum/Product.java b/data-transfer-object-enum-impl/src/main/java/com/iluwatar/datatransferenum/Product.java new file mode 100644 index 000000000000..96758baf4297 --- /dev/null +++ b/data-transfer-object-enum-impl/src/main/java/com/iluwatar/datatransferenum/Product.java @@ -0,0 +1,91 @@ +package com.iluwatar.datatransferenum; + +/** + * {@link Product} is a entity class for product entity. This class act as entity in the demo. + */ +public final class Product { + private Long id; + private String name; + private Double price; + private Double cost; + private String supplier; + + /** + * Constructor. + * + * @param id product id + * @param name product name + * @param price product price + * @param cost product cost + * @param supplier product supplier + */ + public Product(Long id, String name, Double price, Double cost, String supplier) { + this.id = id; + this.name = name; + this.price = price; + this.cost = cost; + this.supplier = supplier; + } + + /** + * Constructor. + */ + public Product() { + } + + public Long getId() { + return id; + } + + public Product setId(Long id) { + this.id = id; + return this; + } + + public String getName() { + return name; + } + + public Product setName(String name) { + this.name = name; + return this; + } + + public Double getPrice() { + return price; + } + + public Product setPrice(Double price) { + this.price = price; + return this; + } + + public Double getCost() { + return cost; + } + + public Product setCost(Double cost) { + this.cost = cost; + return this; + } + + public String getSupplier() { + return supplier; + } + + public Product setSupplier(String supplier) { + this.supplier = supplier; + return this; + } + + @Override + public String toString() { + return "Product{" + + "id=" + id + + ", name='" + name + '\'' + + ", price=" + price + + ", cost=" + cost + + ", supplier='" + supplier + '\'' + + '}'; + } +} diff --git a/data-transfer-object-enum-impl/src/main/java/com/iluwatar/datatransferenum/ProductDto.java b/data-transfer-object-enum-impl/src/main/java/com/iluwatar/datatransferenum/ProductDto.java new file mode 100644 index 000000000000..49d08d896c29 --- /dev/null +++ b/data-transfer-object-enum-impl/src/main/java/com/iluwatar/datatransferenum/ProductDto.java @@ -0,0 +1,264 @@ +package com.iluwatar.datatransferenum; + +/** + * {@link ProductDto} is a data transfer object POJO. + * Instead of sending individual information to + * client We can send related information together in POJO. + * + * <p>Dto will not have any business logic in it. + */ +public enum ProductDto { + ; + + /** + * This is Request class which consist of Create or any other request DTO's + * you might want to use in your API. + */ + public enum Request { + ; + + /** + * This is Create dto class for requesting create new product. + */ + public static final class Create implements Name, Price, Cost, Supplier { + private String name; + private Double price; + private Double cost; + private String supplier; + + @Override + public String getName() { + return name; + } + + public Create setName(String name) { + this.name = name; + return this; + } + + @Override + public Double getPrice() { + return price; + } + + public Create setPrice(Double price) { + this.price = price; + return this; + } + + @Override + public Double getCost() { + return cost; + } + + public Create setCost(Double cost) { + this.cost = cost; + return this; + } + + @Override + public String getSupplier() { + return supplier; + } + + public Create setSupplier(String supplier) { + this.supplier = supplier; + return this; + } + } + } + + /** + * This is Response class which consist of any response DTO's + * you might want to provide to your clients. + */ + public enum Response { + ; + + /** + * This is Public dto class for API response with the lowest data security. + */ + public static final class Public implements Id, Name, Price { + private Long id; + private String name; + private Double price; + + @Override + public Long getId() { + return id; + } + + public Public setId(Long id) { + this.id = id; + return this; + } + + @Override + public String getName() { + return name; + } + + public Public setName(String name) { + this.name = name; + return this; + } + + @Override + public Double getPrice() { + return price; + } + + public Public setPrice(Double price) { + this.price = price; + return this; + } + + @Override + public String toString() { + return "Public{" + + "id=" + + id + + ", name='" + + name + + '\'' + + ", price=" + + price + + '}'; + } + } + + /** + * This is Private dto class for API response with the highest data security. + */ + public static final class Private implements Id, Name, Price, Cost { + private Long id; + private String name; + private Double price; + private Double cost; + + @Override + public Long getId() { + return id; + } + + public Private setId(Long id) { + this.id = id; + return this; + } + + @Override + public String getName() { + return name; + } + + public Private setName(String name) { + this.name = name; + return this; + } + + @Override + public Double getPrice() { + return price; + } + + public Private setPrice(Double price) { + this.price = price; + return this; + } + + @Override + public Double getCost() { + return cost; + } + + public Private setCost(Double cost) { + this.cost = cost; + return this; + } + + @Override + public String toString() { + return "Private{" + + + "id=" + + id + + + ", name='" + + name + + '\'' + + + ", price=" + + price + + + ", cost=" + + cost + + + '}'; + } + } + } + + /** + * Use this interface whenever you want to provide the product Id in your DTO. + */ + private interface Id { + /** + * Unique identifier of the product. + * + * @return : id of the product. + */ + Long getId(); + } + + /** + * Use this interface whenever you want to provide the product Name in your DTO. + */ + private interface Name { + /** + * The name of the product. + * + * @return : name of the product. + */ + String getName(); + } + + /** + * Use this interface whenever you want to provide the product Price in your DTO. + */ + private interface Price { + /** + * The amount we sell a product for. + * <b>This data is not confidential</b> + * + * @return : price of the product. + */ + Double getPrice(); + } + + /** + * Use this interface whenever you want to provide the product Cost in your DTO. + */ + private interface Cost { + /** + * The amount that it costs us to purchase this product + * For the amount we sell a product for, see the {@link Price Price} parameter. + * <b>This data is confidential</b> + * + * @return : cost of the product. + */ + Double getCost(); + } + + /** + * Use this interface whenever you want to provide the product Supplier in your DTO. + */ + private interface Supplier { + /** + * The name of supplier of the product or its manufacturer. + * <b>This data is highly confidential</b> + * + * @return : supplier of the product. + */ + String getSupplier(); + } +} diff --git a/data-transfer-object-enum-impl/src/main/java/com/iluwatar/datatransferenum/ProductResource.java b/data-transfer-object-enum-impl/src/main/java/com/iluwatar/datatransferenum/ProductResource.java new file mode 100644 index 000000000000..5940982b1f86 --- /dev/null +++ b/data-transfer-object-enum-impl/src/main/java/com/iluwatar/datatransferenum/ProductResource.java @@ -0,0 +1,71 @@ +package com.iluwatar.datatransferenum; + +import java.util.List; +import java.util.stream.Collectors; + +/** + * The resource class which serves product information. This class act as server in the demo. Which + * has all product details. + */ +public class ProductResource { + private final List<Product> products; + + /** + * Initialise resource with existing products. + * + * @param products initialize resource with existing products. Act as database. + */ + public ProductResource(final List<Product> products) { + this.products = products; + } + + /** + * Get all products. + * + * @return : all products in list but in the scheme of private dto. + */ + public List<ProductDto.Response.Private> getAllProductsForAdmin() { + return products + .stream() + .map(p -> new ProductDto.Response.Private().setId(p.getId()).setName(p.getName()) + .setCost(p.getCost()) + .setPrice(p.getPrice())) + .collect(Collectors.toList()); + } + + /** + * Get all products. + * + * @return : all products in list but in the scheme of public dto. + */ + public List<ProductDto.Response.Public> getAllProductsForCustomer() { + return products + .stream() + .map(p -> new ProductDto.Response.Public().setId(p.getId()).setName(p.getName()) + .setPrice(p.getPrice())) + .collect(Collectors.toList()); + } + + /** + * Save new product. + * + * @param createProductDto save new product to list. + */ + public void save(ProductDto.Request.Create createProductDto) { + products.add(new Product() + .setId((long) (products.size() + 1)) + .setName(createProductDto.getName()) + .setSupplier(createProductDto.getSupplier()) + .setPrice(createProductDto.getPrice()) + .setCost(createProductDto.getCost())); + } + + /** + * List of all products in an entity representation. + * + * @return : all the products entity that stored in the products list + */ + public List<Product> getProducts() { + return products; + } +} diff --git a/pom.xml b/pom.xml index 86cefa13386a..b6556245b72b 100644 --- a/pom.xml +++ b/pom.xml @@ -199,6 +199,7 @@ <module>filterer</module> <module>factory</module> <module>separated-interface</module> + <module>data-transfer-object-enum-impl</module> </modules> <repositories>
diff --git a/data-transfer-object-enum-impl/src/test/java/com/iluwatar/datatransferenum/AppTest.java b/data-transfer-object-enum-impl/src/test/java/com/iluwatar/datatransferenum/AppTest.java new file mode 100644 index 000000000000..bba131e64163 --- /dev/null +++ b/data-transfer-object-enum-impl/src/test/java/com/iluwatar/datatransferenum/AppTest.java @@ -0,0 +1,44 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.datatransferenum; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + + +import org.junit.jupiter.api.Test; + +class AppTest { + + /** + * Issue: Add at least one assertion to this test case. + * <p> + * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])} + * throws an exception. + */ + + @Test + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +}
test
train
2020-12-08T06:28:39
"2020-10-16T09:44:26Z"
siavashsoleymani
train
iluwatar/java-design-patterns/1601_1604
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1601
iluwatar/java-design-patterns/1604
[ "keyword_pr_to_issue", "timestamp(timedelta=0.0, similarity=0.9508714178765859)", "connected" ]
c282ab80fdd4785a1a8d5bb8b2e5bfe519fd12be
f5a616104497d85f03754ed0b15be316794fcd7f
[ "I am new to this. Can I take up this?", "@ohbus when handling issues set the correct labels and on close set the milestone", "> @ohbus when handling issues set the correct labels and on close set the milestone\n\nThank you for this guiding me on this.\n\nAnd Hacktoberfest is over, I guess we should remove this tag from the repository or stop using it for the time being.", "@ohbus before you know it, it will be the next Hactoberfest, so I would just leave it there :)" ]
[]
"2020-11-30T09:58:31Z"
[ "type: bug", "epic: pattern", "info: good first issue" ]
Word mistake in factory/README.md
![image](https://user-images.githubusercontent.com/48073115/100273344-f44e2680-2f9f-11eb-8f9f-393c4667932f.png) Lines 83-84: Could not find CarSimpleFactory. Isn't it CarsFactory?
[ "factory/README.md" ]
[ "factory/README.md" ]
[]
diff --git a/factory/README.md b/factory/README.md index a1b6208fd736..0112c92c0f06 100644 --- a/factory/README.md +++ b/factory/README.md @@ -81,7 +81,7 @@ public enum CarType { } ``` Then we have the static method `getCar` to create car objects encapsulated in the factory class -`CarSimpleFactory`. +`CarsFactory`. ```java public class CarsFactory {
null
train
train
2020-12-01T21:48:24
"2020-11-25T19:43:50Z"
seungryeolpark
train
iluwatar/java-design-patterns/1600_1610
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1600
iluwatar/java-design-patterns/1610
[ "keyword_pr_to_issue" ]
29ceac2fb06a4ffb85bdd327cdf3824ba6ccdaec
e9f73bcf0b79ef90076ce0bde93f85b8cb6a7557
[ "line 13 : 包装器 should be 装饰器 。\r\n装饰器 is well known than 包装器 in China", "@xiaod-dev could you check this issue?", "> line 13 : 包装器 should be 装饰器 。\r\n> 装饰器 is well known than 包装器 in China\r\n\r\nThank your feedback. the line 36 was corrected, and about the line13, the original text is \" Wrapper\", not \"decorator\", so there is nothing go wrong with \"包装器\". " ]
[]
"2020-12-06T13:15:30Z"
[ "type: bug", "info: good first issue", "epic: documentation" ]
careless grammer mistake in zh/decorator/README.md
line 36:程序mple. First of all we have a simple troll implementing the troll interface should be 程序example. First of all we have a simple troll implementing the troll interface Thank you!
[ "zh/decorator/README.md" ]
[ "zh/bridge/README.md", "zh/callback/README.md", "zh/command/README.md", "zh/decorator/README.md", "zh/dependency-injection/README.md", "zh/iterator/README.md", "zh/state/README.md", "zh/template-method/README.md" ]
[]
diff --git a/zh/bridge/README.md b/zh/bridge/README.md new file mode 100644 index 000000000000..cd9f40ac496a --- /dev/null +++ b/zh/bridge/README.md @@ -0,0 +1,205 @@ +--- +layout: pattern +title: Bridge +folder: bridge +permalink: /patterns/bridge/ +categories: Structural +tags: + - Gang of Four +--- + +## 又被称为 + +手柄/身体模式 + +## 目的 + +将抽象与其实现分离,以便二者可以独立变化。 + +## 解释 + +真实世界例子 + +> 考虑一下你拥有一种具有不同附魔的武器,并且应该允许将具有不同附魔的不同武器混合使用。 你会怎么做? 为每个附魔创建每种武器的多个副本,还是只是创建单独的附魔并根据需要为武器设置它? 桥接模式使您可以进行第二次操作。 + +通俗的说 + +> 桥接模式是一个更推荐组合而不是继承的模式。将实现细节从一个层次结构推送到具有单独层次结构的另一个对象。 + +维基百科说 + +> 桥接模式是软件工程中使用的一种设计模式,旨在“将抽象与其实现分离,从而使两者可以独立变化” + +**程序示例** + +翻译一下上面的武器示例。下面我们有武器的类层级: + +```java +public interface Weapon { + void wield(); + void swing(); + void unwield(); + Enchantment getEnchantment(); +} + +public class Sword implements Weapon { + + private final Enchantment enchantment; + + public Sword(Enchantment enchantment) { + this.enchantment = enchantment; + } + + @Override + public void wield() { + LOGGER.info("The sword is wielded."); + enchantment.onActivate(); + } + + @Override + public void swing() { + LOGGER.info("The sword is swinged."); + enchantment.apply(); + } + + @Override + public void unwield() { + LOGGER.info("The sword is unwielded."); + enchantment.onDeactivate(); + } + + @Override + public Enchantment getEnchantment() { + return enchantment; + } +} + +public class Hammer implements Weapon { + + private final Enchantment enchantment; + + public Hammer(Enchantment enchantment) { + this.enchantment = enchantment; + } + + @Override + public void wield() { + LOGGER.info("The hammer is wielded."); + enchantment.onActivate(); + } + + @Override + public void swing() { + LOGGER.info("The hammer is swinged."); + enchantment.apply(); + } + + @Override + public void unwield() { + LOGGER.info("The hammer is unwielded."); + enchantment.onDeactivate(); + } + + @Override + public Enchantment getEnchantment() { + return enchantment; + } +} +``` + +这里是单独的附魔类结构: + +```java +public interface Enchantment { + void onActivate(); + void apply(); + void onDeactivate(); +} + +public class FlyingEnchantment implements Enchantment { + + @Override + public void onActivate() { + LOGGER.info("The item begins to glow faintly."); + } + + @Override + public void apply() { + LOGGER.info("The item flies and strikes the enemies finally returning to owner's hand."); + } + + @Override + public void onDeactivate() { + LOGGER.info("The item's glow fades."); + } +} + +public class SoulEatingEnchantment implements Enchantment { + + @Override + public void onActivate() { + LOGGER.info("The item spreads bloodlust."); + } + + @Override + public void apply() { + LOGGER.info("The item eats the soul of enemies."); + } + + @Override + public void onDeactivate() { + LOGGER.info("Bloodlust slowly disappears."); + } +} +``` + +这里是两种层次结构的实践: + +```java +var enchantedSword = new Sword(new SoulEatingEnchantment()); +enchantedSword.wield(); +enchantedSword.swing(); +enchantedSword.unwield(); +// The sword is wielded. +// The item spreads bloodlust. +// The sword is swinged. +// The item eats the soul of enemies. +// The sword is unwielded. +// Bloodlust slowly disappears. + +var hammer = new Hammer(new FlyingEnchantment()); +hammer.wield(); +hammer.swing(); +hammer.unwield(); +// The hammer is wielded. +// The item begins to glow faintly. +// The hammer is swinged. +// The item flies and strikes the enemies finally returning to owner's hand. +// The hammer is unwielded. +// The item's glow fades. +``` + + + +## 类图 + +![alt text](../../bridge/etc/bridge.urm.png "Bridge class diagram") + +## 适用性 + +使用桥接模式当 + +* 你想永久性的避免抽象和他的实现之间的绑定。有可能是这种情况,当实现需要被选择或者在运行时切换。 +* 抽象和他们的实现应该能通过写子类来扩展。这种情况下,桥接模式让你可以组合不同的抽象和实现并独立的扩展他们。 +* 对抽象的实现的改动应当不会对客户产生影响;也就是说,他们的代码不必重新编译。 +* 你有种类繁多的类。这样的类层次结构表明需要将一个对象分为两部分。Rumbaugh 使用术语“嵌套归纳”来指代这种类层次结构。 +* 你想在多个对象间分享一种实现(可能使用引用计数),这个事实应该对客户隐藏。一个简单的示例是Coplien的String类,其中多个对象可以共享同一字符串表示形式 + +## 教程 + +* [Bridge Pattern Tutorial](https://www.journaldev.com/1491/bridge-design-pattern-java) + +## 鸣谢 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/zh/callback/README.md b/zh/callback/README.md new file mode 100644 index 000000000000..a70a6a7c2210 --- /dev/null +++ b/zh/callback/README.md @@ -0,0 +1,79 @@ +--- +layout: pattern +title: Callback +folder: callback +permalink: /patterns/callback/ +categories: Idiom +tags: + - Reactive +--- + +## 目的 +回调是一部分被当为参数来传递给其他代码的可执行代码,接收方的代码可以在一些方便的时候来调用它。 + +## 解释 + +真实世界例子 + +> 我们需要被通知当执行的任务结束时。我们为调用者传递一个回调方法然后等它调用通知我们。 + +通俗的讲 + + +> 回调是一个用来传递给调用者的方法,它将在定义的时刻被调用。 + +维基百科说 + +> 在计算机编程中,回调又被称为“稍后调用”函数,可以是任何可执行的代码用来作为参数传递给其他代码;其它代码被期望在给定时间内调用回调方法。 + +**编程示例** + +回调是一个只有一个方法的简单接口。 + +```java +public interface Callback { + + void call(); +} +``` + +下面我们定义一个任务它将在任务执行完成后执行回调。 + +```java +public abstract class Task { + + final void executeWith(Callback callback) { + execute(); + Optional.ofNullable(callback).ifPresent(Callback::call); + } + + public abstract void execute(); +} + +public final class SimpleTask extends Task { + + private static final Logger LOGGER = getLogger(SimpleTask.class); + + @Override + public void execute() { + LOGGER.info("Perform some important activity and after call the callback method."); + } +} +``` + +最后这里是我们如何执行一个任务然后接收一个回调当它完成时。 + +```java + var task = new SimpleTask(); + task.executeWith(() -> LOGGER.info("I'm done now.")); +``` +## 类图 +![alt text](../../callback/etc/callback.png "Callback") + +## 适用性 +使用回调模式当 +* 当一些同步或异步架构动作必须在一些定义好的活动执行后执行时。 + +## Java例子 + +* [CyclicBarrier](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CyclicBarrier.html#CyclicBarrier%28int,%20java.lang.Runnable%29) 构造函数可以接受回调,该回调将在每次障碍被触发时触发。 diff --git a/zh/command/README.md b/zh/command/README.md new file mode 100644 index 000000000000..2c4f03a25997 --- /dev/null +++ b/zh/command/README.md @@ -0,0 +1,253 @@ +--- +layout: pattern +title: Command +folder: command +permalink: /patterns/command/ +categories: Behavioral +tags: + - Gang of Four +--- + +## 或称 +行动, 事务模式 + +## 目的 +将请求封装为对象,从而使你可以将具有不同请求的客户端参数化,队列或记录请求,并且支持可撤销操作。 + +## 解释 +真实世界例子 + +> 有一个巫师在地精上施放咒语。咒语在地精上一一执行。第一个咒语使地精缩小,第二个使他不可见。然后巫师将咒语一个个的反转。这里的每一个咒语都是一个可撤销的命令对象。 + +用通俗的话说 + +> 用命令对象的方式存储请求以在将来时可以执行它或撤销它。 + +维基百科说 + +> 在面向对象编程中,命令模式是一种行为型设计模式,它把在稍后执行的一个动作或触发的一个事件所需要的所有信息封装到一个对象中。 + +**编程示例** + +这是巫师和地精的示例代码。让我们从巫师类开始。 + +```java +public class Wizard { + + private static final Logger LOGGER = LoggerFactory.getLogger(Wizard.class); + + private final Deque<Command> undoStack = new LinkedList<>(); + private final Deque<Command> redoStack = new LinkedList<>(); + + public Wizard() {} + + public void castSpell(Command command, Target target) { + LOGGER.info("{} casts {} at {}", this, command, target); + command.execute(target); + undoStack.offerLast(command); + } + + public void undoLastSpell() { + if (!undoStack.isEmpty()) { + var previousSpell = undoStack.pollLast(); + redoStack.offerLast(previousSpell); + LOGGER.info("{} undoes {}", this, previousSpell); + previousSpell.undo(); + } + } + + public void redoLastSpell() { + if (!redoStack.isEmpty()) { + var previousSpell = redoStack.pollLast(); + undoStack.offerLast(previousSpell); + LOGGER.info("{} redoes {}", this, previousSpell); + previousSpell.redo(); + } + } + + @Override + public String toString() { + return "Wizard"; + } +} +``` + +接下来我们介绍咒语层级 + +```java +public interface Command { + + void execute(Target target); + + void undo(); + + void redo(); + + String toString(); +} + +public class InvisibilitySpell implements Command { + + private Target target; + + @Override + public void execute(Target target) { + target.setVisibility(Visibility.INVISIBLE); + this.target = target; + } + + @Override + public void undo() { + if (target != null) { + target.setVisibility(Visibility.VISIBLE); + } + } + + @Override + public void redo() { + if (target != null) { + target.setVisibility(Visibility.INVISIBLE); + } + } + + @Override + public String toString() { + return "Invisibility spell"; + } +} + +public class ShrinkSpell implements Command { + + private Size oldSize; + private Target target; + + @Override + public void execute(Target target) { + oldSize = target.getSize(); + target.setSize(Size.SMALL); + this.target = target; + } + + @Override + public void undo() { + if (oldSize != null && target != null) { + var temp = target.getSize(); + target.setSize(oldSize); + oldSize = temp; + } + } + + @Override + public void redo() { + undo(); + } + + @Override + public String toString() { + return "Shrink spell"; + } +} +``` + +最后我们有咒语的目标地精。 + +```java +public abstract class Target { + + private static final Logger LOGGER = LoggerFactory.getLogger(Target.class); + + private Size size; + + private Visibility visibility; + + public Size getSize() { + return size; + } + + public void setSize(Size size) { + this.size = size; + } + + public Visibility getVisibility() { + return visibility; + } + + public void setVisibility(Visibility visibility) { + this.visibility = visibility; + } + + @Override + public abstract String toString(); + + public void printStatus() { + LOGGER.info("{}, [size={}] [visibility={}]", this, getSize(), getVisibility()); + } +} + +public class Goblin extends Target { + + public Goblin() { + setSize(Size.NORMAL); + setVisibility(Visibility.VISIBLE); + } + + @Override + public String toString() { + return "Goblin"; + } + +} +``` + +最后是整个示例的实践。 + +```java +var wizard = new Wizard(); +var goblin = new Goblin(); +goblin.printStatus(); +// Goblin, [size=normal] [visibility=visible] +wizard.castSpell(new ShrinkSpell(), goblin); +// Wizard casts Shrink spell at Goblin +goblin.printStatus(); +// Goblin, [size=small] [visibility=visible] +wizard.castSpell(new InvisibilitySpell(), goblin); +// Wizard casts Invisibility spell at Goblin +goblin.printStatus(); +// Goblin, [size=small] [visibility=invisible] +wizard.undoLastSpell(); +// Wizard undoes Invisibility spell +goblin.printStatus(); +// Goblin, [size=small] [visibility=visible] +``` + +## 类图 +![alt text](../../command/etc/command.png "Command") + +## 适用性 +使用命令模式当你想 + +* 通过操作将对象参数化。您可以使用回调函数(即,已在某处注册以便稍后调用的函数)以过程语言表示这种参数化。命令是回调的一种面向对象替代方案。 +* 在不同的时间指定,排队和执行请求。一个命令对象的生存期可以独立于原始请求。如果请求的接收方可以以地址空间无关的方式来表示,那么你可以将请求的命令对象传输到其他进程并在那里执行请求。 +* 支持撤销。命令的执行操作可以在命令本身中存储状态以反转其效果。命令接口必须有添加的反执行操作,该操作可以逆转上一次执行调用的效果。执行的命令存储在历史列表中。无限撤消和重做通过分别向后和向前遍历此列表来实现,分别调用unexecute和execute。 +* 支持日志记录更改,以便在系统崩溃时可以重新应用它们。通过使用加载和存储操作扩展命令接口,你可以保留更改的永久日志。从崩溃中恢复涉及从磁盘重新加载记录的命令,并通过执行操作重新执行它们。 +* 通过原始的操作来构建一个以高级操作围绕的系统。这种结构在支持事务的信息系统中很常见。事务封装了一组数据更改。命令模式提供了一种对事务进行建模的方法。命令具有公共接口,让你以相同的方式调用所有事务。该模式还可以通过新的事务来轻松扩展系统。 + +## 典型用例 + +* 保留请求历史 +* 实现回调功能 +* 实现撤销功能 + +## Java世界例子 + +* [java.lang.Runnable](http://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html) +* [org.junit.runners.model.Statement](https://github.com/junit-team/junit4/blob/master/src/main/java/org/junit/runners/model/Statement.java) +* [Netflix Hystrix](https://github.com/Netflix/Hystrix/wiki) +* [javax.swing.Action](http://docs.oracle.com/javase/8/docs/api/javax/swing/Action.html) + +## 鸣谢 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=f27d2644fbe5026ea448791a8ad09c94) diff --git a/zh/decorator/README.md b/zh/decorator/README.md index ef23eda0b951..6163017afb0f 100644 --- a/zh/decorator/README.md +++ b/zh/decorator/README.md @@ -33,8 +33,6 @@ tags: 以巨魔的为例。首先我有有一个简单的巨魔,实现了巨魔接口。 -程序mple. First of all we have a simple troll implementing the troll interface - ```java public interface Troll { void attack(); diff --git a/zh/dependency-injection/README.md b/zh/dependency-injection/README.md new file mode 100644 index 000000000000..061a55425836 --- /dev/null +++ b/zh/dependency-injection/README.md @@ -0,0 +1,101 @@ +--- +layout: pattern +title: Dependency Injection +folder: dependency-injection +permalink: /patterns/dependency-injection/ +categories: Creational +tags: + - Decoupling +--- + +## 目的 + +依赖注入是一种软件设计模式,其中一个或多个依赖项(或服务)被注入或通过引用传递到一个依赖对象(或客户端)中,并成为客户端状态的一部分。该模式将客户的依赖关系的创建与其自身的行为分开,这使程序设计可以松散耦合,并遵循控制反转和单一职责原则。 + +## 解释 + +真实世界例子 + +> 老巫师喜欢不时地装满烟斗抽烟。 但是,他不想只依赖一个烟草品牌,而是希望能够互换使用它们。 + +通俗的说 + +> 依赖注入将客户端依赖的创建与其自身行为分开。 + +维基百科说 + +> 在软件工程中,依赖注入是一种对象接收其依赖的其他对象的技术。 这些其他对象称为依赖项。 + +**程序示例** + +先介绍一下烟草接口和具体的品牌。 + +```java +public abstract class Tobacco { + + private static final Logger LOGGER = LoggerFactory.getLogger(Tobacco.class); + + public void smoke(Wizard wizard) { + LOGGER.info("{} smoking {}", wizard.getClass().getSimpleName(), + this.getClass().getSimpleName()); + } +} + +public class SecondBreakfastTobacco extends Tobacco { +} + +public class RivendellTobacco extends Tobacco { +} + +public class OldTobyTobacco extends Tobacco { +} +``` + +下面是老巫师的类的层次结构。 + +```java +public interface Wizard { + + void smoke(); +} + +public class AdvancedWizard implements Wizard { + + private final Tobacco tobacco; + + public AdvancedWizard(Tobacco tobacco) { + this.tobacco = tobacco; + } + + @Override + public void smoke() { + tobacco.smoke(this); + } +} +``` + +最后我们可以看到给老巫师任意品牌的烟草是多么的简单。 + +```java + var advancedWizard = new AdvancedWizard(new SecondBreakfastTobacco()); + advancedWizard.smoke(); +``` + +## 类图 + +![alt text](../../dependency-injection/etc/dependency-injection.png "Dependency Injection") + +## 适用性 + +使用依赖注入当: + +- 当你需要从对象中移除掉具体的实现内容时 + +* 使用模拟对象或存根隔离地启用类的单元测试 + +## 鸣谢 + +* [Dependency Injection Principles, Practices, and Patterns](https://www.amazon.com/gp/product/161729473X/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=161729473X&linkId=57079257a5c7d33755493802f3b884bd) +* [Clean Code: A Handbook of Agile Software Craftsmanship](https://www.amazon.com/gp/product/0132350882/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0132350882&linkCode=as2&tag=javadesignpat-20&linkId=2c390d89cc9e61c01b9e7005c7842871) +* [Java 9 Dependency Injection: Write loosely coupled code with Spring 5 and Guice](https://www.amazon.com/gp/product/1788296257/ref=as_li_tl?ie=UTF8&tag=javadesignpat-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=1788296257&linkId=4e9137a3bf722a8b5b156cce1eec0fc1) +* [Google Guice Tutorial: Open source Java based dependency injection framework](https://www.amazon.com/gp/product/B083P7DZ8M/ref=as_li_tl?ie=UTF8&tag=javadesignpat-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B083P7DZ8M&linkId=04f0f902c877921e45215b624a124bfe) diff --git a/zh/iterator/README.md b/zh/iterator/README.md new file mode 100644 index 000000000000..0b9db9e43769 --- /dev/null +++ b/zh/iterator/README.md @@ -0,0 +1,134 @@ +--- +layout: pattern +title: Iterator +folder: iterator +permalink: /patterns/iterator/ +categories: Behavioral +tags: + - Gang of Four +--- + +## 又被称为 +游标 + +## 目的 +提供一种在不暴露其基础表示的情况下顺序访问聚合对象的元素的方法。 + +## 解释 + +真实世界例子 + +> 百宝箱包含一组魔法物品。有多种物品,例如戒指,药水和武器。可以使用藏宝箱提供的迭代器按类型浏览商品。 + +通俗地说 + +> 容器可以提供与表示形式无关的迭代器接口,以提供对元素的访问。 + +维基百科说 + +> 在面向对象的编程中,迭代器模式是一种设计模式,其中迭代器用于遍历容器并访问容器的元素。 + +**程序示例** + +在我们的示例中包含物品的藏宝箱是主要类。 + +```java +public class TreasureChest { + + private final List<Item> items; + + public TreasureChest() { + items = List.of( + new Item(ItemType.POTION, "Potion of courage"), + new Item(ItemType.RING, "Ring of shadows"), + new Item(ItemType.POTION, "Potion of wisdom"), + new Item(ItemType.POTION, "Potion of blood"), + new Item(ItemType.WEAPON, "Sword of silver +1"), + new Item(ItemType.POTION, "Potion of rust"), + new Item(ItemType.POTION, "Potion of healing"), + new Item(ItemType.RING, "Ring of armor"), + new Item(ItemType.WEAPON, "Steel halberd"), + new Item(ItemType.WEAPON, "Dagger of poison")); + } + + public Iterator<Item> iterator(ItemType itemType) { + return new TreasureChestItemIterator(this, itemType); + } + + public List<Item> getItems() { + return new ArrayList<>(items); + } +} + +public class Item { + + private ItemType type; + private final String name; + + public Item(ItemType type, String name) { + this.setType(type); + this.name = name; + } + + @Override + public String toString() { + return name; + } + + public ItemType getType() { + return type; + } + + public final void setType(ItemType type) { + this.type = type; + } +} + +public enum ItemType { + + ANY, WEAPON, RING, POTION + +} +``` + +迭代器接口极度简单。 + +```java +public interface Iterator<T> { + + boolean hasNext(); + + T next(); +} +``` + +在以下示例中,我们遍历在宝箱中找到的戒指类型物品。 + +```java +var itemIterator = TREASURE_CHEST.iterator(ItemType.RING); +while (itemIterator.hasNext()) { + LOGGER.info(itemIterator.next().toString()); +} +// Ring of shadows +// Ring of armor +``` + +## 类图 +![alt text](../../iterator/etc/iterator_1.png "Iterator") + +## 适用性 +以下情况使用迭代器模式 + +* 在不暴露其内部表示的情况下访问聚合对象的内容 +* 为了支持聚合对象的多种遍历方式 +* 提供一个遍历不同聚合结构的统一接口 + +## Java世界例子 + +* [java.util.Iterator](http://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html) +* [java.util.Enumeration](http://docs.oracle.com/javase/8/docs/api/java/util/Enumeration.html) + +## 鸣谢 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) diff --git a/zh/state/README.md b/zh/state/README.md new file mode 100644 index 000000000000..6b46510e08bf --- /dev/null +++ b/zh/state/README.md @@ -0,0 +1,155 @@ +--- +layout: pattern +title: State +folder: state +permalink: /patterns/state/ +categories: Behavioral +tags: + - Gang of Four +--- + +## 又被称为 +对象状态 + +## 目的 +允许对象在内部状态改变时改变它的行为。对象看起来好像修改了它的类。 + +## 解释 +真实世界例子 + +> 当在长毛象的自然栖息地观察长毛象时,似乎它会根据情况来改变自己的行为。它开始可能很平静但是随着时间推移当它检测到威胁时它会对周围的环境感到愤怒和危险。 + +通俗的说 + +> 状态模式允许对象改变它的行为。 + +维基百科说 + +> 状态模式是一种允许对象在内部状态改变时改变它的行为的行为型设计模式。这种模式接近于有限状态机的概念。状态模式可以被理解为策略模式,它能够通过调用在模式接口中定义的方法来切换策略。 + +**编程示例** + +这里是模式接口和它具体的实现。 + +```java +public interface State { + + void onEnterState(); + + void observe(); +} + +public class PeacefulState implements State { + + private static final Logger LOGGER = LoggerFactory.getLogger(PeacefulState.class); + + private final Mammoth mammoth; + + public PeacefulState(Mammoth mammoth) { + this.mammoth = mammoth; + } + + @Override + public void observe() { + LOGGER.info("{} is calm and peaceful.", mammoth); + } + + @Override + public void onEnterState() { + LOGGER.info("{} calms down.", mammoth); + } +} + +public class AngryState implements State { + + private static final Logger LOGGER = LoggerFactory.getLogger(AngryState.class); + + private final Mammoth mammoth; + + public AngryState(Mammoth mammoth) { + this.mammoth = mammoth; + } + + @Override + public void observe() { + LOGGER.info("{} is furious!", mammoth); + } + + @Override + public void onEnterState() { + LOGGER.info("{} gets angry!", mammoth); + } +} +``` + +然后这里是包含状态的长毛象。 + +```java +public class Mammoth { + + private State state; + + public Mammoth() { + state = new PeacefulState(this); + } + + public void timePasses() { + if (state.getClass().equals(PeacefulState.class)) { + changeStateTo(new AngryState(this)); + } else { + changeStateTo(new PeacefulState(this)); + } + } + + private void changeStateTo(State newState) { + this.state = newState; + this.state.onEnterState(); + } + + @Override + public String toString() { + return "The mammoth"; + } + + public void observe() { + this.state.observe(); + } +} +``` + +然后这里是长毛象随着时间的推移后的整个行为示例。 + +```java + var mammoth = new Mammoth(); + mammoth.observe(); + mammoth.timePasses(); + mammoth.observe(); + mammoth.timePasses(); + mammoth.observe(); + + // The mammoth gets angry! + // The mammoth is furious! + // The mammoth calms down. + // The mammoth is calm and peaceful. +``` + +## 类图 +![alt text](../../state/etc/state_1.png "State") + +## 适用性 + +在以下两种情况下,请使用State模式 + +* 对象的行为取决于它的状态,并且它必须在运行时根据状态更改其行为。 +* 根据对象状态的不同,操作有大量的条件语句。此状态通常由一个或多个枚举常量表示。通常,几个操作将包含此相同的条件结构。状态模式把条件语句的分支分别放入单独的类中。这样一来,你就可以将对象的状态视为独立的对象,该对象可以独立于其他对象而变化。 + +## Java中例子 + +* [javax.faces.lifecycle.Lifecycle#execute()](http://docs.oracle.com/javaee/7/api/javax/faces/lifecycle/Lifecycle.html#execute-javax.faces.context.FacesContext-) controlled by [FacesServlet](http://docs.oracle.com/javaee/7/api/javax/faces/webapp/FacesServlet.html), the behavior is dependent on current phase of lifecycle. +* [JDiameter - Diameter State Machine](https://github.com/npathai/jdiameter/blob/master/core/jdiameter/api/src/main/java/org/jdiameter/api/app/State.java) + +## 鸣谢 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) diff --git a/zh/template-method/README.md b/zh/template-method/README.md new file mode 100644 index 000000000000..f848552c33c2 --- /dev/null +++ b/zh/template-method/README.md @@ -0,0 +1,145 @@ +--- +layout: pattern +title: Template method +folder: template-method +permalink: /patterns/template-method/ +categories: Behavioral +tags: + - Gang of Four +--- + +## 目的 +在一个操作中定义算法的骨架,将某些步骤推迟到子类。模板方法允许子类重新定义算法的某些步骤,而无需更改算法的结构。 + +## 解释 +真实世界例子 + +> 偷东西的一般步骤是相同的。 首先,选择目标,然后以某种方式使其迷惑,最后,你偷走了该物品。然而这些步骤有很多实现方式。 + +通俗的说 + +> 模板方法模式在父类中列出一般的步骤然后让具体的子类定义实现细节。 + +维基百科说 + +> 在面向对象的编程中,模板方法是Gamma等人确定的行为设计模式之一。在《设计模式》一书中。模板方法是父类中一个方法,通常是一个抽象父类,根据许多高级步骤定义了操作的骨架。这些步骤本身由与模板方法在同一类中的其他帮助程序方法实现。 + +**编程示例** + +让我们首先介绍模板方法类及其具体实现。 + +```java +public abstract class StealingMethod { + + private static final Logger LOGGER = LoggerFactory.getLogger(StealingMethod.class); + + protected abstract String pickTarget(); + + protected abstract void confuseTarget(String target); + + protected abstract void stealTheItem(String target); + + public void steal() { + var target = pickTarget(); + LOGGER.info("The target has been chosen as {}.", target); + confuseTarget(target); + stealTheItem(target); + } +} + +public class SubtleMethod extends StealingMethod { + + private static final Logger LOGGER = LoggerFactory.getLogger(SubtleMethod.class); + + @Override + protected String pickTarget() { + return "shop keeper"; + } + + @Override + protected void confuseTarget(String target) { + LOGGER.info("Approach the {} with tears running and hug him!", target); + } + + @Override + protected void stealTheItem(String target) { + LOGGER.info("While in close contact grab the {}'s wallet.", target); + } +} + +public class HitAndRunMethod extends StealingMethod { + + private static final Logger LOGGER = LoggerFactory.getLogger(HitAndRunMethod.class); + + @Override + protected String pickTarget() { + return "old goblin woman"; + } + + @Override + protected void confuseTarget(String target) { + LOGGER.info("Approach the {} from behind.", target); + } + + @Override + protected void stealTheItem(String target) { + LOGGER.info("Grab the handbag and run away fast!"); + } +} +``` + +这是包含模板方法的半身贼类。 + +```java +public class HalflingThief { + + private StealingMethod method; + + public HalflingThief(StealingMethod method) { + this.method = method; + } + + public void steal() { + method.steal(); + } + + public void changeMethod(StealingMethod method) { + this.method = method; + } +} +``` +最后,我们展示半身人贼如何利用不同的偷窃方法。 + +```java + var thief = new HalflingThief(new HitAndRunMethod()); + thief.steal(); + thief.changeMethod(new SubtleMethod()); + thief.steal(); +``` + +## 类图 +![alt text](../../template-method/etc/template-method_1.png "Template Method") + +## 适用性 + +使用模板方法模式可以 + +* 一次性实现一个算法中不变的部分并将其留给子类来实现可能变化的行为。 +* 子类之间的共同行为应分解并集中在一个共同类中,以避免代码重复。如Opdyke和Johnson所描述的,这是“重构概括”的一个很好的例子。你首先要确定现有代码中的差异,然后将差异拆分为新的操作。最后,将不同的代码替换为调用这些新操作之一的模板方法。 +* 控制子类扩展。您可以定义一个模板方法,该方法在特定点调用“ 钩子”操作,从而仅允许在这些点进行扩展 + +## 教程 + +* [Template-method Pattern Tutorial](https://www.journaldev.com/1763/template-method-design-pattern-in-java) + +## Java例子 + +* [javax.servlet.GenericServlet.init](https://jakarta.ee/specifications/servlet/4.0/apidocs/javax/servlet/GenericServlet.html#init--): +Method `GenericServlet.init(ServletConfig config)` calls the parameterless method `GenericServlet.init()` which is intended to be overridden in subclasses. +Method `GenericServlet.init(ServletConfig config)` is the template method in this example. + +## 鸣谢 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7)
null
train
train
2020-12-05T09:56:00
"2020-11-24T08:11:34Z"
HKTangShuo
train
iluwatar/java-design-patterns/1469_1631
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1469
iluwatar/java-design-patterns/1631
[ "timestamp(timedelta=0.0, similarity=0.8514845503470311)" ]
25ed2540f4b5d6fc2709c1e178082461a1da222d
18a1a725ee763dbf8f9c10025e23226f038cbb1c
[ "Please assign to me thx", "Ok @maheshsv ", "Do we need to implement Strategy Pattern using Lambda Expressions in Java 8", "Yes, that would be great addition to this pattern example", "ok can i create a branch and work on it, ?", "Go ahead @maheshsv ", "Hi, I want to solve this issue if it is still open.\r\nMay I? @iluwatar ", "There's a pull request from @Tubaleviao but haven't heard of him for a while", "Go ahead @ignite1771 , I'm in a quest right now", "Ok, I will work on this and send a PR to fix this issue.", "Thanks @ignite1771, looking forward to it" ]
[]
"2021-01-18T17:50:25Z"
[ "epic: pattern", "type: enhancement" ]
Functional implementation of Strategy pattern
Strategy has been implemented using Java classes. In modern Java about the same can be achieved by passing methods. Let's amend the Strategy example with functional style implementation.
[ "strategy/README.md", "strategy/etc/strategy.urm.puml", "strategy/src/main/java/com/iluwatar/strategy/App.java" ]
[ "strategy/README.md", "strategy/etc/strategy.urm.puml", "strategy/src/main/java/com/iluwatar/strategy/App.java", "strategy/src/main/java/com/iluwatar/strategy/LambdaStrategy.java" ]
[]
diff --git a/strategy/README.md b/strategy/README.md index b2330ceb84ce..2d2cbf9c4823 100644 --- a/strategy/README.md +++ b/strategy/README.md @@ -122,6 +122,51 @@ Program output: You cast the spell of disintegration and the dragon vaporizes in a pile of dust! ``` +What's more, the new feature Lambda Expressions in Java 8 provides another approach for the implementation: + +```java +public class LambdaStrategy { + + private static final Logger LOGGER = LoggerFactory.getLogger(LambdaStrategy.class); + + public enum Strategy implements DragonSlayingStrategy { + MeleeStrategy(() -> LOGGER.info( + "With your Excalibur you severe the dragon's head!")), + ProjectileStrategy(() -> LOGGER.info( + "You shoot the dragon with the magical crossbow and it falls dead on the ground!")), + SpellStrategy(() -> LOGGER.info( + "You cast the spell of disintegration and the dragon vaporizes in a pile of dust!")); + + private final DragonSlayingStrategy dragonSlayingStrategy; + + Strategy(DragonSlayingStrategy dragonSlayingStrategy) { + this.dragonSlayingStrategy = dragonSlayingStrategy; + } + + @Override + public void execute() { + dragonSlayingStrategy.execute(); + } + } +} +``` + +And here's the dragonslayer in action. + +```java + LOGGER.info("Green dragon spotted ahead!"); + dragonSlayer.changeStrategy(LambdaStrategy.Strategy.MeleeStrategy); + dragonSlayer.goToBattle(); + LOGGER.info("Red dragon emerges."); + dragonSlayer.changeStrategy(LambdaStrategy.Strategy.ProjectileStrategy); + dragonSlayer.goToBattle(); + LOGGER.info("Black dragon lands before you."); + dragonSlayer.changeStrategy(LambdaStrategy.Strategy.SpellStrategy); + dragonSlayer.goToBattle(); +``` + +Program output is the same as above one. + ## Class diagram ![alt text](./etc/strategy_urm.png "Strategy") diff --git a/strategy/etc/strategy.urm.puml b/strategy/etc/strategy.urm.puml index 8b9daabb9db4..d9b9aa526d9a 100644 --- a/strategy/etc/strategy.urm.puml +++ b/strategy/etc/strategy.urm.puml @@ -14,6 +14,19 @@ package com.iluwatar.strategy { interface DragonSlayingStrategy { + execute() {abstract} } + class LambdaStrategy { + - LOGGER : Logger {static} + + LambdaStrategy() + } + enum Strategy { + + MeleeStrategy {static} + + ProjectileStrategy {static} + + SpellStrategy {static} + - dragonSlayingStrategy : DragonSlayingStrategy + + execute() + + valueOf(name : String) : Strategy {static} + + values() : Strategy[] {static} + } class MeleeStrategy { - LOGGER : Logger {static} + MeleeStrategy() @@ -30,7 +43,10 @@ package com.iluwatar.strategy { + execute() } } +Strategy ..+ LambdaStrategy +Strategy --> "-dragonSlayingStrategy" DragonSlayingStrategy DragonSlayer --> "-strategy" DragonSlayingStrategy +Strategy ..|> DragonSlayingStrategy MeleeStrategy ..|> DragonSlayingStrategy ProjectileStrategy ..|> DragonSlayingStrategy SpellStrategy ..|> DragonSlayingStrategy diff --git a/strategy/src/main/java/com/iluwatar/strategy/App.java b/strategy/src/main/java/com/iluwatar/strategy/App.java index c526c791787d..6313087b0bff 100644 --- a/strategy/src/main/java/com/iluwatar/strategy/App.java +++ b/strategy/src/main/java/com/iluwatar/strategy/App.java @@ -45,7 +45,7 @@ public class App { /** * Program entry point. - * + * * @param args command line args */ public static void main(String[] args) { @@ -60,7 +60,7 @@ public static void main(String[] args) { dragonSlayer.changeStrategy(new SpellStrategy()); dragonSlayer.goToBattle(); - // Java 8 Strategy pattern + // Java 8 functional implementation Strategy pattern LOGGER.info("Green dragon spotted ahead!"); dragonSlayer = new DragonSlayer( () -> LOGGER.info("With your Excalibur you severe the dragon's head!")); @@ -73,5 +73,16 @@ public static void main(String[] args) { dragonSlayer.changeStrategy(() -> LOGGER.info( "You cast the spell of disintegration and the dragon vaporizes in a pile of dust!")); dragonSlayer.goToBattle(); + + // Java 8 lambda implementation with enum Strategy pattern + LOGGER.info("Green dragon spotted ahead!"); + dragonSlayer.changeStrategy(LambdaStrategy.Strategy.MeleeStrategy); + dragonSlayer.goToBattle(); + LOGGER.info("Red dragon emerges."); + dragonSlayer.changeStrategy(LambdaStrategy.Strategy.ProjectileStrategy); + dragonSlayer.goToBattle(); + LOGGER.info("Black dragon lands before you."); + dragonSlayer.changeStrategy(LambdaStrategy.Strategy.SpellStrategy); + dragonSlayer.goToBattle(); } } diff --git a/strategy/src/main/java/com/iluwatar/strategy/LambdaStrategy.java b/strategy/src/main/java/com/iluwatar/strategy/LambdaStrategy.java new file mode 100644 index 000000000000..d7480601738b --- /dev/null +++ b/strategy/src/main/java/com/iluwatar/strategy/LambdaStrategy.java @@ -0,0 +1,29 @@ +package com.iluwatar.strategy; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class LambdaStrategy { + + private static final Logger LOGGER = LoggerFactory.getLogger(LambdaStrategy.class); + + public enum Strategy implements DragonSlayingStrategy { + MeleeStrategy(() -> LOGGER.info( + "With your Excalibur you severe the dragon's head!")), + ProjectileStrategy(() -> LOGGER.info( + "You shoot the dragon with the magical crossbow and it falls dead on the ground!")), + SpellStrategy(() -> LOGGER.info( + "You cast the spell of disintegration and the dragon vaporizes in a pile of dust!")); + + private final DragonSlayingStrategy dragonSlayingStrategy; + + Strategy(DragonSlayingStrategy dragonSlayingStrategy) { + this.dragonSlayingStrategy = dragonSlayingStrategy; + } + + @Override + public void execute() { + dragonSlayingStrategy.execute(); + } + } +}
null
train
train
2021-01-16T20:00:23
"2020-08-01T11:15:53Z"
iluwatar
train
iluwatar/java-design-patterns/1638_1650
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1638
iluwatar/java-design-patterns/1650
[ "connected" ]
03bc4a6b9a6d43f20b14fa90758b848c6f4a08c5
846d05672a66e4464ebca61c56d061eb964df4c6
[ "Can I work on this?", "Go ahead @richardmr36 ", "hey @iluwatar @richardmr36 can you please give more info about the issue", "@raghuvanshi65 The link mentioned in the issue gives enough details I guess. It is easier to understand if you are aware about default parameters feature of JavaScript ES6. Let us know if you have any specific questions.", "@iluwatar could you help me with the tool or IntelliJ plugin used to generate class diagram?", "@richardmr36 there's brief explanation in https://github.com/iluwatar/java-design-patterns/wiki/01.-How-to-contribute", "@iluwatar ucls file is not getting generated. Is there any other additional steps required for that?", "@richardmr36 ucls file is not mandatory, and it's not autogenerated. Those are source files of [ObjectAid's UML plugin](https://www.objectaid.com/home). If you want to generate the UML diagram by hand for some reason, then that could be something to try." ]
[ "add an extra line after this", "add an extra line", "Done!", "Done!", "You can remove this \\<p>\r\n```suggestion\r\n * The Parameter Object is simply a wrapper object for all parameters of a method.\r\n```", "Use documentation commenting.\r\n\r\n```suggestion\r\n/**\r\n * Below two methods of name `search` is overloaded so that we can send a default value for\r\n```", "Do not use concatenation in logger.\r\n\r\n_For Syntax use this:_\r\n```suggestion\r\n LOGGER.info(\"SortBy Default parameter value is set during object creation as no value is \",\r\n \"passed.\");\r\n```", "Use default logging methods.\r\n\r\n```suggestion\r\n LOGGER.info(\"SortOrder Default parameter value is set during object creation as no value is \",\r\n \"passed.\");\r\n```", "Do you mean to use this method - info(String format, Object arg1, Object arg2)?", "yes\r\n", "```suggestion\r\nThis pattern shows us the way to have default parameters for a method in Java as the language doesn't have default parameters feature out of the box. \r\n```", "```suggestion\r\n\r\n- [Does Java have default parameters?](http://dolszewski.com/java/java-default-parameters)\r\n\r\n```", "To make the example more real, perhaps we could call some method with the `params` or at least log its contents after the construction.", "Next line to this is calling a search method using the parameter object. Output of that method basically shows the object content. Anyway logging the constructed object now. Let me know if this is fine. ", "Yes, that's fine" ]
"2021-02-10T19:20:44Z"
[ "epic: pattern", "info: good first issue", "type: feature" ]
Parameter Object idiom
It's a simple workaround for Java not having default parameters: http://dolszewski.com/java/java-default-parameters/
[ "pom.xml" ]
[ "parameter-object/README.md", "parameter-object/etc/parameter-object.urm.puml", "parameter-object/pom.xml", "parameter-object/src/main/java/com/iluwatar/parameter/object/App.java", "parameter-object/src/main/java/com/iluwatar/parameter/object/ParameterObject.java", "parameter-object/src/main/java/com/iluwatar/parameter/object/SearchService.java", "parameter-object/src/main/java/com/iluwatar/parameter/object/SortOrder.java", "pom.xml" ]
[ "parameter-object/src/test/java/com/iluwatar/parameter/object/AppTest.java", "parameter-object/src/test/java/com/iluwatar/parameter/object/ParameterObjectTest.java", "parameter-object/src/test/java/com/iluwatar/parameter/object/SearchServiceTest.java" ]
diff --git a/parameter-object/README.md b/parameter-object/README.md new file mode 100644 index 000000000000..9783879f1472 --- /dev/null +++ b/parameter-object/README.md @@ -0,0 +1,138 @@ +--- +layout: pattern +title: Parameter Object +folder: parameter-object +permalink: /patterns/parameter-object/ +categories: Behavioral +tags: + - Extensibility +--- + +## Intent + +The syntax of Java language doesn’t allow you to declare a method with a predefined value +for a parameter. Probably the best option to achieve default method parameters in Java is +by using the method overloading. Method overloading allows you to declare several methods +with the same name but with a different number of parameters. But the main problem with +method overloading as a solution for default parameter values reveals itself when a method +accepts multiple parameters. Creating an overloaded method for each possible combination of +parameters might be cumbersome. To deal with this issue, the Parameter Object pattern is used. + +## Explanation + +The Parameter Object is simply a wrapper object for all parameters of a method. +It is nothing more than just a regular POJO. The advantage of the Parameter Object over a +regular method parameter list is the fact that class fields can have default values. +Once the wrapper class is created for the method parameter list, a corresponding builder class +is also created. Usually it's an inner static class. The final step is to use the builder +to construct a new parameter object. For those parameters that are skipped, +their default values are going to be used. + + +**Programmatic Example** + +Here's the simple `SearchService` class where Method Overloading is used to default values here. To use method overloading, either the number of arguments or argument type has to be different. + +```java +public class SearchService { + //Method Overloading example. SortOrder is defaulted in this method + public String search(String type, String sortBy) { + return getQuerySummary(type, sortBy, SortOrder.DESC); + } + + /* Method Overloading example. SortBy is defaulted in this method. Note that the type has to be + different here to overload the method */ + public String search(String type, SortOrder sortOrder) { + return getQuerySummary(type, "price", sortOrder); + } + + private String getQuerySummary(String type, String sortBy, SortOrder sortOrder) { + return "Requesting shoes of type \"" + type + "\" sorted by \"" + sortBy + "\" in \"" + + sortOrder.getValue() + "ending\" order..."; + } +} + +``` + +Next we present the `SearchService` with `ParameterObject` created with Builder pattern. + +```java +public class SearchService { + + /* Parameter Object example. Default values are abstracted into the Parameter Object + at the time of Object creation */ + public String search(ParameterObject parameterObject) { + return getQuerySummary(parameterObject.getType(), parameterObject.getSortBy(), + parameterObject.getSortOrder()); + } + + private String getQuerySummary(String type, String sortBy, SortOrder sortOrder) { + return "Requesting shoes of type \"" + type + "\" sorted by \"" + sortBy + "\" in \"" + + sortOrder.getValue() + "ending\" order..."; + } +} + +public class ParameterObject { + public static final String DEFAULT_SORT_BY = "price"; + public static final SortOrder DEFAULT_SORT_ORDER = SortOrder.ASC; + + private String type; + private String sortBy = DEFAULT_SORT_BY; + private SortOrder sortOrder = DEFAULT_SORT_ORDER; + + private ParameterObject(Builder builder) { + type = builder.type; + sortBy = builder.sortBy != null && !builder.sortBy.isBlank() ? builder.sortBy : sortBy; + sortOrder = builder.sortOrder != null ? builder.sortOrder : sortOrder; + } + + public static Builder newBuilder() { + return new Builder(); + } + + //Getters and Setters... + + public static final class Builder { + + private String type; + private String sortBy; + private SortOrder sortOrder; + + private Builder() { + } + + public Builder withType(String type) { + this.type = type; + return this; + } + + public Builder sortBy(String sortBy) { + this.sortBy = sortBy; + return this; + } + + public Builder sortOrder(SortOrder sortOrder) { + this.sortOrder = sortOrder; + return this; + } + + public ParameterObject build() { + return new ParameterObject(this); + } + } +} + + +``` + +## Class diagram + +![alt text](./etc/parameter-object.png "Parameter Object") + +## Applicability + +This pattern shows us the way to have default parameters for a method in Java as the language doesn't default parameters feature out of the box. + +## Credits + +- [Does Java have default parameters?](http://dolszewski.com/java/java-default-parameters) diff --git a/parameter-object/etc/parameter-object.urm.puml b/parameter-object/etc/parameter-object.urm.puml new file mode 100644 index 000000000000..6cdab214110c --- /dev/null +++ b/parameter-object/etc/parameter-object.urm.puml @@ -0,0 +1,52 @@ +@startuml +package com.iluwatar.parameter.object { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + } + class ParameterObject { + + DEFAULT_SORT_BY : String {static} + + DEFAULT_SORT_ORDER : SortOrder {static} + - sortBy : String + - sortOrder : SortOrder + - type : String + - ParameterObject(builder : Builder) + + getSortBy() : String + + getSortOrder() : SortOrder + + getType() : String + + newBuilder() : Builder {static} + + setSortBy(sortBy : String) + + setSortOrder(sortOrder : SortOrder) + + setType(type : String) + } + class Builder { + - sortBy : String + - sortOrder : SortOrder + - type : String + - Builder() + + build() : ParameterObject + + sortBy(sortBy : String) : Builder + + sortOrder(sortOrder : SortOrder) : Builder + + withType(type : String) : Builder + } + class SearchService { + + SearchService() + - getQuerySummary(type : String, sortBy : String, sortOrder : SortOrder) : String + + search(parameterObject : ParameterObject) : String + + search(type : String, sortBy : String) : String + + search(type : String, sortOrder : SortOrder) : String + } + enum SortOrder { + + ASC {static} + + DESC {static} + - value : String + + getValue() : String + + valueOf(name : String) : SortOrder {static} + + values() : SortOrder[] {static} + } +} +Builder --> "-sortOrder" SortOrder +Builder ..+ ParameterObject +ParameterObject --> "-DEFAULT_SORT_ORDER" SortOrder +@enduml diff --git a/parameter-object/pom.xml b/parameter-object/pom.xml new file mode 100644 index 000000000000..be64d62df81a --- /dev/null +++ b/parameter-object/pom.xml @@ -0,0 +1,61 @@ +<?xml version="1.0"?> +<!-- + + The MIT License + Copyright © 2014-2019 Ilkka Seppälä + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + +--> +<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>com.iluwatar</groupId> + <artifactId>java-design-patterns</artifactId> + <version>1.24.0-SNAPSHOT</version> + </parent> + <artifactId>parameter-object</artifactId> + <dependencies> + <dependency> + <groupId>org.junit.jupiter</groupId> + <artifactId>junit-jupiter-engine</artifactId> + <scope>test</scope> + </dependency> + </dependencies> + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-assembly-plugin</artifactId> + <executions> + <execution> + <configuration> + <archive> + <manifest> + <mainClass>com.iluwatar.parameter.object.App</mainClass> + </manifest> + </archive> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> +</project> diff --git a/parameter-object/src/main/java/com/iluwatar/parameter/object/App.java b/parameter-object/src/main/java/com/iluwatar/parameter/object/App.java new file mode 100644 index 000000000000..7d4f600e21fa --- /dev/null +++ b/parameter-object/src/main/java/com/iluwatar/parameter/object/App.java @@ -0,0 +1,62 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.parameter.object; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The syntax of Java language doesn’t allow you to declare a method with a predefined value + * for a parameter. Probably the best option to achieve default method parameters in Java is + * by using the method overloading. Method overloading allows you to declare several methods + * with the same name but with a different number of parameters. But the main problem with + * method overloading as a solution for default parameter values reveals itself when a method + * accepts multiple parameters. Creating an overloaded method for each possible combination of + * parameters might be cumbersome. To deal with this issue, the Parameter Object pattern is used. + * The Parameter Object is simply a wrapper object for all parameters of a method. + * It is nothing more than just a regular POJO. The advantage of the Parameter Object over a + * regular method parameter list is the fact that class fields can have default values. + * Once the wrapper class is created for the method parameter list, a corresponding builder class + * is also created. Usually it's an inner static class. The final step is to use the builder + * to construct a new parameter object. For those parameters that are skipped, + * their default values are going to be used. + */ +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) { + ParameterObject params = ParameterObject.newBuilder() + .withType("sneakers") + .sortBy("brand") + .build(); + LOGGER.info(params.toString()); + LOGGER.info(new SearchService().search(params)); + } +} diff --git a/parameter-object/src/main/java/com/iluwatar/parameter/object/ParameterObject.java b/parameter-object/src/main/java/com/iluwatar/parameter/object/ParameterObject.java new file mode 100644 index 000000000000..65f636191b5a --- /dev/null +++ b/parameter-object/src/main/java/com/iluwatar/parameter/object/ParameterObject.java @@ -0,0 +1,113 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.parameter.object; + +public class ParameterObject { + + /** + * Default values are defined here. + */ + public static final String DEFAULT_SORT_BY = "price"; + public static final SortOrder DEFAULT_SORT_ORDER = SortOrder.ASC; + + private String type; + + /** + * Default values are assigned here. + */ + private String sortBy = DEFAULT_SORT_BY; + private SortOrder sortOrder = DEFAULT_SORT_ORDER; + + /** + * Overriding default values on object creation only when builder object has a valid value. + */ + private ParameterObject(Builder builder) { + setType(builder.type); + setSortBy(builder.sortBy != null && !builder.sortBy.isBlank() ? builder.sortBy : sortBy); + setSortOrder(builder.sortOrder != null ? builder.sortOrder : sortOrder); + } + + public static Builder newBuilder() { + return new Builder(); + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getSortBy() { + return sortBy; + } + + public void setSortBy(String sortBy) { + this.sortBy = sortBy; + } + + public SortOrder getSortOrder() { + return sortOrder; + } + + public void setSortOrder(SortOrder sortOrder) { + this.sortOrder = sortOrder; + } + + @Override + public String toString() { + return String.format("ParameterObject[type='%s', sortBy='%s', sortOrder='%s']", + type, sortBy, sortOrder); + } + + public static final class Builder { + + private String type; + private String sortBy; + private SortOrder sortOrder; + + private Builder() { + } + + public Builder withType(String type) { + this.type = type; + return this; + } + + public Builder sortBy(String sortBy) { + this.sortBy = sortBy; + return this; + } + + public Builder sortOrder(SortOrder sortOrder) { + this.sortOrder = sortOrder; + return this; + } + + public ParameterObject build() { + return new ParameterObject(this); + } + } +} diff --git a/parameter-object/src/main/java/com/iluwatar/parameter/object/SearchService.java b/parameter-object/src/main/java/com/iluwatar/parameter/object/SearchService.java new file mode 100644 index 000000000000..62acc840df92 --- /dev/null +++ b/parameter-object/src/main/java/com/iluwatar/parameter/object/SearchService.java @@ -0,0 +1,60 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.parameter.object; + +public class SearchService { + + /** + * Below two methods of name `search` is overloaded so that we can send a default value for + * one of the criteria and call the final api. A default SortOrder is sent in the first method + * and a default SortBy is sent in the second method. So two separate method definitions are + * needed for having default values for one argument in each case. Hence multiple overloaded + * methods are needed as the number of argument increases. + */ + public String search(String type, String sortBy) { + return getQuerySummary(type, sortBy, SortOrder.ASC); + } + + public String search(String type, SortOrder sortOrder) { + return getQuerySummary(type, "price", sortOrder); + } + + + /** + * The need for multiple method definitions can be avoided by the Parameter Object pattern. + * Below is the example where only one method is required and all the logic for having default + * values are abstracted into the Parameter Object at the time of object creation. + */ + public String search(ParameterObject parameterObject) { + return getQuerySummary(parameterObject.getType(), parameterObject.getSortBy(), + parameterObject.getSortOrder()); + } + + private String getQuerySummary(String type, String sortBy, SortOrder sortOrder) { + return String.format("Requesting shoes of type \"%s\" sorted by \"%s\" in \"%sending\" order..", + type, + sortBy, + sortOrder.getValue()); + } +} diff --git a/parameter-object/src/main/java/com/iluwatar/parameter/object/SortOrder.java b/parameter-object/src/main/java/com/iluwatar/parameter/object/SortOrder.java new file mode 100644 index 000000000000..6420ca9e134f --- /dev/null +++ b/parameter-object/src/main/java/com/iluwatar/parameter/object/SortOrder.java @@ -0,0 +1,39 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.parameter.object; + +public enum SortOrder { + ASC("asc"), + DESC("desc"); + + private String value; + + SortOrder(String value) { + this.value = value; + } + + public String getValue() { + return value; + } +} diff --git a/pom.xml b/pom.xml index c7d61a12bfab..48fa6fdcf801 100644 --- a/pom.xml +++ b/pom.xml @@ -208,6 +208,7 @@ <module>factory</module> <module>separated-interface</module> <module>special-case</module> + <module>parameter-object</module> </modules> <repositories>
diff --git a/parameter-object/src/test/java/com/iluwatar/parameter/object/AppTest.java b/parameter-object/src/test/java/com/iluwatar/parameter/object/AppTest.java new file mode 100644 index 000000000000..809e41f3677c --- /dev/null +++ b/parameter-object/src/test/java/com/iluwatar/parameter/object/AppTest.java @@ -0,0 +1,41 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.parameter.object; + +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Application test + */ +class AppTest { + private static final Logger LOGGER = LoggerFactory.getLogger(AppTest.class); + + @Test + void shouldExecuteApplicationWithoutException() { + App.main(new String[]{}); + LOGGER.info("Executed successfully without exception."); + } +} diff --git a/parameter-object/src/test/java/com/iluwatar/parameter/object/ParameterObjectTest.java b/parameter-object/src/test/java/com/iluwatar/parameter/object/ParameterObjectTest.java new file mode 100644 index 000000000000..05907b9c677a --- /dev/null +++ b/parameter-object/src/test/java/com/iluwatar/parameter/object/ParameterObjectTest.java @@ -0,0 +1,63 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.parameter.object; + +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ParameterObjectTest { + + private static final Logger LOGGER = LoggerFactory.getLogger(ParameterObjectTest.class); + + @Test + public void testForDefaultSortBy() { + //Creating parameter object with default value for SortBy set + ParameterObject params = ParameterObject.newBuilder() + .withType("sneakers") + .sortOrder(SortOrder.DESC) + .build(); + + assertEquals(ParameterObject.DEFAULT_SORT_BY, params.getSortBy(), + "Default SortBy is not set."); + LOGGER.info("{} Default parameter value is set during object creation as no value is passed." + , "SortBy"); + } + + @Test + public void testForDefaultSortOrder() { + //Creating parameter object with default value for SortOrder set + ParameterObject params = ParameterObject.newBuilder() + .withType("sneakers") + .sortBy("brand") + .build(); + + assertEquals(ParameterObject.DEFAULT_SORT_ORDER, params.getSortOrder(), + "Default SortOrder is not set."); + LOGGER.info("{} Default parameter value is set during object creation as no value is passed." + , "SortOrder"); + } +} diff --git a/parameter-object/src/test/java/com/iluwatar/parameter/object/SearchServiceTest.java b/parameter-object/src/test/java/com/iluwatar/parameter/object/SearchServiceTest.java new file mode 100644 index 000000000000..d7633f0e3bf9 --- /dev/null +++ b/parameter-object/src/test/java/com/iluwatar/parameter/object/SearchServiceTest.java @@ -0,0 +1,63 @@ +/* + * The MIT License + * Copyright © 2014-2019 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.parameter.object; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class SearchServiceTest { + private static final Logger LOGGER = LoggerFactory.getLogger(SearchServiceTest.class); + private ParameterObject parameterObject; + private SearchService searchService; + + @BeforeEach + public void setUp() { + //Creating parameter object with default values set + parameterObject = ParameterObject.newBuilder() + .withType("sneakers") + .build(); + + searchService = new SearchService(); + } + + /** + * Testing parameter object against the overloaded method to verify if the behaviour is same. + */ + @Test + public void testDefaultParametersMatch() { + assertEquals(searchService.search(parameterObject), searchService.search("sneakers", + SortOrder.ASC), "Default Parameter values do not not match."); + LOGGER.info("SortBy Default parameter value matches."); + + assertEquals(searchService.search(parameterObject), searchService.search("sneakers", + "price"), "Default Parameter values do not not match."); + LOGGER.info("SortOrder Default parameter value matches."); + + LOGGER.info("testDefaultParametersMatch executed successfully without errors."); + } +}
train
train
2021-02-21T14:21:11
"2021-01-28T15:39:37Z"
iluwatar
train
iluwatar/java-design-patterns/1663_1664
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1663
iluwatar/java-design-patterns/1664
[ "keyword_pr_to_issue" ]
0220f3df129e9b1c22f34bc48fc33ac57a009e37
c3c90e2bd451cdd60947704d1250c8b245881199
[]
[]
"2021-02-28T13:04:42Z"
[ "type: feature", "epic: code quality" ]
feature: Run sonar analysis on pull requests
⭐ This feature will help us review pull requests easier by helping us reviewing the modified or newly added code 👨🏻‍💻 by SonarCloud and comment out the report in the pull request. ✔️ This is going to help the contributor to increase their code quality and the coverage while removing static code errors. ✔️ Overall this is going to increase the code quality and make the process more smooth and fast. As we cannot run sonar analysis on pull requests from forked repositories using ❌ GitHub Actions; which we currently use due to its limitations to pass secrets, we will be moving with a solution from Circle CI for the time being to make our jobs easier.
[ ".mvn/wrapper/MavenWrapperDownloader.java", "mvnw.cmd", "parameter-object/pom.xml", "parameter-object/src/main/java/com/iluwatar/parameter/object/App.java", "parameter-object/src/main/java/com/iluwatar/parameter/object/ParameterObject.java", "parameter-object/src/main/java/com/iluwatar/parameter/object/SearchService.java", "parameter-object/src/main/java/com/iluwatar/parameter/object/SortOrder.java" ]
[ ".circleci/config.yml", ".mvn/wrapper/MavenWrapperDownloader.java", "mvnw.cmd", "parameter-object/pom.xml", "parameter-object/src/main/java/com/iluwatar/parameter/object/App.java", "parameter-object/src/main/java/com/iluwatar/parameter/object/ParameterObject.java", "parameter-object/src/main/java/com/iluwatar/parameter/object/SearchService.java", "parameter-object/src/main/java/com/iluwatar/parameter/object/SortOrder.java" ]
[ "parameter-object/src/test/java/com/iluwatar/parameter/object/AppTest.java", "parameter-object/src/test/java/com/iluwatar/parameter/object/ParameterObjectTest.java", "parameter-object/src/test/java/com/iluwatar/parameter/object/SearchServiceTest.java" ]
diff --git a/.circleci/config.yml b/.circleci/config.yml new file mode 100644 index 000000000000..3e35aee712dd --- /dev/null +++ b/.circleci/config.yml @@ -0,0 +1,52 @@ +# +# The MIT License +# Copyright © 2014-2021 Ilkka Seppälä +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# + +version: 2 + +jobs: + sonar-pr: + docker: + - image: circleci/openjdk:11-node + steps: + - checkout + - restore_cache: + key: jdp-sonar-pr-{{ checksum "pom.xml" }} + - run: | + if [ -n "${CIRCLE_PR_NUMBER}" ]; then + MAVEN_OPTS="-Xmx3000m" xvfb-run ./mvnw -B clean verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar \ + -Dsonar.pullrequest.key=${CIRCLE_PR_NUMBER} \ + -Dsonar.pullrequest.branch=${CIRCLE_BRANCH} \ + -Dsonar.pullrequest.base=master + else + echo "No Sonar PR analysis as this is not a pull request" + fi + - save_cache: + key: jdp-sonar-pr-{{ checksum "pom.xml" }} + paths: + - ~/.m2 + +workflows: + version: 2 + all: + jobs: + - sonar-pr diff --git a/.mvn/wrapper/MavenWrapperDownloader.java b/.mvn/wrapper/MavenWrapperDownloader.java index b901097f2db6..cfc696f0122a 100644 --- a/.mvn/wrapper/MavenWrapperDownloader.java +++ b/.mvn/wrapper/MavenWrapperDownloader.java @@ -1,18 +1,26 @@ /* - * Copyright 2007-present the original author or authors. + * The MIT License + * Copyright © 2014-2021 Ilkka Seppälä * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: * - * http://www.apache.org/licenses/LICENSE-2.0 + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. */ + import java.net.*; import java.io.*; import java.nio.channels.*; diff --git a/mvnw.cmd b/mvnw.cmd index 86115719e538..ed1dd59b0539 100644 --- a/mvnw.cmd +++ b/mvnw.cmd @@ -1,21 +1,25 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at @REM -@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM The MIT License +@REM Copyright © 2014-2021 Ilkka Seppälä +@REM +@REM Permission is hereby granted, free of charge, to any person obtaining a copy +@REM of this software and associated documentation files (the "Software"), to deal +@REM in the Software without restriction, including without limitation the rights +@REM to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +@REM copies of the Software, and to permit persons to whom the Software is +@REM furnished to do so, subject to the following conditions: +@REM +@REM The above copyright notice and this permission notice shall be included in +@REM all copies or substantial portions of the Software. +@REM +@REM THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +@REM IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +@REM FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +@REM AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +@REM LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +@REM OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +@REM THE SOFTWARE. @REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- @REM ---------------------------------------------------------------------------- @REM Maven Start Up Batch script diff --git a/parameter-object/pom.xml b/parameter-object/pom.xml index be64d62df81a..5fbf060662c2 100644 --- a/parameter-object/pom.xml +++ b/parameter-object/pom.xml @@ -2,7 +2,7 @@ <!-- The MIT License - Copyright © 2014-2019 Ilkka Seppälä + Copyright © 2014-2021 Ilkka Seppälä Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/parameter-object/src/main/java/com/iluwatar/parameter/object/App.java b/parameter-object/src/main/java/com/iluwatar/parameter/object/App.java index 7d4f600e21fa..e0f2008d9b0e 100644 --- a/parameter-object/src/main/java/com/iluwatar/parameter/object/App.java +++ b/parameter-object/src/main/java/com/iluwatar/parameter/object/App.java @@ -1,6 +1,6 @@ /* * The MIT License - * Copyright © 2014-2019 Ilkka Seppälä + * Copyright © 2014-2021 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/parameter-object/src/main/java/com/iluwatar/parameter/object/ParameterObject.java b/parameter-object/src/main/java/com/iluwatar/parameter/object/ParameterObject.java index 65f636191b5a..d90344930a54 100644 --- a/parameter-object/src/main/java/com/iluwatar/parameter/object/ParameterObject.java +++ b/parameter-object/src/main/java/com/iluwatar/parameter/object/ParameterObject.java @@ -1,6 +1,6 @@ /* * The MIT License - * Copyright © 2014-2019 Ilkka Seppälä + * Copyright © 2014-2021 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/parameter-object/src/main/java/com/iluwatar/parameter/object/SearchService.java b/parameter-object/src/main/java/com/iluwatar/parameter/object/SearchService.java index 62acc840df92..7f038bbce13e 100644 --- a/parameter-object/src/main/java/com/iluwatar/parameter/object/SearchService.java +++ b/parameter-object/src/main/java/com/iluwatar/parameter/object/SearchService.java @@ -1,6 +1,6 @@ /* * The MIT License - * Copyright © 2014-2019 Ilkka Seppälä + * Copyright © 2014-2021 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/parameter-object/src/main/java/com/iluwatar/parameter/object/SortOrder.java b/parameter-object/src/main/java/com/iluwatar/parameter/object/SortOrder.java index 6420ca9e134f..3f7240f6a4ba 100644 --- a/parameter-object/src/main/java/com/iluwatar/parameter/object/SortOrder.java +++ b/parameter-object/src/main/java/com/iluwatar/parameter/object/SortOrder.java @@ -1,6 +1,6 @@ /* * The MIT License - * Copyright © 2014-2019 Ilkka Seppälä + * Copyright © 2014-2021 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal
diff --git a/parameter-object/src/test/java/com/iluwatar/parameter/object/AppTest.java b/parameter-object/src/test/java/com/iluwatar/parameter/object/AppTest.java index 809e41f3677c..16baef96fba6 100644 --- a/parameter-object/src/test/java/com/iluwatar/parameter/object/AppTest.java +++ b/parameter-object/src/test/java/com/iluwatar/parameter/object/AppTest.java @@ -1,6 +1,6 @@ /* * The MIT License - * Copyright © 2014-2019 Ilkka Seppälä + * Copyright © 2014-2021 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/parameter-object/src/test/java/com/iluwatar/parameter/object/ParameterObjectTest.java b/parameter-object/src/test/java/com/iluwatar/parameter/object/ParameterObjectTest.java index 05907b9c677a..999cd19e0b2e 100644 --- a/parameter-object/src/test/java/com/iluwatar/parameter/object/ParameterObjectTest.java +++ b/parameter-object/src/test/java/com/iluwatar/parameter/object/ParameterObjectTest.java @@ -1,6 +1,6 @@ /* * The MIT License - * Copyright © 2014-2019 Ilkka Seppälä + * Copyright © 2014-2021 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/parameter-object/src/test/java/com/iluwatar/parameter/object/SearchServiceTest.java b/parameter-object/src/test/java/com/iluwatar/parameter/object/SearchServiceTest.java index d7633f0e3bf9..76f56121335c 100644 --- a/parameter-object/src/test/java/com/iluwatar/parameter/object/SearchServiceTest.java +++ b/parameter-object/src/test/java/com/iluwatar/parameter/object/SearchServiceTest.java @@ -1,6 +1,6 @@ /* * The MIT License - * Copyright © 2014-2019 Ilkka Seppälä + * Copyright © 2014-2021 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal
val
train
2021-02-28T10:51:47
"2021-02-28T12:37:13Z"
ohbus
train
iluwatar/java-design-patterns/1319_1742
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1319
iluwatar/java-design-patterns/1742
[ "timestamp(timedelta=358.0, similarity=0.8814113081186224)", "keyword_pr_to_issue" ]
122e6edb38a3a1335363447a8a3f638826a6dab6
e498c25675856e00a8c122be5e01bf390f748a72
[ "Could I take this? @iluwatar ", "Sure thing @tao-sun2 \r\n\r\nPlease mention a timeline for when can we expect a PR against this issue.", "I will finish this issue within a week." ]
[ "```suggestion\r\ncategories: Structural\r\n```", "Is there console output that we could show here?", "```suggestion\r\n- The application only uses a few shared common table-oriented data structures.\r\n```", "Add a comment to describe what happens in this section", "Could we use try-with-resources statement for automatic closing? Check elsewhere too.", "Having a separate class for a couple of constants feels unnecessary. Could we combine this to `UserTableModule`?" ]
"2021-05-02T15:23:48Z"
[ "epic: pattern", "type: feature" ]
Table Module pattern
https://inviqa.com/blog/architecture-patterns-domain-model-and-friends
[ "pom.xml" ]
[ "pom.xml", "table-module/README.md", "table-module/etc/table-module.urm.puml", "table-module/pom.xml", "table-module/src/main/java/com/iluwatar/tablemodule/App.java", "table-module/src/main/java/com/iluwatar/tablemodule/User.java", "table-module/src/main/java/com/iluwatar/tablemodule/UserTableModule.java" ]
[ "table-module/src/test/java/com/iluwatar/tablemodule/AppTest.java", "table-module/src/test/java/com/iluwatar/tablemodule/UserTableModuleTest.java", "table-module/src/test/java/com/iluwatar/tablemodule/UserTest.java" ]
diff --git a/pom.xml b/pom.xml index 1b8f30e92b83..8173972bd27a 100644 --- a/pom.xml +++ b/pom.xml @@ -225,6 +225,7 @@ <module>active-object</module> <module>model-view-viewmodel</module> <module>composite-entity</module> + <module>table-module</module> <module>presentation</module> <module>lockable-object</module> </modules> diff --git a/table-module/README.md b/table-module/README.md new file mode 100644 index 000000000000..318a2694da26 --- /dev/null +++ b/table-module/README.md @@ -0,0 +1,134 @@ +--- +layout: pattern +title: Table Module +folder: table-module +permalink: /patterns/table-module/ +categories: Structural +tags: + - Data access +--- +## Intent +Table Module organizes domain logic with one class per table in the database, and a single instance of a class contains the various procedures that will act on the data. + +## Explanation + +Real world example + +> When dealing with a user system, we need some operations on the user table. We can use the table module pattern in this scenario. We can create a class named UserTableModule and initialize a instance of that class to handle the business logic for all rows in the user table. + +In plain words + +> A single instance that handles the business logic for all rows in a database table or view. + +Programmatic Example + +In the example of the user system, we need to deal with the domain logic of user login and user registration. We can use the table module pattern and create an instance of the class `UserTableModule` to handle the business logic for all rows in the user table. + +Here is the basic `User` entity. + +```java +@Setter +@Getter +@ToString +@EqualsAndHashCode +@AllArgsConstructor +public class User { + private int id; + private String username; + private String password; +} +``` + +Here is the `UserTableModule` class. + +```java +public class UserTableModule { + private final DataSource dataSource; + private Connection connection = null; + private ResultSet resultSet = null; + private PreparedStatement preparedStatement = null; + + public UserTableModule(final DataSource userDataSource) { + this.dataSource = userDataSource; + } + + /** + * Login using username and password. + * + * @param username the username of a user + * @param password the password of a user + * @return the execution result of the method + * @throws SQLException if any error + */ + public int login(final String username, final String password) throws SQLException { + // Method implementation. + + } + + /** + * Register a new user. + * + * @param user a user instance + * @return the execution result of the method + * @throws SQLException if any error + */ + public int registerUser(final User user) throws SQLException { + // Method implementation. + } +} +``` + +In the class `App`, we use an instance of the `UserTableModule` to handle user login and registration. + +```java +// Create data source and create the user table. +final var dataSource = createDataSource(); +createSchema(dataSource); +userTableModule = new UserTableModule(dataSource); + +//Initialize two users. +var user1 = new User(1, "123456", "123456"); +var user2 = new User(2, "test", "password"); + +//Login and register using the instance of userTableModule. +userTableModule.registerUser(user1); +userTableModule.login(user1.getUsername(), user1.getPassword()); +userTableModule.login(user2.getUsername(), user2.getPassword()); +userTableModule.registerUser(user2); +userTableModule.login(user2.getUsername(), user2.getPassword()); + +deleteSchema(dataSource); +``` + +The program output: + +```java +12:22:13.095 [main] INFO com.iluwatar.tablemodule.UserTableModule - Register successfully! +12:22:13.117 [main] INFO com.iluwatar.tablemodule.UserTableModule - Login successfully! +12:22:13.128 [main] INFO com.iluwatar.tablemodule.UserTableModule - Fail to login! +12:22:13.136 [main] INFO com.iluwatar.tablemodule.UserTableModule - Register successfully! +12:22:13.144 [main] INFO com.iluwatar.tablemodule.UserTableModule - Login successfully! +``` + +## Class diagram + +![](./etc/table-module.urm.png "table module") + +## Applicability + +Use the Table Module Pattern when + +- Domain logic is simple and data is in tabular form. +- The application only uses a few shared common table-oriented data structures. + +## Related patterns + +- [Transaction Script](https://java-design-patterns.com/patterns/transaction-script/) + +- Domain Model + +## Credits + +* [Table Module Pattern](http://wiki3.cosc.canterbury.ac.nz/index.php/Table_module_pattern) +* [Patterns of Enterprise Application Architecture](https://www.amazon.com/gp/product/0321127420/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0321127420&linkId=18acc13ba60d66690009505577c45c04) +* [Architecture patterns: domain model and friends](https://inviqa.com/blog/architecture-patterns-domain-model-and-friends) \ No newline at end of file diff --git a/table-module/etc/table-module.urm.puml b/table-module/etc/table-module.urm.puml new file mode 100644 index 000000000000..6cf75797f080 --- /dev/null +++ b/table-module/etc/table-module.urm.puml @@ -0,0 +1,38 @@ +@startuml +package com.iluwatar.tablemodule { + class App { + - DB_URL : String {static} + - LOGGER : Logger {static} + - App() + - createDataSource() : DataSource {static} + - createSchema(dataSource : DataSource) {static} + - deleteSchema(dataSource : DataSource) {static} + + main(args : String[]) {static} + } + class User { + - id : int + - password : String + - username : String + + User(id : int, username : String, password : String) + # canEqual(other : Object) : boolean + + equals(o : Object) : boolean + + getId() : int + + getPassword() : String + + getUsername() : String + + hashCode() : int + + setId(id : int) + + setPassword(password : String) + + setUsername(username : String) + + toString() : String + } + class UserTableModule { + + CREATE_SCHEMA_SQL : String {static} + + DELETE_SCHEMA_SQL : String {static} + - LOGGER : Logger {static} + - dataSource : DataSource + + UserTableModule(userDataSource : DataSource) + + login(username : String, password : String) : int + + registerUser(user : User) : int + } +} +@enduml \ No newline at end of file diff --git a/table-module/pom.xml b/table-module/pom.xml new file mode 100644 index 000000000000..eae698c0909e --- /dev/null +++ b/table-module/pom.xml @@ -0,0 +1,73 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + + The MIT License + Copyright © 2014-2021 Ilkka Seppälä + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + +--> +<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns="http://maven.apache.org/POM/4.0.0" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <parent> + <artifactId>java-design-patterns</artifactId> + <groupId>com.iluwatar</groupId> + <version>1.25.0-SNAPSHOT</version> + </parent> + <modelVersion>4.0.0</modelVersion> + + <artifactId>table-module</artifactId> + + <dependencies> + <dependency> + <groupId>com.h2database</groupId> + <artifactId>h2</artifactId> + </dependency> + <dependency> + <groupId>org.junit.jupiter</groupId> + <artifactId>junit-jupiter-engine</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-core</artifactId> + </dependency> + </dependencies> + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-assembly-plugin</artifactId> + <executions> + <execution> + <configuration> + <archive> + <manifest> + <mainClass>com.iluwatar.tablemodule.App</mainClass> + </manifest> + </archive> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> + +</project> diff --git a/table-module/src/main/java/com/iluwatar/tablemodule/App.java b/table-module/src/main/java/com/iluwatar/tablemodule/App.java new file mode 100644 index 000000000000..7b22666e08eb --- /dev/null +++ b/table-module/src/main/java/com/iluwatar/tablemodule/App.java @@ -0,0 +1,81 @@ +package com.iluwatar.tablemodule; + +import java.sql.SQLException; +import javax.sql.DataSource; + +import lombok.extern.slf4j.Slf4j; +import org.h2.jdbcx.JdbcDataSource; + + +/** + * Table Module pattern is a domain logic pattern. + * In Table Module a single class encapsulates all the domain logic for all + * records stored in a table or view. It's important to note that there is no + * translation of data between objects and rows, as it happens in Domain Model, + * hence implementation is relatively simple when compared to the Domain + * Model pattern. + * + * <p>In this example we will use the Table Module pattern to implement register + * and login methods for the records stored in the user table. The main + * method will initialise an instance of {@link UserTableModule} and use it to + * handle the domain logic for the user table.</p> + */ +@Slf4j +public final class App { + private static final String DB_URL = "jdbc:h2:~/test"; + + /** + * Private constructor. + */ + private App() { + + } + + /** + * Program entry point. + * + * @param args command line args. + * @throws SQLException if any error occurs. + */ + public static void main(final String[] args) throws SQLException { + // Create data source and create the user table. + final var dataSource = createDataSource(); + createSchema(dataSource); + var userTableModule = new UserTableModule(dataSource); + + // Initialize two users. + var user1 = new User(1, "123456", "123456"); + var user2 = new User(2, "test", "password"); + + // Login and register using the instance of userTableModule. + userTableModule.registerUser(user1); + userTableModule.login(user1.getUsername(), user1.getPassword()); + userTableModule.login(user2.getUsername(), user2.getPassword()); + userTableModule.registerUser(user2); + userTableModule.login(user2.getUsername(), user2.getPassword()); + + deleteSchema(dataSource); + } + + private static void deleteSchema(final DataSource dataSource) + throws SQLException { + try (var connection = dataSource.getConnection(); + var statement = connection.createStatement()) { + statement.execute(UserTableModule.DELETE_SCHEMA_SQL); + } + } + + private static void createSchema(final DataSource dataSource) + throws SQLException { + try (var connection = dataSource.getConnection(); + var statement = connection.createStatement()) { + statement.execute(UserTableModule.CREATE_SCHEMA_SQL); + } + } + + private static DataSource createDataSource() { + var dataSource = new JdbcDataSource(); + dataSource.setURL(DB_URL); + return dataSource; + } +} diff --git a/table-module/src/main/java/com/iluwatar/tablemodule/User.java b/table-module/src/main/java/com/iluwatar/tablemodule/User.java new file mode 100644 index 000000000000..ac307d4503b3 --- /dev/null +++ b/table-module/src/main/java/com/iluwatar/tablemodule/User.java @@ -0,0 +1,23 @@ +package com.iluwatar.tablemodule; + +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + + +/** + * A user POJO that represents the data that will be read from the data source. + */ +@Setter +@Getter +@ToString +@EqualsAndHashCode +@AllArgsConstructor +public class User { + private int id; + private String username; + private String password; + +} diff --git a/table-module/src/main/java/com/iluwatar/tablemodule/UserTableModule.java b/table-module/src/main/java/com/iluwatar/tablemodule/UserTableModule.java new file mode 100644 index 000000000000..f1a4d044454d --- /dev/null +++ b/table-module/src/main/java/com/iluwatar/tablemodule/UserTableModule.java @@ -0,0 +1,96 @@ +package com.iluwatar.tablemodule; + +import java.sql.ResultSet; +import java.sql.SQLException; +import javax.sql.DataSource; + +import lombok.extern.slf4j.Slf4j; + + +/** + * This class organizes domain logic with the user table in the + * database. A single instance of this class contains the various + * procedures that will act on the data. + */ +@Slf4j +public class UserTableModule { + /** + * Public element for creating schema. + */ + public static final String CREATE_SCHEMA_SQL = + "CREATE TABLE IF NOT EXISTS USERS (ID NUMBER, USERNAME VARCHAR(30) " + + "UNIQUE,PASSWORD VARCHAR(30))"; + /** + * Public element for deleting schema. + */ + public static final String DELETE_SCHEMA_SQL = "DROP TABLE USERS IF EXISTS"; + private final DataSource dataSource; + + + /** + * Public constructor. + * + * @param userDataSource the data source in the database + */ + public UserTableModule(final DataSource userDataSource) { + this.dataSource = userDataSource; + } + + + /** + * Login using username and password. + * + * @param username the username of a user + * @param password the password of a user + * @return the execution result of the method + * @throws SQLException if any error + */ + public int login(final String username, final String password) + throws SQLException { + var sql = "select count(*) from USERS where username=? and password=?"; + ResultSet resultSet = null; + try (var connection = dataSource.getConnection(); + var preparedStatement = + connection.prepareStatement(sql) + ) { + var result = 0; + preparedStatement.setString(1, username); + preparedStatement.setString(2, password); + resultSet = preparedStatement.executeQuery(); + while (resultSet.next()) { + result = resultSet.getInt(1); + } + if (result == 1) { + LOGGER.info("Login successfully!"); + } else { + LOGGER.info("Fail to login!"); + } + return result; + } finally { + if (resultSet != null) { + resultSet.close(); + } + } + } + + /** + * Register a new user. + * + * @param user a user instance + * @return the execution result of the method + * @throws SQLException if any error + */ + public int registerUser(final User user) throws SQLException { + var sql = "insert into USERS (username, password) values (?,?)"; + try (var connection = dataSource.getConnection(); + var preparedStatement = + connection.prepareStatement(sql) + ) { + preparedStatement.setString(1, user.getUsername()); + preparedStatement.setString(2, user.getPassword()); + var result = preparedStatement.executeUpdate(); + LOGGER.info("Register successfully!"); + return result; + } + } +}
diff --git a/table-module/src/test/java/com/iluwatar/tablemodule/AppTest.java b/table-module/src/test/java/com/iluwatar/tablemodule/AppTest.java new file mode 100644 index 000000000000..cafae7cdbe38 --- /dev/null +++ b/table-module/src/test/java/com/iluwatar/tablemodule/AppTest.java @@ -0,0 +1,16 @@ +package com.iluwatar.tablemodule; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +/** + * Tests that the table module example runs without errors. + */ +class AppTest { + + @Test + void shouldExecuteWithoutException() { + assertDoesNotThrow(() -> App.main(new String[]{})); + } +} diff --git a/table-module/src/test/java/com/iluwatar/tablemodule/UserTableModuleTest.java b/table-module/src/test/java/com/iluwatar/tablemodule/UserTableModuleTest.java new file mode 100644 index 000000000000..86685f58dd9c --- /dev/null +++ b/table-module/src/test/java/com/iluwatar/tablemodule/UserTableModuleTest.java @@ -0,0 +1,78 @@ +package com.iluwatar.tablemodule; + +import org.h2.jdbcx.JdbcDataSource; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import javax.sql.DataSource; +import java.sql.DriverManager; +import java.sql.SQLException; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class UserTableModuleTest { + private static final String DB_URL = "jdbc:h2:~/test"; + + private static DataSource createDataSource() { + var dataSource = new JdbcDataSource(); + dataSource.setURL(DB_URL); + return dataSource; + } + + @BeforeEach + void setUp() throws SQLException { + try (var connection = DriverManager.getConnection(DB_URL); + var statement = connection.createStatement()) { + statement.execute(UserTableModule.DELETE_SCHEMA_SQL); + statement.execute(UserTableModule.CREATE_SCHEMA_SQL); + } + } + + @AfterEach + void tearDown() throws SQLException { + try (var connection = DriverManager.getConnection(DB_URL); + var statement = connection.createStatement()) { + statement.execute(UserTableModule.DELETE_SCHEMA_SQL); + } + } + + @Test + void loginShouldFail() throws SQLException { + var dataSource = createDataSource(); + var userTableModule = new UserTableModule(dataSource); + var user = new User(1, "123456", "123456"); + assertEquals(0, userTableModule.login(user.getUsername(), + user.getPassword())); + } + + @Test + void loginShouldSucceed() throws SQLException { + var dataSource = createDataSource(); + var userTableModule = new UserTableModule(dataSource); + var user = new User(1, "123456", "123456"); + userTableModule.registerUser(user); + assertEquals(1, userTableModule.login(user.getUsername(), + user.getPassword())); + } + + @Test + void registerShouldFail() throws SQLException { + var dataSource = createDataSource(); + var userTableModule = new UserTableModule(dataSource); + var user = new User(1, "123456", "123456"); + userTableModule.registerUser(user); + assertThrows(SQLException.class, () -> { + userTableModule.registerUser(user); + }); + } + + @Test + void registerShouldSucceed() throws SQLException { + var dataSource = createDataSource(); + var userTableModule = new UserTableModule(dataSource); + var user = new User(1, "123456", "123456"); + assertEquals(1, userTableModule.registerUser(user)); + } +} \ No newline at end of file diff --git a/table-module/src/test/java/com/iluwatar/tablemodule/UserTest.java b/table-module/src/test/java/com/iluwatar/tablemodule/UserTest.java new file mode 100644 index 000000000000..669d86035f01 --- /dev/null +++ b/table-module/src/test/java/com/iluwatar/tablemodule/UserTest.java @@ -0,0 +1,131 @@ +package com.iluwatar.tablemodule; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class UserTest { + @Test + void testCanEqual() { + assertFalse((new User(1, "janedoe", "iloveyou")) + .canEqual("Other")); + } + + @Test + void testCanEqual2() { + var user = new User(1, "janedoe", "iloveyou"); + assertTrue(user.canEqual(new User(1, "janedoe", + "iloveyou"))); + } + + @Test + void testEquals1() { + var user = new User(1, "janedoe", "iloveyou"); + assertNotEquals("42", user); + } + + @Test + void testEquals2() { + var user = new User(1, "janedoe", "iloveyou"); + assertEquals(user, new User(1, "janedoe", + "iloveyou")); + } + + @Test + void testEquals3() { + var user = new User(123, "janedoe", "iloveyou"); + assertNotEquals(user, new User(1, "janedoe", + "iloveyou")); + } + + @Test + void testEquals4() { + var user = new User(1, null, "iloveyou"); + assertNotEquals(user, new User(1, "janedoe", + "iloveyou")); + } + + @Test + void testEquals5() { + var user = new User(1, "iloveyou", "iloveyou"); + assertNotEquals(user, new User(1, "janedoe", + "iloveyou")); + } + + @Test + void testEquals6() { + var user = new User(1, "janedoe", "janedoe"); + assertNotEquals(user, new User(1, "janedoe", + "iloveyou")); + } + + @Test + void testEquals7() { + var user = new User(1, "janedoe", null); + assertNotEquals(user, new User(1, "janedoe", + "iloveyou")); + } + + @Test + void testEquals8() { + var user = new User(1, null, "iloveyou"); + assertEquals(user, new User(1, null, + "iloveyou")); + } + + @Test + void testEquals9() { + var user = new User(1, "janedoe", null); + assertEquals(user, new User(1, "janedoe", + null)); + } + + @Test + void testHashCode1() { + assertEquals(-1758941372, (new User(1, "janedoe", + "iloveyou")).hashCode()); + + } + + @Test + void testHashCode2() { + assertEquals(-1332207447, (new User(1, null, + "iloveyou")).hashCode()); + } + + @Test + void testHashCode3() { + assertEquals(-426522485, (new User(1, "janedoe", + null)).hashCode()); + } + + @Test + void testSetId() { + var user = new User(1, "janedoe", "iloveyou"); + user.setId(2); + assertEquals(2, user.getId()); + } + + @Test + void testSetPassword() { + var user = new User(1, "janedoe", "tmp"); + user.setPassword("iloveyou"); + assertEquals("iloveyou", user.getPassword()); + } + + @Test + void testSetUsername() { + var user = new User(1, "tmp", "iloveyou"); + user.setUsername("janedoe"); + assertEquals("janedoe", user.getUsername()); + } + + @Test + void testToString() { + var user = new User(1, "janedoe", "iloveyou"); + assertEquals(String.format("User(id=%s, username=%s, password=%s)", + user.getId(), user.getUsername(), user.getPassword()), + user.toString()); + } +} +
train
train
2021-05-14T17:56:41
"2020-07-07T18:12:15Z"
iluwatar
train
iluwatar/java-design-patterns/1747_1748
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1747
iluwatar/java-design-patterns/1748
[ "keyword_pr_to_issue" ]
1dd26289e5836ee31dca18b6077666f357322ca3
1388e38744b7b83ea4bfa473a719e764ef83534a
[ "Thanks, @DEV-VRUPER for mentioning the problem.\r\n\r\nThere seems to be an error due to an additional hyphen at the end of the URL.\r\n\r\nPlease do let me know if you want to raise a PR for fixing this.", "@ohbus I have fixed it and raised the PR . Please could you review .\r\n\r\nThanks." ]
[ "```suggestion\r\n[![All Contributors](https://img.shields.io/badge/all_contributors-165-orange.svg?style=flat-square)](#contributors)\r\n```\r\n\r\nCan you explain why did you decrease the value of the number of contributors?", "There was merge conflicts earlier and so to make it consistent with master i reduced the number to 164 . But i guess #1749 has been merged to `master` now ,so i've incorporated the changes in my readme file. ", "I can understand that.\r\n\r\n_As a general rule of thumb, Whenever there is a conflict try to resolve it by rebasing with the branch you are trying to make a PR._" ]
"2021-05-08T15:14:53Z"
[ "info: help wanted", "info: good first issue", "epic: documentation" ]
Issue with all contributors badge in Readme.md file
Observed that when we click on the `all contributors` badge on the project page , it does not re-direct us to the sections where all the project contributors are listed . ![image](https://user-images.githubusercontent.com/30525467/117465715-df5fc100-af49-11eb-8a72-e0181a11478b.png) **Possible fix will be to correct the URL for this badge inside the projects Readme.md file .**
[ "README.md" ]
[ "README.md" ]
[]
diff --git a/README.md b/README.md index 971fe9073997..8c520b741499 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ [![Coverage](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=coverage)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) [![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) <!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section --> -[![All Contributors](https://img.shields.io/badge/all_contributors-165-orange.svg?style=flat-square)](#contributors-) +[![All Contributors](https://img.shields.io/badge/all_contributors-165-orange.svg?style=flat-square)](#contributors) <!-- ALL-CONTRIBUTORS-BADGE:END --> <br/>
null
train
train
2021-05-09T16:00:47
"2021-05-07T14:40:52Z"
DEV-VRUPER
train
iluwatar/java-design-patterns/1821_1823
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1821
iluwatar/java-design-patterns/1823
[ "timestamp(timedelta=107.0, similarity=0.8905420145123631)" ]
42eb7950aef44e00b9a5363e681762a1bf1271c3
0ff4e16f0c5ed3960e08df16a6ebb67470bcaf28
[ "@iluwatar I want to work on this issue. Please assign it to me.", "Sounds awesome @chandrikadeb7, please go ahead", "@chandrikadeb7 and @iluwatar While all contributors have been allowing us to mention contributions on the doc, especially the Wiki, I am not sure how or if we will be able to identify them at all.", "@iluwatar Please suggest.", "Can I work on this issue?? @ohbus ", "> Can I work on this issue?? @ohbus\r\n\r\nPR #1823 is already raised.\r\n\r\nIf you want you may collaborate with @chandrikadeb7 to make it configurable like all contributors and not just a simple image generated by using GitHub API", "I like the idea of generating the contributor list automatically, but the implementation seems insufficient. There's no way to click the contributor avatars and see their profile and there's no way to see what they have contributed. I'm sorry, but it seems we are going to stick with the old all-contributors bot if these points can't be addressed.", "Closing this issue for now.\r\n\r\nWe can look for a better alternative when it is available in the future. U until then we need to live with the commits." ]
[]
"2021-10-01T04:04:55Z"
[ "type: enhancement", "resolution: won't fix", "epic: documentation" ]
Readme Update: Show Project Contributors automatically without adding them in successive commits
- Using dynamic web app [contributors-img](https://contrib.rocks/preview) - Reduces commits made for successive contributors - Takes less space in Readme file and increases the count automatically. **Example screenshot** ![Screenshot 2021-09-30 at 9 35 05 AM](https://user-images.githubusercontent.com/29686102/135385647-ad5d5109-f638-40fc-ae11-1e114a9caf8f.png)
[ "README.md" ]
[ "README.md" ]
[]
diff --git a/README.md b/README.md index c7c137fa3d5c..a28380099c06 100644 --- a/README.md +++ b/README.md @@ -74,271 +74,10 @@ This project is licensed under the terms of the MIT license. <!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section --> <!-- prettier-ignore-start --> <!-- markdownlint-disable --> -<table> - <tr> - <td align="center"><a href="https://github.com/iluwatar"><img src="https://avatars1.githubusercontent.com/u/582346?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Ilkka Seppälä</b></sub></a><br /><a href="#projectManagement-iluwatar" title="Project Management">📆</a> <a href="#maintenance-iluwatar" title="Maintenance">🚧</a> <a href="#content-iluwatar" title="Content">🖋</a></td> - <td align="center"><a href="https://github.com/amit1307"><img src="https://avatars0.githubusercontent.com/u/23420222?v=4?s=100" width="100px;" alt=""/><br /><sub><b>amit1307</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=amit1307" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/npathai"><img src="https://avatars2.githubusercontent.com/u/1792515?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Narendra Pathai</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=npathai" title="Code">💻</a> <a href="#ideas-npathai" title="Ideas, Planning, & Feedback">🤔</a> <a href="https://github.com/iluwatar/java-design-patterns/pulls?q=is%3Apr+reviewed-by%3Anpathai" title="Reviewed Pull Requests">👀</a></td> - <td align="center"><a href="https://github.com/fluxw42"><img src="https://avatars1.githubusercontent.com/u/1545460?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jeroen Meulemeester</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=fluxw42" title="Code">💻</a></td> - </tr> - <tr> - <td align="center"><a href="http://www.joemccarthy.co.uk"><img src="https://avatars0.githubusercontent.com/u/4526195?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Joseph McCarthy</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=mikulucky" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/thomasoss"><img src="https://avatars1.githubusercontent.com/u/22516154?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Thomas</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=thomasoss" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/anuragagarwal561994"><img src="https://avatars1.githubusercontent.com/u/6075379?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Anurag Agarwal</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=anuragagarwal561994" title="Code">💻</a></td> - <td align="center"><a href="https://markusmo3.github.io"><img src="https://avatars1.githubusercontent.com/u/3317416?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Markus Moser</b></sub></a><br /><a href="#design-markusmo3" title="Design">🎨</a> <a href="https://github.com/iluwatar/java-design-patterns/commits?author=markusmo3" title="Code">💻</a> <a href="#ideas-markusmo3" title="Ideas, Planning, & Feedback">🤔</a></td> - </tr> - <tr> - <td align="center"><a href="https://twitter.com/i_sabiq"><img src="https://avatars1.githubusercontent.com/u/19510920?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Sabiq Ihab</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=isabiq" title="Code">💻</a></td> - <td align="center"><a href="http://inbravo.github.io"><img src="https://avatars3.githubusercontent.com/u/5253764?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Amit Dixit</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=inbravo" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/piyushchaudhari04"><img src="https://avatars3.githubusercontent.com/u/10268029?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Piyush Kailash Chaudhari</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=piyushchaudhari04" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/joshzambales"><img src="https://avatars1.githubusercontent.com/u/8704552?v=4?s=100" width="100px;" alt=""/><br /><sub><b>joshzambales</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=joshzambales" title="Code">💻</a></td> - </tr> - <tr> - <td align="center"><a href="https://github.com/Crossy147"><img src="https://avatars2.githubusercontent.com/u/7272996?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Kamil Pietruszka</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=Crossy147" title="Code">💻</a></td> - <td align="center"><a href="http://cs.joensuu.fi/~zkhayda"><img src="https://avatars2.githubusercontent.com/u/660742?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Zafar Khaydarov</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=zafarella" title="Code">💻</a> <a href="https://github.com/iluwatar/java-design-patterns/commits?author=zafarella" title="Documentation">📖</a></td> - <td align="center"><a href="https://kemitix.github.io/"><img src="https://avatars1.githubusercontent.com/u/1147749?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Paul Campbell</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=kemitix" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/Argyro-Sioziou"><img src="https://avatars0.githubusercontent.com/u/22822639?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Argyro Sioziou</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=Argyro-Sioziou" title="Code">💻</a></td> - </tr> - <tr> - <td align="center"><a href="https://github.com/TylerMcConville"><img src="https://avatars0.githubusercontent.com/u/4946449?v=4?s=100" width="100px;" alt=""/><br /><sub><b>TylerMcConville</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=TylerMcConville" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/saksham93"><img src="https://avatars1.githubusercontent.com/u/37399540?v=4?s=100" width="100px;" alt=""/><br /><sub><b>saksham93</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=saksham93" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/nikhilbarar"><img src="https://avatars2.githubusercontent.com/u/37332144?v=4?s=100" width="100px;" alt=""/><br /><sub><b>nikhilbarar</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=nikhilbarar" title="Code">💻</a></td> - <td align="center"><a href="http://colinbut.com"><img src="https://avatars2.githubusercontent.com/u/10725674?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Colin But</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=colinbut" title="Code">💻</a></td> - </tr> - <tr> - <td align="center"><a href="https://github.com/ruslanpa"><img src="https://avatars2.githubusercontent.com/u/1503411?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Ruslan</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=ruslanpa" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/JuhoKang"><img src="https://avatars1.githubusercontent.com/u/4745294?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Juho Kang</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=JuhoKang" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/dheeraj-mummareddy"><img src="https://avatars2.githubusercontent.com/u/7002230?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Dheeraj Mummareddy</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=dheeraj-mummareddy" title="Code">💻</a></td> - <td align="center"><a href="https://www.bernardosulzbach.com"><img src="https://avatars0.githubusercontent.com/u/8271090?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Bernardo Sulzbach</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=bernardosulzbach" title="Code">💻</a></td> - </tr> - <tr> - <td align="center"><a href="https://github.com/4lexis"><img src="https://avatars0.githubusercontent.com/u/19871727?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Aleksandar Dudukovic</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=4lexis" title="Code">💻</a></td> - <td align="center"><a href="https://www.yusufaytas.com"><img src="https://avatars2.githubusercontent.com/u/1049483?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Yusuf Aytaş</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=yusufaytas" title="Code">💻</a></td> - <td align="center"><a href="http://futurehomes.hu"><img src="https://avatars2.githubusercontent.com/u/1001491?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Mihály Kuprivecz</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=qpi" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/kapinuss"><img src="https://avatars0.githubusercontent.com/u/17639945?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Stanislav Kapinus</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=kapinuss" title="Code">💻</a></td> - </tr> - <tr> - <td align="center"><a href="https://github.com/gvsharma"><img src="https://avatars1.githubusercontent.com/u/6648152?v=4?s=100" width="100px;" alt=""/><br /><sub><b>GVSharma</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=gvsharma" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/SrdjanPaunovic"><img src="https://avatars1.githubusercontent.com/u/22815104?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Srđan Paunović</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=SrdjanPaunovic" title="Code">💻</a></td> - <td align="center"><a href="https://sideris.xyz/"><img src="https://avatars3.githubusercontent.com/u/5484694?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Petros G. Sideris</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=sideris" title="Code">💻</a></td> - <td align="center"><a href="https://www.linkedin.com/in/pramodgupta3/"><img src="https://avatars1.githubusercontent.com/u/2184241?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Pramod Gupta</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/pulls?q=is%3Apr+reviewed-by%3AIAmPramod" title="Reviewed Pull Requests">👀</a></td> - </tr> - <tr> - <td align="center"><a href="https://amarnath510.github.io/portfolio"><img src="https://avatars0.githubusercontent.com/u/4599623?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Amarnath Chandana</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=Amarnath510" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/Anurag870"><img src="https://avatars1.githubusercontent.com/u/6295975?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Anurag870</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=Anurag870" title="Code">💻</a> <a href="https://github.com/iluwatar/java-design-patterns/commits?author=Anurag870" title="Documentation">📖</a></td> - <td align="center"><a href="http://theerroris.me"><img src="https://avatars0.githubusercontent.com/u/1685953?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Wes Gilleland</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=Deathnerd" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/Harshrajsinh"><img src="https://avatars2.githubusercontent.com/u/22811531?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Harshraj Thakor</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=Harshrajsinh" title="Code">💻</a></td> - </tr> - <tr> - <td align="center"><a href="https://github.com/MaVdbussche"><img src="https://avatars1.githubusercontent.com/u/26136934?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Martin Vandenbussche</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=MaVdbussche" title="Code">💻</a></td> - <td align="center"><a href="https://alexsomai.com"><img src="https://avatars1.githubusercontent.com/u/5720977?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Alexandru Somai</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=alexsomai" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/amogozov"><img src="https://avatars3.githubusercontent.com/u/7372215?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Artur Mogozov</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=amogozov" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/anthonycampbell"><img src="https://avatars3.githubusercontent.com/u/10249255?v=4?s=100" width="100px;" alt=""/><br /><sub><b>anthony</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=anthonycampbell" title="Code">💻</a></td> - </tr> - <tr> - <td align="center"><a href="http://ccygnus.com/"><img src="https://avatars1.githubusercontent.com/u/9342724?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Christian Cygnus</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=christophercolumbusdog" title="Code">💻</a></td> - <td align="center"><a href="https://about.me/dzmitryh"><img src="https://avatars2.githubusercontent.com/u/5390492?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Dima Gubin</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=dzmitryh" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/jjjimenez100"><img src="https://avatars3.githubusercontent.com/u/22243493?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Joshua Jimenez</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=jjjimenez100" title="Code">💻</a></td> - <td align="center"><a href="http://about.me/kaiwinter"><img src="https://avatars0.githubusercontent.com/u/110982?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Kai Winter</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=kaiwinter" title="Code">💻</a></td> - </tr> - <tr> - <td align="center"><a href="https://github.com/lbroman"><img src="https://avatars1.githubusercontent.com/u/86007?v=4?s=100" width="100px;" alt=""/><br /><sub><b>lbroman</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=lbroman" title="Code">💻</a></td> - <td align="center"><a href="https://przemeknowak.com"><img src="https://avatars1.githubusercontent.com/u/3254609?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Przemek</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=pnowy" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/prafful1"><img src="https://avatars0.githubusercontent.com/u/14350274?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Prafful Agarwal</b></sub></a><br /><a href="#content-prafful1" title="Content">🖋</a></td> - <td align="center"><a href="https://github.com/sankypanhale"><img src="https://avatars1.githubusercontent.com/u/6478783?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Sanket Panhale</b></sub></a><br /><a href="#content-sankypanhale" title="Content">🖋</a></td> - </tr> - <tr> - <td align="center"><a href="https://github.com/staillebois"><img src="https://avatars0.githubusercontent.com/u/23701200?v=4?s=100" width="100px;" alt=""/><br /><sub><b>staillebois</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=staillebois" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/valdar-hu"><img src="https://avatars3.githubusercontent.com/u/17962817?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Krisztián Nagy</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=valdar-hu" title="Code">💻</a></td> - <td align="center"><a href="https://www.vanogrid.com"><img src="https://avatars0.githubusercontent.com/u/4307918?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Alexander Ivanov</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=vanogrid" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/yosfik"><img src="https://avatars3.githubusercontent.com/u/4850270?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Yosfik Alqadri</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=yosfik" title="Code">💻</a></td> - </tr> - <tr> - <td align="center"><a href="https://github.com/7agustibm"><img src="https://avatars0.githubusercontent.com/u/8149332?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Agustí Becerra Milà</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=7agustibm" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/Juaanma"><img src="https://avatars3.githubusercontent.com/u/7390500?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Juan Manuel Suárez</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=Juaanma" title="Code">💻</a></td> - <td align="center"><a href="http://www.devsedge.net/"><img src="https://avatars0.githubusercontent.com/u/9956006?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Luigi Cortese</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=LuigiCortese" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/Rzeposlaw"><img src="https://avatars2.githubusercontent.com/u/18425745?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Katarzyna Rzepecka</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=Rzeposlaw" title="Code">💻</a></td> - </tr> - <tr> - <td align="center"><a href="http://adamski.pro"><img src="https://avatars1.githubusercontent.com/u/6537430?v=4?s=100" width="100px;" alt=""/><br /><sub><b>adamski.pro</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=akrystian" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/baislsl"><img src="https://avatars0.githubusercontent.com/u/17060584?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Shengli Bai</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=baislsl" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/besok"><img src="https://avatars2.githubusercontent.com/u/29834592?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Boris</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=besok" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/dmitraver"><img src="https://avatars3.githubusercontent.com/u/1798156?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Dmitry Avershin</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=dmitraver" title="Code">💻</a></td> - </tr> - <tr> - <td align="center"><a href="https://github.com/fanofxiaofeng"><img src="https://avatars0.githubusercontent.com/u/3983683?v=4?s=100" width="100px;" alt=""/><br /><sub><b>靳阳</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=fanofxiaofeng" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/hoangnam2261"><img src="https://avatars2.githubusercontent.com/u/31692990?v=4?s=100" width="100px;" alt=""/><br /><sub><b>hoangnam2261</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=hoangnam2261" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/jarpit96"><img src="https://avatars2.githubusercontent.com/u/10098713?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Arpit Jain</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=jarpit96" title="Code">💻</a></td> - <td align="center"><a href="http://joningi.net"><img src="https://avatars2.githubusercontent.com/u/6115148?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jón Ingi Sveinbjörnsson</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=joningiwork" title="Code">💻</a></td> - </tr> - <tr> - <td align="center"><a href="https://github.com/kirill-vlasov"><img src="https://avatars3.githubusercontent.com/u/16112495?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Kirill Vlasov</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=kirill-vlasov" title="Code">💻</a></td> - <td align="center"><a href="http://mitchell-irvin.com"><img src="https://avatars0.githubusercontent.com/u/16233245?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Mitchell Irvin</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=mitchellirvin" title="Code">💻</a></td> - <td align="center"><a href="https://ranjeet-floyd.github.io"><img src="https://avatars0.githubusercontent.com/u/1992972?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Ranjeet</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=ranjeet-floyd" title="Code">💻</a></td> - <td align="center"><a href="https://alwayswithme.github.io"><img src="https://avatars3.githubusercontent.com/u/3234786?v=4?s=100" width="100px;" alt=""/><br /><sub><b>PhoenixYip</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=Alwayswithme" title="Code">💻</a></td> - </tr> - <tr> - <td align="center"><a href="https://github.com/MSaifAsif"><img src="https://avatars1.githubusercontent.com/u/6280554?v=4?s=100" width="100px;" alt=""/><br /><sub><b>M Saif Asif</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=MSaifAsif" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/kanwarpreet25"><img src="https://avatars0.githubusercontent.com/u/39183641?v=4?s=100" width="100px;" alt=""/><br /><sub><b>kanwarpreet25</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=kanwarpreet25" title="Code">💻</a></td> - <td align="center"><a href="http://leonmak.me"><img src="https://avatars3.githubusercontent.com/u/13071508?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Leon Mak</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=leonmak" title="Code">💻</a></td> - <td align="center"><a href="http://www.wramdemark.se"><img src="https://avatars2.githubusercontent.com/u/7052193?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Per Wramdemark</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=perwramdemark" title="Code">💻</a></td> - </tr> - <tr> - <td align="center"><a href="https://github.com/waisuan"><img src="https://avatars2.githubusercontent.com/u/10975700?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Evan Sia Wai Suan</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=waisuan" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/AnaghaSasikumar"><img src="https://avatars2.githubusercontent.com/u/42939261?v=4?s=100" width="100px;" alt=""/><br /><sub><b>AnaghaSasikumar</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=AnaghaSasikumar" title="Code">💻</a></td> - <td align="center"><a href="https://christofferh.com"><img src="https://avatars1.githubusercontent.com/u/767643?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Christoffer Hamberg</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=christofferh" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/dgruntz"><img src="https://avatars0.githubusercontent.com/u/1516800?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Dominik Gruntz</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=dgruntz" title="Code">💻</a></td> - </tr> - <tr> - <td align="center"><a href="https://bitbucket.org/hannespernpeintner/"><img src="https://avatars3.githubusercontent.com/u/1679437?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Hannes</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=hannespernpeintner" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/leogtzr"><img src="https://avatars0.githubusercontent.com/u/1211969?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Leo Gutiérrez Ramírez</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=leogtzr" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/npczwh"><img src="https://avatars0.githubusercontent.com/u/14066422?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Zhang WH</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=npczwh" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/oconnelc"><img src="https://avatars0.githubusercontent.com/u/1112973?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Christopher O'Connell</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=oconnelc" title="Code">💻</a></td> - </tr> - <tr> - <td align="center"><a href="https://github.com/giorgosmav21"><img src="https://avatars2.githubusercontent.com/u/22855493?v=4?s=100" width="100px;" alt=""/><br /><sub><b>George Mavroeidis</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=giorgosmav21" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/hbothra15"><img src="https://avatars1.githubusercontent.com/u/7418012?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Hemant Bothra</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=hbothra15" title="Code">💻</a> <a href="#design-hbothra15" title="Design">🎨</a></td> - <td align="center"><a href="https://www.kevinpeters.net/about/"><img src="https://avatars1.githubusercontent.com/u/12736734?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Kevin Peters</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=igeligel" title="Code">💻</a></td> - <td align="center"><a href="https://llorllale.github.io/"><img src="https://avatars1.githubusercontent.com/u/2019896?v=4?s=100" width="100px;" alt=""/><br /><sub><b>George Aristy</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=llorllale" title="Code">💻</a></td> - </tr> - <tr> - <td align="center"><a href="https://github.com/mookkiah"><img src="https://avatars1.githubusercontent.com/u/8975264?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Mahendran Mookkiah</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=mookkiah" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/Azureyjt"><img src="https://avatars2.githubusercontent.com/u/18476317?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Azureyjt</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=Azureyjt" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/vehpsr"><img src="https://avatars2.githubusercontent.com/u/3133265?v=4?s=100" width="100px;" alt=""/><br /><sub><b>gans</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=vehpsr" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/ThatGuyWithTheHat"><img src="https://avatars0.githubusercontent.com/u/24470582?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Matt</b></sub></a><br /><a href="#content-ThatGuyWithTheHat" title="Content">🖋</a></td> - </tr> - <tr> - <td align="center"><a href="https://www.linkedin.com/in/gopinathlangote/"><img src="https://avatars2.githubusercontent.com/u/10210778?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Gopinath Langote</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=gopinath-langote" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/hoswey"><img src="https://avatars3.githubusercontent.com/u/3689445?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Hoswey</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=hoswey" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/amit2103"><img src="https://avatars3.githubusercontent.com/u/7566692?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Amit Pandey</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=amit2103" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/gwildor28"><img src="https://avatars0.githubusercontent.com/u/16000365?v=4?s=100" width="100px;" alt=""/><br /><sub><b>gwildor28</b></sub></a><br /><a href="#content-gwildor28" title="Content">🖋</a></td> - </tr> - <tr> - <td align="center"><a href="https://t.me/paul_docker"><img src="https://avatars1.githubusercontent.com/u/2404785?v=4?s=100" width="100px;" alt=""/><br /><sub><b>田浩</b></sub></a><br /><a href="#content-llitfkitfk" title="Content">🖋</a></td> - <td align="center"><a href="https://twitter.com/StPitsios"><img src="https://avatars1.githubusercontent.com/u/6773603?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Stamatis Pitsios</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=pitsios-s" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/qza"><img src="https://avatars3.githubusercontent.com/u/233149?v=4?s=100" width="100px;" alt=""/><br /><sub><b>qza</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=qza" title="Code">💻</a></td> - <td align="center"><a href="http://tschis.github.io"><img src="https://avatars1.githubusercontent.com/u/20662669?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Rodolfo Forte</b></sub></a><br /><a href="#content-Tschis" title="Content">🖋</a></td> - </tr> - <tr> - <td align="center"><a href="https://github.com/ankurkaushal"><img src="https://avatars2.githubusercontent.com/u/2236616?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Ankur Kaushal</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=ankurkaushal" title="Code">💻</a></td> - <td align="center"><a href="https://www.linkedin.com/in/ovidijus-okinskas/"><img src="https://avatars0.githubusercontent.com/u/20372387?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Ovidijus Okinskas</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=okinskas" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/robertt240"><img src="https://avatars1.githubusercontent.com/u/9137432?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Robert Kasperczyk</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=robertt240" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/trautonen"><img src="https://avatars3.githubusercontent.com/u/1641063?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Tapio Rautonen</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=trautonen" title="Code">💻</a></td> - </tr> - <tr> - <td align="center"><a href="http://vk.com/yuri.orlov"><img src="https://avatars0.githubusercontent.com/u/1595733?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Yuri Orlov</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=yorlov" title="Code">💻</a></td> - <td align="center"><a href="https://www.linkedin.com/in/varunu28/"><img src="https://avatars0.githubusercontent.com/u/7676016?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Varun Upadhyay</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=varunu28" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/PalAditya"><img src="https://avatars2.githubusercontent.com/u/25523604?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Aditya Pal</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=PalAditya" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/grzesiekkedzior"><img src="https://avatars3.githubusercontent.com/u/23739158?v=4?s=100" width="100px;" alt=""/><br /><sub><b>grzesiekkedzior</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=grzesiekkedzior" title="Code">💻</a> <a href="https://github.com/iluwatar/java-design-patterns/pulls?q=is%3Apr+reviewed-by%3Agrzesiekkedzior" title="Reviewed Pull Requests">👀</a></td> - </tr> - <tr> - <td align="center"><a href="https://github.com/sivasubramanim"><img src="https://avatars2.githubusercontent.com/u/51107434?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Sivasubramani M</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=sivasubramanim" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/d4gg4d"><img src="https://avatars2.githubusercontent.com/u/99457?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Sami Airaksinen</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=d4gg4d" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/vertti"><img src="https://avatars0.githubusercontent.com/u/557751?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Janne Sinivirta</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=vertti" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/Bobo1239"><img src="https://avatars1.githubusercontent.com/u/2302947?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Boris-Chengbiao Zhou</b></sub></a><br /><a href="#content-Bobo1239" title="Content">🖋</a></td> - </tr> - <tr> - <td align="center"><a href="https://jahhein.github.io"><img src="https://avatars2.githubusercontent.com/u/10779515?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jacob Hein</b></sub></a><br /><a href="#content-Jahhein" title="Content">🖋</a></td> - <td align="center"><a href="https://github.com/iamrichardjones"><img src="https://avatars3.githubusercontent.com/u/14842151?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Richard Jones</b></sub></a><br /><a href="#content-iamrichardjones" title="Content">🖋</a></td> - <td align="center"><a href="https://rachelcarmena.github.io"><img src="https://avatars0.githubusercontent.com/u/22792183?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Rachel M. Carmena</b></sub></a><br /><a href="#content-rachelcarmena" title="Content">🖋</a></td> - <td align="center"><a href="https://zd-zero.github.io"><img src="https://avatars0.githubusercontent.com/u/21978370?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Zaerald Denze Lungos</b></sub></a><br /><a href="#content-zd-zero" title="Content">🖋</a></td> - </tr> - <tr> - <td align="center"><a href="https://webpro.nl"><img src="https://avatars1.githubusercontent.com/u/456426?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Lars Kappert</b></sub></a><br /><a href="#content-webpro" title="Content">🖋</a></td> - <td align="center"><a href="https://xiaod.info"><img src="https://avatars2.githubusercontent.com/u/21277644?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Mike Liu</b></sub></a><br /><a href="#translation-xiaod-dev" title="Translation">🌍</a></td> - <td align="center"><a href="https://github.com/charlesfinley"><img src="https://avatars1.githubusercontent.com/u/6307904?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Matt Dolan</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=charlesfinley" title="Code">💻</a> <a href="https://github.com/iluwatar/java-design-patterns/pulls?q=is%3Apr+reviewed-by%3Acharlesfinley" title="Reviewed Pull Requests">👀</a></td> - <td align="center"><a href="https://github.com/MananS77"><img src="https://avatars3.githubusercontent.com/u/21033516?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Manan</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/pulls?q=is%3Apr+reviewed-by%3AMananS77" title="Reviewed Pull Requests">👀</a></td> - </tr> - <tr> - <td align="center"><a href="https://github.com/nishant"><img src="https://avatars2.githubusercontent.com/u/15331971?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Nishant Arora</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=nishant" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/raja-peeyush-kumar-singh"><img src="https://avatars0.githubusercontent.com/u/5496024?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Peeyush</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=raja-peeyush-kumar-singh" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/ravening"><img src="https://avatars1.githubusercontent.com/u/10645273?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Rakesh</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=ravening" title="Code">💻</a> <a href="https://github.com/iluwatar/java-design-patterns/pulls?q=is%3Apr+reviewed-by%3Aravening" title="Reviewed Pull Requests">👀</a></td> - <td align="center"><a href="https://github.com/vINCENT8888801"><img src="https://avatars0.githubusercontent.com/u/8037883?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Wei Seng</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=vINCENT8888801" title="Code">💻</a></td> - </tr> - <tr> - <td align="center"><a href="https://www.linkedin.com/in/ashish-trivedi-218379135/"><img src="https://avatars3.githubusercontent.com/u/23194128?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Ashish Trivedi</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=ashishtrivedi16" title="Code">💻</a></td> - <td align="center"><a href="https://rayyounghong.com"><img src="https://avatars1.githubusercontent.com/u/41055099?v=4?s=100" width="100px;" alt=""/><br /><sub><b>洪月阳</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=RayYH" title="Code">💻</a></td> - <td align="center"><a href="https://xdvrx1.github.io/"><img src="https://avatars0.githubusercontent.com/u/47092464?v=4?s=100" width="100px;" alt=""/><br /><sub><b>xdvrx1</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/pulls?q=is%3Apr+reviewed-by%3Axdvrx1" title="Reviewed Pull Requests">👀</a> <a href="#ideas-xdvrx1" title="Ideas, Planning, & Feedback">🤔</a></td> - <td align="center"><a href="http://subho.xyz"><img src="https://avatars0.githubusercontent.com/u/13291222?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Subhrodip Mohanta</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=ohbus" title="Code">💻</a> <a href="https://github.com/iluwatar/java-design-patterns/pulls?q=is%3Apr+reviewed-by%3Aohbus" title="Reviewed Pull Requests">👀</a> <a href="#maintenance-ohbus" title="Maintenance">🚧</a></td> - </tr> - <tr> - <td align="center"><a href="https://github.com/nahteb"><img src="https://avatars3.githubusercontent.com/u/13121570?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Bethan Palmer</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=nahteb" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/ToxicDreamz"><img src="https://avatars0.githubusercontent.com/u/45225562?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Toxic Dreamz</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=ToxicDreamz" title="Code">💻</a></td> - <td align="center"><a href="http://www.edycutjong.com"><img src="https://avatars1.githubusercontent.com/u/1098102?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Edy Cu Tjong</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=edycutjong" title="Documentation">📖</a></td> - <td align="center"><a href="https://github.com/mkrzywanski"><img src="https://avatars0.githubusercontent.com/u/15279585?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Michał Krzywański</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=mkrzywanski" title="Code">💻</a></td> - </tr> - <tr> - <td align="center"><a href="https://www.stefan-birkner.de"><img src="https://avatars1.githubusercontent.com/u/711349?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Stefan Birkner</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=stefanbirkner" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/fedorskvorcov"><img src="https://avatars3.githubusercontent.com/u/43882212?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Fedor Skvorcov</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=fedorskvorcov" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/samilAyoub"><img src="https://avatars0.githubusercontent.com/u/61546990?v=4?s=100" width="100px;" alt=""/><br /><sub><b>samilAyoub</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=samilAyoub" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/vdlald"><img src="https://avatars0.githubusercontent.com/u/29997701?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Vladislav Golubinov</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=vdlald" title="Code">💻</a></td> - </tr> - <tr> - <td align="center"><a href="https://github.com/swarajsaaj"><img src="https://avatars2.githubusercontent.com/u/6285049?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Swaraj</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=swarajsaaj" title="Code">💻</a></td> - <td align="center"><a href="http://christophflick.de"><img src="https://avatars0.githubusercontent.com/u/4465376?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Christoph Flick</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=ChFlick" title="Documentation">📖</a></td> - <td align="center"><a href="https://github.com/Ascenio"><img src="https://avatars1.githubusercontent.com/u/7662016?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Ascênio</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/pulls?q=is%3Apr+reviewed-by%3AAscenio" title="Reviewed Pull Requests">👀</a></td> - <td align="center"><a href="https://www.linkedin.com/in/domenico-sibilio/"><img src="https://avatars2.githubusercontent.com/u/24280982?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Domenico Sibilio</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=dsibilio" title="Documentation">📖</a></td> - </tr> - <tr> - <td align="center"><a href="https://github.com/akashchandwani"><img src="https://avatars2.githubusercontent.com/u/3483277?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Akash Chandwani</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/pulls?q=is%3Apr+reviewed-by%3Aakashchandwani" title="Reviewed Pull Requests">👀</a></td> - <td align="center"><a href="http://www.linkedin.com/in/manannikov"><img src="https://avatars2.githubusercontent.com/u/7019769?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Pavlo Manannikov</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=manannikov" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/eimanip"><img src="https://avatars0.githubusercontent.com/u/20307301?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Eiman</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=eimanip" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/OrangePants-R"><img src="https://avatars0.githubusercontent.com/u/42976136?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Rocky</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=OrangePants-R" title="Documentation">📖</a></td> - </tr> - <tr> - <td align="center"><a href="https://ibrahimalii.github.io/"><img src="https://avatars2.githubusercontent.com/u/21141301?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Ibrahim ali abdelghany</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/pulls?q=is%3Apr+reviewed-by%3AibrahimAlii" title="Reviewed Pull Requests">👀</a></td> - <td align="center"><a href="https://github.com/gkulkarni2020"><img src="https://avatars3.githubusercontent.com/u/5161548?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Girish Kulkarni</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=gkulkarni2020" title="Documentation">📖</a></td> - <td align="center"><a href="https://github.com/omk13"><img src="https://avatars0.githubusercontent.com/u/59054172?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Omar Karazoun</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=omk13" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/jeff303"><img src="https://avatars0.githubusercontent.com/u/3521562?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jeff Evans</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=jeff303" title="Code">💻</a></td> - </tr> - <tr> - <td align="center"><a href="https://viveksb007.github.io"><img src="https://avatars1.githubusercontent.com/u/12713808?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Vivek Singh</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=viveksb007" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/siavashsoleymani"><img src="https://avatars2.githubusercontent.com/u/18074419?v=4?s=100" width="100px;" alt=""/><br /><sub><b>siavash</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=siavashsoleymani" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/ruchpeanuts"><img src="https://avatars0.githubusercontent.com/u/29301900?v=4?s=100" width="100px;" alt=""/><br /><sub><b>ruchpeanuts</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=ruchpeanuts" title="Documentation">📖</a></td> - <td align="center"><a href="https://github.com/warp125"><img src="https://avatars1.githubusercontent.com/u/48073115?v=4?s=100" width="100px;" alt=""/><br /><sub><b>warp125</b></sub></a><br /><a href="#translation-warp125" title="Translation">🌍</a></td> - </tr> - <tr> - <td align="center"><a href="http://libkhadir.fr"><img src="https://avatars1.githubusercontent.com/u/45130488?v=4?s=100" width="100px;" alt=""/><br /><sub><b>KHADIR Tayeb</b></sub></a><br /><a href="#translation-tkhadir" title="Translation">🌍</a></td> - <td align="center"><a href="https://github.com/ignite1771"><img src="https://avatars2.githubusercontent.com/u/59446563?v=4?s=100" width="100px;" alt=""/><br /><sub><b>ignite1771</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=ignite1771" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/demirhalil"><img src="https://avatars1.githubusercontent.com/u/22895118?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Halil Demir</b></sub></a><br /><a href="#translation-demirhalil" title="Translation">🌍</a></td> - <td align="center"><a href="https://github.com/rohit10000"><img src="https://avatars.githubusercontent.com/u/20845565?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Rohit Singh</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=rohit10000" title="Code">💻</a></td> - </tr> - <tr> - <td align="center"><a href="https://github.com/byoungju94"><img src="https://avatars.githubusercontent.com/u/42516378?v=4?s=100" width="100px;" alt=""/><br /><sub><b>byoungju94</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=byoungju94" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/moustafafarhat"><img src="https://avatars.githubusercontent.com/u/38836727?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Moustafa Farhat</b></sub></a><br /><a href="#translation-moustafafarhat" title="Translation">🌍</a></td> - <td align="center"><a href="https://github.com/richardmr36"><img src="https://avatars.githubusercontent.com/u/19147333?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Martel Richard</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=richardmr36" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/va1m"><img src="https://avatars.githubusercontent.com/u/17025445?v=4?s=100" width="100px;" alt=""/><br /><sub><b>va1m</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=va1m" title="Code">💻</a></td> - </tr> - <tr> - <td align="center"><a href="https://github.com/noamgrinch"><img src="https://avatars.githubusercontent.com/u/31648669?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Noam Greenshtain</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=noamgrinch" title="Code">💻</a></td> - <td align="center"><a href="https://xuyonghong.cn/"><img src="https://avatars.githubusercontent.com/u/14086462?v=4?s=100" width="100px;" alt=""/><br /><sub><b>yonghong Xu</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=qfxl" title="Documentation">📖</a></td> - <td align="center"><a href="https://www.linkedin.com/in/jinisha-vora"><img src="https://avatars.githubusercontent.com/u/40777762?v=4?s=100" width="100px;" alt=""/><br /><sub><b>jinishavora</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/pulls?q=is%3Apr+reviewed-by%3Ajinishavora" title="Reviewed Pull Requests">👀</a> <a href="https://github.com/iluwatar/java-design-patterns/commits?author=jinishavora" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/eas5"><img src="https://avatars.githubusercontent.com/u/50836521?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Elvys Soares</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=eas5" title="Code">💻</a></td> - </tr> - <tr> - <td align="center"><a href="https://github.com/zWeBrain"><img src="https://avatars.githubusercontent.com/u/46642512?v=4?s=100" width="100px;" alt=""/><br /><sub><b>zWeBrain</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=zWeBrain" title="Code">💻</a></td> - <td align="center"><a href="https://al-assad.github.io/notion/"><img src="https://avatars.githubusercontent.com/u/22493821?v=4?s=100" width="100px;" alt=""/><br /><sub><b>余林颖</b></sub></a><br /><a href="#translation-Al-assad" title="Translation">🌍</a></td> - <td align="center"><a href="https://github.com/STudio26"><img src="https://avatars.githubusercontent.com/u/6988911?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Alain</b></sub></a><br /><a href="#translation-STudio26" title="Translation">🌍</a></td> - <td align="center"><a href="https://github.com/DEV-VRUPER"><img src="https://avatars.githubusercontent.com/u/30525467?v=4?s=100" width="100px;" alt=""/><br /><sub><b>VR</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=DEV-VRUPER" title="Documentation">📖</a></td> - </tr> - <tr> - <td align="center"><a href="https://github.com/JackieNim"><img src="https://avatars.githubusercontent.com/u/4138836?v=4?s=100" width="100px;" alt=""/><br /><sub><b>JackieNim</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=JackieNim" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/EdisonE3"><img src="https://avatars.githubusercontent.com/u/52118917?v=4?s=100" width="100px;" alt=""/><br /><sub><b>EdisonE3</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=EdisonE3" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/tao-sun2"><img src="https://avatars.githubusercontent.com/u/66189688?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Tao</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=tao-sun2" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/JuanManuelAbate"><img src="https://avatars.githubusercontent.com/u/16357060?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Juan Manuel Abate</b></sub></a><br /><a href="#translation-JuanManuelAbate" title="Translation">🌍</a></td> - </tr> - <tr> - <td align="center"><a href="https://github.com/Xenilo137"><img src="https://avatars.githubusercontent.com/u/24865069?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Xenilo137</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=Xenilo137" title="Code">💻</a></td> - <td align="center"><a href="https://www.linkedin.com/in/souzasamuel/"><img src="https://avatars.githubusercontent.com/u/17254162?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Samuel Souza</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=samuelpsouza" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/marlo2222"><img src="https://avatars.githubusercontent.com/u/40809563?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Marlo Henrique</b></sub></a><br /><a href="#translation-marlo2222" title="Translation">🌍</a></td> - <td align="center"><a href="https://github.com/AndriyPyzh"><img src="https://avatars.githubusercontent.com/u/57706635?v=4?s=100" width="100px;" alt=""/><br /><sub><b>AndriyPyzh</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=AndriyPyzh" title="Code">💻</a></td> - </tr> - <tr> - <td align="center"><a href="https://github.com/karthikbhat13"><img src="https://avatars.githubusercontent.com/u/22431014?v=4?s=100" width="100px;" alt=""/><br /><sub><b>karthikbhat13</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=karthikbhat13" title="Code">💻</a></td> - <td align="center"><a href="https://github.com/mortezaadi"><img src="https://avatars.githubusercontent.com/u/1329687?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Morteza Adigozalpour</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=mortezaadi" title="Code">💻</a></td> - <td align="center"><a href="https://stackoverflow.com/users/308565/nagaraj-tantri"><img src="https://avatars.githubusercontent.com/u/3784194?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Nagaraj Tantri</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=tan31989" title="Code">💻</a></td> - </tr> -</table> + +<a href="https://github.com/iluwatar/java-design-patterns/graphs/contributors"> + <img src="https://contributors-img.web.app/image?repo=iluwatar/java-design-patterns&max=250" /> +</a> <!-- markdownlint-restore --> <!-- prettier-ignore-end -->
null
train
train
2021-09-28T20:43:31
"2021-09-30T04:10:12Z"
chandrikadeb7
train
iluwatar/java-design-patterns/1803_1828
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1803
iluwatar/java-design-patterns/1828
[ "timestamp(timedelta=0.0, similarity=0.9120354148911209)" ]
42eb7950aef44e00b9a5363e681762a1bf1271c3
57f9c2e9687d959a9753297ab7641ded639947da
[ "Thanks @beooo79 for reporting. Although we currently claim to support only JDK11, I would like to see Lombok in the most recent version. If someone is willing to work on this, update Lombok to the latest version and test that the build and the tests still work.", "> Thanks @beooo79 for reporting. Although we currently claim to support only JDK11, I would like to see Lombok in the most recent version. If someone is willing to work on this, update Lombok to the latest version and test that the build and the tests still work.\r\n\r\nI tested Lombok version 1.18 with Eclipse version v4.20 (2021-06) creating problems for me with reflection API for Java." ]
[]
"2021-10-03T16:10:18Z"
[ "epic: build issue", "epic: dependencies", "type: feature" ]
Update Lombok version (possible migration issue for JDK17)
Lombok does not work in the current master branch when using JDK16. `[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project abstract-factory: Fatal error compiling: java.lang.IllegalAccessError: class lombok.javac.apt.LombokProcessor (in unnamed module @0x4809c771) cannot access class com.sun.tools.javac.processing.JavacProcessingEnvironment (in module jdk.compiler) because module jdk.compiler does not export com.sun.tools.javac.processing to unnamed module @0x4809c771 -> [Help 1]` To fix it i used: ``` diff --git a/pom.xml b/pom.xml index 31cf03b4d..d7f05d796 100644 --- a/pom.xml +++ b/pom.xml @@ -71,7 +71,7 @@ <system-lambda.version>1.1.0</system-lambda.version> <urm.version>2.0.0</urm.version> <mockito-junit-jupiter.version>3.5.0</mockito-junit-jupiter.version> - <lombok.version>1.18.14</lombok.version> + <lombok.version>1.18.20</lombok.version> <byte-buddy.version>1.10.21</byte-buddy.version> <javassist.version>3.27.0-GA</javassist.version> <maven-surefire-plugin.version>3.0.0-M5</maven-surefire-plugin.version> ```
[ "pom.xml" ]
[ "pom.xml" ]
[]
diff --git a/pom.xml b/pom.xml index cb726a43e352..3e5e51abfbc5 100644 --- a/pom.xml +++ b/pom.xml @@ -71,7 +71,7 @@ <system-lambda.version>1.1.0</system-lambda.version> <urm.version>2.0.0</urm.version> <mockito-junit-jupiter.version>3.5.0</mockito-junit-jupiter.version> - <lombok.version>1.18.14</lombok.version> + <lombok.version>1.18.20</lombok.version> <byte-buddy.version>1.11.5</byte-buddy.version> <javassist.version>3.27.0-GA</javassist.version> <maven-surefire-plugin.version>3.0.0-M5</maven-surefire-plugin.version>
null
train
train
2021-09-28T20:43:31
"2021-07-21T06:14:32Z"
beooo79
train
iluwatar/java-design-patterns/1012_1833
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1012
iluwatar/java-design-patterns/1833
[ "connected" ]
ddb9b14eedfe317e4c95571bc5197f2e5e1ed596
5a644f1092079f4f0152641b704dec1d668727ff
[ "Can I take this issue?", "Sure @ykayacan ", "This issue is free for taking again.", "I would like to take this issue.", "Through out checking the files causing issues on SonarCloud, I've encountered test cases that are not properly named to the functionality that they are to be tested against. \r\n\r\nExample`\r\n\r\nIn-correct naming convention of a test method.\r\n> ` @Test\r\n> void test() throws Exception {\r\n> App.main(new String[]{});\r\n> }`\r\n\r\nCorrect naming convention of a test method.\r\n\r\n> `@Test\r\n> public void shouldExecuteAppWithoutException() {\r\n> assertDoesNotThrow(() -> App.main(null));\r\n> }`\r\n\r\nA test method should describe what its testing directly in the naming, I will rename the test cases that I find throughout the refactoring process to match proper convention rules, if the test case is understandable as to what it's testing, but I would encourage that these test cases be looked at and properly named for other contributors making changes to certain files that the test cases test against, otherwise it causes a lot of confusion as to whether said contributor is testing the right thing.", "Ok @ToxicDreamz, assigned to you. I agree with your comment regarding test naming.", "I've already finished with the issue. \r\n\r\nRequest to run another SonarCloud report after merging, to see what else remains, and whether or not they can be modified so issues do not come up again.", "13 blockers and 24 criticals remaining: https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL", "`HotelDaoImpl.java` seems to be one of the hotspots we should fix: https://sonarcloud.io/component_measures?id=iluwatar_java-design-patterns&selected=iluwatar_java-design-patterns%3Atransaction-script%2Fsrc%2Fmain%2Fjava%2Fcom%2Filuwatar%2Ftransactionscript%2FHotelDaoImpl.java&view=list", "@iluwatar happy to be back again :)\r\nCan I help with this issue?", "I will resolve the report:\r\n\r\nhttps://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AW5RukINqcCiTG-gJi15&resolved=false&severities=CRITICAL", "Ok, assigned @anuragagarwal561994 and @daniel-augusto. Thanks guys!", "@iluwatar Can I help with this issue?", "Sure if @anuragagarwal561994 is no longer working on it?", "No @iluwatar I didn't get time to look into this, you can re-assign", "@iluwatar I will start working on it ", "No problem @anuragagarwal561994 \r\n@kanwarpreet25 you're good to go", "@iluwatar can I help with this and coordinate with @kanwarpreet25 @daniel-augusto ?", "@kanwarpreet25 has no public commits since Jul 28, 2019, [f7e22a1](https://github.com/iluwatar/java-design-patterns/commit/f7e22a1cf6f7664e8790cc5c76285adbcc6ab19d)\r\n@daniel-augusto has no public commits to this repo since Oct 11, 2020 [3a72abb](https://github.com/daniel-augusto/java-design-patterns/pull/1/commits/3a72abba25535b9f3bd90ac71c6cc77c530039d3)\r\n\r\nAre you guys working on this know? ", "Thanks for helping out @joseosuna-engineer. I'm looking forward to your pull request!", "Thank you. I'm going to begin with this.", "@iluwatar @ohbus \r\nI have added this project to my own CircleCI and SonarCloud accounts to run SonarCloud before create a pull request.\r\n\r\n**My accounts:**\r\n![image](https://user-images.githubusercontent.com/2281302/113358032-669e9100-931b-11eb-8d05-5b3dbf3c0b7b.png)\r\n\r\n\r\nI **changed two config files**, :scream: **.circleci/config.yml** and **pom.xml** (my fork, another branch) \r\nI'm sure @iluwatar @ohbus that we can find a better approach using environment vars or some characteristic of \r\nCircleCI 2.1 [Youtube](https://www.youtube.com/watch?v=etXD9sCFxIU)\r\n\r\nMy strategy is: \r\n- to use this branch **A** only in my fork.\r\n- to create another branch **B** to commit my code.\r\n- to merge **B** to **A** and run CircleCI + SonarCloud\r\n- when code is okay create a pull request from **B** (that has original config files) to master\r\n\r\n![image](https://user-images.githubusercontent.com/2281302/113358878-fbee5500-931c-11eb-8cbf-caeeca0a0d52.png)\r\n\r\n![image](https://user-images.githubusercontent.com/2281302/113358940-1c1e1400-931d-11eb-940f-a744b88f4a75.png)\r\n\r\n\r\n\r\n\r\n", "I think the general approach presented above is going to work, but as pointed out there are chances to streamline the workflow. @joseosuna-engineer feel free to create another issue where you point out the exact spots we should change.", "@iluwatar I have created issue [1697](https://github.com/iluwatar/java-design-patterns/issues/1697)", "> \r\n> \r\n> The project is using SonarCloud static code analysis. The latest results are showing that it has found several blocker and critical severity code smells (major, minor and info level we ignore). In this task those are fixed or marked as false positives. To mark false positives, SuppressWarnings annotation should be used in code as explained in the linked documentation.\r\n> \r\n> Links:\r\n> [Blocker and critical severity code smells in SonarCloud](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL&types=CODE_SMELL)\r\n> [Sonar false positives](https://docs.sonarqube.org/latest/analysis/languages/java/#JavaFAQ-HowtoremoveFalse-Positiveissues)\r\n\r\n@iluwatar I want to ask you some things:\r\n1.- This issue (1012) is not about all sonarcloud issues. is it?\r\n2.- major, minor and info issues are not included here\r\n3.- it is only about (blocker and critical) + code smell issues\r\n\r\n![image](https://user-images.githubusercontent.com/2281302/113944874-3ea7a580-97d3-11eb-8c10-097e2e03a933.png)\r\n\r\n4.- Do you want I add **@java.lang.SuppressWarnings(\"squid:some-number\")** annotation for **all** in question number 3? or Do I have to do something like [ykayacan](https://github.com/ykayacan/java-design-patterns/commit/d5ed1a1f22467d396c1f61f4ac18ded662591ccb): suppress false positives (test by example) and fix number 3 issues?\r\n", "@joseosuna-engineer \r\n\r\n1. No, it's about blocker and critical level issues only\r\n2. Yes\r\n3. Yes\r\n4. For false positives we can suppress the warnings as you suggested\r\n", "@iluwatar Thank you! ", "Can I help to fix this issue? Has anyone solved this one? https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AW3G0WaAwB6UiZzQNqwC&resolved=false&severities=BLOCKER", "@samuelpsouza Yes. Feel free to colaborate. @iluwatar I'm so sorry. I'm studying for a couple of certification test.", "> @samuelpsouza Yes. Feel free to collaborate. @iluwatar I'm so sorry. I'm studying for a couple of certification tests.\r\n\r\nPlease @joseosuna-engineer, no need for an apology here.\r\n\r\nYou can mention a timeline for when you will be able to make the contributions or let us know in [Gitter](https://gitter.im/iluwatar/java-design-patterns) about the same as well.\r\n\r\nAnd all the very best for your examinations! May you ace them ⭐ ", "> Can I help to fix this issue? Has anyone solved this one? https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AW3G0WaAwB6UiZzQNqwC&resolved=false&severities=BLOCKER\r\n\r\nThank you so much for your interest in our project @samuelpsouza through #1784", "Raised a PR for the following two Critical Code Smells: [#1831](https://github.com/iluwatar/java-design-patterns/pull/1831)\r\n\r\n1. https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AXhD5LIoXfseSECKkezl&resolved=false&severities=CRITICAL&types=CODE_SMELL\r\n2. https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AXhD5LIoXfseSECKkezm&resolved=false&severities=CRITICAL&types=CODE_SMELL\r\n\r\nFirst time contributing to open source software. Please review and provide your feedback.", "> Raised a PR for the following two Critical Code Smells: [#1831](https://github.com/iluwatar/java-design-patterns/pull/1831)\r\n> \r\n> 1. https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AXhD5LIoXfseSECKkezl&resolved=false&severities=CRITICAL&types=CODE_SMELL\r\n> 2. https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AXhD5LIoXfseSECKkezm&resolved=false&severities=CRITICAL&types=CODE_SMELL\r\n> \r\n> First time contributing to open source software. Please review and provide your feedback.\r\n\r\nPlease also review https://github.com/iluwatar/java-design-patterns/pull/1833 and https://github.com/iluwatar/java-design-patterns/pull/1832", "I would like to work on this issue and resolve some of the code smells/ critical issues in Sonar. Can I take this up? @iluwatar", "Sure @parulagg27, go ahead", "We need assistance to resolve the remaining blocker and critical level SonarCloud issues", "I have resolved 1 blocker & 5 critical Sonar issues using [this PR](https://github.com/iluwatar/java-design-patterns/pull/1899). Kindly review and merge.\r\n<img width=\"1730\" alt=\"Screenshot 2021-10-30 at 11 27 15 PM\" src=\"https://user-images.githubusercontent.com/18613127/139554128-d1b1d1f6-0d95-4663-b3bf-096aa31b8b26.png\">\r\n<img width=\"1728\" alt=\"Screenshot 2021-10-30 at 11 26 50 PM\" src=\"https://user-images.githubusercontent.com/18613127/139554131-468ada1a-d34c-4cb9-8c71-2a77a3fe1195.png\">\r\n\r\n\r\n", "- **Resolved** 1 blocker & 5 critical Sonar issues \r\n\r\n- **Old sonar report** :- [here](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER&types=CODE_SMELL)\r\n\r\n- **Code Cov**: Added an extensive test cases for Commander pattern.\r\n\r\n- **PR Quality Gate** is also [green](https://sonarcloud.io/summary/new_code?id=iluwatar_java-design-patterns&pullRequest=1899)\r\n\r\n@iluwatar @ohbus \r\nKindly review and merge [this PR](https://github.com/iluwatar/java-design-patterns/pull/1899)", "hey can i work on this issue :)", "Ok, go ahead @ShivanshCharak ", "Raised a pr for the following Critical code smell\r\nhttps://github.com/iluwatar/java-design-patterns/pull/1960\r\n\r\nplease also review\r\na minor code smell\r\nhttps://github.com/iluwatar/java-design-patterns/pull/1959#issue-1118731779", "Can I help? ", "Ok @S7sRuss, thanks for the help" ]
[]
"2021-10-04T18:51:15Z"
[ "type: bug", "info: good first issue", "type: refactoring", "epic: code quality" ]
SonarCloud reports issues
The project is using SonarCloud static code analysis. The latest results are showing that it has found several blockers and critical severity code smells (major, minor, and info level we ignore). In this task, those are fixed or marked as false positives. To mark false positives, SuppressWarnings annotation should be used in code as explained in the linked documentation. Links: [Blocker and critical severity code smells in SonarCloud](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL&types=CODE_SMELL) [Sonar false positives](https://docs.sonarqube.org/latest/analysis/languages/java/#JavaFAQ-HowtoremoveFalse-Positiveissues) *** Note: When Submitting a PR please provide a **hyperlinked** list of all the issues that you are issuing a fix for. [_See this example_](https://github.com/iluwatar/java-design-patterns/pull/1833#issue-1015516036)
[ "async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/App.java", "bytecode/src/main/java/com/iluwatar/bytecode/App.java", "caching/src/main/java/com/iluwatar/caching/DbManager.java" ]
[ "async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/App.java", "bytecode/src/main/java/com/iluwatar/bytecode/App.java", "caching/src/main/java/com/iluwatar/caching/DbManager.java" ]
[]
diff --git a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/App.java b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/App.java index b7d5e386b83a..ca63520be298 100644 --- a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/App.java +++ b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/App.java @@ -59,9 +59,12 @@ @Slf4j public class App { + private static final String ROCKET_LAUNCH_LOG_PATTERN = "Space rocket <%s> launched successfully"; + /** * Program entry point. */ + public static void main(String[] args) throws Exception { // construct a new executor that will run async tasks var executor = new ThreadAsyncExecutor(); @@ -87,9 +90,9 @@ public static void main(String[] args) throws Exception { asyncResult5.await(); // log the results of the tasks, callbacks log immediately when complete - log("Space rocket <" + result1 + "> launch complete"); - log("Space rocket <" + result2 + "> launch complete"); - log("Space rocket <" + result3 + "> launch complete"); + log(String.format(ROCKET_LAUNCH_LOG_PATTERN, result1)); + log(String.format(ROCKET_LAUNCH_LOG_PATTERN, result2)); + log(String.format(ROCKET_LAUNCH_LOG_PATTERN, result3)); } /** @@ -102,7 +105,7 @@ public static void main(String[] args) throws Exception { private static <T> Callable<T> lazyval(T value, long delayMillis) { return () -> { Thread.sleep(delayMillis); - log("Space rocket <" + value + "> launched successfully"); + log(String.format(ROCKET_LAUNCH_LOG_PATTERN, value)); return value; }; } diff --git a/bytecode/src/main/java/com/iluwatar/bytecode/App.java b/bytecode/src/main/java/com/iluwatar/bytecode/App.java index f76a8e6a4f87..43ddd4b9dc72 100644 --- a/bytecode/src/main/java/com/iluwatar/bytecode/App.java +++ b/bytecode/src/main/java/com/iluwatar/bytecode/App.java @@ -42,6 +42,14 @@ @Slf4j public class App { + private static final String LITERAL_0 = "LITERAL 0"; + private static final String HEALTH_PATTERN = "%s_HEALTH"; + private static final String GET_AGILITY = "GET_AGILITY"; + private static final String GET_WISDOM = "GET_WISDOM"; + private static final String ADD = "ADD"; + private static final String LITERAL_2 = "LITERAL 2"; + private static final String DIVIDE = "DIVIDE"; + /** * Main app method. * @@ -53,17 +61,17 @@ public static void main(String[] args) { new Wizard(45, 7, 11, 0, 0), new Wizard(36, 18, 8, 0, 0)); - vm.execute(InstructionConverterUtil.convertToByteCode("LITERAL 0")); - vm.execute(InstructionConverterUtil.convertToByteCode("LITERAL 0")); - vm.execute(InstructionConverterUtil.convertToByteCode("GET_HEALTH")); - vm.execute(InstructionConverterUtil.convertToByteCode("LITERAL 0")); - vm.execute(InstructionConverterUtil.convertToByteCode("GET_AGILITY")); - vm.execute(InstructionConverterUtil.convertToByteCode("LITERAL 0")); - vm.execute(InstructionConverterUtil.convertToByteCode("GET_WISDOM")); - vm.execute(InstructionConverterUtil.convertToByteCode("ADD")); - vm.execute(InstructionConverterUtil.convertToByteCode("LITERAL 2")); - vm.execute(InstructionConverterUtil.convertToByteCode("DIVIDE")); - vm.execute(InstructionConverterUtil.convertToByteCode("ADD")); - vm.execute(InstructionConverterUtil.convertToByteCode("SET_HEALTH")); + vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0)); + vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0)); + vm.execute(InstructionConverterUtil.convertToByteCode(String.format(HEALTH_PATTERN, "GET"))); + vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0)); + vm.execute(InstructionConverterUtil.convertToByteCode(GET_AGILITY)); + vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0)); + vm.execute(InstructionConverterUtil.convertToByteCode(GET_WISDOM)); + vm.execute(InstructionConverterUtil.convertToByteCode(ADD)); + vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_2)); + vm.execute(InstructionConverterUtil.convertToByteCode(DIVIDE)); + vm.execute(InstructionConverterUtil.convertToByteCode(ADD)); + vm.execute(InstructionConverterUtil.convertToByteCode(String.format(HEALTH_PATTERN, "SET"))); } } diff --git a/caching/src/main/java/com/iluwatar/caching/DbManager.java b/caching/src/main/java/com/iluwatar/caching/DbManager.java index d0223496948c..3284d3118fdf 100644 --- a/caching/src/main/java/com/iluwatar/caching/DbManager.java +++ b/caching/src/main/java/com/iluwatar/caching/DbManager.java @@ -50,6 +50,7 @@ public final class DbManager { private static boolean useMongoDB; private static Map<String, UserAccount> virtualDB; + private static final String ERROR_MESSAGE_LOG = "Error connecting to MongoDB"; private DbManager() { } @@ -85,7 +86,7 @@ public static UserAccount readFromDb(String userId) { try { connect(); } catch (ParseException e) { - LOGGER.error("Error connecting to MongoDB", e); + LOGGER.error(ERROR_MESSAGE_LOG, e); } } var iterable = db @@ -112,7 +113,7 @@ public static void writeToDb(UserAccount userAccount) { try { connect(); } catch (ParseException e) { - LOGGER.error("Error connecting to MongoDB", e); + LOGGER.error(ERROR_MESSAGE_LOG, e); } } db.getCollection(CachingConstants.USER_ACCOUNT).insertOne( @@ -134,7 +135,7 @@ public static void updateDb(UserAccount userAccount) { try { connect(); } catch (ParseException e) { - LOGGER.error("Error connecting to MongoDB", e); + LOGGER.error(ERROR_MESSAGE_LOG, e); } } db.getCollection(CachingConstants.USER_ACCOUNT).updateOne( @@ -155,7 +156,7 @@ public static void upsertDb(UserAccount userAccount) { try { connect(); } catch (ParseException e) { - LOGGER.error("Error connecting to MongoDB", e); + LOGGER.error(ERROR_MESSAGE_LOG, e); } } db.getCollection(CachingConstants.USER_ACCOUNT).updateOne(
null
train
train
2021-10-08T19:47:25
"2019-10-15T17:54:46Z"
iluwatar
train
iluwatar/java-design-patterns/1875_1879
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1875
iluwatar/java-design-patterns/1879
[ "keyword_pr_to_issue" ]
90b1b922e1f60b25e73493f6f71fa6ad8a10fdee
72bb189dc06d8edd4e8e3ef1a92b9201043087cd
[]
[ "Perhaps this should be called just `build` since the other is called `build-and-analyze`?", "Here too, maybe we can call it just `Build on JDK 11`", "I suggest `Build and run Sonar analysis on JDK 11.0.3`", "This comment is not related to any line, but it would be great to have some comments above the code to explain operations. I mean it's getting rather complex and is no longer self-explanatory what we are doing.", "You are correct.\r\n\r\nLet us add some comments to help understand what is going on.\r\n\r\nAnd things are going to be more complex once we start implementing the automatic code styling by spotless." ]
"2021-10-21T18:28:12Z"
[ "type: enhancement", "epic: build issue" ]
Make a separate build line in for Sonar analysis
I have overlooked that there will be two simultaneous reports generated for Sonar issues which I have overlooked. - [ ] Dismiss Matrix building of the project. - [ ] We need to split into two build pipelines, one for running sonar analysis against the latest `zulu` build, and one with the latest JDK build. - [ ] Let us use the cache feature for `maven` dependencies. _Originally posted by @ohbus in https://github.com/iluwatar/java-design-patterns/pull/1868#pullrequestreview-785844000_
[ ".github/workflows/maven-ci.yml", ".github/workflows/maven-pr-builder.yml" ]
[ ".github/workflows/maven-ci.yml", ".github/workflows/maven-pr-builder.yml" ]
[]
diff --git a/.github/workflows/maven-ci.yml b/.github/workflows/maven-ci.yml index 94406095e02a..3b1bcafb0630 100644 --- a/.github/workflows/maven-ci.yml +++ b/.github/workflows/maven-ci.yml @@ -24,6 +24,9 @@ # This workflow will build a Java project with Maven # For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven +# We are using two jobs here for testing our code on the latest JDK 11 build as well as a more satble build version of 11.0.3 +# You can see the full discussion here https://github.com/iluwatar/java-design-patterns/pull/1868#issue-1029459688 + name: Java CI on: @@ -33,12 +36,11 @@ on: jobs: - build: + # This Workflow Job will build this project and run Sonar analysis using JDK 11.0.3 + build-and-analyze: + name: Build and Run Sonar analysis on JDK 11.0.3 runs-on: ubuntu-20.04 - strategy: - matrix: - java-version: [ 11.0.3, 11 ] steps: - name: Checkout Code @@ -47,12 +49,14 @@ jobs: # Disabling shallow clone for improving relevancy of SonarQube reporting fetch-depth: 0 - - name: Set up JDK ${{ matrix.java-version }} + - name: Set up JDK 11.0.3 uses: actions/setup-java@v2 with: - java-version: ${{ matrix.java-version }} + java-version: 11.0.3 distribution: 'zulu' + cache: 'maven' + # Cache Sonar packages which as used to run anaylysis and collect metrics - name: Cache SonarCloud packages uses: actions/cache@v2 with: @@ -60,14 +64,6 @@ jobs: key: ${{ runner.os }}-sonar restore-keys: ${{ runner.os }}-sonar - - name: Cache Maven dependencies - uses: actions/cache@v2 - with: - path: ~/.m2/repository - key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} - restore-keys: | - ${{ runner.os }}-maven- - # Some tests need screen access - name: Install xvfb run: sudo apt-get install -y xvfb @@ -78,3 +74,28 @@ jobs: # These two env variables are needed for sonar analysis GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + + + # This Workflow Job is going to build the project on the latest stable JDK 11 + build: + + name: Build and Test on JDK 11 + runs-on: ubuntu-20.04 + steps: + + - name: Checkout Code + uses: actions/checkout@v2 + + - name: Set up JDK 11 (Latest) + uses: actions/setup-java@v2 + with: + java-version: 11 + distribution: 'zulu' + cache: 'maven' + + # Some tests need screen access + - name: Install xvfb + run: sudo apt-get install -y xvfb + + - name: Build with Maven + run: xvfb-run ./mvnw clean verify diff --git a/.github/workflows/maven-pr-builder.yml b/.github/workflows/maven-pr-builder.yml index c1fd2bd82beb..8e5c5d9c7ced 100644 --- a/.github/workflows/maven-pr-builder.yml +++ b/.github/workflows/maven-pr-builder.yml @@ -34,11 +34,13 @@ on: jobs: build: + name: Build JDP runs-on: ubuntu-20.04 strategy: matrix: java-version: [ 11.0.3, 11 ] steps: + - name: Checkout Code uses: actions/checkout@v2 @@ -47,14 +49,7 @@ jobs: with: java-version: ${{ matrix.java-version }} distribution: 'zulu' - - - name: Cache Maven Dependecies - uses: actions/cache@v2 - with: - path: ~/.m2/repository - key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} - restore-keys: | - ${{ runner.os }}-maven- + cache: 'maven' # Some tests need screen access - name: Install xvfb
null
train
train
2021-10-21T20:15:45
"2021-10-21T15:42:52Z"
ohbus
train
iluwatar/java-design-patterns/1012_1896
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1012
iluwatar/java-design-patterns/1896
[ "keyword_pr_to_issue" ]
bee1283371d25dd5f0c5e7d4bac66b4c05f9aeac
36c6ce1df7f0008c71d82a6eb784df788505a9b3
[ "Can I take this issue?", "Sure @ykayacan ", "This issue is free for taking again.", "I would like to take this issue.", "Through out checking the files causing issues on SonarCloud, I've encountered test cases that are not properly named to the functionality that they are to be tested against. \r\n\r\nExample`\r\n\r\nIn-correct naming convention of a test method.\r\n> ` @Test\r\n> void test() throws Exception {\r\n> App.main(new String[]{});\r\n> }`\r\n\r\nCorrect naming convention of a test method.\r\n\r\n> `@Test\r\n> public void shouldExecuteAppWithoutException() {\r\n> assertDoesNotThrow(() -> App.main(null));\r\n> }`\r\n\r\nA test method should describe what its testing directly in the naming, I will rename the test cases that I find throughout the refactoring process to match proper convention rules, if the test case is understandable as to what it's testing, but I would encourage that these test cases be looked at and properly named for other contributors making changes to certain files that the test cases test against, otherwise it causes a lot of confusion as to whether said contributor is testing the right thing.", "Ok @ToxicDreamz, assigned to you. I agree with your comment regarding test naming.", "I've already finished with the issue. \r\n\r\nRequest to run another SonarCloud report after merging, to see what else remains, and whether or not they can be modified so issues do not come up again.", "13 blockers and 24 criticals remaining: https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL", "`HotelDaoImpl.java` seems to be one of the hotspots we should fix: https://sonarcloud.io/component_measures?id=iluwatar_java-design-patterns&selected=iluwatar_java-design-patterns%3Atransaction-script%2Fsrc%2Fmain%2Fjava%2Fcom%2Filuwatar%2Ftransactionscript%2FHotelDaoImpl.java&view=list", "@iluwatar happy to be back again :)\r\nCan I help with this issue?", "I will resolve the report:\r\n\r\nhttps://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AW5RukINqcCiTG-gJi15&resolved=false&severities=CRITICAL", "Ok, assigned @anuragagarwal561994 and @daniel-augusto. Thanks guys!", "@iluwatar Can I help with this issue?", "Sure if @anuragagarwal561994 is no longer working on it?", "No @iluwatar I didn't get time to look into this, you can re-assign", "@iluwatar I will start working on it ", "No problem @anuragagarwal561994 \r\n@kanwarpreet25 you're good to go", "@iluwatar can I help with this and coordinate with @kanwarpreet25 @daniel-augusto ?", "@kanwarpreet25 has no public commits since Jul 28, 2019, [f7e22a1](https://github.com/iluwatar/java-design-patterns/commit/f7e22a1cf6f7664e8790cc5c76285adbcc6ab19d)\r\n@daniel-augusto has no public commits to this repo since Oct 11, 2020 [3a72abb](https://github.com/daniel-augusto/java-design-patterns/pull/1/commits/3a72abba25535b9f3bd90ac71c6cc77c530039d3)\r\n\r\nAre you guys working on this know? ", "Thanks for helping out @joseosuna-engineer. I'm looking forward to your pull request!", "Thank you. I'm going to begin with this.", "@iluwatar @ohbus \r\nI have added this project to my own CircleCI and SonarCloud accounts to run SonarCloud before create a pull request.\r\n\r\n**My accounts:**\r\n![image](https://user-images.githubusercontent.com/2281302/113358032-669e9100-931b-11eb-8d05-5b3dbf3c0b7b.png)\r\n\r\n\r\nI **changed two config files**, :scream: **.circleci/config.yml** and **pom.xml** (my fork, another branch) \r\nI'm sure @iluwatar @ohbus that we can find a better approach using environment vars or some characteristic of \r\nCircleCI 2.1 [Youtube](https://www.youtube.com/watch?v=etXD9sCFxIU)\r\n\r\nMy strategy is: \r\n- to use this branch **A** only in my fork.\r\n- to create another branch **B** to commit my code.\r\n- to merge **B** to **A** and run CircleCI + SonarCloud\r\n- when code is okay create a pull request from **B** (that has original config files) to master\r\n\r\n![image](https://user-images.githubusercontent.com/2281302/113358878-fbee5500-931c-11eb-8cbf-caeeca0a0d52.png)\r\n\r\n![image](https://user-images.githubusercontent.com/2281302/113358940-1c1e1400-931d-11eb-940f-a744b88f4a75.png)\r\n\r\n\r\n\r\n\r\n", "I think the general approach presented above is going to work, but as pointed out there are chances to streamline the workflow. @joseosuna-engineer feel free to create another issue where you point out the exact spots we should change.", "@iluwatar I have created issue [1697](https://github.com/iluwatar/java-design-patterns/issues/1697)", "> \r\n> \r\n> The project is using SonarCloud static code analysis. The latest results are showing that it has found several blocker and critical severity code smells (major, minor and info level we ignore). In this task those are fixed or marked as false positives. To mark false positives, SuppressWarnings annotation should be used in code as explained in the linked documentation.\r\n> \r\n> Links:\r\n> [Blocker and critical severity code smells in SonarCloud](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL&types=CODE_SMELL)\r\n> [Sonar false positives](https://docs.sonarqube.org/latest/analysis/languages/java/#JavaFAQ-HowtoremoveFalse-Positiveissues)\r\n\r\n@iluwatar I want to ask you some things:\r\n1.- This issue (1012) is not about all sonarcloud issues. is it?\r\n2.- major, minor and info issues are not included here\r\n3.- it is only about (blocker and critical) + code smell issues\r\n\r\n![image](https://user-images.githubusercontent.com/2281302/113944874-3ea7a580-97d3-11eb-8c10-097e2e03a933.png)\r\n\r\n4.- Do you want I add **@java.lang.SuppressWarnings(\"squid:some-number\")** annotation for **all** in question number 3? or Do I have to do something like [ykayacan](https://github.com/ykayacan/java-design-patterns/commit/d5ed1a1f22467d396c1f61f4ac18ded662591ccb): suppress false positives (test by example) and fix number 3 issues?\r\n", "@joseosuna-engineer \r\n\r\n1. No, it's about blocker and critical level issues only\r\n2. Yes\r\n3. Yes\r\n4. For false positives we can suppress the warnings as you suggested\r\n", "@iluwatar Thank you! ", "Can I help to fix this issue? Has anyone solved this one? https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AW3G0WaAwB6UiZzQNqwC&resolved=false&severities=BLOCKER", "@samuelpsouza Yes. Feel free to colaborate. @iluwatar I'm so sorry. I'm studying for a couple of certification test.", "> @samuelpsouza Yes. Feel free to collaborate. @iluwatar I'm so sorry. I'm studying for a couple of certification tests.\r\n\r\nPlease @joseosuna-engineer, no need for an apology here.\r\n\r\nYou can mention a timeline for when you will be able to make the contributions or let us know in [Gitter](https://gitter.im/iluwatar/java-design-patterns) about the same as well.\r\n\r\nAnd all the very best for your examinations! May you ace them ⭐ ", "> Can I help to fix this issue? Has anyone solved this one? https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AW3G0WaAwB6UiZzQNqwC&resolved=false&severities=BLOCKER\r\n\r\nThank you so much for your interest in our project @samuelpsouza through #1784", "Raised a PR for the following two Critical Code Smells: [#1831](https://github.com/iluwatar/java-design-patterns/pull/1831)\r\n\r\n1. https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AXhD5LIoXfseSECKkezl&resolved=false&severities=CRITICAL&types=CODE_SMELL\r\n2. https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AXhD5LIoXfseSECKkezm&resolved=false&severities=CRITICAL&types=CODE_SMELL\r\n\r\nFirst time contributing to open source software. Please review and provide your feedback.", "> Raised a PR for the following two Critical Code Smells: [#1831](https://github.com/iluwatar/java-design-patterns/pull/1831)\r\n> \r\n> 1. https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AXhD5LIoXfseSECKkezl&resolved=false&severities=CRITICAL&types=CODE_SMELL\r\n> 2. https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AXhD5LIoXfseSECKkezm&resolved=false&severities=CRITICAL&types=CODE_SMELL\r\n> \r\n> First time contributing to open source software. Please review and provide your feedback.\r\n\r\nPlease also review https://github.com/iluwatar/java-design-patterns/pull/1833 and https://github.com/iluwatar/java-design-patterns/pull/1832", "I would like to work on this issue and resolve some of the code smells/ critical issues in Sonar. Can I take this up? @iluwatar", "Sure @parulagg27, go ahead", "We need assistance to resolve the remaining blocker and critical level SonarCloud issues", "I have resolved 1 blocker & 5 critical Sonar issues using [this PR](https://github.com/iluwatar/java-design-patterns/pull/1899). Kindly review and merge.\r\n<img width=\"1730\" alt=\"Screenshot 2021-10-30 at 11 27 15 PM\" src=\"https://user-images.githubusercontent.com/18613127/139554128-d1b1d1f6-0d95-4663-b3bf-096aa31b8b26.png\">\r\n<img width=\"1728\" alt=\"Screenshot 2021-10-30 at 11 26 50 PM\" src=\"https://user-images.githubusercontent.com/18613127/139554131-468ada1a-d34c-4cb9-8c71-2a77a3fe1195.png\">\r\n\r\n\r\n", "- **Resolved** 1 blocker & 5 critical Sonar issues \r\n\r\n- **Old sonar report** :- [here](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER&types=CODE_SMELL)\r\n\r\n- **Code Cov**: Added an extensive test cases for Commander pattern.\r\n\r\n- **PR Quality Gate** is also [green](https://sonarcloud.io/summary/new_code?id=iluwatar_java-design-patterns&pullRequest=1899)\r\n\r\n@iluwatar @ohbus \r\nKindly review and merge [this PR](https://github.com/iluwatar/java-design-patterns/pull/1899)", "hey can i work on this issue :)", "Ok, go ahead @ShivanshCharak ", "Raised a pr for the following Critical code smell\r\nhttps://github.com/iluwatar/java-design-patterns/pull/1960\r\n\r\nplease also review\r\na minor code smell\r\nhttps://github.com/iluwatar/java-design-patterns/pull/1959#issue-1118731779", "Can I help? ", "Ok @S7sRuss, thanks for the help" ]
[]
"2021-10-27T17:07:34Z"
[ "type: bug", "info: good first issue", "type: refactoring", "epic: code quality" ]
SonarCloud reports issues
The project is using SonarCloud static code analysis. The latest results are showing that it has found several blockers and critical severity code smells (major, minor, and info level we ignore). In this task, those are fixed or marked as false positives. To mark false positives, SuppressWarnings annotation should be used in code as explained in the linked documentation. Links: [Blocker and critical severity code smells in SonarCloud](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL&types=CODE_SMELL) [Sonar false positives](https://docs.sonarqube.org/latest/analysis/languages/java/#JavaFAQ-HowtoremoveFalse-Positiveissues) *** Note: When Submitting a PR please provide a **hyperlinked** list of all the issues that you are issuing a fix for. [_See this example_](https://github.com/iluwatar/java-design-patterns/pull/1833#issue-1015516036)
[ "factory-method/src/main/java/com/iluwatar/factory/method/App.java" ]
[ "factory-method/src/main/java/com/iluwatar/factory/method/App.java" ]
[]
diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/App.java b/factory-method/src/main/java/com/iluwatar/factory/method/App.java index b76a918d1876..d903ee7c7fee 100644 --- a/factory-method/src/main/java/com/iluwatar/factory/method/App.java +++ b/factory-method/src/main/java/com/iluwatar/factory/method/App.java @@ -41,6 +41,8 @@ @Slf4j public class App { + private static final String MANUFACTURED = "{} manufactured {}"; + /** * Program entry point. * @param args command line args @@ -49,14 +51,14 @@ public static void main(String[] args) { Blacksmith blacksmith = new OrcBlacksmith(); Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); - LOGGER.info("{} manufactured {}", blacksmith, weapon); + LOGGER.info(MANUFACTURED, blacksmith, weapon); weapon = blacksmith.manufactureWeapon(WeaponType.AXE); - LOGGER.info("{} manufactured {}", blacksmith, weapon); + LOGGER.info(MANUFACTURED, blacksmith, weapon); blacksmith = new ElfBlacksmith(); weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); - LOGGER.info("{} manufactured {}", blacksmith, weapon); + LOGGER.info(MANUFACTURED, blacksmith, weapon); weapon = blacksmith.manufactureWeapon(WeaponType.AXE); - LOGGER.info("{} manufactured {}", blacksmith, weapon); + LOGGER.info(MANUFACTURED, blacksmith, weapon); } }
null
train
train
2021-10-24T16:27:24
"2019-10-15T17:54:46Z"
iluwatar
train
iluwatar/java-design-patterns/1012_1898
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1012
iluwatar/java-design-patterns/1898
[ "keyword_pr_to_issue" ]
72bb189dc06d8edd4e8e3ef1a92b9201043087cd
22ddd571467f811e120d37a43dae0edbc9071779
[ "Can I take this issue?", "Sure @ykayacan ", "This issue is free for taking again.", "I would like to take this issue.", "Through out checking the files causing issues on SonarCloud, I've encountered test cases that are not properly named to the functionality that they are to be tested against. \r\n\r\nExample`\r\n\r\nIn-correct naming convention of a test method.\r\n> ` @Test\r\n> void test() throws Exception {\r\n> App.main(new String[]{});\r\n> }`\r\n\r\nCorrect naming convention of a test method.\r\n\r\n> `@Test\r\n> public void shouldExecuteAppWithoutException() {\r\n> assertDoesNotThrow(() -> App.main(null));\r\n> }`\r\n\r\nA test method should describe what its testing directly in the naming, I will rename the test cases that I find throughout the refactoring process to match proper convention rules, if the test case is understandable as to what it's testing, but I would encourage that these test cases be looked at and properly named for other contributors making changes to certain files that the test cases test against, otherwise it causes a lot of confusion as to whether said contributor is testing the right thing.", "Ok @ToxicDreamz, assigned to you. I agree with your comment regarding test naming.", "I've already finished with the issue. \r\n\r\nRequest to run another SonarCloud report after merging, to see what else remains, and whether or not they can be modified so issues do not come up again.", "13 blockers and 24 criticals remaining: https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL", "`HotelDaoImpl.java` seems to be one of the hotspots we should fix: https://sonarcloud.io/component_measures?id=iluwatar_java-design-patterns&selected=iluwatar_java-design-patterns%3Atransaction-script%2Fsrc%2Fmain%2Fjava%2Fcom%2Filuwatar%2Ftransactionscript%2FHotelDaoImpl.java&view=list", "@iluwatar happy to be back again :)\r\nCan I help with this issue?", "I will resolve the report:\r\n\r\nhttps://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AW5RukINqcCiTG-gJi15&resolved=false&severities=CRITICAL", "Ok, assigned @anuragagarwal561994 and @daniel-augusto. Thanks guys!", "@iluwatar Can I help with this issue?", "Sure if @anuragagarwal561994 is no longer working on it?", "No @iluwatar I didn't get time to look into this, you can re-assign", "@iluwatar I will start working on it ", "No problem @anuragagarwal561994 \r\n@kanwarpreet25 you're good to go", "@iluwatar can I help with this and coordinate with @kanwarpreet25 @daniel-augusto ?", "@kanwarpreet25 has no public commits since Jul 28, 2019, [f7e22a1](https://github.com/iluwatar/java-design-patterns/commit/f7e22a1cf6f7664e8790cc5c76285adbcc6ab19d)\r\n@daniel-augusto has no public commits to this repo since Oct 11, 2020 [3a72abb](https://github.com/daniel-augusto/java-design-patterns/pull/1/commits/3a72abba25535b9f3bd90ac71c6cc77c530039d3)\r\n\r\nAre you guys working on this know? ", "Thanks for helping out @joseosuna-engineer. I'm looking forward to your pull request!", "Thank you. I'm going to begin with this.", "@iluwatar @ohbus \r\nI have added this project to my own CircleCI and SonarCloud accounts to run SonarCloud before create a pull request.\r\n\r\n**My accounts:**\r\n![image](https://user-images.githubusercontent.com/2281302/113358032-669e9100-931b-11eb-8d05-5b3dbf3c0b7b.png)\r\n\r\n\r\nI **changed two config files**, :scream: **.circleci/config.yml** and **pom.xml** (my fork, another branch) \r\nI'm sure @iluwatar @ohbus that we can find a better approach using environment vars or some characteristic of \r\nCircleCI 2.1 [Youtube](https://www.youtube.com/watch?v=etXD9sCFxIU)\r\n\r\nMy strategy is: \r\n- to use this branch **A** only in my fork.\r\n- to create another branch **B** to commit my code.\r\n- to merge **B** to **A** and run CircleCI + SonarCloud\r\n- when code is okay create a pull request from **B** (that has original config files) to master\r\n\r\n![image](https://user-images.githubusercontent.com/2281302/113358878-fbee5500-931c-11eb-8cbf-caeeca0a0d52.png)\r\n\r\n![image](https://user-images.githubusercontent.com/2281302/113358940-1c1e1400-931d-11eb-940f-a744b88f4a75.png)\r\n\r\n\r\n\r\n\r\n", "I think the general approach presented above is going to work, but as pointed out there are chances to streamline the workflow. @joseosuna-engineer feel free to create another issue where you point out the exact spots we should change.", "@iluwatar I have created issue [1697](https://github.com/iluwatar/java-design-patterns/issues/1697)", "> \r\n> \r\n> The project is using SonarCloud static code analysis. The latest results are showing that it has found several blocker and critical severity code smells (major, minor and info level we ignore). In this task those are fixed or marked as false positives. To mark false positives, SuppressWarnings annotation should be used in code as explained in the linked documentation.\r\n> \r\n> Links:\r\n> [Blocker and critical severity code smells in SonarCloud](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL&types=CODE_SMELL)\r\n> [Sonar false positives](https://docs.sonarqube.org/latest/analysis/languages/java/#JavaFAQ-HowtoremoveFalse-Positiveissues)\r\n\r\n@iluwatar I want to ask you some things:\r\n1.- This issue (1012) is not about all sonarcloud issues. is it?\r\n2.- major, minor and info issues are not included here\r\n3.- it is only about (blocker and critical) + code smell issues\r\n\r\n![image](https://user-images.githubusercontent.com/2281302/113944874-3ea7a580-97d3-11eb-8c10-097e2e03a933.png)\r\n\r\n4.- Do you want I add **@java.lang.SuppressWarnings(\"squid:some-number\")** annotation for **all** in question number 3? or Do I have to do something like [ykayacan](https://github.com/ykayacan/java-design-patterns/commit/d5ed1a1f22467d396c1f61f4ac18ded662591ccb): suppress false positives (test by example) and fix number 3 issues?\r\n", "@joseosuna-engineer \r\n\r\n1. No, it's about blocker and critical level issues only\r\n2. Yes\r\n3. Yes\r\n4. For false positives we can suppress the warnings as you suggested\r\n", "@iluwatar Thank you! ", "Can I help to fix this issue? Has anyone solved this one? https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AW3G0WaAwB6UiZzQNqwC&resolved=false&severities=BLOCKER", "@samuelpsouza Yes. Feel free to colaborate. @iluwatar I'm so sorry. I'm studying for a couple of certification test.", "> @samuelpsouza Yes. Feel free to collaborate. @iluwatar I'm so sorry. I'm studying for a couple of certification tests.\r\n\r\nPlease @joseosuna-engineer, no need for an apology here.\r\n\r\nYou can mention a timeline for when you will be able to make the contributions or let us know in [Gitter](https://gitter.im/iluwatar/java-design-patterns) about the same as well.\r\n\r\nAnd all the very best for your examinations! May you ace them ⭐ ", "> Can I help to fix this issue? Has anyone solved this one? https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AW3G0WaAwB6UiZzQNqwC&resolved=false&severities=BLOCKER\r\n\r\nThank you so much for your interest in our project @samuelpsouza through #1784", "Raised a PR for the following two Critical Code Smells: [#1831](https://github.com/iluwatar/java-design-patterns/pull/1831)\r\n\r\n1. https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AXhD5LIoXfseSECKkezl&resolved=false&severities=CRITICAL&types=CODE_SMELL\r\n2. https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AXhD5LIoXfseSECKkezm&resolved=false&severities=CRITICAL&types=CODE_SMELL\r\n\r\nFirst time contributing to open source software. Please review and provide your feedback.", "> Raised a PR for the following two Critical Code Smells: [#1831](https://github.com/iluwatar/java-design-patterns/pull/1831)\r\n> \r\n> 1. https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AXhD5LIoXfseSECKkezl&resolved=false&severities=CRITICAL&types=CODE_SMELL\r\n> 2. https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AXhD5LIoXfseSECKkezm&resolved=false&severities=CRITICAL&types=CODE_SMELL\r\n> \r\n> First time contributing to open source software. Please review and provide your feedback.\r\n\r\nPlease also review https://github.com/iluwatar/java-design-patterns/pull/1833 and https://github.com/iluwatar/java-design-patterns/pull/1832", "I would like to work on this issue and resolve some of the code smells/ critical issues in Sonar. Can I take this up? @iluwatar", "Sure @parulagg27, go ahead", "We need assistance to resolve the remaining blocker and critical level SonarCloud issues", "I have resolved 1 blocker & 5 critical Sonar issues using [this PR](https://github.com/iluwatar/java-design-patterns/pull/1899). Kindly review and merge.\r\n<img width=\"1730\" alt=\"Screenshot 2021-10-30 at 11 27 15 PM\" src=\"https://user-images.githubusercontent.com/18613127/139554128-d1b1d1f6-0d95-4663-b3bf-096aa31b8b26.png\">\r\n<img width=\"1728\" alt=\"Screenshot 2021-10-30 at 11 26 50 PM\" src=\"https://user-images.githubusercontent.com/18613127/139554131-468ada1a-d34c-4cb9-8c71-2a77a3fe1195.png\">\r\n\r\n\r\n", "- **Resolved** 1 blocker & 5 critical Sonar issues \r\n\r\n- **Old sonar report** :- [here](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER&types=CODE_SMELL)\r\n\r\n- **Code Cov**: Added an extensive test cases for Commander pattern.\r\n\r\n- **PR Quality Gate** is also [green](https://sonarcloud.io/summary/new_code?id=iluwatar_java-design-patterns&pullRequest=1899)\r\n\r\n@iluwatar @ohbus \r\nKindly review and merge [this PR](https://github.com/iluwatar/java-design-patterns/pull/1899)", "hey can i work on this issue :)", "Ok, go ahead @ShivanshCharak ", "Raised a pr for the following Critical code smell\r\nhttps://github.com/iluwatar/java-design-patterns/pull/1960\r\n\r\nplease also review\r\na minor code smell\r\nhttps://github.com/iluwatar/java-design-patterns/pull/1959#issue-1118731779", "Can I help? ", "Ok @S7sRuss, thanks for the help" ]
[]
"2021-10-28T04:38:30Z"
[ "type: bug", "info: good first issue", "type: refactoring", "epic: code quality" ]
SonarCloud reports issues
The project is using SonarCloud static code analysis. The latest results are showing that it has found several blockers and critical severity code smells (major, minor, and info level we ignore). In this task, those are fixed or marked as false positives. To mark false positives, SuppressWarnings annotation should be used in code as explained in the linked documentation. Links: [Blocker and critical severity code smells in SonarCloud](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL&types=CODE_SMELL) [Sonar false positives](https://docs.sonarqube.org/latest/analysis/languages/java/#JavaFAQ-HowtoremoveFalse-Positiveissues) *** Note: When Submitting a PR please provide a **hyperlinked** list of all the issues that you are issuing a fix for. [_See this example_](https://github.com/iluwatar/java-design-patterns/pull/1833#issue-1015516036)
[ "strategy/src/main/java/com/iluwatar/strategy/App.java" ]
[ "strategy/src/main/java/com/iluwatar/strategy/App.java" ]
[]
diff --git a/strategy/src/main/java/com/iluwatar/strategy/App.java b/strategy/src/main/java/com/iluwatar/strategy/App.java index 383712c39806..d54c06008692 100644 --- a/strategy/src/main/java/com/iluwatar/strategy/App.java +++ b/strategy/src/main/java/com/iluwatar/strategy/App.java @@ -41,6 +41,10 @@ @Slf4j public class App { + private static final String RED_DRAGON_EMERGES = "Red dragon emerges."; + private static final String GREEN_DRAGON_SPOTTED = "Green dragon spotted ahead!"; + private static final String BLACK_DRAGON_LANDS = "Black dragon lands before you."; + /** * Program entry point. * @@ -48,38 +52,38 @@ public class App { */ public static void main(String[] args) { // GoF Strategy pattern - LOGGER.info("Green dragon spotted ahead!"); + LOGGER.info(GREEN_DRAGON_SPOTTED); var dragonSlayer = new DragonSlayer(new MeleeStrategy()); dragonSlayer.goToBattle(); - LOGGER.info("Red dragon emerges."); + LOGGER.info(RED_DRAGON_EMERGES); dragonSlayer.changeStrategy(new ProjectileStrategy()); dragonSlayer.goToBattle(); - LOGGER.info("Black dragon lands before you."); + LOGGER.info(BLACK_DRAGON_LANDS); dragonSlayer.changeStrategy(new SpellStrategy()); dragonSlayer.goToBattle(); // Java 8 functional implementation Strategy pattern - LOGGER.info("Green dragon spotted ahead!"); + LOGGER.info(GREEN_DRAGON_SPOTTED); dragonSlayer = new DragonSlayer( () -> LOGGER.info("With your Excalibur you severe the dragon's head!")); dragonSlayer.goToBattle(); - LOGGER.info("Red dragon emerges."); + LOGGER.info(RED_DRAGON_EMERGES); dragonSlayer.changeStrategy(() -> LOGGER.info( "You shoot the dragon with the magical crossbow and it falls dead on the ground!")); dragonSlayer.goToBattle(); - LOGGER.info("Black dragon lands before you."); + LOGGER.info(BLACK_DRAGON_LANDS); dragonSlayer.changeStrategy(() -> LOGGER.info( "You cast the spell of disintegration and the dragon vaporizes in a pile of dust!")); dragonSlayer.goToBattle(); // Java 8 lambda implementation with enum Strategy pattern - LOGGER.info("Green dragon spotted ahead!"); + LOGGER.info(GREEN_DRAGON_SPOTTED); dragonSlayer.changeStrategy(LambdaStrategy.Strategy.MeleeStrategy); dragonSlayer.goToBattle(); - LOGGER.info("Red dragon emerges."); + LOGGER.info(RED_DRAGON_EMERGES); dragonSlayer.changeStrategy(LambdaStrategy.Strategy.ProjectileStrategy); dragonSlayer.goToBattle(); - LOGGER.info("Black dragon lands before you."); + LOGGER.info(BLACK_DRAGON_LANDS); dragonSlayer.changeStrategy(LambdaStrategy.Strategy.SpellStrategy); dragonSlayer.goToBattle(); }
null
train
train
2021-10-27T20:44:00
"2019-10-15T17:54:46Z"
iluwatar
train
iluwatar/java-design-patterns/1908_1909
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1908
iluwatar/java-design-patterns/1909
[ "timestamp(timedelta=147.0, similarity=0.8948982414844022)" ]
0a7b524bd10b0eb67ac6045d12415759b1dc7fd0
89b20721316f256994c3194b8dedb589ca6b7362
[ "I have submitted a PR for fixing this bug, please review. @iluwatar @ohbus " ]
[]
"2021-11-10T06:13:15Z"
[ "type: bug", "epic: pattern" ]
Concurrency problems in leader-followers pattern
I have found a bug in the leader-followers pattern during unit test. In the state of concurrency, there is a small chance that no new leader will be promoted. The reason is that in the worker class, there is no double check before calling the wait method of workercenter. It causes the thread which should become leader mistakenly believe that the leader already exists and waits.
[ "leader-followers/src/main/java/com/iluwatar/leaderfollowers/Worker.java" ]
[ "leader-followers/src/main/java/com/iluwatar/leaderfollowers/Worker.java" ]
[]
diff --git a/leader-followers/src/main/java/com/iluwatar/leaderfollowers/Worker.java b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/Worker.java index 6c7caed244b7..21326bb0a77c 100644 --- a/leader-followers/src/main/java/com/iluwatar/leaderfollowers/Worker.java +++ b/leader-followers/src/main/java/com/iluwatar/leaderfollowers/Worker.java @@ -57,9 +57,11 @@ public void run() { try { if (workCenter.getLeader() != null && !workCenter.getLeader().equals(this)) { synchronized (workCenter) { - workCenter.wait(); + if (workCenter.getLeader() != null && !workCenter.getLeader().equals(this)) { + workCenter.wait(); + continue; + } } - continue; } final Task task = taskSet.getTask(); synchronized (workCenter) {
null
train
train
2021-10-31T08:12:05
"2021-11-10T06:11:24Z"
npczwh
train
iluwatar/java-design-patterns/1871_1956
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1871
iluwatar/java-design-patterns/1956
[ "timestamp(timedelta=0.0, similarity=0.9090095920491283)" ]
dde31bfe349fabf800c2ddcf0ac36e69acf8bf8c
b51bca1a6744f2d18d69f52047e70fd5948131f7
[ "I strongly recommend @Dev-AliGhasemi to take this up.", "I do it but @ohbus i don't know where is the problem ! can you give me some tips to solve it ?", "@Dev-AliGhasemi You need to add your monitor pattern to the parent pom.\r\n\r\nJust like all the patterns are added as modules here in this line. You need to add your monitor pattern.\r\n\r\nWrite test cases for your code and resolve all the sonar-reported issues once you submit the PR.\r\n\r\nNothing to worry about we will guide you in each step to make it really successful.\r\n\r\n***\r\n\r\nSo, are you willing to take it?", "Yes .", "i added monitor module to parent POM.\r\n", "> i added monitor module to parent POM.\r\n\r\nPlease submit a PR\r\n", "> > i added monitor module to parent POM.\r\n> \r\n> Please submit a PR\r\n\r\n[#1873](https://github.com/iluwatar/java-design-patterns/pull/1873)", "Hi, @iluwatar @ohbus I am looking forward to fixing this issue. I saw that a PR was raised against it, but it had some failing tests and there was no update after 24 October 2021. I am willing to work on this.\r\n\r\nSo will you assign this issue to me?\r\n\r\n> **PS:** I am new to Java, so any kind of feedback or guidance would be really appreciated.", "Assigned to @arnabsen1729 ", "Thanks for assigning the issue @iluwatar \r\n\r\n---\r\n\r\nI have raised a PR here https://github.com/iluwatar/java-design-patterns/pull/1956\r\nI need some help in improving the final coverage, the rest of the builds are passing.", "Hii..@iluwatar I am looking forward to working on this issue. So, will you please assign this issue to me?", "Hello, @akash19coder I have already made changes and the build is passing. You can take a look at my PR https://github.com/iluwatar/java-design-patterns/pull/1956, just stuck at improving the test coverage. If you can help in that respect it would be really helpful.", "Hi, @arnabsen1729 I don't have real-world experience with Java but with guidance, I can surely help out with improving the test coverage" ]
[]
"2022-01-29T15:55:16Z"
[ "type: bug", "info: good first issue", "epic: build issue" ]
Monitor pattern is not being built
In https://github.com/iluwatar/java-design-patterns/pull/1640 we merged the monitor pattern but noticed that it's not included in the main `pom.xml` and not being built. Let's fix that in this issue.
[ "monitor/pom.xml", "monitor/src/main/java/com/iluwatar/monitor/Bank.java", "monitor/src/main/java/com/iluwatar/monitor/Main.java", "pom.xml" ]
[ "monitor/pom.xml", "monitor/src/main/java/com/iluwatar/monitor/Bank.java", "monitor/src/main/java/com/iluwatar/monitor/Main.java", "pom.xml" ]
[ "monitor/src/test/java/com/iluwatar/monitor/BankTest.java", "monitor/src/test/java/com/iluwatar/monitor/MainTest.java" ]
diff --git a/monitor/pom.xml b/monitor/pom.xml index f337350190a0..9246f33caff9 100644 --- a/monitor/pom.xml +++ b/monitor/pom.xml @@ -21,9 +21,9 @@ <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> - <artifactId>java-design-patterns</artifactId> <groupId>com.iluwatar</groupId> - <version>1.24.0-SNAPSHOT</version> + <artifactId>java-design-patterns</artifactId> + <version>1.26.0-SNAPSHOT</version> </parent> <artifactId>monitor</artifactId> <dependencies> diff --git a/monitor/src/main/java/com/iluwatar/monitor/Bank.java b/monitor/src/main/java/com/iluwatar/monitor/Bank.java index d4defa6d16ca..3652129657b6 100644 --- a/monitor/src/main/java/com/iluwatar/monitor/Bank.java +++ b/monitor/src/main/java/com/iluwatar/monitor/Bank.java @@ -1,37 +1,87 @@ +/* +*The MIT License +*Copyright © 2014-2021 Ilkka Seppälä +* +*Permission is hereby granted, free of charge, to any person obtaining a copy +*of this software and associated documentation files (the "Software"), to deal +*in the Software without restriction, including without limitation the rights +*to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +*copies of the Software, and to permit persons to whom the Software is +*furnished to do so, subject to the following conditions: +* +*The above copyright notice and this permission notice shall be included in +*all copies or substantial portions of the Software. +* +*THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +*IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +*FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +*AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +*LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +*OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +*THE SOFTWARE. +*/ + package com.iluwatar.monitor; import java.util.Arrays; -import java.util.logging.Logger; +import lombok.extern.slf4j.Slf4j; -// Bank class implements the Monitor pattern +/** Bank Definition. */ +@Slf4j public class Bank { - private int[] accounts; - Logger logger; + private final int[] accounts; - public Bank(int accountNum, int baseAmount, Logger logger) { - this.logger = logger; - accounts = new int[accountNum]; - Arrays.fill(accounts, baseAmount); - } + /** + * Constructor. + * + * @param accountNum - account number + * @param baseAmount - base amount + */ + public Bank(int accountNum, int baseAmount) { + accounts = new int[accountNum]; + Arrays.fill(accounts, baseAmount); + } - public synchronized void transfer(int accountA, int accountB, int amount) { - if (accounts[accountA] >= amount) { - accounts[accountB] += amount; - accounts[accountA] -= amount; - logger.info("Transferred from account :" + accountA + " to account :" + accountB + " , amount :" + amount + " . balance :" + getBalance()); - } + /** + * Transfer amounts from one account to another. + * + * @param accountA - source account + * @param accountB - destination account + * @param amount - amount to be transferred + */ + public synchronized void transfer(int accountA, int accountB, int amount) { + if (accounts[accountA] >= amount) { + accounts[accountB] += amount; + accounts[accountA] -= amount; + LOGGER.info( + "Transferred from account: {} to account: {} , amount: {} , balance: {}", + accountA, + accountB, + amount, + getBalance()); } + } - public synchronized int getBalance() { - int balance = 0; - for (int account : accounts) { - balance += account; - } - return balance; + /** + * Calculates the total balance. + * + * @return balance + */ + public synchronized int getBalance() { + int balance = 0; + for (int account : accounts) { + balance += account; } + return balance; + } - public int[] getAccounts() { - return accounts; - } + /** + * Get all accounts. + * + * @return accounts + */ + public int[] getAccounts() { + return accounts; + } } diff --git a/monitor/src/main/java/com/iluwatar/monitor/Main.java b/monitor/src/main/java/com/iluwatar/monitor/Main.java index c1e1bcccb8d2..317cbd337c73 100644 --- a/monitor/src/main/java/com/iluwatar/monitor/Main.java +++ b/monitor/src/main/java/com/iluwatar/monitor/Main.java @@ -1,60 +1,73 @@ /* - * The MIT License - * Copyright © 2014-2021 Ilkka Seppälä + *The MIT License + *Copyright © 2014-2021 Ilkka Seppälä * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: + *Permission is hereby granted, free of charge, to any person obtaining a copy + *of this software and associated documentation files (the "Software"), to deal + *in the Software without restriction, including without limitation the rights + *to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + *copies of the Software, and to permit persons to whom the Software is + *furnished to do so, subject to the following conditions: * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. + *The above copyright notice and this permission notice shall be included in + *all copies or substantial portions of the Software. * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. + *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + *IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + *FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + *AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + *LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + *OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + *THE SOFTWARE. */ package com.iluwatar.monitor; -import java.util.*; +import java.security.SecureRandom; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import java.util.logging.Logger; +import lombok.extern.slf4j.Slf4j; /** - * <p>The Monitor pattern is used in concurrent algorithms to achieve mutual exclusion.</p> + * The Monitor pattern is used in concurrent algorithms to achieve mutual exclusion. * - * <p>Bank is a simple class that transfers money from an account to another account using - * {@link Bank#transfer}. It can also return the balance of the bank account stored in the bank.</p> + * <p>Bank is a simple class that transfers money from an account to another account using {@link + * Bank#transfer}. It can also return the balance of the bank account stored in the bank. * - * <p>Main class uses ThreadPool to run threads that do transactions on the bank accounts.</p> + * <p>Main class uses ThreadPool to run threads that do transactions on the bank accounts. */ - +@Slf4j public class Main { - public static void main(String[] args) { - Logger logger = Logger.getLogger("monitor"); - var bank = new Bank(4, 1000, logger); - Runnable runnable = () -> { - try { - Thread.sleep((long) (Math.random() * 1000)); - Random random = new Random(); - for (int i = 0; i < 1000000; i++) - bank.transfer(random.nextInt(4), random.nextInt(4), (int) (Math.random() * 1000)); - } catch (InterruptedException e) { - logger.info(e.getMessage()); - } - }; - ExecutorService executorService = Executors.newFixedThreadPool(5); - for (int i = 0; i < 5; i++) { - executorService.execute(runnable); - } + /** + * Runner to perform a bunch of transfers and handle exception. + * + * @param bank bank object + */ + public static void runner(Bank bank) { + try { + SecureRandom random = new SecureRandom(); + Thread.sleep(random.nextInt(1000)); + for (int i = 0; i < 1000000; i++) { + bank.transfer(random.nextInt(4), random.nextInt(4), random.nextInt()); + } + } catch (InterruptedException e) { + LOGGER.info(e.getMessage()); + Thread.currentThread().interrupt(); + } + } + + /** + * Program entry point. + * + * @param args command line args + */ + public static void main(String[] args) { + var bank = new Bank(4, 1000); + Runnable runnable = () -> runner(bank); + ExecutorService executorService = Executors.newFixedThreadPool(5); + for (int i = 0; i < 5; i++) { + executorService.execute(runnable); } -} \ No newline at end of file + } +} diff --git a/pom.xml b/pom.xml index e58146c72cd2..064e7c1a7eff 100644 --- a/pom.xml +++ b/pom.xml @@ -85,6 +85,7 @@ </properties> <modules> <module>abstract-factory</module> + <module>monitor</module> <module>tls</module> <module>builder</module> <module>factory-method</module>
diff --git a/monitor/src/main/test/java/com/iluwater/java/BankTest.java b/monitor/src/main/test/java/com/iluwater/java/BankTest.java deleted file mode 100644 index eab7d7a3c59d..000000000000 --- a/monitor/src/main/test/java/com/iluwater/java/BankTest.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.iluwater.java; - -import com.iluwatar.monitor.Bank; -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.*; -import static org.junit.jupiter.api.Assumptions.*; - -import java.util.logging.Logger; - -public class BankTest { - - private static Bank bank; - private static final int ACCOUNT_NUM = 4; - private static final int BASE_AMOUNT = 1000; - private static final Logger LOGGER = Logger.getLogger("monitor"); - - @BeforeAll - public static void Setup() { - bank = new Bank(ACCOUNT_NUM, BASE_AMOUNT, LOGGER); - } - - @Test - public void GetAccountHaveNotBeNull() { - assertNotNull(bank.getAccounts()); - } - - @Test - public void LengthOfAccountsHaveToEqualsToAccountNumConstant() { - assumeTrue(bank.getAccounts() != null); - assertEquals(ACCOUNT_NUM, bank.getAccounts().length); - } - - @Test - public void TransferMethodHaveToTransferAmountFromAnAccountToOtherAccount() { - bank.transfer(0, 1, 1000); - int accounts[] = bank.getAccounts(); - assertEquals(0, accounts[0]); - assertEquals(2000, 2000); - } - - @Test - public void BalanceHaveToBeOK() { - assertEquals(4000, bank.getBalance()); - } - - - @AfterAll - public static void TearDown() { - bank = null; - } - -} diff --git a/monitor/src/test/java/com/iluwatar/monitor/BankTest.java b/monitor/src/test/java/com/iluwatar/monitor/BankTest.java new file mode 100644 index 000000000000..a961ec091ef6 --- /dev/null +++ b/monitor/src/test/java/com/iluwatar/monitor/BankTest.java @@ -0,0 +1,71 @@ +/* + *The MIT License + *Copyright © 2014-2021 Ilkka Seppälä + * + *Permission is hereby granted, free of charge, to any person obtaining a copy + *of this software and associated documentation files (the "Software"), to deal + *in the Software without restriction, including without limitation the rights + *to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + *copies of the Software, and to permit persons to whom the Software is + *furnished to do so, subject to the following conditions: + * + *The above copyright notice and this permission notice shall be included in + *all copies or substantial portions of the Software. + * + *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + *IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + *FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + *AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + *LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + *OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + *THE SOFTWARE. + */ + +package com.iluwatar.monitor; + +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.*; +import static org.junit.jupiter.api.Assumptions.*; + +public class BankTest { + + private static final int ACCOUNT_NUM = 4; + private static final int BASE_AMOUNT = 1000; + private static Bank bank; + + @BeforeAll + public static void Setup() { + bank = new Bank(ACCOUNT_NUM, BASE_AMOUNT); + } + + @AfterAll + public static void TearDown() { + bank = null; + } + + @Test + void GetAccountHaveNotBeNull() { + assertNotNull(bank.getAccounts()); + } + + @Test + void LengthOfAccountsHaveToEqualsToAccountNumConstant() { + assumeTrue(bank.getAccounts() != null); + assertEquals(ACCOUNT_NUM, bank.getAccounts().length); + } + + @Test + void TransferMethodHaveToTransferAmountFromAnAccountToOtherAccount() { + bank.transfer(0, 1, 1000); + int[] accounts = bank.getAccounts(); + assertEquals(0, accounts[0]); + assertEquals(2000, accounts[1]); + } + + @Test + void BalanceHaveToBeOK() { + assertEquals(4000, bank.getBalance()); + } +} diff --git a/monitor/src/test/java/com/iluwatar/monitor/MainTest.java b/monitor/src/test/java/com/iluwatar/monitor/MainTest.java new file mode 100644 index 000000000000..75a313519fdc --- /dev/null +++ b/monitor/src/test/java/com/iluwatar/monitor/MainTest.java @@ -0,0 +1,42 @@ +/* + *The MIT License + *Copyright © 2014-2021 Ilkka Seppälä + * + *Permission is hereby granted, free of charge, to any person obtaining a copy + *of this software and associated documentation files (the "Software"), to deal + *in the Software without restriction, including without limitation the rights + *to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + *copies of the Software, and to permit persons to whom the Software is + *furnished to do so, subject to the following conditions: + * + *The above copyright notice and this permission notice shall be included in + *all copies or substantial portions of the Software. + * + *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + *IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + *FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + *AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + *LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + *OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + *THE SOFTWARE. + */ + +package com.iluwatar.monitor; + +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +/** Test if the application starts without throwing an exception. */ +class MainTest { + + @Test + void shouldExecuteApplicationWithoutException() { + assertDoesNotThrow(() -> Main.main(new String[] {})); + } + + @Test + void RunnerExecuteWithoutException() { + var bank = new Bank(4, 1000); + assertDoesNotThrow(() -> Main.runner(bank)); + } +}
test
train
2022-02-12T19:14:44
"2021-10-19T17:34:01Z"
iluwatar
train
iluwatar/java-design-patterns/1299_1978
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1299
iluwatar/java-design-patterns/1978
[ "timestamp(timedelta=89669.0, similarity=0.8460100922676592)" ]
4cdc309e65f3a1eae597ecb3b22e5ad6b7abbd41
f6a8e26f620322de21e0bf3c0cb7bb2c0719c191
[ "@iluwatar Can I take this? I can probably finish this before this Sunday.", "⭐ Sure thing! Thanks for your interest in our project 😃 ", "Hello @iluwatar, @ohbus and @SuperNovaExtrem, I read the links you provided in the issue and I would like to work on this issue.\r\nI found that pull request #1773 already made for this and it is inactive from some time. \r\nSo if this issue is available can I work on this ?", "Closed https://github.com/iluwatar/java-design-patterns/pull/1773 due to inactivity. @DhavalsinhChavda the issue is now assigned to you, please proceed.", "Sure @iluwatar, I will start working on this.", "Hey @iluwatar I would like to work on this pattern. Do you mind assigning it to me.", "Ok @u7275858 " ]
[ "```suggestion\r\ntitle: Identity Field\r\n```", "Please use the version from the parent pom.xml", "The configuration seems overly verbose. Can you check how maven-assembly-plugin has been configured in the other patterns?", "This should be left out. Use the Java version that's coming from the parent pom.xml (11)" ]
"2022-04-04T12:22:54Z"
[ "epic: pattern", "type: feature" ]
Identity Map pattern
https://www.sourcecodeexamples.net/2018/04/identity-map-pattern.html https://en.wikipedia.org/wiki/Identity_map_pattern
[ "pom.xml" ]
[ "identity-field/README.md", "identity-field/etc/identity-field.puml", "identity-field/pom.xml", "identity-field/src/main/java/com/iluwatar/identityfield/App.java", "identity-field/src/main/java/com/iluwatar/identityfield/Person.java", "pom.xml" ]
[ "identity-field/src/test/java/com/iluwatar/identityfield/AppTest.java", "identity-field/src/test/java/com/iluwatar/identityfield/PersonTest.java" ]
diff --git a/identity-field/README.md b/identity-field/README.md new file mode 100644 index 000000000000..055d6a685b39 --- /dev/null +++ b/identity-field/README.md @@ -0,0 +1,64 @@ +--- +layout: pattern +title: Identity-Field +folder: identity-field +permalink: /patterns/identity-fields/ +categories: Structural +tags: +- Data access +--- + +## Intent +Saves a database ID field in an object to maintain an identity between an in-memory object and a database row. + +## Explanation + +In plain words + +> It uses a java class that has one field matching the primary key in a database table. + +**Programmatic Example** + +We have a **person** table which contains **id**, **name**, **age**, and **gender** as columns. + +| id | name | age | gender | +| :--------: | :--------: | :--------: | :--------: | +| 1 | ramesh | 28 | male | +| 2 | prakash | 28 | male | + +We also have a java class **Person** which contains **id**, **name**, **age**, and **gender** as fields. + +```java +class Person{ + private long id; + private String name; + private int age; + private String gender; + // standard getter and setter methods. +} +``` +1. **id** column is the **primary key** in a database that is unique and distinguishes each row. +2. In the above table, there are two rows and which are uniquely identified by the primary key. +3. The relational database uses the primary key to identify one row from another. + +The **id** column with datatype long represents the identity field. + +In **Person** java class, the **id** field is an identity field that matches the primary key in a database table. + +##Representing the Identity Field in an Object + +The simplest form of Identity Field is a field that matches the type of key in the database. Thus, if you use a simple integral key, an integral field will work very nicely. + +There are three basic choices to get the key: +- Get the database to auto-generate +- Use a GUID +- Generate your own + +## Class diagram +![alt text](./etc/identity-field.png "identity-field") + +## Applicability +Use the Identity-Field pattern when + +* There’s a mapping between objects in memory and rows in a database. + \ No newline at end of file diff --git a/identity-field/etc/identity-field.puml b/identity-field/etc/identity-field.puml new file mode 100644 index 000000000000..c223331f93c9 --- /dev/null +++ b/identity-field/etc/identity-field.puml @@ -0,0 +1,17 @@ +@startuml +package com.iluwatar.identityfield { + class App { + + App() + + main(args : String[]) {static} + } + class Person { + - id : long + - name : string + + Person(id : long, name:string) + + getName():string + + setName(name:string) + + getId() : long + + setId(id:long) + } +} +@enduml \ No newline at end of file diff --git a/identity-field/pom.xml b/identity-field/pom.xml new file mode 100644 index 000000000000..e028dfeebdee --- /dev/null +++ b/identity-field/pom.xml @@ -0,0 +1,65 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <parent> + <artifactId>java-design-patterns</artifactId> + <groupId>com.iluwatar</groupId> + <version>1.26.0-SNAPSHOT</version> + </parent> + <modelVersion>4.0.0</modelVersion> + + <artifactId>identity-field</artifactId> + + <dependencies> + <dependency> + <groupId>org.junit.jupiter</groupId> + <artifactId>junit-jupiter-engine</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-core</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.projectlombok</groupId> + <artifactId>lombok</artifactId> + <version>1.18.22</version> + </dependency> + </dependencies> + <build> + <plugins> + <plugin> + <artifactId>maven-assembly-plugin</artifactId> + <configuration> + <archive> + <manifest> + <mainClass>com.test.MainClassName</mainClass> + </manifest> + </archive> + <descriptorRefs> + <descriptorRef>jar-with-dependencies</descriptorRef> + </descriptorRefs> + </configuration> + <executions> + <execution> + <id>make-assembly</id> + <phase>package</phase> <!-- packaging phase --> + <goals> + <goal>single</goal> + </goals> + </execution> + </executions> + </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-compiler-plugin</artifactId> + <configuration> + <source>8</source> + <target>8</target> + </configuration> + </plugin> + </plugins> + </build> +</project> \ No newline at end of file diff --git a/identity-field/src/main/java/com/iluwatar/identityfield/App.java b/identity-field/src/main/java/com/iluwatar/identityfield/App.java new file mode 100644 index 000000000000..4d97c029b001 --- /dev/null +++ b/identity-field/src/main/java/com/iluwatar/identityfield/App.java @@ -0,0 +1,63 @@ +/* + * The MIT License + * Copyright © 2014-2021 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.identityfield; + +import java.util.LinkedList; +import lombok.extern.slf4j.Slf4j; +import lombok.var; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The identity field pattern is used to save a database ID field in an object + * to maintain an identity between an in-memory object and a database row. + * + * <p>In this example, the {@link Person} is used to save each row in the database in a java object. + * It uses the field id to identify the row in the database. + */ +@Slf4j +public class App { + + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** + * The entry point of application. + * + * @param args the input arguments 、 + */ + + public static void main(String[] args) { + var pearsonList = new LinkedList<Person>(); + for (var i = 0; i < 5; i++) { + var name = "pearson" + i; + var person = new Person(i, name, i, "male"); + pearsonList.add(person); + } + for (var i = 0; i < 5; i++) { + LOGGER.info("Id: " + pearsonList.get(i).getId() + + " Name: " + pearsonList.get(i).getName() + + " Age: " + pearsonList.get(i).getAge() + + " Gender: " + pearsonList.get(i).getGender()); + } + } +} \ No newline at end of file diff --git a/identity-field/src/main/java/com/iluwatar/identityfield/Person.java b/identity-field/src/main/java/com/iluwatar/identityfield/Person.java new file mode 100644 index 000000000000..b5eafd583e22 --- /dev/null +++ b/identity-field/src/main/java/com/iluwatar/identityfield/Person.java @@ -0,0 +1,54 @@ +/* + * The MIT License + * Copyright © 2014-2021 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.identityfield; + +import lombok.Getter; +import lombok.Setter; + +/** + * Person is the class to store each row of the table in the database. + */ + +public class Person { + @Getter @Setter private long id; + @Getter @Setter private String name; + @Getter @Setter private int age; + @Getter @Setter private String gender; + + /** + * Instantiates a new Pearson. + * + * @param id the id of the person + * @param name the name of the person + * @param age the age of the person + * @param gender the gender of the person + */ + public Person(long id, String name, int age, String gender) { + this.id = id; + this.name = name; + this.age = age; + this.gender = gender; + } + +} \ No newline at end of file diff --git a/pom.xml b/pom.xml index 064e7c1a7eff..b1a503bdac77 100644 --- a/pom.xml +++ b/pom.xml @@ -231,6 +231,7 @@ <module>domain-model</module> <module>composite-view</module> <module>metadata-mapping</module> + <module>identity-field</module> </modules> <repositories> <repository>
diff --git a/identity-field/src/test/java/com/iluwatar/identityfield/AppTest.java b/identity-field/src/test/java/com/iluwatar/identityfield/AppTest.java new file mode 100644 index 000000000000..955618df68c9 --- /dev/null +++ b/identity-field/src/test/java/com/iluwatar/identityfield/AppTest.java @@ -0,0 +1,41 @@ +/* + * The MIT License + * Copyright © 2014-2021 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.identityfield; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +/** + * The type App test. + */ +class AppTest { + /** + * App test. + */ + @Test + void shouldExecuteWithoutException() { + assertDoesNotThrow(() -> App.main(new String[]{})); + } +} \ No newline at end of file diff --git a/identity-field/src/test/java/com/iluwatar/identityfield/PersonTest.java b/identity-field/src/test/java/com/iluwatar/identityfield/PersonTest.java new file mode 100644 index 000000000000..70d80bbd5d7e --- /dev/null +++ b/identity-field/src/test/java/com/iluwatar/identityfield/PersonTest.java @@ -0,0 +1,89 @@ +/* + * The MIT License + * Copyright © 2014-2021 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.identityfield; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import lombok.var; +import org.junit.jupiter.api.Test; + +/** + * The type Pearson test. + */ +class PersonTest { + /** + * Pearson test. + */ + @Test + void setNameTest() { + var person = new Person(1, "ramesh", 28, "male"); + assertEquals(1, person.getId()); + assertEquals("ramesh", person.getName()); + assertEquals(28, person.getAge()); + assertEquals("male", person.getGender()); + var name = "prakash"; + person.setName(name); + assertEquals("prakash", person.getName()); + assertEquals(1, person.getId()); + } + + @Test + void setAgeTest() { + var person = new Person(1, "ramesh", 28, "male"); + assertEquals(1, person.getId()); + assertEquals("ramesh", person.getName()); + assertEquals(28, person.getAge()); + assertEquals("male", person.getGender()); + var age = 29; + person.setAge(age); + assertEquals(29, person.getAge()); + assertEquals(1, person.getId()); + } + + @Test + void setGenderTest() { + var person = new Person(1, "ramesh", 28, "male"); + assertEquals(1, person.getId()); + assertEquals("ramesh", person.getName()); + assertEquals(28, person.getAge()); + assertEquals("male", person.getGender()); + var gender = "female"; + person.setGender(gender); + assertEquals("female", person.getGender()); + assertEquals(1, person.getId()); + } + + @Test + void setIdTest() { + var person = new Person(1, "ramesh", 28, "male"); + assertEquals(1, person.getId()); + assertEquals("ramesh", person.getName()); + assertEquals(28, person.getAge()); + assertEquals("male", person.getGender()); + var id = 10; + person.setId(id); + assertEquals("ramesh", person.getName()); + assertEquals(10, person.getId()); + } +} \ No newline at end of file
train
train
2022-04-16T19:46:59
"2020-07-07T17:38:27Z"
iluwatar
train
iluwatar/java-design-patterns/1957_1994
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1957
iluwatar/java-design-patterns/1994
[ "keyword_pr_to_issue" ]
4cdc309e65f3a1eae597ecb3b22e5ad6b7abbd41
a143af638c04cf8797e9788d1d66111d7bfe35f1
[ "@MaheshMadushan can you explain what this issue is about?", "Hi @iluwatar , There is a small casting issue. \r\n![image](https://user-images.githubusercontent.com/58337761/153973583-cf198d38-4525-4a32-ae44-a45b5c6f4972.png)\r\n", "Hi @MaheshMadushan @iluwatar .\r\nI'm beginner in java and during learning the java literals , I encountered one nice point which address this issue . \r\nIn java **integer literal** can always be assigned to a **long** variable . However , to specify a **long literal** you will need to explicitly tell the compiler that the literal value is of type **long** . We can do this by appending an **uppercase** or **lowercase** **L** to the literal .\r\nHere in this case we have variable **futureTime** as type of **long** type but the literal assigned to it is of type **integer** . So here compiler first do the casting of **1000 * 1000 * 1000 * 1000** to an integer literal and then assigned it to **futureTime** .\r\nSolution to this problem is to use the **long literal**.\r\nFor example :\r\n\r\n- **1000L * 1000 * 1000 * 1000**\r\n- **1000 * 1000L * 1000 * 1000**\r\n- **1000 * 1000 * 1000L * 1000**\r\n- **1000 * 1000 * 1000 * 1000L**\r\nThese are few valid long literal we can use ( we can also use variation like 1000000000000L ) .\r\nI hope you got my point here . \r\n", "I want to fix this issue! Thanks a lot. @iluwatar ", "Hi is this issue still up for taking, or is it closed? I would like to contribute", "Fixed with https://github.com/iluwatar/java-design-patterns/pull/1994" ]
[]
"2022-05-06T02:15:26Z"
[ "type: bug", "info: good first issue", "epic: code quality" ]
Casting Issue
![CB](https://user-images.githubusercontent.com/58337761/151684862-b05babb8-180e-472d-b6c0-923b0b16127a.png)
[ "circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DefaultCircuitBreaker.java" ]
[ "circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DefaultCircuitBreaker.java" ]
[]
diff --git a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DefaultCircuitBreaker.java b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DefaultCircuitBreaker.java index 2194d75cbd2a..8c59f394bee1 100644 --- a/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DefaultCircuitBreaker.java +++ b/circuit-breaker/src/main/java/com/iluwatar/circuitbreaker/DefaultCircuitBreaker.java @@ -38,7 +38,7 @@ public class DefaultCircuitBreaker implements CircuitBreaker { int failureCount; private final int failureThreshold; private State state; - private final long futureTime = 1000 * 1000 * 1000 * 1000; + private final long futureTime = 1000L * 1000 * 1000 * 1000; /** * Constructor to create an instance of Circuit Breaker.
null
train
train
2022-04-16T19:46:59
"2022-01-30T02:53:04Z"
MaheshMadushan
train
iluwatar/java-design-patterns/1968_2023
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1968
iluwatar/java-design-patterns/2023
[ "keyword_pr_to_issue" ]
5edcb2341c67feb003c5a5510fc4e6a0c6dcecb6
a568656036a135492bfe35ba767b77e52e9d3019
[ "By the way, happy to pick this fix up if you all agree that this is indeed an issue 😄 ", "Thanks for raising the issue @yonatankarp. I'd like to see the improvement implemented.", "After reading a bit deeper about this design pattern in multiple sources (see below), it seems like the design itself is (almost) correctly implemented, but the example is confusing.\r\n\r\nIn the design, each visitor should have a `visit` method for each of the elements (e.g. `DisplayUnitVisitor`), however, in the current example we have 3 different visitors that are doing the same thing (logging that we visit the specific element or nothing if this is not the correct element).\r\n\r\nI would suggest making the following changes to the code:\r\n\r\n- Amend `UnitVisitor` methods to overload the `visit` method with the different elements in our system (`Commander`, `Sergeant` and `Solider`) as follow:\r\n```java\r\npublic interface UnitVisitor {\r\n\r\n void visit(Soldier soldier);\r\n\r\n void visit(Sergeant sergeant);\r\n\r\n void visit(Commander commander);\r\n\r\n}\r\n```\r\n\r\n- Create a single concrete implementation of the `UnitVisitor` interface (e.g. `LogUnitVisitor`). There's an option to have multiple visitors - however IMHO it will complicate the example for no good reason.\r\n\r\n- Add `Consequences` with the disclaimer that this pattern requires changes to each visitor when adding a new element to the system.\r\n\r\n**sources:**\r\n\r\n- https://www.baeldung.com/java-visitor-pattern\r\n- https://www.tutorialspoint.com/design_pattern/visitor_pattern.htm\r\n- https://en.wikipedia.org/wiki/Visitor_pattern\r\n", "I want to fix this issue. And I have pull a request, Thank you. @iluwatar ", "I have fixed this issue, pls review and merge this. Thanks! @iluwatar " ]
[]
"2022-09-10T15:52:41Z"
[ "epic: pattern", "type: enhancement" ]
Visitor pattern code example violate SOLID
In the current example of the Visitor patter the `UnitVisitor` described as follow: ```java public interface UnitVisitor { void visitSoldier(Soldier soldier); void visitSergeant(Sergeant sergeant); void visitCommander(Commander commander); } ``` This interface violate the interface segregation principle as shown later on when implementing `CommanderVisitor`, `SergeantVisitor` and `SoldierVisitor` as each one of them have methods that are not relevant for the instance. The problem becomes even worst if someone will call be mistake the wrong method in the Unit concrete instances. For example: ```java public class Soldier extends Unit { public Soldier(Unit... children) { super(children); } @Override public void accept(UnitVisitor visitor) { visitor.visitCommander(this); // <-- Wrongly calling the commander method super.accept(visitor); } @Override public String toString() { return "soldier"; } } ``` This should be fixed by having a single method in the `UnitVisitor` interface as follow: ```java public interface Visitor { void visit(Unit unit); } ``` Or alternatively if you want to make sure that you're type safe: ```java public interface Visitor<T extends Unit> { void visit(T t); } ```
[ "visitor/README.md", "visitor/src/main/java/com/iluwatar/visitor/Commander.java", "visitor/src/main/java/com/iluwatar/visitor/CommanderVisitor.java", "visitor/src/main/java/com/iluwatar/visitor/Sergeant.java", "visitor/src/main/java/com/iluwatar/visitor/SergeantVisitor.java", "visitor/src/main/java/com/iluwatar/visitor/Soldier.java", "visitor/src/main/java/com/iluwatar/visitor/SoldierVisitor.java", "visitor/src/main/java/com/iluwatar/visitor/UnitVisitor.java" ]
[ "visitor/README.md", "visitor/src/main/java/com/iluwatar/visitor/Commander.java", "visitor/src/main/java/com/iluwatar/visitor/CommanderVisitor.java", "visitor/src/main/java/com/iluwatar/visitor/Sergeant.java", "visitor/src/main/java/com/iluwatar/visitor/SergeantVisitor.java", "visitor/src/main/java/com/iluwatar/visitor/Soldier.java", "visitor/src/main/java/com/iluwatar/visitor/SoldierVisitor.java", "visitor/src/main/java/com/iluwatar/visitor/UnitVisitor.java" ]
[ "visitor/src/test/java/com/iluwatar/visitor/CommanderTest.java", "visitor/src/test/java/com/iluwatar/visitor/SergeantTest.java", "visitor/src/test/java/com/iluwatar/visitor/SoldierTest.java", "visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java" ]
diff --git a/visitor/README.md b/visitor/README.md index 38df87d284cc..dae82966bf0f 100644 --- a/visitor/README.md +++ b/visitor/README.md @@ -72,7 +72,7 @@ public class Commander extends Unit { @Override public void accept(UnitVisitor visitor) { - visitor.visitCommander(this); + visitor.visit(this); super.accept(visitor); } @@ -90,7 +90,7 @@ public class Sergeant extends Unit { @Override public void accept(UnitVisitor visitor) { - visitor.visitSergeant(this); + visitor.visit(this); super.accept(visitor); } @@ -108,7 +108,7 @@ public class Soldier extends Unit { @Override public void accept(UnitVisitor visitor) { - visitor.visitSoldier(this); + visitor.visit(this); super.accept(visitor); } @@ -126,17 +126,17 @@ Here are then some concrete visitors. public class CommanderVisitor implements UnitVisitor { @Override - public void visitSoldier(Soldier soldier) { + public void visit(Soldier soldier) { // Do nothing } @Override - public void visitSergeant(Sergeant sergeant) { + public void visit(Sergeant sergeant) { // Do nothing } @Override - public void visitCommander(Commander commander) { + public void visit(Commander commander) { LOGGER.info("Good to see you {}", commander); } } @@ -145,17 +145,17 @@ public class CommanderVisitor implements UnitVisitor { public class SergeantVisitor implements UnitVisitor { @Override - public void visitSoldier(Soldier soldier) { + public void visit(Soldier soldier) { // Do nothing } @Override - public void visitSergeant(Sergeant sergeant) { + public void visit(Sergeant sergeant) { LOGGER.info("Hello {}", sergeant); } @Override - public void visitCommander(Commander commander) { + public void visit(Commander commander) { // Do nothing } } @@ -164,17 +164,17 @@ public class SergeantVisitor implements UnitVisitor { public class SoldierVisitor implements UnitVisitor { @Override - public void visitSoldier(Soldier soldier) { + public void visit(Soldier soldier) { LOGGER.info("Greetings {}", soldier); } @Override - public void visitSergeant(Sergeant sergeant) { + public void visit(Sergeant sergeant) { // Do nothing } @Override - public void visitCommander(Commander commander) { + public void visit(Commander commander) { // Do nothing } } diff --git a/visitor/src/main/java/com/iluwatar/visitor/Commander.java b/visitor/src/main/java/com/iluwatar/visitor/Commander.java index a7c0a0252ad2..9fd10dcd4b77 100644 --- a/visitor/src/main/java/com/iluwatar/visitor/Commander.java +++ b/visitor/src/main/java/com/iluwatar/visitor/Commander.java @@ -32,9 +32,13 @@ public Commander(Unit... children) { super(children); } + /** + * Accept a Visitor. + * @param visitor UnitVisitor to be accepted + */ @Override public void accept(UnitVisitor visitor) { - visitor.visitCommander(this); + visitor.visit(this); super.accept(visitor); } diff --git a/visitor/src/main/java/com/iluwatar/visitor/CommanderVisitor.java b/visitor/src/main/java/com/iluwatar/visitor/CommanderVisitor.java index cf91623bf2b1..f26a4154aada 100644 --- a/visitor/src/main/java/com/iluwatar/visitor/CommanderVisitor.java +++ b/visitor/src/main/java/com/iluwatar/visitor/CommanderVisitor.java @@ -31,18 +31,30 @@ @Slf4j public class CommanderVisitor implements UnitVisitor { + /** + * Soldier Visitor method. + * @param soldier Soldier to be visited + */ @Override - public void visitSoldier(Soldier soldier) { + public void visit(Soldier soldier) { // Do nothing } + /** + * Sergeant Visitor method. + * @param sergeant Sergeant to be visited + */ @Override - public void visitSergeant(Sergeant sergeant) { + public void visit(Sergeant sergeant) { // Do nothing } + /** + * Commander Visitor method. + * @param commander Commander to be visited + */ @Override - public void visitCommander(Commander commander) { + public void visit(Commander commander) { LOGGER.info("Good to see you {}", commander); } } diff --git a/visitor/src/main/java/com/iluwatar/visitor/Sergeant.java b/visitor/src/main/java/com/iluwatar/visitor/Sergeant.java index d92cfce3fcc5..96d1531be506 100644 --- a/visitor/src/main/java/com/iluwatar/visitor/Sergeant.java +++ b/visitor/src/main/java/com/iluwatar/visitor/Sergeant.java @@ -32,9 +32,13 @@ public Sergeant(Unit... children) { super(children); } + /** + * Accept a Visitor. + * @param visitor UnitVisitor to be accepted + */ @Override public void accept(UnitVisitor visitor) { - visitor.visitSergeant(this); + visitor.visit(this); super.accept(visitor); } diff --git a/visitor/src/main/java/com/iluwatar/visitor/SergeantVisitor.java b/visitor/src/main/java/com/iluwatar/visitor/SergeantVisitor.java index f4bf23d5abc2..66fe05f129d6 100644 --- a/visitor/src/main/java/com/iluwatar/visitor/SergeantVisitor.java +++ b/visitor/src/main/java/com/iluwatar/visitor/SergeantVisitor.java @@ -31,18 +31,30 @@ @Slf4j public class SergeantVisitor implements UnitVisitor { + /** + * Soldier Visitor method. + * @param soldier Soldier to be visited + */ @Override - public void visitSoldier(Soldier soldier) { + public void visit(Soldier soldier) { // Do nothing } + /** + * Sergeant Visitor method. + * @param sergeant Sergeant to be visited + */ @Override - public void visitSergeant(Sergeant sergeant) { + public void visit(Sergeant sergeant) { LOGGER.info("Hello {}", sergeant); } + /** + * Commander Visitor method. + * @param commander Commander to be visited + */ @Override - public void visitCommander(Commander commander) { + public void visit(Commander commander) { // Do nothing } } diff --git a/visitor/src/main/java/com/iluwatar/visitor/Soldier.java b/visitor/src/main/java/com/iluwatar/visitor/Soldier.java index ae27bd9c5555..ef7645891519 100644 --- a/visitor/src/main/java/com/iluwatar/visitor/Soldier.java +++ b/visitor/src/main/java/com/iluwatar/visitor/Soldier.java @@ -32,9 +32,13 @@ public Soldier(Unit... children) { super(children); } + /** + * Accept a Visitor. + * @param visitor UnitVisitor to be accepted + */ @Override public void accept(UnitVisitor visitor) { - visitor.visitSoldier(this); + visitor.visit(this); super.accept(visitor); } diff --git a/visitor/src/main/java/com/iluwatar/visitor/SoldierVisitor.java b/visitor/src/main/java/com/iluwatar/visitor/SoldierVisitor.java index eb931e23858d..2ed8b66b980d 100644 --- a/visitor/src/main/java/com/iluwatar/visitor/SoldierVisitor.java +++ b/visitor/src/main/java/com/iluwatar/visitor/SoldierVisitor.java @@ -31,18 +31,30 @@ @Slf4j public class SoldierVisitor implements UnitVisitor { + /** + * Soldier Visitor method. + * @param soldier Soldier to be visited + */ @Override - public void visitSoldier(Soldier soldier) { + public void visit(Soldier soldier) { LOGGER.info("Greetings {}", soldier); } + /** + * Sergeant Visitor method. + * @param sergeant Sergeant to be visited + */ @Override - public void visitSergeant(Sergeant sergeant) { + public void visit(Sergeant sergeant) { // Do nothing } + /** + * Commander Visitor method. + * @param commander Commander to be visited + */ @Override - public void visitCommander(Commander commander) { + public void visit(Commander commander) { // Do nothing } } diff --git a/visitor/src/main/java/com/iluwatar/visitor/UnitVisitor.java b/visitor/src/main/java/com/iluwatar/visitor/UnitVisitor.java index 29aefc1adbbf..08cce7babca8 100644 --- a/visitor/src/main/java/com/iluwatar/visitor/UnitVisitor.java +++ b/visitor/src/main/java/com/iluwatar/visitor/UnitVisitor.java @@ -28,10 +28,10 @@ */ public interface UnitVisitor { - void visitSoldier(Soldier soldier); + void visit(Soldier soldier); - void visitSergeant(Sergeant sergeant); + void visit(Sergeant sergeant); - void visitCommander(Commander commander); + void visit(Commander commander); }
diff --git a/visitor/src/test/java/com/iluwatar/visitor/CommanderTest.java b/visitor/src/test/java/com/iluwatar/visitor/CommanderTest.java index 1e68955509f5..a6054f7244f3 100644 --- a/visitor/src/test/java/com/iluwatar/visitor/CommanderTest.java +++ b/visitor/src/test/java/com/iluwatar/visitor/CommanderTest.java @@ -42,7 +42,7 @@ public CommanderTest() { @Override void verifyVisit(Commander unit, UnitVisitor mockedVisitor) { - verify(mockedVisitor).visitCommander(eq(unit)); + verify(mockedVisitor).visit(eq(unit)); } } \ No newline at end of file diff --git a/visitor/src/test/java/com/iluwatar/visitor/SergeantTest.java b/visitor/src/test/java/com/iluwatar/visitor/SergeantTest.java index 77fcbafe6a52..4d430f5beedb 100644 --- a/visitor/src/test/java/com/iluwatar/visitor/SergeantTest.java +++ b/visitor/src/test/java/com/iluwatar/visitor/SergeantTest.java @@ -42,7 +42,7 @@ public SergeantTest() { @Override void verifyVisit(Sergeant unit, UnitVisitor mockedVisitor) { - verify(mockedVisitor).visitSergeant(eq(unit)); + verify(mockedVisitor).visit(eq(unit)); } } \ No newline at end of file diff --git a/visitor/src/test/java/com/iluwatar/visitor/SoldierTest.java b/visitor/src/test/java/com/iluwatar/visitor/SoldierTest.java index a59eca6b450d..f5f31767ee9a 100644 --- a/visitor/src/test/java/com/iluwatar/visitor/SoldierTest.java +++ b/visitor/src/test/java/com/iluwatar/visitor/SoldierTest.java @@ -42,7 +42,7 @@ public SoldierTest() { @Override void verifyVisit(Soldier unit, UnitVisitor mockedVisitor) { - verify(mockedVisitor).visitSoldier(eq(unit)); + verify(mockedVisitor).visit(eq(unit)); } } \ No newline at end of file diff --git a/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java b/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java index 694be7ab23f8..dbc342806685 100644 --- a/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java +++ b/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java @@ -97,7 +97,7 @@ public VisitorTest( @Test void testVisitCommander() { - this.visitor.visitCommander(new Commander()); + this.visitor.visit(new Commander()); if (this.commanderResponse.isPresent()) { assertEquals(this.commanderResponse.get(), appender.getLastMessage()); assertEquals(1, appender.getLogSize()); @@ -106,7 +106,7 @@ void testVisitCommander() { @Test void testVisitSergeant() { - this.visitor.visitSergeant(new Sergeant()); + this.visitor.visit(new Sergeant()); if (this.sergeantResponse.isPresent()) { assertEquals(this.sergeantResponse.get(), appender.getLastMessage()); assertEquals(1, appender.getLogSize()); @@ -115,7 +115,7 @@ void testVisitSergeant() { @Test void testVisitSoldier() { - this.visitor.visitSoldier(new Soldier()); + this.visitor.visit(new Soldier()); if (this.soldierResponse.isPresent()) { assertEquals(this.soldierResponse.get(), appender.getLastMessage()); assertEquals(1, appender.getLogSize());
train
train
2022-09-10T15:43:39
"2022-02-26T18:32:18Z"
yonatankarp
train
iluwatar/java-design-patterns/2034_2038
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2034
iluwatar/java-design-patterns/2038
[ "timestamp(timedelta=132.0, similarity=0.8836069126259878)" ]
7e87cf9005edea0cedb354e305598eb3feb18f65
57fe447f9c0f0ca07a65adafdadcae808d2be344
[ "@iluwatar : I will update those hotfixes for java 17. Will create separate branch and create pr for the same.", "Ok @karshil2309 " ]
[]
"2022-09-30T19:48:22Z"
[ "info: good first issue", "epic: build issue", "epic: dependencies", "type: feature" ]
Upgrade Lombok version to support Java 17
This issue is a part of the Java 17 transition plan at https://github.com/iluwatar/java-design-patterns/wiki/19.-Java-17-transition. According to https://github.com/projectlombok/lombok/issues/2898, Lombok supports Java 17 since version 1.18.22. Our version is a bit behind that, so let's upgrade to the latest. Acceptance criteria - Lombok version has been updated to the latest available
[ "pom.xml" ]
[ "pom.xml" ]
[]
diff --git a/pom.xml b/pom.xml index a9477de828d8..3e02bfd45eb2 100644 --- a/pom.xml +++ b/pom.xml @@ -66,7 +66,7 @@ <system-lambda.version>1.1.0</system-lambda.version> <urm.version>2.0.0</urm.version> <mockito-junit-jupiter.version>3.5.0</mockito-junit-jupiter.version> - <lombok.version>1.18.20</lombok.version> + <lombok.version>1.18.22</lombok.version> <byte-buddy.version>1.11.5</byte-buddy.version> <javassist.version>3.27.0-GA</javassist.version> <maven-surefire-plugin.version>3.0.0-M5</maven-surefire-plugin.version>
null
train
train
2022-09-25T20:16:42
"2022-09-28T16:17:38Z"
iluwatar
train
iluwatar/java-design-patterns/2045_2046
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2045
iluwatar/java-design-patterns/2046
[ "keyword_pr_to_issue", "timestamp(timedelta=1.0, similarity=0.9312632156071167)" ]
7e87cf9005edea0cedb354e305598eb3feb18f65
84f733d137313af6f9bf1847fa140b07ea390d1f
[ "Ok @aitorfi " ]
[]
"2022-10-02T10:31:21Z"
[ "epic: web site", "info: good first issue", "type: feature", "epic: documentation" ]
Translate abstract-document readme to Spanish
I'll translate the readme file of the abstract-document design pattern to Spanish and place it under localization.es.abstract-document.
[]
[ "localization/es/abstract-document/README.md" ]
[]
diff --git a/localization/es/abstract-document/README.md b/localization/es/abstract-document/README.md new file mode 100644 index 000000000000..f9b698b939cc --- /dev/null +++ b/localization/es/abstract-document/README.md @@ -0,0 +1,183 @@ +--- +layout: pattern +title: Abstract Document +folder: abstract-document +permalink: /patterns/abstract-document/ +categories: Structural +language: es +tags: + - Extensibility +--- + +## Propósito + +Usar propiedades dinámicas y conseguir la felexibilidad de los lenguajes no tipados manteniendo la seguridad de tipos. + +## Explicación + +El uso del patrón Abstract Document permite gestionar propiedades no estáticas adicionales. Este patrón usa el concepto de atributos para permitir seguridad de tipos y propiedades separadas de diferentes clases en un grupo de interfaces. + +Ejemplo del mundo real + +> Toma como ejemplo un coche que está formado por muchas partes. Sin embargo, no sabemos si el coche tiene todas las partes o solo una parte de ellas. Nuestros coches son dinámicos y extremadamente flexibles. + +En resumen + +> El patrón Abstract Document permite añadir propiedades a objetos sin que estos sean conscientes de ello. + +Según Wikipedia + +> Un patrón de diseño estructural orientado a objetos para organizar objetos en contenedores clave-valor vagamente tipados y exponiendo los datos usando vistas tipadas. El propósito del patrón es conseguir un alto grado de flexibilidad entre componentes en un lenguaje de tipado fuerte donde nuevas propiedades pueden añadirse al arbol de objetos sobre la marcha sin perder el soporte de la seguridad de tipos. El patrón hace uso de atributos para separar diferentes propiedades de una clase en distintas interfaces. + +**Ejemplo Programático** + +Primero definamos las clases base `Document` y `AbstractDocument`. Básicamente hacen que el objeto contenga un mapa de propiedades y cualquier número de objetos hijo. + +```java +public interface Document { + + Void put(String key, Object value); + + Object get(String key); + + <T> Stream<T> children(String key, Function<Map<String, Object>, T> constructor); +} + +public abstract class AbstractDocument implements Document { + + private final Map<String, Object> properties; + + protected AbstractDocument(Map<String, Object> properties) { + Objects.requireNonNull(properties, "properties map is required"); + this.properties = properties; + } + + @Override + public Void put(String key, Object value) { + properties.put(key, value); + return null; + } + + @Override + public Object get(String key) { + return properties.get(key); + } + + @Override + public <T> Stream<T> children(String key, Function<Map<String, Object>, T> constructor) { + return Stream.ofNullable(get(key)) + .filter(Objects::nonNull) + .map(el -> (List<Map<String, Object>>) el) + .findAny() + .stream() + .flatMap(Collection::stream) + .map(constructor); + } + ... +} +``` +A continuación definimos un enum `Property` y un grupo de interfaces para tipo, precio, modelo y partes. Esto nos permite crear interfaces de apariencia estática para nuestra clase `Car`. + +```java +public enum Property { + + PARTS, TYPE, PRICE, MODEL +} + +public interface HasType extends Document { + + default Optional<String> getType() { + return Optional.ofNullable((String) get(Property.TYPE.toString())); + } +} + +public interface HasPrice extends Document { + + default Optional<Number> getPrice() { + return Optional.ofNullable((Number) get(Property.PRICE.toString())); + } +} +public interface HasModel extends Document { + + default Optional<String> getModel() { + return Optional.ofNullable((String) get(Property.MODEL.toString())); + } +} + +public interface HasParts extends Document { + + default Stream<Part> getParts() { + return children(Property.PARTS.toString(), Part::new); + } +} +``` + +Ahora estamos listos para introducir el Coche `Car`. + +```java +public class Car extends AbstractDocument implements HasModel, HasPrice, HasParts { + + public Car(Map<String, Object> properties) { + super(properties); + } +} +``` + +Y finalmente asi es como construimos y usamos el Coche `Car` en un ejemplo completo. + +```java + LOGGER.info("Constructing parts and car"); + + var wheelProperties = Map.of( + Property.TYPE.toString(), "wheel", + Property.MODEL.toString(), "15C", + Property.PRICE.toString(), 100L); + + var doorProperties = Map.of( + Property.TYPE.toString(), "door", + Property.MODEL.toString(), "Lambo", + Property.PRICE.toString(), 300L); + + var carProperties = Map.of( + Property.MODEL.toString(), "300SL", + Property.PRICE.toString(), 10000L, + Property.PARTS.toString(), List.of(wheelProperties, doorProperties)); + + var car = new Car(carProperties); + + LOGGER.info("Here is our car:"); + LOGGER.info("-> model: {}", car.getModel().orElseThrow()); + LOGGER.info("-> price: {}", car.getPrice().orElseThrow()); + LOGGER.info("-> parts: "); + car.getParts().forEach(p -> LOGGER.info("\t{}/{}/{}", + p.getType().orElse(null), + p.getModel().orElse(null), + p.getPrice().orElse(null)) + ); + + // Constructing parts and car + // Here is our car: + // model: 300SL + // price: 10000 + // parts: + // wheel/15C/100 + // door/Lambo/300 +``` + +## Diagrama de clases + +![alt text](./etc/abstract-document.png "Abstract Document Traits and Domain") + +## Aplicación + +Usar el patrón Abstract Document cuando + +* Existe la necesidad de añadir propiedades sobre la marcha. +* Quieres una manera flexible de organizar el dominio en una estructura similar a un arbol. +* Quieres un sistema menos acoplado. + +## Créditos + +* [Wikipedia: Abstract Document Pattern](https://en.wikipedia.org/wiki/Abstract_Document_Pattern) +* [Martin Fowler: Dealing with properties](http://martinfowler.com/apsupp/properties.pdf) +* [Pattern-Oriented Software Architecture Volume 4: A Pattern Language for Distributed Computing (v. 4)](https://www.amazon.com/gp/product/0470059028/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0470059028&linkId=e3aacaea7017258acf184f9f3283b492)
null
train
train
2022-09-25T20:16:42
"2022-10-02T09:29:24Z"
aitorfi
train
iluwatar/java-design-patterns/1099_2057
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1099
iluwatar/java-design-patterns/2057
[ "keyword_issue_to_pr" ]
4c1f5cf7fe8cf4ecd427fb5603158bbe17a51406
67f01d43aaa06a8b1191e55665f3fa5b6805c1c9
[ "Yes, I agree with you.", "That‘s right.", "@iluwatar can you please assign this to me?", "@iluwatar @dgruntz \r\nwhere would you want to put this new comment?\r\n`To make sure that subclasses don’t override the template method, we should make it final.`", "I do not want to add this comment but rather change the code and make the template method final. This change has already been made with PR #1100, but as long as this PR is open this issue remains open as well; and the PR can't be merged yet as there is a [issue](https://github.com/mockito/mockito/issues/1826) in Mockito which has not yet been fixed.", "@elouie-code it's assigned to you now", "@elouie-code is there any update regarding this issue or any progress that you made?", "hi @ohbus , @iluwatar , looks like nothing happens here, can I do a PR for this ticket?", "The PR #1100 is already open, but the PR can't be merged yet as there is a [issue](https://github.com/mockito/mockito/issues/1826) in Mockito which has not yet been fixed. I just checked whether the problem has been fixed with version 3.12.4 of Mockito, but this is not the case.", "I see, but in the PR #1100 there is no adjustment of README documentation (explanation why template method should be marked \"final\" and changing the sample code). ", "Agreed, this could be added, and probably the class diagram needs to be adjusted as well (I don't know whether final methods are specially marked, in UML I would use a <<final>> stereotype).", "ok, so assign this ticket to me if you want to have the adjustment of the documentation:\r\n* explanation why final is important in the Template Pattern\r\n* adjustment of all code snippets\r\n* adjustment of the class diagram\r\n\r\n@dgruntz to be honest I wouldn't wait with your change until mockito fixes the issue with final methods. I would merge the code (without unit test) and create a reminder ticket for future to create a unit test with mockito so you are not blocked with the change in the sample. What do you think about it?", "@syfds We could do that. We can merge the code without the unit tests which would drop code coverage and is not a good thing to do, though these are not production codes.\r\n\r\nWe can wait for @iluwatar's suggestion on this. What do you suggest @dgruntz?", "What @syfds suggested sounds reasonable to me", "I will take over and submit a new pull request.", "Hello, @iluwatar, I would like to work on this please assign this issue to me", "All right, good luck @shibicr93 ", "Fixed with PR #2057", "@iluwatar please assign this to @dgruntz since he has already fixed it", "Let's keep the issue open until the PR has been merged" ]
[]
"2022-10-05T09:23:02Z"
[ "type: enhancement", "info: good first issue", "epic: design" ]
Template Method
As statet in the referenced tutorial [Template-method Pattern Tutorial](https://www.journaldev.com/1763/template-method-design-pattern-in-java) I would add a note in the pattern description that the template method should be declared `final`. > To make sure that subclasses don’t override the template method, we should make it final. And I would change the code accordingly.
[ "template-method/README.md", "template-method/pom.xml", "template-method/src/main/java/com/iluwatar/templatemethod/StealingMethod.java" ]
[ "template-method/README.md", "template-method/pom.xml", "template-method/src/main/java/com/iluwatar/templatemethod/StealingMethod.java" ]
[ "template-method/src/test/java/com/iluwatar/templatemethod/HalflingThiefTest.java" ]
diff --git a/template-method/README.md b/template-method/README.md index 7209176f2255..ba34441e0ca8 100644 --- a/template-method/README.md +++ b/template-method/README.md @@ -39,6 +39,10 @@ Wikipedia says **Programmatic Example** Let's first introduce the template method class along with its concrete implementations. +To make sure that subclasses don’t override the template method, the template method (in our case +method `steal`) should be declared `final`, otherwise the skeleton defined in the base class could +be overridden in subclasses. + ```java @Slf4j @@ -50,7 +54,7 @@ public abstract class StealingMethod { protected abstract void stealTheItem(String target); - public void steal() { + public final void steal() { var target = pickTarget(); LOGGER.info("The target has been chosen as {}.", target); confuseTarget(target); diff --git a/template-method/pom.xml b/template-method/pom.xml index ec791eae4c55..dc75fdef0212 100644 --- a/template-method/pom.xml +++ b/template-method/pom.xml @@ -41,7 +41,7 @@ </dependency> <dependency> <groupId>org.mockito</groupId> - <artifactId>mockito-core</artifactId> + <artifactId>mockito-inline</artifactId> <scope>test</scope> </dependency> </dependencies> diff --git a/template-method/src/main/java/com/iluwatar/templatemethod/StealingMethod.java b/template-method/src/main/java/com/iluwatar/templatemethod/StealingMethod.java index ea4248548db2..db8813fa2bb9 100644 --- a/template-method/src/main/java/com/iluwatar/templatemethod/StealingMethod.java +++ b/template-method/src/main/java/com/iluwatar/templatemethod/StealingMethod.java @@ -41,7 +41,7 @@ public abstract class StealingMethod { /** * Steal. */ - public void steal() { + public final void steal() { var target = pickTarget(); LOGGER.info("The target has been chosen as {}.", target); confuseTarget(target);
diff --git a/template-method/src/test/java/com/iluwatar/templatemethod/HalflingThiefTest.java b/template-method/src/test/java/com/iluwatar/templatemethod/HalflingThiefTest.java index eaf7699acffd..9f802597394e 100644 --- a/template-method/src/test/java/com/iluwatar/templatemethod/HalflingThiefTest.java +++ b/template-method/src/test/java/com/iluwatar/templatemethod/HalflingThiefTest.java @@ -24,7 +24,7 @@ */ package com.iluwatar.templatemethod; -import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; @@ -42,11 +42,14 @@ public class HalflingThiefTest { */ @Test void testSteal() { - final var method = mock(StealingMethod.class); + final var method = spy(StealingMethod.class); final var thief = new HalflingThief(method); thief.steal(); verify(method).steal(); + String target = verify(method).pickTarget(); + verify(method).confuseTarget(target); + verify(method).stealTheItem(target); verifyNoMoreInteractions(method); } @@ -56,19 +59,23 @@ void testSteal() { */ @Test void testChangeMethod() { - final var initialMethod = mock(StealingMethod.class); + final var initialMethod = spy(StealingMethod.class); final var thief = new HalflingThief(initialMethod); thief.steal(); verify(initialMethod).steal(); + String target = verify(initialMethod).pickTarget(); + verify(initialMethod).confuseTarget(target); + verify(initialMethod).stealTheItem(target); - final var newMethod = mock(StealingMethod.class); + final var newMethod = spy(StealingMethod.class); thief.changeMethod(newMethod); thief.steal(); verify(newMethod).steal(); - + String newTarget = verify(newMethod).pickTarget(); + verify(newMethod).confuseTarget(newTarget); + verify(newMethod).stealTheItem(newTarget); verifyNoMoreInteractions(initialMethod, newMethod); - } } \ No newline at end of file
train
val
2022-10-04T19:42:31
"2019-11-17T14:25:21Z"
dgruntz
train
iluwatar/java-design-patterns/2066_2072
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2066
iluwatar/java-design-patterns/2072
[ "keyword_pr_to_issue", "timestamp(timedelta=1.0, similarity=0.9493204817788601)" ]
ec07dda65899c5bdcd079a6513e4138b6a96c1a5
d43b21472dfd18ca07ca9f9ec30c31ef0ab2af3c
[ "All right @aitorfi ", "Hello Sir,\r\nI would like to contribute to this project,\r\nI am new to hacktoctoberfest and this would be a great beginning.\r\nThank you..." ]
[]
"2022-10-09T10:10:33Z"
[ "epic: web site", "info: good first issue", "type: feature", "epic: documentation" ]
Translate the abstract-factory readme to Spanish
I'll translate the readme file of the abstract-factory design pattern to Spanish and place it under localization.es.abstract-factory.
[ "localization/es/abstract-document/README.md" ]
[ "localization/es/abstract-document/README.md", "localization/es/abstract-factory/README.md" ]
[]
diff --git a/localization/es/abstract-document/README.md b/localization/es/abstract-document/README.md index f9b698b939cc..2baf94551b09 100644 --- a/localization/es/abstract-document/README.md +++ b/localization/es/abstract-document/README.md @@ -21,7 +21,7 @@ Ejemplo del mundo real > Toma como ejemplo un coche que está formado por muchas partes. Sin embargo, no sabemos si el coche tiene todas las partes o solo una parte de ellas. Nuestros coches son dinámicos y extremadamente flexibles. -En resumen +Dicho de otra forma > El patrón Abstract Document permite añadir propiedades a objetos sin que estos sean conscientes de ello. @@ -166,7 +166,7 @@ Y finalmente asi es como construimos y usamos el Coche `Car` en un ejemplo compl ## Diagrama de clases -![alt text](./etc/abstract-document.png "Abstract Document Traits and Domain") +![alt text](../../../abstract-document/etc/abstract-document.png "Abstract Document Traits and Domain") ## Aplicación diff --git a/localization/es/abstract-factory/README.md b/localization/es/abstract-factory/README.md new file mode 100644 index 000000000000..610b139a0235 --- /dev/null +++ b/localization/es/abstract-factory/README.md @@ -0,0 +1,234 @@ +--- +layout: pattern +title: Abstract Factory +folder: abstract-factory +permalink: /patterns/abstract-factory/ +categories: Creational +language: es +tags: + - Gang of Four +--- + +## También conocido como + +Kit + +## Propósito + +Proveer de una interfaz para crear familias de objetos relacionados dependientes sin especificar su clase concreta. + +## Explicación + +Ejemplo del mundo real + +> Para crear un reino necesitamos objetos con una temática común. El reino élfico necesita un rey elfo, un castillo élfico y un ejército élfico mientras que el reino orco necesita un rey orco, un castillo orco y un ejércico orco. Hay una dependencia entre los objetos del reino. + +Dicho de otra forma + +> Una factoría de factorías; una factoría que agrupa otras factorias individuales pero relacionadas/dependientes sin especificar su clase concreta. + +Según Wikipedia + +> El patrón abstract factory provee una forma de encapsular un grupo de factorías individuales que tienen una temática común sin especificar sus clases concretas. + +**Ejemplo Programático** + +Traduciendo el ejemplo anterior sobre los reinos. Primero tenemos algunas interfaces e implementaciones de los objetos del reino. + +```java +public interface Castle { + String getDescription(); +} + +public interface King { + String getDescription(); +} + +public interface Army { + String getDescription(); +} + +// Elven implementations -> +public class ElfCastle implements Castle { + static final String DESCRIPTION = "This is the elven castle!"; + @Override + public String getDescription() { + return DESCRIPTION; + } +} +public class ElfKing implements King { + static final String DESCRIPTION = "This is the elven king!"; + @Override + public String getDescription() { + return DESCRIPTION; + } +} +public class ElfArmy implements Army { + static final String DESCRIPTION = "This is the elven Army!"; + @Override + public String getDescription() { + return DESCRIPTION; + } +} + +// Orcish implementations similarly -> ... + +``` + +Luego tenemos la abstracción e implementación de la factoría del reino. + +```java +public interface KingdomFactory { + Castle createCastle(); + King createKing(); + Army createArmy(); +} + +public class ElfKingdomFactory implements KingdomFactory { + + @Override + public Castle createCastle() { + return new ElfCastle(); + } + + @Override + public King createKing() { + return new ElfKing(); + } + + @Override + public Army createArmy() { + return new ElfArmy(); + } +} + +public class OrcKingdomFactory implements KingdomFactory { + + @Override + public Castle createCastle() { + return new OrcCastle(); + } + + @Override + public King createKing() { + return new OrcKing(); + } + + @Override + public Army createArmy() { + return new OrcArmy(); + } +} +``` + +Ahora tenemos la factoría abstracta que nos permite hacer familias de objetos relacionados por ejemplo la factoria del reino élfico crea el castillo, rey y ejercito élficos etc. + + +```java +var factory = new ElfKingdomFactory(); +var castle = factory.createCastle(); +var king = factory.createKing(); +var army = factory.createArmy(); + +castle.getDescription(); +king.getDescription(); +army.getDescription(); +``` + +Output del programa: + +```java +This is the elven castle! +This is the elven king! +This is the elven Army! +``` + +Ahora podemos diseñar una factoría para nuestras factorías de reinos. En este ejemplo creamos `FactoryMaker`, responsable de devolver una instancia de `ElfKingdomFactory` o `OrcKingdomFactory`. +El cliente puede usar `FactoryMaker` para crear una factoría concreta, que a su vez, producirá diferentes objetos concretos (derivados de `Army`, `King`, `Castle`). +En este ejemplo también usamos un enum para parametrizar el tipo de factoría de reinos pedirá el cliente. + +```java +public static class FactoryMaker { + + public enum KingdomType { + ELF, ORC + } + + public static KingdomFactory makeFactory(KingdomType type) { + switch (type) { + case ELF: + return new ElfKingdomFactory(); + case ORC: + return new OrcKingdomFactory(); + default: + throw new IllegalArgumentException("KingdomType not supported."); + } + } +} + +public static void main(String[] args) { + var app = new App(); + + LOGGER.info("Elf Kingdom"); + app.createKingdom(FactoryMaker.makeFactory(KingdomType.ELF)); + LOGGER.info(app.getArmy().getDescription()); + LOGGER.info(app.getCastle().getDescription()); + LOGGER.info(app.getKing().getDescription()); + + LOGGER.info("Orc Kingdom"); + app.createKingdom(FactoryMaker.makeFactory(KingdomType.ORC)); + -- similar use of the orc factory +} +``` + +## Diagrama de clases + +![alt text](../../../abstract-factory/etc/abstract-factory.urm.png "Diagrama de Clases de Abstract Factory") + + +## Aplicación + +Usar el patrón Abstract Factory cuando + +* El sistema debe ser agnóstico a como se crean, componen y representan sus objetos. +* El sistema debe ser configurado con una de las múltiples familias de productos. +* La familia de objetos relacionados está diseñada para ser usada en conjunto y necesitas forzar esta premisa. +* Quieres proveer de una librería de productos y solo quieres revelar sus interfaces, no su implementación. +* El tiempo de vida de la dependencia es conceptualmente mas corte que el del cliente. +* Necesitas un valor en tiempo de ejecución para construir una dependencia. +* Quieres decidir que producto de una familia llamar en tiempo de ejecución. +* Necesitas proveer de uno o mas parámetros solo conocidos en tiempo de ejecución antes de poder resolver la dependencia. +* Necesitas consistencia entre productos. +* No quieres cambiar el código existente al añadir nuevos productos o familias de productos al programa. + +Ejemplos de casos de uso + +* Elegir llamar a la implementación correcta de FileSystemAcmeService o DatabaseAcmeService o NetworkAcmeService en tiempo de ejecución. +* Escribir test unitarios se hace mucho mas sencillo. +* Herramientas UI (User Interface) para diferentes SO (Sistemas Operativos). + +## Consecuencias + +* La inyección de dependencias en java esconde las dependencias de la clase servicio lo que puede llevar a errores de ejecución que se podrian haber evitado al compilar. +* Mientras que el patrón es muy bueno creando objetos predefinidos, añadir nuevos puede ser complicado. +* El código es mas complicado de lo que deberia porque se añaden muchas interfaces y clases nuevas junto con el patrón. + +## Tutoriales + +* [Abstract Factory Pattern Tutorial](https://www.journaldev.com/1418/abstract-factory-design-pattern-in-java) + +## Usos conocidos + +* [javax.xml.parsers.DocumentBuilderFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/parsers/DocumentBuilderFactory.html) +* [javax.xml.transform.TransformerFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/transform/TransformerFactory.html#newInstance--) +* [javax.xml.xpath.XPathFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/xpath/XPathFactory.html#newInstance--) + +## Patrones relacionados + +* [Factory Method](https://java-design-patterns.com/patterns/factory-method/) +* [Factory Kit](https://java-design-patterns.com/patterns/factory-kit/) + +## Créditos + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b)
null
val
val
2022-10-09T09:00:16
"2022-10-08T15:05:32Z"
aitorfi
train
iluwatar/java-design-patterns/2054_2073
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2054
iluwatar/java-design-patterns/2073
[ "keyword_pr_to_issue" ]
ec07dda65899c5bdcd079a6513e4138b6a96c1a5
09f97206a72f8e13a4da6b3d998bd94802afd43e
[]
[]
"2022-10-09T11:48:53Z"
[ "type: bug", "epic: build issue", "epic: code quality" ]
Sonar analysis failing due to obsolete Node version
This came up in a recent pull request build: > [ERROR] Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.8.0.2131:sonar (default-cli) on project java-design-patterns: > [ERROR] > [ERROR] The version of node.js (12) you have used to run this analysis is deprecated and we stopped accepting it. > [ERROR] Please update to at least node.js 14. You can find more information here: https://docs.sonarcloud.io/appendices/scanner-environment/ Acceptance criteria - Node version used in the CI build has been upgraded to fix the Sonar analysis
[ ".circleci/config.yml" ]
[ ".circleci/config.yml" ]
[]
diff --git a/.circleci/config.yml b/.circleci/config.yml index 3e35aee712dd..dad7997a8699 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -26,12 +26,14 @@ version: 2 jobs: sonar-pr: docker: - - image: circleci/openjdk:11-node + - image: cimg/openjdk:11.0-node steps: - checkout - restore_cache: key: jdp-sonar-pr-{{ checksum "pom.xml" }} - run: | + sudo apt-get update + sudo apt-get install -y openjdk-11-jdk xvfb if [ -n "${CIRCLE_PR_NUMBER}" ]; then MAVEN_OPTS="-Xmx3000m" xvfb-run ./mvnw -B clean verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar \ -Dsonar.pullrequest.key=${CIRCLE_PR_NUMBER} \
null
train
val
2022-10-09T09:00:16
"2022-10-04T17:23:28Z"
iluwatar
train
iluwatar/java-design-patterns/2077_2078
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2077
iluwatar/java-design-patterns/2078
[ "keyword_pr_to_issue", "timestamp(timedelta=1.0, similarity=0.9470861963188459)" ]
8a7c7b6f21200e33d724fff350c8449964d02c08
505454cbae5fbb58bfd2df51beb48b3307c4f6e6
[ "Ok @aitorfi ", "Hello Sir,\r\nI would like to contribute to this project,\r\nI am new to hacktoctoberfest and this would be a great beginning.\r\nThank you...", "Hello Sir\r\nI want to contribute in this project.\r\nIt will be a great beginning for me if you assign me this issue.\r\nThank you" ]
[]
"2022-10-09T19:50:28Z"
[ "epic: web site", "info: good first issue", "type: feature", "epic: documentation" ]
Translate the active-object readme to Spanish
I'll translate the readme file of the active-object design pattern to Spanish and place it under localization.es.active-object.
[]
[ "localization/es/active-object/README.md" ]
[]
diff --git a/localization/es/active-object/README.md b/localization/es/active-object/README.md new file mode 100644 index 000000000000..617d07b77eab --- /dev/null +++ b/localization/es/active-object/README.md @@ -0,0 +1,130 @@ +--- +layout: pattern +title: Active Object +folder: active-object +permalink: /patterns/active-object/ +categories: Concurrency +language: es +tags: + - Performance +--- + + +## Propósito +El patrón de diseño de objeto activo desacopla la ejecución del método de la invocación del método para los objetos que residen en su propio hilo de control. El objetivo es introducir la concurrencia mediante el uso de la invocación de métodos asíncronos y un planificador para manejar solicitudes. + +## Explicación + +La clase que implementa el patrón de diseño de objeto activo contendrá un mecanismo de autosincronización sin utilizar métodos sincronizados (synchronized). + +Ejemplo del mundo real + +> Los orcos son conocidos por su salvajismo y filosofía de no hacer equipo. Basandonos en este comportamiento se podría decir que tienen su propio hilo de control. + +Podemos usar el patrón Active Object para implementar una criatura que tiene su propio hilo de control y exponer su API pero no la ejecución como tal. + + +**Ejemplo Programático** + +```java +public abstract class ActiveCreature{ + private final Logger logger = LoggerFactory.getLogger(ActiveCreature.class.getName()); + + private BlockingQueue<Runnable> requests; + + private String name; + + private Thread thread; + + public ActiveCreature(String name) { + this.name = name; + this.requests = new LinkedBlockingQueue<Runnable>(); + thread = new Thread(new Runnable() { + @Override + public void run() { + while (true) { + try { + requests.take().run(); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + } + } + } + ); + thread.start(); + } + + public void eat() throws InterruptedException { + requests.put(new Runnable() { + @Override + public void run() { + logger.info("{} is eating!",name()); + logger.info("{} has finished eating!",name()); + } + } + ); + } + + public void roam() throws InterruptedException { + requests.put(new Runnable() { + @Override + public void run() { + logger.info("{} has started to roam the wastelands.",name()); + } + } + ); + } + + public String name() { + return this.name; + } +} +``` + +Podemos ver que cualquier clase que extienda de ActiveCreature tendrá su propio hilo de control para invocar y ejecutar métodos. + +Por ejemplo, la clase Orc: + +```java +public class Orc extends ActiveCreature { + + public Orc(String name) { + super(name); + } + +} +``` + +Ahora podemos crear múltiples criaturas como los Orcos, diles que coman y deambulen y lo harán en su propio hilo de control: + +```java + public static void main(String[] args) { + var app = new App(); + app.run(); + } + + @Override + public void run() { + ActiveCreature creature; + try { + for (int i = 0;i < creatures;i++) { + creature = new Orc(Orc.class.getSimpleName().toString() + i); + creature.eat(); + creature.roam(); + } + Thread.sleep(1000); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + Runtime.getRuntime().exit(1); + } +``` + +## Diagrama de clases + +![alt text](../../../active-object/etc/active-object.urm.png "Active Object class diagram") + +## Tutoriales + +* [Android and Java Concurrency: The Active Object Pattern](https://www.youtube.com/watch?v=Cd8t2u5Qmvc) \ No newline at end of file
null
test
val
2022-10-09T19:49:58
"2022-10-09T19:09:23Z"
aitorfi
train
iluwatar/java-design-patterns/2089_2090
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2089
iluwatar/java-design-patterns/2090
[ "timestamp(timedelta=1.0, similarity=0.9474253277262119)", "keyword_pr_to_issue" ]
1e232d855267274a0dd7b2d46ab11728015612b8
03feaa9faf7bb8de209b8fa72a8d3559629e6c64
[]
[]
"2022-10-14T14:33:18Z"
[ "info: good first issue", "type: feature", "epic: documentation" ]
Translate the acyclic-visitor readme to Spanish
I'll translate the readme file of the acyclic-visitor design pattern to Spanish and place it under localization.es.acyclic-visitor.
[]
[ "localization/es/acyclic-visitor/README.md" ]
[]
diff --git a/localization/es/acyclic-visitor/README.md b/localization/es/acyclic-visitor/README.md new file mode 100644 index 000000000000..08d016b80430 --- /dev/null +++ b/localization/es/acyclic-visitor/README.md @@ -0,0 +1,162 @@ +--- +layout: pattern +title: Acyclic Visitor +folder: acyclic-visitor +permalink: /patterns/acyclic-visitor/ +categories: Behavioral +language: es +tags: + - Extensibility +--- + +## Propósito + +Permitir añadir nuevas funciones a jerarquías de clases existentes sin que estas se vean afectadas, y sin crear los problemáticos círculos de dependencias que son inherentes al patrón GoF (Gang of Four) Visitor. + +## Explicación + +Ejemplo del mundo real + +> Tenemos una jerarquía de clases módem. Los modems de esta jerarquía deben ser visitados por un algoritmo externo basándose en unos filtros (el módem es compatible con Unix o DOS). + +En otras palabras + +> Acyclic Visitor permite añadir funciones a jerarquías de clases existentes sin modificarlas. + +[WikiWikiWeb](https://wiki.c2.com/?AcyclicVisitor) dice + +> El patrón Acyclic Visitor permite que nuevas funciones sean añadidas a jerarquías de clases existentes sin afectar a las mismas, y sin crear los círculos de dependencias que son inherentes al patrón Visitor Pattern de GangOfFour. + +**Ejemplo Programático** + +Aquí tenemos la jerarquía `Modem`. + +```java +public abstract class Modem { + public abstract void accept(ModemVisitor modemVisitor); +} + +public class Zoom extends Modem { + ... + @Override + public void accept(ModemVisitor modemVisitor) { + if (modemVisitor instanceof ZoomVisitor) { + ((ZoomVisitor) modemVisitor).visit(this); + } else { + LOGGER.info("Only ZoomVisitor is allowed to visit Zoom modem"); + } + } +} + +public class Hayes extends Modem { + ... + @Override + public void accept(ModemVisitor modemVisitor) { + if (modemVisitor instanceof HayesVisitor) { + ((HayesVisitor) modemVisitor).visit(this); + } else { + LOGGER.info("Only HayesVisitor is allowed to visit Hayes modem"); + } + } +} +``` + +Después tenemos la jerarquía `ModemVisitor`. + +```java +public interface ModemVisitor { +} + +public interface HayesVisitor extends ModemVisitor { + void visit(Hayes hayes); +} + +public interface ZoomVisitor extends ModemVisitor { + void visit(Zoom zoom); +} + +public interface AllModemVisitor extends ZoomVisitor, HayesVisitor { +} + +public class ConfigureForDosVisitor implements AllModemVisitor { + ... + @Override + public void visit(Hayes hayes) { + LOGGER.info(hayes + " used with Dos configurator."); + } + @Override + public void visit(Zoom zoom) { + LOGGER.info(zoom + " used with Dos configurator."); + } +} + +public class ConfigureForUnixVisitor implements ZoomVisitor { + ... + @Override + public void visit(Zoom zoom) { + LOGGER.info(zoom + " used with Unix configurator."); + } +} +``` + +Finalmente aquí están los "visitors" en acción. + +```java + var conUnix = new ConfigureForUnixVisitor(); + var conDos = new ConfigureForDosVisitor(); + var zoom = new Zoom(); + var hayes = new Hayes(); + hayes.accept(conDos); + zoom.accept(conDos); + hayes.accept(conUnix); + zoom.accept(conUnix); +``` + +Output del programa: + +``` + // Hayes modem used with Dos configurator. + // Zoom modem used with Dos configurator. + // Only HayesVisitor is allowed to visit Hayes modem + // Zoom modem used with Unix configurator. +``` + +## Diagrama de clases + +![alt text](../../../acyclic-visitor/etc/acyclic-visitor.png "Acyclic Visitor") + +## Aplicación + +Este patrón puede ser usado: + +* Cuando necesitas añadir una nueva función a una jerarquía de clases sin que esta se vea afectada o alterada. +* Cuando hay funciones que operan sobre la jerarquía pero no pertenecen a la jerarquía como tal. Las clases ConfigureForDOS / ConfigureForUnix / ConfigureForX por ejemplo. +* Cuando necesitas ejecutar operaciones muy diferentes en un objeto dependiendo de su tipo. +* Cuando la jerarquía visitada va a ser frecuentemente extendida con derivados de la clase elemento. +* Cuando el proceso de volver a compilar, enlazar, probar o distribuir los derivados de la clase elemento es muy pesado. + +## Tutoriales + +* [Acyclic Visitor Pattern Example](https://codecrafter.blogspot.com/2012/12/the-acyclic-visitor-pattern.html) + +## Consecuencias + +Buenas: + +* No hay círculos de dependencias entre las jerarquías. +* No es necesario compilar todos los visitantes si se añade uno nuevo. +* No provoca errores de compilación en visitantes existentes si la jerarquía tiene un nuevo miembro. + +Malas: + +* Viola el [Principio de sustitución de Liskov](https://java-design-patterns.com/principles/#liskov-substitution-principle) al mostrar que puede aceptar todos los visitantes solamente estando interesado en uno en particular. +* Hay que crear una jerarquía de visitantes paralela para todos los miembros de una jerarquía visitable. + +## Patrones relacionados + +* [Visitor Pattern](https://java-design-patterns.com/patterns/visitor/) + +## Créditos + +* [Acyclic Visitor by Robert C. Martin](http://condor.depaul.edu/dmumaugh/OOT/Design-Principles/acv.pdf) +* [Acyclic Visitor in WikiWikiWeb](https://wiki.c2.com/?AcyclicVisitor)
null
val
val
2022-10-10T18:28:06
"2022-10-14T13:14:28Z"
aitorfi
train
iluwatar/java-design-patterns/2096_2099
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2096
iluwatar/java-design-patterns/2099
[ "timestamp(timedelta=1.0, similarity=0.9787524512303212)" ]
1e232d855267274a0dd7b2d46ab11728015612b8
250bb5be3fc351231b3f9ce93946706facf71082
[ "Also, I noticed that a lot of modules in the project has the same situation, should we create one issue per each, since a module is not coupled or you suggest another approach @iluwatar ", "I have opened 2 PRS, haven't noticed the bot who handles contributors (sorry about that)", "> Also, I noticed that a lot of modules in the project has the same situation, should we create one issue per each, since a module is not coupled or you suggest another approach @iluwatar\r\n\r\nYes, this approach is fine @burno1 " ]
[]
"2022-10-16T14:48:05Z"
[ "type: enhancement", "info: good first issue", "epic: code quality" ]
Add lombok to data-transfer-object pattern
I noticed that the pattern is well written but is using a lot of getters and setters without need. We can add lombok to it and have it cleaner to read and understand
[ "data-transfer-object/src/main/java/com/iluwatar/datatransfer/App.java", "data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/Product.java", "data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/ProductResource.java" ]
[ "data-transfer-object/src/main/java/com/iluwatar/datatransfer/App.java", "data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/Product.java", "data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/ProductResource.java" ]
[]
diff --git a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/App.java b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/App.java index 8a731303a664..e9164600ce7e 100644 --- a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/App.java +++ b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/App.java @@ -87,29 +87,29 @@ public static void main(String[] args) { printCustomerDetails(allCustomers); // Example 2: Product DTO - Product tv = - new Product().setId(1L).setName("TV").setSupplier("Sony").setPrice(1000D).setCost(1090D); + + Product tv = Product.builder().id(1L).name("TV").supplier("Sony").price(1000D).cost(1090D).build(); Product microwave = - new Product() - .setId(2L) - .setName("microwave") - .setSupplier("Delonghi") - .setPrice(1000D) - .setCost(1090D); + Product.builder() + .id(2L) + .name("microwave") + .supplier("Delonghi") + .price(1000D) + .cost(1090D).build(); Product refrigerator = - new Product() - .setId(3L) - .setName("refrigerator") - .setSupplier("Botsch") - .setPrice(1000D) - .setCost(1090D); + Product.builder() + .id(3L) + .name("refrigerator") + .supplier("Botsch") + .price(1000D) + .cost(1090D).build(); Product airConditioner = - new Product() - .setId(4L) - .setName("airConditioner") - .setSupplier("LG") - .setPrice(1000D) - .setCost(1090D); + Product.builder() + .id(4L) + .name("airConditioner") + .supplier("LG") + .price(1000D) + .cost(1090D).build(); List<Product> products = new ArrayList<>(Arrays.asList(tv, microwave, refrigerator, airConditioner)); ProductResource productResource = new ProductResource(products); diff --git a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/Product.java b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/Product.java index 2fed53dda8a9..633c0b82997d 100644 --- a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/Product.java +++ b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/Product.java @@ -24,9 +24,18 @@ */ package com.iluwatar.datatransfer.product; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + /** * {@link Product} is a entity class for product entity. This class act as entity in the demo. */ +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor public final class Product { private Long id; private String name; @@ -34,82 +43,14 @@ public final class Product { private Double cost; private String supplier; - /** - * Constructor. - * - * @param id product id - * @param name product name - * @param price product price - * @param cost product cost - * @param supplier product supplier - */ - public Product(Long id, String name, Double price, Double cost, String supplier) { - this.id = id; - this.name = name; - this.price = price; - this.cost = cost; - this.supplier = supplier; - } - - /** - * Constructor. - */ - public Product() { - } - - public Long getId() { - return id; - } - - public Product setId(Long id) { - this.id = id; - return this; - } - - public String getName() { - return name; - } - - public Product setName(String name) { - this.name = name; - return this; - } - - public Double getPrice() { - return price; - } - - public Product setPrice(Double price) { - this.price = price; - return this; - } - - public Double getCost() { - return cost; - } - - public Product setCost(Double cost) { - this.cost = cost; - return this; - } - - public String getSupplier() { - return supplier; - } - - public Product setSupplier(String supplier) { - this.supplier = supplier; - return this; - } - @Override public String toString() { return "Product{" - + "id=" + id - + ", name='" + name + '\'' - + ", price=" + price - + ", cost=" + cost - + ", supplier='" + supplier + '\'' - + '}'; + + "id=" + id + + ", name='" + name + '\'' + + ", price=" + price + + ", cost=" + cost + + ", supplier='" + supplier + '\'' + + '}'; } } diff --git a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/ProductResource.java b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/ProductResource.java index a48f0bc8d702..2c3158fe5441 100644 --- a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/ProductResource.java +++ b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/product/ProductResource.java @@ -50,11 +50,11 @@ public ProductResource(final List<Product> products) { */ public List<ProductDto.Response.Private> getAllProductsForAdmin() { return products - .stream() - .map(p -> new ProductDto.Response.Private().setId(p.getId()).setName(p.getName()) - .setCost(p.getCost()) - .setPrice(p.getPrice())) - .collect(Collectors.toList()); + .stream() + .map(p -> new ProductDto.Response.Private().setId(p.getId()).setName(p.getName()) + .setCost(p.getCost()) + .setPrice(p.getPrice())) + .collect(Collectors.toList()); } /** @@ -64,10 +64,10 @@ public List<ProductDto.Response.Private> getAllProductsForAdmin() { */ public List<ProductDto.Response.Public> getAllProductsForCustomer() { return products - .stream() - .map(p -> new ProductDto.Response.Public().setId(p.getId()).setName(p.getName()) - .setPrice(p.getPrice())) - .collect(Collectors.toList()); + .stream() + .map(p -> new ProductDto.Response.Public().setId(p.getId()).setName(p.getName()) + .setPrice(p.getPrice())) + .collect(Collectors.toList()); } /** @@ -76,12 +76,13 @@ public List<ProductDto.Response.Public> getAllProductsForCustomer() { * @param createProductDto save new product to list. */ public void save(ProductDto.Request.Create createProductDto) { - products.add(new Product() - .setId((long) (products.size() + 1)) - .setName(createProductDto.getName()) - .setSupplier(createProductDto.getSupplier()) - .setPrice(createProductDto.getPrice()) - .setCost(createProductDto.getCost())); + products.add(Product.builder() + .id((long) (products.size() + 1)) + .name(createProductDto.getName()) + .supplier(createProductDto.getSupplier()) + .price(createProductDto.getPrice()) + .cost(createProductDto.getCost()) + .build()); } /**
null
test
val
2022-10-10T18:28:06
"2022-10-16T14:17:52Z"
burno1
train
iluwatar/java-design-patterns/2107_2108
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2107
iluwatar/java-design-patterns/2108
[ "timestamp(timedelta=2.0, similarity=0.9866990623376677)" ]
505454cbae5fbb58bfd2df51beb48b3307c4f6e6
3454a9817509ab455a14cf73fb367e591ff717a2
[ "PR created, waiting for review." ]
[]
"2022-10-17T13:15:30Z"
[ "type: enhancement", "info: good first issue", "epic: code quality" ]
Add lombok to step-builder pattern
This pattern doesn't have lombok added to it, we should add to have cleaner code.
[ "step-builder/src/main/java/com/iluwatar/stepbuilder/Character.java" ]
[ "step-builder/src/main/java/com/iluwatar/stepbuilder/Character.java" ]
[]
diff --git a/step-builder/src/main/java/com/iluwatar/stepbuilder/Character.java b/step-builder/src/main/java/com/iluwatar/stepbuilder/Character.java index 6f04fc09d6eb..05ba3e733c48 100644 --- a/step-builder/src/main/java/com/iluwatar/stepbuilder/Character.java +++ b/step-builder/src/main/java/com/iluwatar/stepbuilder/Character.java @@ -26,9 +26,16 @@ import java.util.List; +import lombok.Getter; +import lombok.Setter; + + + /** * The class with many parameters. */ +@Getter +@Setter public class Character { private String name; @@ -42,53 +49,6 @@ public Character(String name) { this.name = name; } - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getFighterClass() { - return fighterClass; - } - - public void setFighterClass(String fighterClass) { - this.fighterClass = fighterClass; - } - - public String getWizardClass() { - return wizardClass; - } - - public void setWizardClass(String wizardClass) { - this.wizardClass = wizardClass; - } - - public String getWeapon() { - return weapon; - } - - public void setWeapon(String weapon) { - this.weapon = weapon; - } - - public String getSpell() { - return spell; - } - - public void setSpell(String spell) { - this.spell = spell; - } - - public List<String> getAbilities() { - return abilities; - } - - public void setAbilities(List<String> abilities) { - this.abilities = abilities; - } @Override public String toString() {
null
test
val
2022-10-16T18:25:36
"2022-10-17T13:14:10Z"
burno1
train
iluwatar/java-design-patterns/2082_2109
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2082
iluwatar/java-design-patterns/2109
[ "timestamp(timedelta=1.0, similarity=0.9237463224564836)" ]
505454cbae5fbb58bfd2df51beb48b3307c4f6e6
608f6d21cf94cb7a8621b910d865df415b34ed1a
[ "!assign\r\n", "Ok @seongkyu-lim ", "Hello Sir,\r\nI would like to contribute to this project,\r\nI am new to hacktoctoberfest and this would be a great beginning.\r\nThank you...", "Hello sir,\r\nCan you please assign me this issue." ]
[]
"2022-10-17T15:05:44Z"
[ "info: good first issue", "type: feature", "epic: documentation" ]
Translate template-method pattern readme to Korean
I'll translate the readme file of the template-method design pattern to Korean and place it under localization/ko/template-method.
[]
[ "localization/ko/template-method/README.md" ]
[]
diff --git a/localization/ko/template-method/README.md b/localization/ko/template-method/README.md new file mode 100644 index 000000000000..4aeae0c3c738 --- /dev/null +++ b/localization/ko/template-method/README.md @@ -0,0 +1,148 @@ +--- +layout: pattern +title: Template method +folder: template-method +permalink: /patterns/template-method/ko +categories: Behavioral +language: ko +tags: +- Gang of Four +--- + +## 의도 + +동작 상의 알고리즘의 뼈대를 정의하고 일부 단계들을 하위 클래스에게 미룹니다. 템플릿 메소드는 알고리즘 구조의 변경없이 하위 클래스들이 알고리즘의 특정 단계들을 재정의할 수 있게 합니다. + +## 설명 + +실제 예제 + +> 일반적으로 물건을 훔치는 절차는 동일합니다. 첫번째 단계로 대상을 고릅니다. 다음 단계로 대상을 어느정도 혼란스럽게 만듭니다. 마지막 단계로 물건을 훔칩니다. 하지만, 이 단계를 실행하는 구체적인 방법에는 여러가지가 있습니다. + +쉽게 말하자면 + +> 템플릿 메소드 패턴은 일반적인 단계의 아웃라인을 부모 클래스에 제시합니다. 그리고 구체적인 자식 클래스의 구현으로 디테일한 사항들을 정의합니다. + +Wikipedia에 의하면 + +> 객체지향 프로그래밍에서, 템플릿 메소드는 디자인 패턴 책에서 감마를 포함한 책의 저자들이 확인한 행동 디자인 패턴 중 하나입니다. 템플릿 메소드는 보통 추상 수퍼클래스인 수퍼클래스에서의 메소드이며 수많은 high-level 단계들의 관점에서 동작의 뼈대를 정의합니다. 이러한 절차들은 템플릿 메소드와 동일한 클래스의 추가적인 헬퍼 메소드들에 의해 구현됩니다. + +**코드 예제** + +먼저 구체적인 구현과 함께 템플릿 방법 클래스를 소개합니다. 하위클래스들이 템플릿 메소드를 재정의하지 않는 것을 확실히 하기위해 템플릿 메소드(예제에서는 메소드명`steal`)는 `final`로 선언해야 합니다. 그렇지 않으면 기본 클래스에 정의된 뼈대는 하위 클래스에서 재정의될 수 있습니다. + + +```java +@Slf4j +public abstract class StealingMethod { + + protected abstract String pickTarget(); + + protected abstract void confuseTarget(String target); + + protected abstract void stealTheItem(String target); + + public final void steal() { + var target = pickTarget(); + LOGGER.info("The target has been chosen as {}.", target); + confuseTarget(target); + stealTheItem(target); + } +} + +@Slf4j +public class SubtleMethod extends StealingMethod { + + @Override + protected String pickTarget() { + return "shop keeper"; + } + + @Override + protected void confuseTarget(String target) { + LOGGER.info("Approach the {} with tears running and hug him!", target); + } + + @Override + protected void stealTheItem(String target) { + LOGGER.info("While in close contact grab the {}'s wallet.", target); + } +} + +@Slf4j +public class HitAndRunMethod extends StealingMethod { + + @Override + protected String pickTarget() { + return "old goblin woman"; + } + + @Override + protected void confuseTarget(String target) { + LOGGER.info("Approach the {} from behind.", target); + } + + @Override + protected void stealTheItem(String target) { + LOGGER.info("Grab the handbag and run away fast!"); + } +} +``` + +템플릿 메소드를 담고 있는 반쪽짜리 도적 클래스입니다. + +```java +public class HalflingThief { + + private StealingMethod method; + + public HalflingThief(StealingMethod method) { + this.method = method; + } + + public void steal() { + method.steal(); + } + + public void changeMethod(StealingMethod method) { + this.method = method; + } +} +``` + +그리고 마지막으로, 반쪽짜리 도둑이 다른 도둑질 방법을 어떻게 활용하는지 보여줍니다. + +```java + var thief = new HalflingThief(new HitAndRunMethod()); + thief.steal(); + thief.changeMethod(new SubtleMethod()); + thief.steal(); +``` + +## 클래스 다이어그램 + +![alt text](../../../template-method/etc/template_method_urm.png "Template Method") + +## 적용 가능성 + +템플릿 메소드는 사용되어야합니다. + +* 알고리즘의 변하지않는 부분을 한번만 구현하고, 다양할 수 있는 행위의 구현을 서브클래스에게 맡기기 위해 +* 중복되는 코드를 피하기위해 서브클래스들 사이의 공통적인 행위를 공통 클래스에서 고려하고 현지화해야 하는 경우. 이것은 Opdyke 와 Johonson이 묘사한 "일반화하기 위한 수정"의 좋은 예입니다. 먼저 기존 코드들 간의 차이를 확인한 다음 새로운 동작으로 구분합니다. 마지막으로, 다른 코드들을 새로운 동작중 하나를 호출하는 템플릿 메소드로 대체합니다. +* 서브클래스들의 확장을 컨트롤하기 위해. 특정 지점에서 "훅" 작업을 호출하여 해당 지점에서만 확장을 허용하는 템플릿 메서드를 정의할 수 있습니다. + +## 튜토리얼 + +* [Template-method Pattern Tutorial](https://www.journaldev.com/1763/template-method-design-pattern-in-java) + +## 실제 사례 + +* [javax.servlet.GenericServlet.init](https://jakarta.ee/specifications/servlet/4.0/apidocs/javax/servlet/GenericServlet.html#init--): + Method `GenericServlet.init(ServletConfig config)` calls the parameterless method `GenericServlet.init()` which is intended to be overridden in subclasses. + Method `GenericServlet.init(ServletConfig config)` is the template method in this example. + +## 크레딧 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7)
null
train
val
2022-10-16T18:25:36
"2022-10-11T13:48:28Z"
seongkyu-lim
train
iluwatar/java-design-patterns/2124_2126
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2124
iluwatar/java-design-patterns/2126
[ "keyword_pr_to_issue", "timestamp(timedelta=1.0, similarity=0.945691482234587)" ]
3dcda6f2457b27e4b0652ddd9f07e9c6b5b6d4c1
df52e1fd4e57abde9356b581e4b0f87d5eba5ccd
[ "Ok @aitorfi ", "Subtask of #2277 " ]
[ "Please check the new yaml frontmatter requirements at https://github.com/iluwatar/java-design-patterns/wiki/01.-How-to-contribute" ]
"2022-10-19T20:37:48Z"
[ "info: good first issue", "epic: documentation" ]
Translate the adapter readme to Spanish
I'll translate the readme file of the adapter design pattern to Spanish and place it under localization.es.adapter.
[ "adapter/README.md" ]
[ "adapter/README.md", "localization/es/adapter/README.md" ]
[]
diff --git a/adapter/README.md b/adapter/README.md index 2539d0b45fee..7fa4af751b32 100644 --- a/adapter/README.md +++ b/adapter/README.md @@ -112,12 +112,12 @@ Use the Adapter pattern when Class and object adapters have different trade-offs. A class adapter * Adapts Adaptee to Target by committing to a concrete Adaptee class. As a consequence, a class adapter won’t work when we want to adapt a class and all its subclasses. -* Let’s Adapter override some of Adaptee’s behavior since Adapter is a subclass of Adaptee. +* Lets Adapter override some of Adaptee’s behavior since Adapter is a subclass of Adaptee. * Introduces only one object, and no additional pointer indirection is needed to get to the adaptee. An object adapter -* Lets a single Adapter work with many Adaptees—that is, the Adaptee itself and all of its subclasses (if any). The Adapter can also add functionality to all Adaptees at once. +* Lets a single Adapter work with many Adaptees, that is, the Adaptee itself and all of its subclasses (if any). The Adapter can also add functionality to all Adaptees at once. * Makes it harder to override Adaptee behavior. It will require subclassing Adaptee and making the Adapter refer to the subclass rather than the Adaptee itself. diff --git a/localization/es/adapter/README.md b/localization/es/adapter/README.md new file mode 100644 index 000000000000..31ffeb4bf442 --- /dev/null +++ b/localization/es/adapter/README.md @@ -0,0 +1,136 @@ +--- +title: Adapter +category: Structural +language: es +tags: + - Gang of Four +--- + +## También conocido como +Wrapper + +## Propósito +Convertir la interfaz de una clase en otra que espera el cliente. El patrón Adapter permite a clases funcionar en conjunto con otras clases con las que no podrían de otra forma por problemas de compatibilidad. + +## Explicación + +Ejemplo del mundo real + +> Imagina que tienes unas imágenes en una tarjeta de memoria y quieres transferirlas a tu ordenador. Para transferirlas necesitas algún tipo de adaptador compatible con los puertos de tu ordenador que te permita introducir tu tarjeta. En este caso el lector de tarjetas es un adaptador (adapter). +> Otro ejemplo podría ser el famoso adaptador de corriente; un enchufe con tres patas no se puede conectar a una toma de corriente con dos agujeros, necesita un adaptador para hacerlo compatible con la toma de corriente. +> Otro ejemplo mas seria un traductor traduciendo palabras de una persona para otra. + +En otras palabras + +> El patrón Adapter permite envolver un objeto en un adaptador para hacerlo compatible con una clase con la que seria incompatible de otra manera. + +Según Wikipedia + +> En ingeniería de software el patrón Adapter es un patrón de diseño de software que permite usar la interfaz de una clase existente como otra interfaz diferente. A menudo es utilizado para hacer que clases existentes trabajen con otras clases sin necesidad de modificar su código fuente. + +**Ejemplo Programático** + +Toma como ejemplo un capitán que solo puede usar botes de remo y no puede navegar en absoluto. + +Primero tenemos las interfaces `RowingBoat` (bote de remo) y `FishingBoat` (bote de pesca). + +```java +public interface RowingBoat { + void row(); +} + +@Slf4j +public class FishingBoat { + public void sail() { + LOGGER.info("The fishing boat is sailing"); + } +} +``` + +Y el capitán espera una implementación de la interfaz `RowingBoat` (bote de remo) para poder moverse. + +```java +public class Captain { + + private final RowingBoat rowingBoat; + // default constructor and setter for rowingBoat + public Captain(RowingBoat rowingBoat) { + this.rowingBoat = rowingBoat; + } + + public void row() { + rowingBoat.row(); + } +} +``` + +Ahora supongamos que viene un grupo de piratas y nuestro capitán tiene que escapar pero solo hay un bote de pesca. Necesitamos crear un adaptador que permita al capitán usar el bote de pesca con sus habilidades para usar botes de remo. + +```java +@Slf4j +public class FishingBoatAdapter implements RowingBoat { + + private final FishingBoat boat; + + public FishingBoatAdapter() { + boat = new FishingBoat(); + } + + @Override + public void row() { + boat.sail(); + } +} +``` + +Y ahora el `Captain` (capitán) puede usar el `FishingBoat` (bote de pesca) para escapar de los piratas. + +```java +var captain = new Captain(new FishingBoatAdapter()); +captain.row(); +``` + +## Diagrama de clases +![alt text](../../../adapter/etc/adapter.urm.png "Adapter class diagram") + +## Aplicación +Usa el patrón Adapter cuando + +* Quieres usar una clase existente y su interfaz no coincide con la que necesitas. +* Quieres crear una clase reutilizable que coopere con clases que no están relacionadas o con las que su cooperación no estaba planeada, esto es, clases que no necesariamente tienen interfaces compatibles. +* Necesitas usar varias subclases existentes pero es impráctico adaptar su interfaz creando subclases para todas. Un adaptador puede adaptar la interfaz de la clase padre. +* Muchas aplicaciones que usan librerías de terceros usan adaptadores como capas intermedias entre la aplicación y la librería para desacoplar la aplicación de la librería. Si es necesario usar otra librería solo hace falta crear un adaptador para la nueva librería sin necesidad de modificar el código de la aplicación. + +## Tutoriales + +* [Dzone](https://dzone.com/articles/adapter-design-pattern-in-java) +* [Refactoring Guru](https://refactoring.guru/design-patterns/adapter/java/example) +* [Baeldung](https://www.baeldung.com/java-adapter-pattern) + +## Consecuencias +Los adaptadores de clases y objetos tienen distintas cualidades. Un adaptador de clases + +* Hace la adaptación quedando enlazado a una clase adaptada concreta. Como consecuencia un adaptador de clases no funcionará cuando queramos adaptar una clase y sus subclases. +* Permite al adaptador modificar el comportamiento de la clase adaptada porque el adaptador es una subclase de la clase adaptada. +* Usa un solo objeto y no es necesario usar punteros adicionales para referenciar la clase adaptada. + +Un adaptador de objetos + +* Permite a un solo adaptador trabajar con varias clases, esto es, con la clase adaptada y todas sus subclases (si tiene alguna). El adaptador también puede añadir funcionalidad a todas las clases adaptadas a la vez. +* Hace mas complicado modificar el comportamiento de la clase adaptada. Sería necesario hacer una subclase de la clase a adaptar y hacer que el adaptador referencie la subclase en lugar de la clase a adaptar. + + +## Ejemplos del mundo real + +* [java.util.Arrays#asList()](http://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#asList%28T...%29) +* [java.util.Collections#list()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#list-java.util.Enumeration-) +* [java.util.Collections#enumeration()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#enumeration-java.util.Collection-) +* [javax.xml.bind.annotation.adapters.XMLAdapter](http://docs.oracle.com/javase/8/docs/api/javax/xml/bind/annotation/adapters/XmlAdapter.html#marshal-BoundType-) + + +## Créditos + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=48d37c67fb3d845b802fa9b619ad8f31) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7)
null
val
val
2022-10-26T19:43:25
"2022-10-19T19:12:52Z"
aitorfi
train
iluwatar/java-design-patterns/1261_2134
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1261
iluwatar/java-design-patterns/2134
[ "timestamp(timedelta=141.0, similarity=0.8914670140645583)" ]
03feaa9faf7bb8de209b8fa72a8d3559629e6c64
fcaf72fdf8ccfe4da7d4207f6c042d1a43b3d535
[ "Hello, I would like to work on this issue. I manage to finish it within a month.", "Great to have you onboarded @santyelegy!\r\n\r\nWe are expecting the PR for this by the end of May '21", "Hey @iluwatar, may I please pick up on this issue? I am interested in working on this.", "Ok @JoshuaSinglaANU ", "@iluwatar I am almost ready to make a PR, however, the automatic class diagram generation isn't working on my end. I have updated the parent pom.xml file to include my work and locally installed PlantUML, yet still, no class diagram is made. The wiki does not give much detail either. May I please know how to have this feature work?", "UML diagram added." ]
[ "Check out yaml frontmatter requirements at https://github.com/iluwatar/java-design-patterns/wiki/01.-How-to-contribute", "I suggest category `Idiom` and tags `Generic`. See https://github.com/iluwatar/java-design-patterns/wiki/07.-Categories-and-Tags", "```suggestion\r\n## Name\r\n```", "```suggestion\r\nIn the Collecting Parameter idiom a collection (list, map, etc.) is passed repeatedly as a parameter to a method which adds items to the collection.\r\n```", "This part is already defined in the parent pom.xml and shouldn't normally need any additional configuration here", "Add comments to this part as well", "Fixed now.", "Fixed now.", "Fixed now.", "Fixed now.", "Fixed now." ]
"2022-10-21T13:10:21Z"
[ "epic: pattern", "type: feature" ]
Collecting Parameter pattern
https://wiki.c2.com/?CollectingParameter
[ "pom.xml" ]
[ "collecting-parameter/README.md", "collecting-parameter/etc/collecting-parameter.urm.puml", "collecting-parameter/pom.xml", "collecting-parameter/src/main/java/com/iluwatar/collectingparameter/App.java", "collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PaperSizes.java", "collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PrinterItem.java", "collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PrinterQueue.java", "pom.xml" ]
[ "collecting-parameter/src/test/java/com/iluwatar/collectingparameter/AppTest.java", "collecting-parameter/src/test/java/com/iluwatar/collectingparameter/CollectingParameterTest.java", "collecting-parameter/src/test/java/com/iluwatar/collectingparameter/PrinterQueueTest.java" ]
diff --git a/collecting-parameter/README.md b/collecting-parameter/README.md new file mode 100644 index 000000000000..a57b8d2991da --- /dev/null +++ b/collecting-parameter/README.md @@ -0,0 +1,197 @@ +--- +title: Collecting Parameter +category: Idiom +language: en +tags: +- Generic +--- + +## Name +Collecting Parameter + +## Intent +To store the collaborative result of numerous methods within a collection. + +## Explanation +### Real-world example +Within a large corporate building, there exists a global printer queue that is a collection of all the printing jobs +that are currently pending. Various floors contain different models of printers, each having a different printing +policy. We must construct a program that can continually add appropriate printing jobs to a collection, which is called the *collecting parameter*. + +### In plain words +Instead of having one giant method that contains numerous policies for collecting information into a variable, we can +create numerous smaller functions that each take parameter, and append new information. We can pass the parameter to +all of these smaller functions and by the end, we will have what we wanted originally. This time, the code is cleaner +and easier to understand. Because the larger function has been broken down, the code is also easier to modify as changes +are localised to the smaller functions. + +### Wikipedia says +In the Collecting Parameter idiom a collection (list, map, etc.) is passed repeatedly as a parameter to a method which adds items to the collection. + +### Programmatic example +Coding our example from above, we may use the collection `result` as a collecting parameter. The following restrictions +are implemented: +- If an A4 paper is coloured, it must also be single-sided. All other non-coloured papers are accepted +- A3 papers must be non-coloured and single-sided +- A2 papers must be single-page, single-sided, and non-coloured + +```java +package com.iluwatar.collectingparameter; +import java.util.LinkedList; +import java.util.Queue; +public class App { + static PrinterQueue printerQueue = PrinterQueue.getInstance(); + + /** + * Program entry point. + * + * @param args command line args + */ + public static void main(String[] args) { + /* + Initialising the printer queue with jobs + */ + printerQueue.addPrinterItem(new PrinterItem(PaperSizes.A4, 5, false, false)); + printerQueue.addPrinterItem(new PrinterItem(PaperSizes.A3, 2, false, false)); + printerQueue.addPrinterItem(new PrinterItem(PaperSizes.A2, 5, false, false)); + + /* + This variable is the collecting parameter. + */ + var result = new LinkedList<PrinterItem>(); + + /* + * Using numerous sub-methods to collaboratively add information to the result collecting parameter + */ + addA4Papers(result); + addA3Papers(result); + addA2Papers(result); + } +} +``` + +We use the `addA4Paper`, `addA3Paper`, and `addA2Paper` methods to populate the `result` collecting parameter with the +appropriate print jobs as per the policy described previously. The three policies are encoded below, + +```java +public class App { + static PrinterQueue printerQueue = PrinterQueue.getInstance(); + /** + * Adds A4 document jobs to the collecting parameter according to some policy that can be whatever the client + * (the print center) wants. + * + * @param printerItemsCollection the collecting parameter + */ + public static void addA4Papers(Queue<PrinterItem> printerItemsCollection) { + /* + Iterate through the printer queue, and add A4 papers according to the correct policy to the collecting parameter, + which is 'printerItemsCollection' in this case. + */ + for (PrinterItem nextItem : printerQueue.getPrinterQueue()) { + if (nextItem.paperSize.equals(PaperSizes.A4)) { + var isColouredAndSingleSided = nextItem.isColour && !nextItem.isDoubleSided; + if (isColouredAndSingleSided) { + printerItemsCollection.add(nextItem); + } else if (!nextItem.isColour) { + printerItemsCollection.add(nextItem); + } + } + } + } + + /** + * Adds A3 document jobs to the collecting parameter according to some policy that can be whatever the client + * (the print center) wants. The code is similar to the 'addA4Papers' method. The code can be changed to accommodate + * the wants of the client. + * + * @param printerItemsCollection the collecting parameter + */ + public static void addA3Papers(Queue<PrinterItem> printerItemsCollection) { + for (PrinterItem nextItem : printerQueue.getPrinterQueue()) { + if (nextItem.paperSize.equals(PaperSizes.A3)) { + + // Encoding the policy into a Boolean: the A3 paper cannot be coloured and double-sided at the same time + var isNotColouredAndSingleSided = !nextItem.isColour && !nextItem.isDoubleSided; + if (isNotColouredAndSingleSided) { + printerItemsCollection.add(nextItem); + } + } + } + } + + /** + * Adds A2 document jobs to the collecting parameter according to some policy that can be whatever the client + * (the print center) wants. The code is similar to the 'addA4Papers' method. The code can be changed to accommodate + * the wants of the client. + * + * @param printerItemsCollection the collecting parameter + */ + public static void addA2Papers(Queue<PrinterItem> printerItemsCollection) { + for (PrinterItem nextItem : printerQueue.getPrinterQueue()) { + if (nextItem.paperSize.equals(PaperSizes.A2)) { + + // Encoding the policy into a Boolean: the A2 paper must be single page, single-sided, and non-coloured. + var isNotColouredSingleSidedAndOnePage = nextItem.pageCount == 1 && !nextItem.isDoubleSided + && !nextItem.isColour; + if (isNotColouredSingleSidedAndOnePage) { + printerItemsCollection.add(nextItem); + } + } + } + } +} +``` + +Each method takes a collecting parameter as an argument. It then adds elements, taken from a global variable, +to this collecting parameter if each element satisfies a given criteria. These methods can have whatever policy the client desires. + +In this programmatic example, three print jobs are added to the queue. Only the first two print jobs should be added to +the collecting parameter as per the policy. The elements of the `result` variable after execution are, + +| paperSize | pageCount | isDoubleSided | isColour | +|-----------|-----------|---------------|----------| +| A4 | 5 | false | false | +| A3 | 2 | false | false | + +which is what we expected. + +## Class diagram +![alt text](./etc/collecting-parameter.urm.png "Collecting Parameter") + +## Applicability +Use the Collecting Parameter design pattern when +- you want to return a collection or object that is the collaborative result of several methods +- You want to simplify a method that accumulates data as the original method is too complex + +## Tutorials +Tutorials for this method are found in: +- [Refactoring To Patterns](http://www.tarrani.net/RefactoringToPatterns.pdf) by Joshua Kerivsky +- [Smalltalk Best Practice Patterns](https://ptgmedia.pearsoncmg.com/images/9780134769042/samplepages/013476904X.pdf) by Kent Beck + +## Known uses +Joshua Kerivsky gives a real-world example in his book 'Refactoring to Patterns'. He gives an example of using the +Collecting Parameter Design Pattern to create a `toString()` method for an XML tree. Without using this design pattern, +this would require a bulky function with conditionals and concatenation that would worsen code readability. Such a method +can be broken down into smaller methods, each appending their own set of information to the collecting parameter. + +See this in [Refactoring To Patterns](http://www.tarrani.net/RefactoringToPatterns.pdf). + +## Consequences +Pros: +- Makes code more readable +- Avoids 'linkages', where numerous methods reference the same global variable +- Increases maintainability by decomposing larger functions + +Cons: +- May increase code length +- Adds 'layers' of methods + +## Related patterns +- [Compose Methods](https://www.geeksforgeeks.org/composite-design-pattern/) + +## Credits +Following books were used: +- [Refactoring To Patterns](http://www.tarrani.net/RefactoringToPatterns.pdf) by Joshua Kerivsky +- [Smalltalk Best Practice Patterns](https://ptgmedia.pearsoncmg.com/images/9780134769042/samplepages/013476904X.pdf) by Kent Beck +Sites: +- [Wiki](https://wiki.c2.com/?CollectingParameter) diff --git a/collecting-parameter/etc/collecting-parameter.urm.puml b/collecting-parameter/etc/collecting-parameter.urm.puml new file mode 100644 index 000000000000..06320fa022ee --- /dev/null +++ b/collecting-parameter/etc/collecting-parameter.urm.puml @@ -0,0 +1,39 @@ +@startuml +package com.iluwatar.collectingparameter { + class App { + ~ printerQueue : PrinterQueue {static} + + App() + + addValidA2Papers(printerItemsCollection : Queue<PrinterItem>) {static} + + addValidA3Papers(printerItemsCollection : Queue<PrinterItem>) {static} + + addValidA4Papers(printerItemsCollection : Queue<PrinterItem>) {static} + + main(args : String[]) {static} + } + ~enum PaperSizes { + + A2 {static} + + A3 {static} + + A4 {static} + + valueOf(name : String) : PaperSizes {static} + + values() : PaperSizes[] {static} + } + class PrinterItem { + ~ isColour : boolean + ~ isDoubleSided : boolean + ~ pageCount : int + ~ paperSize : PaperSizes + + PrinterItem(paperSize : PaperSizes, pageCount : int, isDoubleSided : boolean, isColour : boolean) + } + class PrinterQueue { + ~ currentInstance : PrinterQueue {static} + - printerItemQueue : Queue<PrinterItem> + - PrinterQueue() + + addPrinterItem(printerItem : PrinterItem) + + emptyQueue() + + getInstance() : PrinterQueue {static} + + getPrinterQueue() : Queue<PrinterItem> + } +} +PrinterQueue --> "-currentInstance" PrinterQueue +PrinterQueue --> "-printerItemQueue" PrinterItem +App --> "-printerQueue" PrinterQueue +PrinterItem --> "-paperSize" PaperSizes +@enduml \ No newline at end of file diff --git a/collecting-parameter/pom.xml b/collecting-parameter/pom.xml new file mode 100644 index 000000000000..8f7fdc2b52db --- /dev/null +++ b/collecting-parameter/pom.xml @@ -0,0 +1,67 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + + This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + + The MIT License + Copyright © 2014-2022 Ilkka Seppälä + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + +--> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <parent> + <artifactId>java-design-patterns</artifactId> + <groupId>com.iluwatar</groupId> + <version>1.26.0-SNAPSHOT</version> + </parent> + <modelVersion>4.0.0</modelVersion> + <artifactId>collecting-parameter</artifactId> + <dependencies> + <dependency> + <groupId>org.junit.jupiter</groupId> + <artifactId>junit-jupiter-engine</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <scope>test</scope> + </dependency> + </dependencies> + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-assembly-plugin</artifactId> + <executions> + <execution> + <configuration> + <archive> + <manifest> + <mainClass>com.iluwatar.collectingparameter.App</mainClass> + </manifest> + </archive> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> +</project> diff --git a/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/App.java b/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/App.java new file mode 100644 index 000000000000..93ead620da95 --- /dev/null +++ b/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/App.java @@ -0,0 +1,138 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.collectingparameter; + +import java.util.LinkedList; +import java.util.Queue; + +/** + * The Collecting Parameter Design Pattern aims to return a result that is the collaborative result of several + * methods. This design pattern uses a 'collecting parameter' that is passed to several functions, accumulating results + * as it travels from method-to-method. This is different to the Composed Method design pattern, where a single + * collection is modified via several methods. + * + * <p>This example is inspired by Kent Beck's example in his book, 'Smalltalk Best Practice Patterns'. The context for this + * situation is that there is a single printer queue {@link PrinterQueue} that holds numerous print jobs + * {@link PrinterItem} that must be distributed to various print centers. + * Each print center has its own requirements and printing limitations. In this example, the following requirements are: + * If an A4 document is coloured, it must also be single-sided. All other non-coloured A4 documents are accepted. + * All A3 documents must be non-coloured and single sided. All A2 documents must be a single page, single sided, and + * non-coloured. + * + * <p>A collecting parameter (the result variable) is used to filter the global printer queue so that it meets the + * requirements for this centre, + **/ + +public class App { + static PrinterQueue printerQueue = PrinterQueue.getInstance(); + + /** + * Program entry point. + * + * @param args command line args + */ + public static void main(String[] args) { + /* + Initialising the printer queue with jobs + */ + printerQueue.addPrinterItem(new PrinterItem(PaperSizes.A4, 5, false, false)); + printerQueue.addPrinterItem(new PrinterItem(PaperSizes.A3, 2, false, false)); + printerQueue.addPrinterItem(new PrinterItem(PaperSizes.A2, 5, false, false)); + + /* + This variable is the collecting parameter, and will store the policy abiding print jobs. + */ + var result = new LinkedList<PrinterItem>(); + + /* + Adding A4, A3, and A2 papers that obey the policy + */ + addValidA4Papers(result); + addValidA3Papers(result); + addValidA2Papers(result); + } + + /** + * Adds A4 document jobs to the collecting parameter according to some policy that can be whatever the client + * (the print center) wants. + * + * @param printerItemsCollection the collecting parameter + */ + public static void addValidA4Papers(Queue<PrinterItem> printerItemsCollection) { + /* + Iterate through the printer queue, and add A4 papers according to the correct policy to the collecting parameter, + which is 'printerItemsCollection' in this case. + */ + for (PrinterItem nextItem : printerQueue.getPrinterQueue()) { + if (nextItem.paperSize.equals(PaperSizes.A4)) { + var isColouredAndSingleSided = nextItem.isColour && !nextItem.isDoubleSided; + if (isColouredAndSingleSided || !nextItem.isColour) { + printerItemsCollection.add(nextItem); + } + } + } + } + + /** + * Adds A3 document jobs to the collecting parameter according to some policy that can be whatever the client + * (the print center) wants. The code is similar to the 'addA4Papers' method. The code can be changed to accommodate + * the wants of the client. + * + * @param printerItemsCollection the collecting parameter + */ + public static void addValidA3Papers(Queue<PrinterItem> printerItemsCollection) { + for (PrinterItem nextItem : printerQueue.getPrinterQueue()) { + if (nextItem.paperSize.equals(PaperSizes.A3)) { + + // Encoding the policy into a Boolean: the A3 paper cannot be coloured and double-sided at the same time + var isNotColouredAndSingleSided = !nextItem.isColour && !nextItem.isDoubleSided; + if (isNotColouredAndSingleSided) { + printerItemsCollection.add(nextItem); + } + } + } + } + + /** + * Adds A2 document jobs to the collecting parameter according to some policy that can be whatever the client + * (the print center) wants. The code is similar to the 'addA4Papers' method. The code can be changed to accommodate + * the wants of the client. + * + * @param printerItemsCollection the collecting parameter + */ + public static void addValidA2Papers(Queue<PrinterItem> printerItemsCollection) { + for (PrinterItem nextItem : printerQueue.getPrinterQueue()) { + if (nextItem.paperSize.equals(PaperSizes.A2)) { + + // Encoding the policy into a Boolean: the A2 paper must be single page, single-sided, and non-coloured. + var isNotColouredSingleSidedAndOnePage = nextItem.pageCount == 1 && !nextItem.isDoubleSided + && !nextItem.isColour; + if (isNotColouredSingleSidedAndOnePage) { + printerItemsCollection.add(nextItem); + } + } + } + } +} diff --git a/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PaperSizes.java b/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PaperSizes.java new file mode 100644 index 000000000000..352bf3cc241a --- /dev/null +++ b/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PaperSizes.java @@ -0,0 +1,7 @@ +package com.iluwatar.collectingparameter; + +enum PaperSizes { + A2, + A3, + A4 +} diff --git a/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PrinterItem.java b/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PrinterItem.java new file mode 100644 index 000000000000..629cdb62500e --- /dev/null +++ b/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PrinterItem.java @@ -0,0 +1,34 @@ +package com.iluwatar.collectingparameter; + +import java.util.Objects; + +/** + * This class represents a Print Item, that should be added to the queue. + **/ +public class PrinterItem { + PaperSizes paperSize; + int pageCount; + boolean isDoubleSided; + boolean isColour; + + /** + * The {@link PrinterItem} constructor. + **/ + public PrinterItem(PaperSizes paperSize, int pageCount, boolean isDoubleSided, boolean isColour) { + if (!Objects.isNull(paperSize)) { + this.paperSize = paperSize; + } else { + throw new IllegalArgumentException(); + } + + if (pageCount > 0) { + this.pageCount = pageCount; + } else { + throw new IllegalArgumentException(); + } + + this.isColour = isColour; + this.isDoubleSided = isDoubleSided; + + } +} diff --git a/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PrinterQueue.java b/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PrinterQueue.java new file mode 100644 index 000000000000..2408d076c7c6 --- /dev/null +++ b/collecting-parameter/src/main/java/com/iluwatar/collectingparameter/PrinterQueue.java @@ -0,0 +1,52 @@ +package com.iluwatar.collectingparameter; + +import java.util.LinkedList; +import java.util.Objects; +import java.util.Queue; + +/** + * This class represents a singleton Printer Queue. It contains a queue that can be filled up with {@link PrinterItem}. + **/ +public class PrinterQueue { + + static PrinterQueue currentInstance = null; + private final Queue<PrinterItem> printerItemQueue; + + /** + * This class is a singleton. The getInstance method will ensure that only one instance exists at a time. + */ + public static PrinterQueue getInstance() { + if (Objects.isNull(currentInstance)) { + currentInstance = new PrinterQueue(); + } + return currentInstance; + } + + /** + * Empty the printer queue. + */ + public void emptyQueue() { + currentInstance.getPrinterQueue().clear(); + } + + /** + * Private constructor prevents instantiation, unless using the getInstance() method. + */ + private PrinterQueue() { + printerItemQueue = new LinkedList<>(); + } + + public Queue<PrinterItem> getPrinterQueue() { + return currentInstance.printerItemQueue; + } + + /** + * Adds a single print job to the queue. + * + * @param printerItem The printing job to be added to the queue + */ + public void addPrinterItem(PrinterItem printerItem) { + currentInstance.getPrinterQueue().add(printerItem); + } + +} diff --git a/pom.xml b/pom.xml index 3aacbad55d4a..c14cf5dbdcb3 100644 --- a/pom.xml +++ b/pom.xml @@ -84,6 +84,7 @@ </properties> <modules> <module>abstract-factory</module> + <module>collecting-parameter</module> <module>monitor</module> <module>tls</module> <module>builder</module>
diff --git a/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/AppTest.java b/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/AppTest.java new file mode 100644 index 000000000000..57f9037778ae --- /dev/null +++ b/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/AppTest.java @@ -0,0 +1,39 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.collectingparameter; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +class AppTest { + /** + * Checks whether {@link App} executes without throwing exception + */ + @Test + void executesWithoutException() { + assertDoesNotThrow(() -> App.main(new String[]{})); + } +} diff --git a/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/CollectingParameterTest.java b/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/CollectingParameterTest.java new file mode 100644 index 000000000000..53b7a4635df1 --- /dev/null +++ b/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/CollectingParameterTest.java @@ -0,0 +1,55 @@ +package com.iluwatar.collectingparameter; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import java.util.LinkedList; +import java.util.Queue; + +class CollectingParameterTest { + + @Test + @Timeout(1000) + void testCollectingParameter() { + PrinterQueue printerQueue = PrinterQueue.getInstance(); + printerQueue.emptyQueue(); + + PrinterItem item1 = new PrinterItem(PaperSizes.A4, 1, false, true); + PrinterItem item2 = new PrinterItem(PaperSizes.A4, 10, true, false); + PrinterItem item3 = new PrinterItem(PaperSizes.A4, 4, true, true); + PrinterItem item4 = new PrinterItem(PaperSizes.A3, 9, false, false); + PrinterItem item5 = new PrinterItem(PaperSizes.A3, 3, true, true); + PrinterItem item6 = new PrinterItem(PaperSizes.A3, 3, false, true); + PrinterItem item7 = new PrinterItem(PaperSizes.A3, 3, true, false); + PrinterItem item8 = new PrinterItem(PaperSizes.A2, 1, false, false); + PrinterItem item9 = new PrinterItem(PaperSizes.A2, 2, false, false); + PrinterItem item10 = new PrinterItem(PaperSizes.A2, 1, true, false); + PrinterItem item11 = new PrinterItem(PaperSizes.A2, 1, false, true); + + printerQueue.addPrinterItem(item1); + printerQueue.addPrinterItem(item2); + printerQueue.addPrinterItem(item3); + printerQueue.addPrinterItem(item4); + printerQueue.addPrinterItem(item5); + printerQueue.addPrinterItem(item6); + printerQueue.addPrinterItem(item7); + printerQueue.addPrinterItem(item8); + printerQueue.addPrinterItem(item9); + printerQueue.addPrinterItem(item10); + printerQueue.addPrinterItem(item11); + + Queue<PrinterItem> result = new LinkedList<>(); + App.addValidA4Papers(result); + App.addValidA3Papers(result); + App.addValidA2Papers(result); + + Queue<PrinterItem> testResult = new LinkedList<>(); + testResult.add(item1); + testResult.add(item2); + testResult.add(item4); + testResult.add(item8); + + Assertions.assertArrayEquals(testResult.toArray(), result.toArray()); + } +} diff --git a/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/PrinterQueueTest.java b/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/PrinterQueueTest.java new file mode 100644 index 000000000000..8371732f66e0 --- /dev/null +++ b/collecting-parameter/src/test/java/com/iluwatar/collectingparameter/PrinterQueueTest.java @@ -0,0 +1,34 @@ +package com.iluwatar.collectingparameter; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import java.util.LinkedList; +import java.util.Queue; + +import static org.junit.jupiter.api.Assertions.*; + +class PrinterQueueTest { + + @Test + @Timeout(1000) + void singletonTest() { + PrinterQueue printerQueue1 = PrinterQueue.getInstance(); + PrinterQueue printerQueue2 = PrinterQueue.getInstance(); + assertSame(printerQueue1, printerQueue2); + } + + @Test() + @Timeout(1000) + void negativePageCount() throws IllegalArgumentException { + Assertions.assertThrows(IllegalArgumentException.class, () -> new PrinterItem(PaperSizes.A4, -1, true, true)); + } + + @Test() + @Timeout(1000) + void nullPageSize() throws IllegalArgumentException { + Assertions.assertThrows(IllegalArgumentException.class, () -> new PrinterItem(null, 1, true, true)); + } + +} \ No newline at end of file
train
val
2022-10-17T19:34:33
"2020-07-07T15:42:55Z"
iluwatar
train
iluwatar/java-design-patterns/1275_2150
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1275
iluwatar/java-design-patterns/2150
[ "timestamp(timedelta=382.0, similarity=0.9292875799799427)", "keyword_pr_to_issue" ]
953f9a4e0c0acf12342937bb96fe724393189875
b103e44ecd61c24f9eb0550fe01d6ca2419b6abd
[ "Hi iluwatar, I'd like to volunteer to take a crack at this and try to fix in November/December if you're okay with that.", "I'm happy to hear you're interested @komminen. You're welcome to take a shot!", "Can I take this?", "Ok, you're assigned @JurenXu ", "> Ok, you're assigned @JurenXu\r\n\r\nThank you! I will start working on this\r\n", "> Ok, you're assigned @JurenXu\r\n\r\nHi, Iluwatar.\r\nI got a question, do I have to use the h2 database, or can I use MySQL instead?", "@JurenXu I would use h2 by default. If you want, you can add a configuration option to use MySQL. This is because people want to run the example quickly and easily and probably most people don't want to setup the MySQL server for this." ]
[ "Please check the updated YAML frontmatter requirements in https://github.com/iluwatar/java-design-patterns/wiki/01.-How-to-contribute", "Describe the pattern and explain how this example implements it", "We need comments explaining what is going on", "Use logger", "Use logger", "> Use logger\r\n\r\nI have resolved all changes you required! Could you check it again?" ]
"2022-10-23T15:37:51Z"
[ "epic: pattern", "type: feature" ]
Serialized Entity pattern
https://www.oreilly.com/library/view/j2ee-design-patterns/0596004273/re21.html
[ "pom.xml", "servant/pom.xml" ]
[ "pom.xml", "serialized-entity/README.md", "serialized-entity/etc/serialize-entity.urm.puml", "serialized-entity/pom.xml", "serialized-entity/src/main/java/com/iluwatar/serializedentity/App.java", "serialized-entity/src/main/java/com/iluwatar/serializedentity/Country.java", "serialized-entity/src/main/java/com/iluwatar/serializedentity/CountryDao.java", "serialized-entity/src/main/java/com/iluwatar/serializedentity/CountrySchemaSql.java", "servant/pom.xml" ]
[ "serialized-entity/src/test/java/com/iluwatar/serializedentity/AppTest.java", "serialized-entity/src/test/java/com/iluwatar/serializedentity/CountryTest.java" ]
diff --git a/pom.xml b/pom.xml index 7ed97bcae754..c0ead428cba0 100644 --- a/pom.xml +++ b/pom.xml @@ -215,6 +215,7 @@ <module>composite-view</module> <module>metadata-mapping</module> <module>service-to-worker</module> + <module>serialized-entity</module> <module>identity-map</module> </modules> <repositories> diff --git a/serialized-entity/README.md b/serialized-entity/README.md new file mode 100644 index 000000000000..a0a3853f9c63 --- /dev/null +++ b/serialized-entity/README.md @@ -0,0 +1,221 @@ +--- +title: Serialized Entity Pattern +categories: Architectural +language: en +tags: + - Data access +--- + + +## Intent + +To easily persist Java objects to the database. + +## Explanation +Java serialization allow us to convert the object to a set of bytes. We can store these bytes into database as +BLOB(binary long objects) and read them at any time and reconstruct them into Java objects. + + +**Programmatic Example** + +Walking through our customers example, here's the basic `Customer` entity. + +```java +@Getter +@Setter +@EqualsAndHashCode +@ToString +@AllArgsConstructor +public class Country implements Serializable { + + private int code; + private String name; + private String continents; + private String language; + public static final long serialVersionUID = 7149851; + // Constructor -> + // getters and setters -> +} + +``` +Here is `CountrySchemaSql`, this class have method allow us to serialize `Country` object and insert it into the +database, also have a method that read serialized data from the database and deserialize it to `Country` object. + +```java +@Slf4j +public class CountrySchemaSql { + public static final String CREATE_SCHEMA_SQL = "CREATE TABLE IF NOT EXISTS WORLD (ID INT PRIMARY KEY, COUNTRY BLOB)"; + + public static final String DELETE_SCHEMA_SQL = "DROP TABLE WORLD IF EXISTS"; + + private Country country; + private DataSource dataSource; + + /** + * Public constructor. + * + * @param dataSource datasource + * @param country country + */ + public CountrySchemaSql(Country country, DataSource dataSource) { + this.country = new Country( + country.getCode(), + country.getName(), + country.getContinents(), + country.getLanguage() + ); + this.dataSource = dataSource; + } + + /** + * This method will serialize a Country object and store it to database. + * @return int type, if successfully insert a serialized object to database then return country code, else return -1. + * @throws IOException if any. + */ + public int insertCountry() throws IOException { + var sql = "INSERT INTO WORLD (ID, COUNTRY) VALUES (?, ?)"; + try (var connection = dataSource.getConnection(); + var preparedStatement = connection.prepareStatement(sql); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oss = new ObjectOutputStream(baos)) { + + oss.writeObject(country); + oss.flush(); + + preparedStatement.setInt(1, country.getCode()); + preparedStatement.setBlob(2, new ByteArrayInputStream(baos.toByteArray())); + preparedStatement.execute(); + return country.getCode(); + } catch (SQLException e) { + LOGGER.info("Exception thrown " + e.getMessage()); + } + return -1; + } + + /** + * This method will select a data item from database and deserialize it. + * @return int type, if successfully select and deserialized object from database then return country code, + * else return -1. + * @throws IOException if any. + * @throws ClassNotFoundException if any. + */ + public int selectCountry() throws IOException, ClassNotFoundException { + var sql = "SELECT ID, COUNTRY FROM WORLD WHERE ID = ?"; + try (var connection = dataSource.getConnection(); + var preparedStatement = connection.prepareStatement(sql)) { + + preparedStatement.setInt(1, country.getCode()); + + try (ResultSet rs = preparedStatement.executeQuery()) { + if (rs.next()) { + Blob countryBlob = rs.getBlob("country"); + ByteArrayInputStream baos = new ByteArrayInputStream(countryBlob.getBytes(1, (int) countryBlob.length())); + ObjectInputStream ois = new ObjectInputStream(baos); + country = (Country) ois.readObject(); + LOGGER.info("Country: " + country); + } + return rs.getInt("id"); + } + } catch (SQLException e) { + LOGGER.info("Exception thrown " + e.getMessage()); + } + return -1; + } + +} +``` + +This `App.java` will first delete a World table from the h2 database(if there is one) and create a new table called +`WORLD` to ensure we have a table we want. +It will then create two `Country` objects called `China` and `UnitedArabEmirates`, then create two `CountrySchemaSql` +objects and use objects `China` and `UnitedArabEmirates` as arguments. +Finally, call `SerializedChina.insertCountry()` and `serializedUnitedArabEmirates.insertCountry()` to serialize and +store them to database, and call `SerializedChina.selectCountry()` and `serializedUnitedArabEmirates.selectCountry()` +methods to read and deserialize data items to `Country` objects. + +```java +@Slf4j +public class App { + private static final String DB_URL = "jdbc:h2:~/test"; + + private App() { + + } + + /** + * Program entry point. + * @param args command line args. + * @throws IOException if any + * @throws ClassNotFoundException if any + */ + public static void main(String[] args) throws IOException, ClassNotFoundException { + final var dataSource = createDataSource(); + + deleteSchema(dataSource); + createSchema(dataSource); + + final var China = new Country( + 86, + "China", + "Asia", + "Chinese" + ); + + final var UnitedArabEmirates = new Country( + 971, + "United Arab Emirates", + "Asia", + "Arabic" + ); + + final var serializedChina = new CountrySchemaSql(China, dataSource); + final var serializedUnitedArabEmirates = new CountrySchemaSql(UnitedArabEmirates, dataSource); + serializedChina.insertCountry(); + serializedUnitedArabEmirates.insertCountry(); + + serializedChina.selectCountry(); + serializedUnitedArabEmirates.selectCountry(); + } + + private static void deleteSchema(DataSource dataSource) { + try (var connection = dataSource.getConnection(); + var statement = connection.createStatement()) { + statement.execute(CountrySchemaSql.DELETE_SCHEMA_SQL); + } catch (SQLException e) { + LOGGER.info("Exception thrown " + e.getMessage()); + } + } + + private static void createSchema(DataSource dataSource) { + try (var connection = dataSource.getConnection(); + var statement = connection.createStatement()) { + statement.execute(CountrySchemaSql.CREATE_SCHEMA_SQL); + } catch (SQLException e) { + LOGGER.info("Exception thrown " + e.getMessage()); + } + } + + private static DataSource createDataSource() { + var dataSource = new JdbcDataSource(); + dataSource.setURL(DB_URL); + return dataSource; + } +} +``` + +## Class diagram +![alt_text](./etc/class_diagram.urm.png "Serialized Entity") + +## Applicability + +Use the Serialized Entity pattern when + +* You want to easily persist Java objects to the database. + +## Related patterns +[Data Access Object](https://github.com/iluwatar/java-design-patterns/tree/master/dao) + +## Credits + +* [J2EE Design Patterns by William Crawford, Jonathan Kaplan](https://www.oreilly.com/library/view/j2ee-design-patterns/0596004273/re21.html) +* [komminen](https://github.com/komminen/java-design-patterns) (His attempts of serialized-entity inspired me and learned a lot from his code) diff --git a/serialized-entity/etc/serialize-entity.urm.puml b/serialized-entity/etc/serialize-entity.urm.puml new file mode 100644 index 000000000000..7bf89dbb98af --- /dev/null +++ b/serialized-entity/etc/serialize-entity.urm.puml @@ -0,0 +1,56 @@ +@startuml +package com.iluwatar.serializedentity { + class App { + - DB_URL : String {static} + - LOGGER : Logger {static} + + App() + - createDataSource() : DataSource {static} + - createSchema(dataSource : DataSource) {static} + - deleteSchema(dataSource : DataSource) {static} + + main(args : String[]) {static} + } + + class Country { + - code : int + - name : String + - continents : String + - language : String + + serialVersionUID : final Long {static} + ~Country(int, String, String, String) + + getCode() : int + + getName() : String + + getContinents() : String + + getLanguage() : String + + setCode(code : int) + + setName(name : String) + + setContinents(continents : String) + + setLanguage(language : String) + + equals(that: Object) : boolean + + hashCode() : int + + toString() : String + } + + interface CountryDao { + + insertCountry : int {abstract} + + selectCountry : int {abstract} + } + + class CountrySchemaSql { + - CREATE_SCHEMA_SQL : String {static} + - DELETE_SCHEMA_SQL : String {static} + - LOGGER : Logger {static} + - dataSource : DataSource + - country : Country + ~ CountrySchemaSql(country : Country, dataSource : DataSource) + + insertCountry() + + selectCountry() + } + diamond h2db +} + +App --> "Initialize Country objects" Country +App --> "Initialize CountrySchemaSql" CountrySchemaSql +CountrySchemaSql --> "implements" CountryDao +Country --> "Stored in database" h2db +CountrySchemaSql --> "Perform INSERT and SELECT operation after serialize and deserialize Country object" h2db +@enduml \ No newline at end of file diff --git a/serialized-entity/pom.xml b/serialized-entity/pom.xml new file mode 100644 index 000000000000..aea122f5a0ac --- /dev/null +++ b/serialized-entity/pom.xml @@ -0,0 +1,71 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + + This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + + The MIT License + Copyright © 2014-2022 Ilkka Seppälä + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + +--> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>com.iluwatar</groupId> + <artifactId>java-design-patterns</artifactId> + <version>1.26.0-SNAPSHOT</version> + </parent> + <artifactId>serialized-entity</artifactId> + <dependencies> + <dependency> + <groupId>org.junit.jupiter</groupId> + <artifactId>junit-jupiter-engine</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-core</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>com.h2database</groupId> + <artifactId>h2</artifactId> + </dependency> + </dependencies> + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-assembly-plugin</artifactId> + <executions> + <execution> + <configuration> + <archive> + <manifest> + <mainClass>com.iluwatar.serializedentity.App</mainClass> + </manifest> + </archive> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> +</project> diff --git a/serialized-entity/src/main/java/com/iluwatar/serializedentity/App.java b/serialized-entity/src/main/java/com/iluwatar/serializedentity/App.java new file mode 100644 index 000000000000..fb3b383e69f7 --- /dev/null +++ b/serialized-entity/src/main/java/com/iluwatar/serializedentity/App.java @@ -0,0 +1,128 @@ +/* + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.serializedentity; + +import java.io.IOException; +import java.sql.SQLException; +import javax.sql.DataSource; +import lombok.extern.slf4j.Slf4j; +import org.h2.jdbcx.JdbcDataSource; + + +/** + * Serialized Entity Pattern. + * + * <p> Serialized Entity Pattern allow us to easily persist Java objects to the database. It uses Serializable interface + * and DAO pattern. Serialized Entity Pattern will first use Serializable to convert a Java object into a set of bytes, + * then it will using DAO pattern to store this set of bytes as BLOB to database.</p> + * + * <p> In this example, we first initialize two Java objects (Country) "China" and "UnitedArabEmirates", then we + * initialize "serializedChina" with "China" object and "serializedUnitedArabEmirates" with "UnitedArabEmirates", + * then we use method "serializedChina.insertCountry()" and "serializedUnitedArabEmirates.insertCountry()" to serialize + * "China" and "UnitedArabEmirates" and persist them to database. + * Last, with "serializedChina.selectCountry()" and "serializedUnitedArabEmirates.selectCountry()" we could read "China" + * and "UnitedArabEmirates" from database as sets of bytes, then deserialize them back to Java object (Country). </p> + * + */ +@Slf4j +public class App { + private static final String DB_URL = "jdbc:h2:~/test"; + + private App() { + + } + + /** + * Program entry point. + * @param args command line args. + * @throws IOException if any + * @throws ClassNotFoundException if any + */ + public static void main(String[] args) throws IOException, ClassNotFoundException { + final var dataSource = createDataSource(); + + deleteSchema(dataSource); + createSchema(dataSource); + + // Initializing Country Object China + final var China = new Country( + 86, + "China", + "Asia", + "Chinese" + ); + + // Initializing Country Object UnitedArabEmirates + final var UnitedArabEmirates = new Country( + 971, + "United Arab Emirates", + "Asia", + "Arabic" + ); + + // Initializing CountrySchemaSql Object with parameter "China" and "dataSource" + final var serializedChina = new CountrySchemaSql(China, dataSource); + // Initializing CountrySchemaSql Object with parameter "UnitedArabEmirates" and "dataSource" + final var serializedUnitedArabEmirates = new CountrySchemaSql(UnitedArabEmirates, dataSource); + + /* + By using CountrySchemaSql.insertCountry() method, the private (Country) type variable within Object + CountrySchemaSql will be serialized to a set of bytes and persist to database. + For more details of CountrySchemaSql.insertCountry() method please refer to CountrySchemaSql.java file + */ + serializedChina.insertCountry(); + serializedUnitedArabEmirates.insertCountry(); + + /* + By using CountrySchemaSql.selectCountry() method, CountrySchemaSql object will read the sets of bytes from database + and deserialize it to Country object. + For more details of CountrySchemaSql.selectCountry() method please refer to CountrySchemaSql.java file + */ + serializedChina.selectCountry(); + serializedUnitedArabEmirates.selectCountry(); + } + + private static void deleteSchema(DataSource dataSource) { + try (var connection = dataSource.getConnection(); + var statement = connection.createStatement()) { + statement.execute(CountrySchemaSql.DELETE_SCHEMA_SQL); + } catch (SQLException e) { + LOGGER.info("Exception thrown " + e.getMessage()); + } + } + + private static void createSchema(DataSource dataSource) { + try (var connection = dataSource.getConnection(); + var statement = connection.createStatement()) { + statement.execute(CountrySchemaSql.CREATE_SCHEMA_SQL); + } catch (SQLException e) { + LOGGER.info("Exception thrown " + e.getMessage()); + } + } + + private static DataSource createDataSource() { + var dataSource = new JdbcDataSource(); + dataSource.setURL(DB_URL); + return dataSource; + } +} diff --git a/serialized-entity/src/main/java/com/iluwatar/serializedentity/Country.java b/serialized-entity/src/main/java/com/iluwatar/serializedentity/Country.java new file mode 100644 index 000000000000..25ebddf89857 --- /dev/null +++ b/serialized-entity/src/main/java/com/iluwatar/serializedentity/Country.java @@ -0,0 +1,47 @@ +/* + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.serializedentity; +import java.io.Serializable; +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * A Country POJO taht represents the data that will serialize and store in database. + */ +@Getter +@Setter +@EqualsAndHashCode +@ToString +@AllArgsConstructor +public class Country implements Serializable { + + private int code; + private String name; + private String continents; + private String language; + public static final long serialVersionUID = 7149851; + +} diff --git a/serialized-entity/src/main/java/com/iluwatar/serializedentity/CountryDao.java b/serialized-entity/src/main/java/com/iluwatar/serializedentity/CountryDao.java new file mode 100644 index 000000000000..f5d91544672a --- /dev/null +++ b/serialized-entity/src/main/java/com/iluwatar/serializedentity/CountryDao.java @@ -0,0 +1,45 @@ +/* + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +/** + * In an application the Data Access Object (DAO) is a part of Data access layer. It is an object + * that provides an interface to some type of persistence mechanism. By mapping application calls to + * the persistence layer, DAO provides some specific data operations without exposing details of the + * database. This isolation supports the Single responsibility principle. It separates what data + * accesses the application needs, in terms of domain-specific objects and data types (the public + * interface of the DAO), from how these needs can be satisfied with a specific DBMS, database + * schema, etc. + * + * <p>Any change in the way data is stored and retrieved will not change the client code as the + * client will be using interface and need not worry about exact source. + * + * @see InMemoryCustomerDao + * @see DbCustomerDao + */ +package com.iluwatar.serializedentity; + +import java.io.IOException; + +public interface CountryDao { + int insertCountry() throws IOException; + int selectCountry() throws IOException, ClassNotFoundException; +} diff --git a/serialized-entity/src/main/java/com/iluwatar/serializedentity/CountrySchemaSql.java b/serialized-entity/src/main/java/com/iluwatar/serializedentity/CountrySchemaSql.java new file mode 100644 index 000000000000..4887ed9ddfd9 --- /dev/null +++ b/serialized-entity/src/main/java/com/iluwatar/serializedentity/CountrySchemaSql.java @@ -0,0 +1,122 @@ +/* + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.serializedentity; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.sql.Blob; +import java.sql.ResultSet; +import java.sql.SQLException; +import javax.sql.DataSource; + +import lombok.extern.slf4j.Slf4j; + +/** + * Country Schema SQL Class. + */ +@Slf4j +public class CountrySchemaSql implements CountryDao { + public static final String CREATE_SCHEMA_SQL = "CREATE TABLE IF NOT EXISTS WORLD (ID INT PRIMARY KEY, COUNTRY BLOB)"; + + public static final String DELETE_SCHEMA_SQL = "DROP TABLE WORLD IF EXISTS"; + + private Country country; + private DataSource dataSource; + + /** + * Public constructor. + * + * @param dataSource datasource + * @param country country + */ + public CountrySchemaSql(Country country, DataSource dataSource) { + this.country = new Country( + country.getCode(), + country.getName(), + country.getContinents(), + country.getLanguage() + ); + this.dataSource = dataSource; + } + + /** + * This method will serialize a Country object and store it to database. + * @return int type, if successfully insert a serialized object to database then return country code, else return -1. + * @throws IOException if any. + */ + @Override + public int insertCountry() throws IOException { + var sql = "INSERT INTO WORLD (ID, COUNTRY) VALUES (?, ?)"; + try (var connection = dataSource.getConnection(); + var preparedStatement = connection.prepareStatement(sql); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oss = new ObjectOutputStream(baos)) { + + oss.writeObject(country); + oss.flush(); + + preparedStatement.setInt(1, country.getCode()); + preparedStatement.setBlob(2, new ByteArrayInputStream(baos.toByteArray())); + preparedStatement.execute(); + return country.getCode(); + } catch (SQLException e) { + LOGGER.info("Exception thrown " + e.getMessage()); + } + return -1; + } + + /** + * This method will select a data item from database and deserialize it. + * @return int type, if successfully select and deserialized object from database then return country code, + * else return -1. + * @throws IOException if any. + * @throws ClassNotFoundException if any. + */ + @Override + public int selectCountry() throws IOException, ClassNotFoundException { + var sql = "SELECT ID, COUNTRY FROM WORLD WHERE ID = ?"; + try (var connection = dataSource.getConnection(); + var preparedStatement = connection.prepareStatement(sql)) { + + preparedStatement.setInt(1, country.getCode()); + + try (ResultSet rs = preparedStatement.executeQuery()) { + if (rs.next()) { + Blob countryBlob = rs.getBlob("country"); + ByteArrayInputStream baos = new ByteArrayInputStream(countryBlob.getBytes(1, (int) countryBlob.length())); + ObjectInputStream ois = new ObjectInputStream(baos); + country = (Country) ois.readObject(); + LOGGER.info("Country: " + country); + } + return rs.getInt("id"); + } + } catch (SQLException e) { + LOGGER.info("Exception thrown " + e.getMessage()); + } + return -1; + } + +} diff --git a/servant/pom.xml b/servant/pom.xml index 5e0b139154e3..65650364bd6b 100644 --- a/servant/pom.xml +++ b/servant/pom.xml @@ -27,6 +27,7 @@ --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> + <groupId>servant</groupId> <parent> <groupId>com.iluwatar</groupId> <artifactId>java-design-patterns</artifactId>
diff --git a/serialized-entity/src/test/java/com/iluwatar/serializedentity/AppTest.java b/serialized-entity/src/test/java/com/iluwatar/serializedentity/AppTest.java new file mode 100644 index 000000000000..52ac9cd6e026 --- /dev/null +++ b/serialized-entity/src/test/java/com/iluwatar/serializedentity/AppTest.java @@ -0,0 +1,23 @@ +package com.iluwatar.serializedentity; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +/** + * Tests that Serialized Entity example runs without errors. + */ +class AppTest { + + /** + * Issue: Add at least one assertion to this test case. + * + * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])} + * throws an exception. + */ + + @Test + void shouldExecuteSerializedEntityWithoutException() { + assertDoesNotThrow(() -> App.main(new String[]{})); + } +} diff --git a/serialized-entity/src/test/java/com/iluwatar/serializedentity/CountryTest.java b/serialized-entity/src/test/java/com/iluwatar/serializedentity/CountryTest.java new file mode 100644 index 000000000000..85d3ed87fac2 --- /dev/null +++ b/serialized-entity/src/test/java/com/iluwatar/serializedentity/CountryTest.java @@ -0,0 +1,101 @@ +/* + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.serializedentity; +import org.junit.jupiter.api.Test; + +import java.io.*; + +import static org.junit.jupiter.api.Assertions.*; + +public class CountryTest { + + @Test + void testGetMethod() { + Country China = new Country( + 86, + "China", + "Asia", + "Chinese" + ); + + assertEquals(86, China.getCode()); + assertEquals("China", China.getName()); + assertEquals("Asia", China.getContinents()); + assertEquals("Chinese", China.getLanguage()); + } + + @Test + void testSetMethod() { + Country country = new Country( + 86, + "China", + "Asia", + "Chinese" + ); + + country.setCode(971); + country.setName("UAE"); + country.setContinents("West-Asia"); + country.setLanguage("Arabic"); + + assertEquals(971, country.getCode()); + assertEquals("UAE", country.getName()); + assertEquals("West-Asia", country.getContinents()); + assertEquals("Arabic", country.getLanguage()); + } + + @Test + void testSerializable(){ + // Serializing Country + try { + Country country = new Country( + 86, + "China", + "Asia", + "Chinese"); + ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("output.txt")); + objectOutputStream.writeObject(country); + objectOutputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + + // De-serialize Country + try { + ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("output.txt")); + Country country = (Country) objectInputStream.readObject(); + objectInputStream.close(); + System.out.println(country); + + Country China = new Country( + 86, + "China", + "Asia", + "Chinese"); + + assertEquals(China, country); + } catch (Exception e) { + e.printStackTrace(); + } + } +}
train
val
2022-11-13T08:19:39
"2020-07-07T16:31:44Z"
iluwatar
train
iluwatar/java-design-patterns/1288_2155
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1288
iluwatar/java-design-patterns/2155
[ "timestamp(timedelta=1.0, similarity=0.8645788493327409)", "keyword_pr_to_issue" ]
9c4829ea56ebeaf54deda9445a0ef0a0ac3c269c
fd402fc876613282aaf855fd8fb5b92413af8522
[ "I would like to work on this issue. Could you assign me this?", "Yes, please go ahead @nakul251197 ", "This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.\n", "@nakul251197, the PR build is failing and we need your effort to investigate it" ]
[ "See the YAML frontmatter requirements in https://github.com/iluwatar/java-design-patterns/wiki/01.-How-to-contribute\r\n\r\nPlease pick the category and the tags from the existing list, if applicable. See https://github.com/iluwatar/java-design-patterns/wiki/07.-Categories-and-Tags", "Please add at least the programmatic example here", "Add maven-assembly-plugin so that the example can be executed from the command line e.g. java -jar client-session.jar", "Here, above the App, please explain the pattern briefly and describe how the code example implements it", "You need to add comments to describe what is going on. This is studying material for people.\r\n\r\nYou can use `var` for local variables.", "Use Lombok to get rid of boilerplate code. Check this throughout the code.", "I'm not sure we need the archetype. I propose we remove this file.", "Is this file needed somewhere?", "I would remove this file", "I think you are using an old version of JUnit here. Please upgrade to the latest version.", "Fixed.", "Added example.", "Added.", "Added comments.", "Fixed.", "Fixed", "Removed.", "Removed.", "Removed.", "Fixed.", "We need a bit more verbosity and description. Show the code for the used classes, describe their purposes and relations. The reader should be able to understand the design pattern by only reading this document.", "I have added additional description as requested. Please let me know if they are adequate." ]
"2022-10-24T14:04:23Z"
[ "epic: pattern", "type: feature" ]
Client Session State pattern
https://dzone.com/articles/practical-php-patterns/practical-php-patterns-client
[ "pom.xml" ]
[ "client-session/README.md", "client-session/pom.xml", "client-session/src/main/java/com/iluwatar/client/session/App.java", "client-session/src/main/java/com/iluwatar/client/session/Request.java", "client-session/src/main/java/com/iluwatar/client/session/Server.java", "client-session/src/main/java/com/iluwatar/client/session/Session.java", "pom.xml" ]
[ "client-session/src/test/java/com/iluwatar/client/session/AppTest.java", "client-session/src/test/java/com/iluwatar/client/session/ServerTest.java" ]
diff --git a/client-session/README.md b/client-session/README.md new file mode 100644 index 000000000000..82204eb3495d --- /dev/null +++ b/client-session/README.md @@ -0,0 +1,114 @@ +--- +title: Client Session Pattern +category: Architectural +language: en +tags: +- Decoupling +--- + +## Name + +[Client Session pattern](https://dzone.com/articles/practical-php-patterns/practical-php-patterns-client) + +## Intent + +- Create stateless servers that removes the problem of clustering, as users can switch between servers seamlessly. +- Makes data more resilient in case of server fail-over. +- Works well with smaller data sizes. + +## Explanation + +Real-World Example + +> You're looking to create a data management app allowing users to send requests to the server to +> modify and make changes to data stored on their devices. These requests are small in size and the +> data is individual to each user, negating the need for a large scale database implementation. +> Using the client session pattern, you are able to handle multiple concurrent requests, load +> balancing clients across different servers with ease due to servers remaining stateless. You also +> remove the need to store session IDs on the server side due to clients providing all the +> information that a server needs to perform their process. + +In Plain words + +> Instead of storing information about the current client and the information being accessed on the +> server, it is maintained client side only. Client has to send session data with each request to +> the server and has to send an updated state back to the client, which is stored on the clients +> machine. The server doesn't have to store the client information. +> ([ref](https://dzone.com/articles/practical-php-patterns/practical-php-patterns-client)) + +**Programmatic Example** + +Here is the sample code to describe the client-session pattern. In the below code we are first +creating an instance of the Server. This server instance will then be used to get Session objects +for two clients. As you can see from the code below the Session object can be used to store any +relevant information that are required by the server to process the client request. These session +objects will then be passed on with every Request to the server. The Request will have the Session +object that stores the relevant client details along with the required data for processing the +request. The session information in every request helps the server identify the client and process +the request accordingly. + +```java +public class App { + + 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); + } +} + +@Data +@AllArgsConstructor +public class Session { + + /** + * Session id. + */ + private String id; + + /** + * Client name. + */ + private String clientName; + +} + +@Data +@AllArgsConstructor +public class Request { + + private String data; + + private Session session; + +} +``` + +## Architecture Diagram + +![alt text](./etc/session_state_pattern.png "Session State Pattern") + +## Applicability + +Use the client state pattern when: + +- Processing smaller amounts of data to prevent larger requests and response sizes. +- Remove the need for servers to save client states. Doing so also removes the need to store session IDs. +- Clustering is an issue and needs to be avoided. Stateless servers allow clients to be easily distributed across servers. +- Creates resilience from data losses due to server fails. + +## Consequences + +- The server is stateless. Any compute API will not store any data. +- Struggles to deal with large amounts of data. Creates longer send and receive times due to larger amounts of session data to manage. +- Security. All data is stored on the client's machine. This means that any vulnerabilities on the clients side can expose all data being sent and received by the server. + + +## Credits + +- [Dzone - Practical PHP patterns](https://dzone.com/articles/practical-php-patterns/practical-php-patterns-client) +- [Client Session State Design Pattern - Ram N Java](https://www.youtube.com/watch?v=ycOSj9g41pc) diff --git a/client-session/pom.xml b/client-session/pom.xml new file mode 100644 index 000000000000..b7ff08637091 --- /dev/null +++ b/client-session/pom.xml @@ -0,0 +1,62 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + + This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + + The MIT License + Copyright © 2014-2022 Ilkka Seppälä + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + +--> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>com.iluwatar</groupId> + <artifactId>java-design-patterns</artifactId> + <version>1.26.0-SNAPSHOT</version> + </parent> + <artifactId>client-session</artifactId> + <dependencies> + <dependency> + <groupId>org.junit.jupiter</groupId> + <artifactId>junit-jupiter-engine</artifactId> + <scope>test</scope> + </dependency> + </dependencies> + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-assembly-plugin</artifactId> + <executions> + <execution> + <configuration> + <archive> + <manifest> + <mainClass>com.iluwatar.client.session.App</mainClass> + </manifest> + </archive> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> +</project> diff --git a/client-session/src/main/java/com/iluwatar/client/session/App.java b/client-session/src/main/java/com/iluwatar/client/session/App.java new file mode 100644 index 000000000000..282d8a7f3b28 --- /dev/null +++ b/client-session/src/main/java/com/iluwatar/client/session/App.java @@ -0,0 +1,55 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT 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); + } +} diff --git a/client-session/src/main/java/com/iluwatar/client/session/Request.java b/client-session/src/main/java/com/iluwatar/client/session/Request.java new file mode 100644 index 000000000000..008011f180f7 --- /dev/null +++ b/client-session/src/main/java/com/iluwatar/client/session/Request.java @@ -0,0 +1,42 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT 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; + +} diff --git a/client-session/src/main/java/com/iluwatar/client/session/Server.java b/client-session/src/main/java/com/iluwatar/client/session/Server.java new file mode 100644 index 000000000000..6d9dc3dbc80a --- /dev/null +++ b/client-session/src/main/java/com/iluwatar/client/session/Server.java @@ -0,0 +1,65 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT 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()); + } + +} diff --git a/client-session/src/main/java/com/iluwatar/client/session/Session.java b/client-session/src/main/java/com/iluwatar/client/session/Session.java new file mode 100644 index 000000000000..bb9f7246cb4e --- /dev/null +++ b/client-session/src/main/java/com/iluwatar/client/session/Session.java @@ -0,0 +1,48 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT 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; + +} diff --git a/pom.xml b/pom.xml index 09e4dea4fb70..90c4b29410bb 100644 --- a/pom.xml +++ b/pom.xml @@ -198,6 +198,7 @@ <module>composite-view</module> <module>metadata-mapping</module> <module>service-to-worker</module> + <module>client-session</module> <module>embedded-value</module> <module>currying</module> <module>serialized-entity</module>
diff --git a/client-session/src/test/java/com/iluwatar/client/session/AppTest.java b/client-session/src/test/java/com/iluwatar/client/session/AppTest.java new file mode 100644 index 000000000000..0e33f74f460b --- /dev/null +++ b/client-session/src/test/java/com/iluwatar/client/session/AppTest.java @@ -0,0 +1,38 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT 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[]{})); + } +} diff --git a/client-session/src/test/java/com/iluwatar/client/session/ServerTest.java b/client-session/src/test/java/com/iluwatar/client/session/ServerTest.java new file mode 100644 index 000000000000..dc09441f0a6a --- /dev/null +++ b/client-session/src/test/java/com/iluwatar/client/session/ServerTest.java @@ -0,0 +1,14 @@ +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()); + } +}
val
val
2022-12-29T10:22:22
"2020-07-07T17:18:53Z"
iluwatar
train
iluwatar/java-design-patterns/1762_2165
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1762
iluwatar/java-design-patterns/2165
[ "keyword_pr_to_issue" ]
4108f86177254b72cec4f05c3c2e0dab35e63536
13cb2e8d482d2e6505d8d68722625e5af220c40f
[ "Thank you so much for your interest @marouaneaba.\r\n\r\nPlease let us know if you are willing to work on this issue.", "I'm not entirely sure what we need to do here. Please elaborate @marouaneaba what pattern are you referring to and where exactly do you see a problem?", "> Ambiguity mapper pattern definition.\r\n> Defining the mapper model for a specific problem case (fetching data) that produces a definition is not correct.\r\n> we need an explanation on how/why to use this design template.\r\n\r\nThe explanation is indeed ambiguous.\r\n\r\nPlease provide a detailed explanation _(with line numbers if possible)_ to show us where exactly the problem lies so that we can investigate the matter and understand the issue with a clear picture in our mind. \r\n\r\nThis would also help any fellow who is looking to resolve this issue as well and make us all understand the goal that we should have in mind while handling this issue.", "Hello @ohbus @iluwatar ,\r\nIn the description, it is specified that the mapper should be used only for retrieving/mapped data from the database.\r\nOn the other hand, a mapper is a pattern which makes it possible to create an object in a single sence, is responsible for executing operations to construct the parameters of a constructor.\r\nIn another way, a mapper takes care of centralizing a set of operations that produces the arguments of a constructor to create an object.", "@marouaneaba let's start from the basics.\r\n\r\n1. Which pattern are you talking about? Please provide a direct link.\r\n2. I understood that you see a problem in the pattern's `README.md` file, is that correct? Can you point out the exact line numbers there?\r\n3. Since at the moment you seem to know the problem best and how to fix it, why not raise a pull request to fix it?\r\n", "Hello,\r\nI talk about this mapper pattern : https://github.com/iluwatar/java-design-patterns/tree/master/data-mapper.\r\nThe description used to describe this mapper pattern, it is too specific for retrieving data from the database.\r\n\r\n- Description currently used:\r\n\r\nIntent\r\nA layer of mappers that moves data between objects and a database while keeping them independent of each other and the mapper itself\r\n\r\nApplicability\r\nUse the Data Mapper in any of the following situations:\r\n -when you want to decouple data objects from DB access layer\r\n\r\n\r\n- Mapper Pattern used for: \r\n\r\nMapper is a pattern which makes it possible to create an object in a single sence, is responsible for executing operations to construct the parameters of a constructor.\r\nIn another way, a mapper takes care of centralizing a set of operations that produces the arguments of a constructor to create an object.\r\n\r\n\r\nYes I can contribute and thank you.\r\n\r\n\r\n", "> Hello,\r\n> I talk about this mapper pattern : https://github.com/iluwatar/java-design-patterns/tree/master/data-mapper.\r\n> The description used to describe this mapper pattern, it is too specific for retrieving data from the database.\r\n> \r\n> * Description currently used:\r\n> \r\n> Intent\r\n> A layer of mappers that moves data between objects and a database while keeping them independent of each other and the mapper itself\r\n> \r\n> Applicability\r\n> Use the Data Mapper in any of the following situations:\r\n> -when you want to decouple data objects from DB access layer\r\n> \r\n> * Mapper Pattern used for:\r\n> \r\n> Mapper is a pattern which makes it possible to create an object in a single sence, is responsible for executing operations to construct the parameters of a constructor.\r\n> In another way, a mapper takes care of centralizing a set of operations that produces the arguments of a constructor to create an object.\r\n> \r\n> Yes I can contribute and thank you.\r\n\r\n⭐ Sure thing! Thanks for your interest in our project 😃 \r\n\r\n✔️ Please mention a 📆 timeline 🕙 for when can we expect 🤔 a Pull Request against this issue.", "Thanks @marouaneaba for the clarification. It looks like data mapper pattern's readme is not currently fulfilling our quality criteria (see https://github.com/iluwatar/java-design-patterns/wiki/01.-How-to-contribute) and there's a lot to improve. We surely would appreciate your help here.", "@marouaneaba Are you working on this issue?", "As I can see @marouaneaba is not responding to any communications.\r\n\r\nThis issue is free to be taken again!", "If this problem still needs to be solved, I think I can help, can this issue be assigned to me?", "Ok @KyleSongxy, thanks for helping out" ]
[]
"2022-10-25T12:11:47Z"
[ "type: enhancement", "epic: documentation" ]
Ambiguity mapper pattern definition.
Ambiguity mapper pattern definition. Defining the mapper model for a specific problem case (fetching data) that produces a definition is not correct. we need an explanation on how/why to use this design template.
[ "data-mapper/README.md" ]
[ "data-mapper/README.md" ]
[]
diff --git a/data-mapper/README.md b/data-mapper/README.md index 7766ca0b625c..b36414807612 100644 --- a/data-mapper/README.md +++ b/data-mapper/README.md @@ -3,21 +3,53 @@ title: Data Mapper category: Architectural language: en tags: - - Decoupling +- Decoupling --- ## Intent A layer of mappers that moves data between objects and a database while keeping them independent of each other and the mapper itself +This layer consists of one or more mappers (or data access objects) that perform data transfer. The scope of mapper implementations varies. +A generic mapper will handle many different domain entity types, a dedicated mapper will handle one or a few. + +## Explanation + +Real-world example + +> When accessing web resources through a browser, there is generally no need to interact with the server directly; +> the browser and the proxy server will complete the data acquisition operation, and the three will remain independent. + +In plain words + +> The data mapper will help complete the bi-directional transfer of persistence layer and in-memory data. + +Wikipedia says + +> A Data Mapper is a Data Access Layer that performs bidirectional transfer of data between a +> persistent data store (often a relational database) and an in-memory data representation (the domain layer). + +Programmatic example + ## Class diagram ![alt text](./etc/data-mapper.png "Data Mapper") ## Applicability Use the Data Mapper in any of the following situations -* when you want to decouple data objects from DB access layer +* when you want to decouple data objects from DB access layer * when you want to write multiple data retrieval/persistence implementations -## Credits +## Known uses +* [SqlSession.getMapper()](https://mybatis.org/mybatis-3/java-api.html) + +## Consequences -* [Data Mapper](http://richard.jp.leguen.ca/tutoring/soen343-f2010/tutorials/implementing-data-mapper/) +> Neatly mapped persistence layer data +> Data model follows the single function principle + +## Related patterns +* [Active Record Pattern](https://en.wikipedia.org/wiki/Active_record_pattern) +* [Object–relational Mapping](https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping) + +## Credits +* [Data Mapper](http://richard.jp.leguen.ca/tutoring/soen343-f2010/tutorials/implementing-data-mapper/) \ No newline at end of file
null
val
val
2022-10-23T15:29:49
"2021-05-20T00:21:47Z"
marouaneaba
train
iluwatar/java-design-patterns/2160_2171
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2160
iluwatar/java-design-patterns/2171
[ "timestamp(timedelta=1.0, similarity=0.8968537004113961)" ]
4108f86177254b72cec4f05c3c2e0dab35e63536
e063bd14e032fd1de78f17dc473a61642c76e75e
[ "Ok @seongkyu-lim ", "Subtask of #2282 " ]
[]
"2022-10-26T04:57:29Z"
[ "info: good first issue", "type: feature", "epic: documentation" ]
I'll translate the readme file of the proxy design pattern to Korean
I'll translate the readme file of the proxy design pattern to Korean and place it under localization/ko/proxy.
[]
[ "localization/ko/proxy/README.md" ]
[]
diff --git a/localization/ko/proxy/README.md b/localization/ko/proxy/README.md new file mode 100644 index 000000000000..95eb9dca992b --- /dev/null +++ b/localization/ko/proxy/README.md @@ -0,0 +1,160 @@ +--- +title: Proxy +category: Structural +language: ko +tags: +- Gang Of Four +- Decoupling +--- + +## 또한 ~으로 알려진 + +Surrogate + +## 의도 + +다른 객체에 대한 접근을 제어할 수 있는 대리인 또는 자리 표시자(placeholder)를 제공합니다. + +## 설명 + +실제 예제 + +> 지역 마법사들이 주문을 공부하러 가는 탑을 상상해 보세요. 상아탑은 프록시를 통해서만 접근할 수 있으며, 프록시는 처음 세 명의 마법사만 들어갈 수 있도록 합니다. 여기서 프록시는 타워의 기능을 나타내며 액세스 제어를 추가합니다. + +쉽게 말하자면 + +> 프록시 패턴을 사용하여, 클래스는 다른 클래스의 기능을 나타냅니다. + +Wikipedia에 의하면 + +> 프록시는 가장 일반적인 형태로 다른 것에 대한 인터페이스로서 기능하는 클래스이다. 프록시는 클라이언트가 백그라운드에서 실제 서비스 객체에 액세스하기 위해 호출하는 래퍼 또는 에이전트 객체입니다. 프록시의 사용은 단순히 실제 객체로 포워딩하거나 추가적인 논리를 제공할 수 있습니다. 프록시에서 실제 객체에 대한 작업이 리소스 집약적일 때, 캐싱하거나 실제 객체에 대한 작업이 호출되기 전에 사전 조건을 확인하는 등의 추가 기능이 제공될 수 있습니다. + +**코드 예제** + +위로부터 마법사 타워를 예로 들어보겠습니다. 먼저 `WiszrdTower` 인터페이스와 이를 구현한 +`IvoryTower` 클래스가 있습니다. + +```java +public interface WizardTower { + + void enter(Wizard wizard); +} + +@Slf4j +public class IvoryTower implements WizardTower { + + public void enter(Wizard wizard) { + LOGGER.info("{} enters the tower.", wizard); + } + +} +``` + +그리고 간단한 `Wizard` 클래스입니다. + + +```java +public class Wizard { + + private final String name; + + public Wizard(String name) { + this.name = name; + } + + @Override + public String toString() { + return name; + } +} +``` + +그리고 `WizardTower`에 대한 엑세스 통제를 추가하기 위해 `WizardTowerProxy`를 가집니다. + +```java +@Slf4j +public class WizardTowerProxy implements WizardTower { + + private static final int NUM_WIZARDS_ALLOWED = 3; + + private int numWizards; + + private final WizardTower tower; + + public WizardTowerProxy(WizardTower tower) { + this.tower = tower; + } + + @Override + public void enter(Wizard wizard) { + if (numWizards < NUM_WIZARDS_ALLOWED) { + tower.enter(wizard); + numWizards++; + } else { + LOGGER.info("{} is not allowed to enter!", wizard); + } + } +} +``` + +그리고 다음은 타워에 입장하는 시나리오입니다. + +```java +var proxy = new WizardTowerProxy(new IvoryTower()); +proxy.enter(new Wizard("Red wizard")); +proxy.enter(new Wizard("White wizard")); +proxy.enter(new Wizard("Black wizard")); +proxy.enter(new Wizard("Green wizard")); +proxy.enter(new Wizard("Brown wizard")); +``` + +프로그램 실행 결과: + +``` +Red wizard enters the tower. +White wizard enters the tower. +Black wizard enters the tower. +Green wizard is not allowed to enter! +Brown wizard is not allowed to enter! +``` + +## 클래스 다이어그램 + +![alt text](../../../proxy/etc/proxy.urm.png "Proxy pattern class diagram") + +## 적용 가능성 + +프록시는 단순한 포인터보다 더 다재다능하거나 정교한 오브젝트 참조가 필요할 때마다 적용할 수 있습니다. 다음은 프록시 패턴을 적용할 수 있는 몇 가지 일반적인 상황입니다. + + +* 원격 프록시는 다른 주소 공간에 있는 체의 로컬 대리자를 제공합니다. +* 가상 프록시는 요청 시 값비싼 개체를 생성합니다. +* 보호 프록시는 원래 객체에 대한 액세스를 제어합니다. 보호 프록시는 객체가 서로 다른 액세스 권한을 가져야 할 때 유용합니다. + +일반적으로 프록시 패턴은 다음과 같이 사용됩니다. + +* 다른 객체에 대한 액세스 제어 +* 지연 초기화 +* 로깅(logging) 구현 +* 네트워크 연결 촉진 +* 객체에 대한 참조 카운팅 + +## 튜토리얼 + +* [Controlling Access With Proxy Pattern](http://java-design-patterns.com/blog/controlling-access-with-proxy-pattern/) + +## 실제 사례 + +* [java.lang.reflect.Proxy](http://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Proxy.html) +* [Apache Commons Proxy](https://commons.apache.org/proper/commons-proxy/) +* Mocking frameworks [Mockito](https://site.mockito.org/), + [Powermock](https://powermock.github.io/), [EasyMock](https://easymock.org/) + +## 관련 패턴 + +* [Ambassador](https://java-design-patterns.com/patterns/ambassador/) + +## 크레딧 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b)
null
train
val
2022-10-23T15:29:49
"2022-10-25T03:02:48Z"
seongkyu-lim
train
iluwatar/java-design-patterns/2161_2172
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2161
iluwatar/java-design-patterns/2172
[ "timestamp(timedelta=0.0, similarity=0.8990843545354169)" ]
4108f86177254b72cec4f05c3c2e0dab35e63536
d9b4965eb94cf96693a765ebce7450a76f967836
[ "Ok @seongkyu-lim ", "Subtask of #2282 " ]
[]
"2022-10-26T04:58:12Z"
[ "info: good first issue", "type: feature", "epic: documentation" ]
I'll translate the readme file of the builder design pattern to Korean
I'll translate the readme file of the builder design pattern to Korean and place it under localization/ko/builder.
[]
[ "localization/ko/builder/README.md" ]
[]
diff --git a/localization/ko/builder/README.md b/localization/ko/builder/README.md new file mode 100644 index 000000000000..25a93f5fe0fb --- /dev/null +++ b/localization/ko/builder/README.md @@ -0,0 +1,144 @@ +--- +title: Builder +category: Creational +language: ko +tags: +- Gang of Four +--- + +## 의도 + +동일한 구성 프로세스가 다른 표현을 생성할 수 있도록 복잡한 객체의 구성을 해당 표현과 분리합니다. + +## 설명 + +실제 예제 + +> 롤플레잉 게임의 캐릭터 생성기를 상상해 보세요. 가장 쉬운 옵션은 컴퓨터가 사용자를 위해 문자를 만들도록 하는 것입니다. 직업, 성별, 머리색 등 캐릭터 세부 정보를 수동으로 선택하려면 캐릭터 생성은 모든 선택이 준비되었을 때 완료되는 단계별 프로세스가 됩니다. + +쉽게 말하자면 + +> 생성자의 오염을 방지하면서 객체의 다른 맛들을 만들 수 있습니다. 여러 가지 맛의 객체가 있을 때 유용합니다. 또는 개체를 만드는 데 많은 단계가 수반될 때 유용합니다. + +Wikipedia에 의하면 + +> 빌더 패턴은 점층적 생성자 안티-패턴(telescoping constructor anti-pattern)에 대한 해결책을 찾기 위한 목적을 가진 객체 생성 소프트웨어 디자인 패턴이다. + +그렇긴 하지만, 점층적 생성자 안티-패턴(telescoping constructor anti-pattern)이 무엇인지 조금 더 설명하겠습니다. 어느 시점에서, 우리는 모두 다음과 같은 생성자를 보았습니다. + +```java +public Hero(Profession profession, String name, HairType hairType, HairColor hairColor, Armor armor, Weapon weapon) { +} +``` + +보시다시피 생성자 매개 변수의 수는 빠르게 감당할 수 없게 되고 매개 변수의 배치를 이해하는 것이 어려워질 수 있습니다. 또한 이 매개 변수 목록은 나중에 더 많은 옵션을 추가하려는 경우 계속 증가할 수 있습니다. 이를 점층적 생성자 안티-패턴(telescoping constructor anti-pattern)이라고 합니다. + +**코드 예제** + +올바른 대안은 빌더 패턴을 사용하는 것입니다. 우선, 우리는 우리가 창조하고 싶은 영웅을 가지고 있습니다. : + + +```java +public final class Hero { + private final Profession profession; + private final String name; + private final HairType hairType; + private final HairColor hairColor; + private final Armor armor; + private final Weapon weapon; + + private Hero(Builder builder) { + this.profession = builder.profession; + this.name = builder.name; + this.hairColor = builder.hairColor; + this.hairType = builder.hairType; + this.weapon = builder.weapon; + this.armor = builder.armor; + } +} +``` + +그리고 우리는 빌더를 가지고 있습니다. : + +```java + public static class Builder { + private final Profession profession; + private final String name; + private HairType hairType; + private HairColor hairColor; + private Armor armor; + private Weapon weapon; + + public Builder(Profession profession, String name) { + if (profession == null || name == null) { + throw new IllegalArgumentException("profession and name can not be null"); + } + this.profession = profession; + this.name = name; + } + + public Builder withHairType(HairType hairType) { + this.hairType = hairType; + return this; + } + + public Builder withHairColor(HairColor hairColor) { + this.hairColor = hairColor; + return this; + } + + public Builder withArmor(Armor armor) { + this.armor = armor; + return this; + } + + public Builder withWeapon(Weapon weapon) { + this.weapon = weapon; + return this; + } + + public Hero build() { + return new Hero(this); + } + } +``` + +그런 다음, 다음과 같이 사용할 수 있습니다. + + +```java +var mage = new Hero.Builder(Profession.MAGE, "Riobard").withHairColor(HairColor.BLACK).withWeapon(Weapon.DAGGER).build(); +``` + +## 클래스 다이어그램 + +![alt text](../../../builder/etc/builder.urm.png "Builder class diagram") + +## 적용 가능성 + +다음과 같은 경우 빌더 패턴을 사용합니다. + +* 복잡한 객체를 만드는 알고리즘은 객체를 구성하는 부품과 이들이 조립되는 방법에 독립적이어야 한다. +* 구축 프로세스는 구성된 객체에 대해 서로 다른 표현을 허용해야 합니다. + +## 튜토리얼 + +* [Refactoring Guru](https://refactoring.guru/design-patterns/builder) +* [Oracle Blog](https://blogs.oracle.com/javamagazine/post/exploring-joshua-blochs-builder-design-pattern-in-java) +* [Journal Dev](https://www.journaldev.com/1425/builder-design-pattern-in-java) + +## 실제 사례 + +* [java.lang.StringBuilder](http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html) +* [java.nio.ByteBuffer](http://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html#put-byte-) as well as similar buffers such as FloatBuffer, IntBuffer and so on. +* [java.lang.StringBuffer](http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html#append-boolean-) +* All implementations of [java.lang.Appendable](http://docs.oracle.com/javase/8/docs/api/java/lang/Appendable.html) +* [Apache Camel builders](https://github.com/apache/camel/tree/0e195428ee04531be27a0b659005e3aa8d159d23/camel-core/src/main/java/org/apache/camel/builder) +* [Apache Commons Option.Builder](https://commons.apache.org/proper/commons-cli/apidocs/org/apache/commons/cli/Option.Builder.html) + +## 크레딧 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Effective Java](https://www.amazon.com/gp/product/0134685997/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0134685997&linkCode=as2&tag=javadesignpat-20&linkId=4e349f4b3ff8c50123f8147c828e53eb) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7)
null
train
val
2022-10-23T15:29:49
"2022-10-25T03:04:07Z"
seongkyu-lim
train
iluwatar/java-design-patterns/2162_2173
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2162
iluwatar/java-design-patterns/2173
[ "timestamp(timedelta=1.0, similarity=0.9050173816098842)" ]
4108f86177254b72cec4f05c3c2e0dab35e63536
cfeee239570226f50b857770676686bc65b495df
[ "Thanks for contributing back to the community @seongkyu-lim 😄 Looking forward to the next pull request!", "Subtask of #2282 " ]
[]
"2022-10-26T04:59:52Z"
[ "info: good first issue", "type: feature", "epic: documentation" ]
I'll translate the readme file of the iterator design pattern to Korean
I'll translate the readme file of the iterator design pattern to Korean and place it under localization/ko/iterator. --- Contributing to the repo is almost my first contribution. And I realized that contributing to translation helped me a lot in my own learning. Thank you for creating this opportunity! @iluwatar
[]
[ "localization/ko/iterator/README.md" ]
[]
diff --git a/localization/ko/iterator/README.md b/localization/ko/iterator/README.md new file mode 100644 index 000000000000..54f2e564032e --- /dev/null +++ b/localization/ko/iterator/README.md @@ -0,0 +1,150 @@ +--- +title: Iterator +categories: Behavioral +language: ko +tags: +- Gang of Four +--- + +## 또한 ~으로 알려진 + +커서(Cursor) 패턴 + +## 의도 +기반이되는 표현을 노출하지 않고 Aggregate 객체의 요소에 순차적으로 접근할 수 있는 방법을 제공합니다. + +## 설명 + +실제 예제 + +> 보물상자에는 마법의 아이템이 들어 있습니다. 반지, 물약, 무기와 같은 다양한 종류의 물건들이 있습니다. 보물상자가 제공하는 반복기(iterator)를 사용하여 아이템은 유형별로 검색될 수 있을 것입니다. + +쉽게 말하자면 + +> 컨테이너는 요소에 대한 접근을 제공하기 위해 표현에 구애받지 않는 반복기(iterator) 인터페이스를 제공할 수 있습니다. + +Wikipedia에 의하면 + +> 반복자 패턴(iterator pattern)은 객체 지향 프로그래밍에서 반복자를 사용하여 컨테이너를 가로지르며 컨테이너의 요소들에 접근하는 디자인 패턴입니다. + +**코드 예제** + +예제의 메인 클래스는 아이템들을 담고있는 `보물상자(TreasureChest)` 입니다. + +```java +public class TreasureChest { + + private final List<Item> items; + + public TreasureChest() { + items = List.of( + new Item(ItemType.POTION, "Potion of courage"), + new Item(ItemType.RING, "Ring of shadows"), + new Item(ItemType.POTION, "Potion of wisdom"), + new Item(ItemType.POTION, "Potion of blood"), + new Item(ItemType.WEAPON, "Sword of silver +1"), + new Item(ItemType.POTION, "Potion of rust"), + new Item(ItemType.POTION, "Potion of healing"), + new Item(ItemType.RING, "Ring of armor"), + new Item(ItemType.WEAPON, "Steel halberd"), + new Item(ItemType.WEAPON, "Dagger of poison")); + } + + public Iterator<Item> iterator(ItemType itemType) { + return new TreasureChestItemIterator(this, itemType); + } + + public List<Item> getItems() { + return new ArrayList<>(items); + } +} +``` + +다음은 `아이템(item)` 클래스입니다. : + +```java +public class Item { + + private ItemType type; + private final String name; + + public Item(ItemType type, String name) { + this.setType(type); + this.name = name; + } + + @Override + public String toString() { + return name; + } + + public ItemType getType() { + return type; + } + + public final void setType(ItemType type) { + this.type = type; + } +} + +public enum ItemType { + + ANY, WEAPON, RING, POTION + +} +``` + +`반복자(Iterator)` 인터페이스는 아주 단순합니다. + +```java +public interface Iterator<T> { + + boolean hasNext(); + + T next(); +} +``` + +다음 예제에서는 보물상자에서 발견되는 고리형 항목을 반복한다. + +```java +var itemIterator = TREASURE_CHEST.iterator(ItemType.RING); +while (itemIterator.hasNext()) { + LOGGER.info(itemIterator.next().toString()); +} +``` + +프로그램 실행결과: + +```java +Ring of shadows +Ring of armor +``` + +## 클래스 다이어그램 + +![alt text](../../../iterator/etc/iterator_1.png "Iterator") + +## 적용 가능성 + +템플릿 메소드는 사용되어야합니다. + +* 내부 표현을 드러내지않고 aggregate 객체의 컨텐츠에 접근하기 위해서 + +* aggregate 오브젝트들의 여러 번의 횡단을 지원하기 위해서 + +* 서로 다른 aggregate 구조들의 횡단을 위한 획일적인 인터페이스를 제공하기 위해서 + +## 튜토리얼 + +* [How to Use Iterator?](http://www.tutorialspoint.com/java/java_using_iterator.htm) + +## 실제 사례 + +* [java.util.Iterator](http://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html) +* [java.util.Enumeration](http://docs.oracle.com/javase/8/docs/api/java/util/Enumeration.html) + +## 크레딧 + +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b)
null
train
val
2022-10-23T15:29:49
"2022-10-25T03:07:00Z"
seongkyu-lim
train
iluwatar/java-design-patterns/1012_2175
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1012
iluwatar/java-design-patterns/2175
[ "keyword_pr_to_issue" ]
4108f86177254b72cec4f05c3c2e0dab35e63536
925996fcbde0465c2dcca5068a6a90420fcc8535
[ "Can I take this issue?", "Sure @ykayacan ", "This issue is free for taking again.", "I would like to take this issue.", "Through out checking the files causing issues on SonarCloud, I've encountered test cases that are not properly named to the functionality that they are to be tested against. \r\n\r\nExample`\r\n\r\nIn-correct naming convention of a test method.\r\n> ` @Test\r\n> void test() throws Exception {\r\n> App.main(new String[]{});\r\n> }`\r\n\r\nCorrect naming convention of a test method.\r\n\r\n> `@Test\r\n> public void shouldExecuteAppWithoutException() {\r\n> assertDoesNotThrow(() -> App.main(null));\r\n> }`\r\n\r\nA test method should describe what its testing directly in the naming, I will rename the test cases that I find throughout the refactoring process to match proper convention rules, if the test case is understandable as to what it's testing, but I would encourage that these test cases be looked at and properly named for other contributors making changes to certain files that the test cases test against, otherwise it causes a lot of confusion as to whether said contributor is testing the right thing.", "Ok @ToxicDreamz, assigned to you. I agree with your comment regarding test naming.", "I've already finished with the issue. \r\n\r\nRequest to run another SonarCloud report after merging, to see what else remains, and whether or not they can be modified so issues do not come up again.", "13 blockers and 24 criticals remaining: https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL", "`HotelDaoImpl.java` seems to be one of the hotspots we should fix: https://sonarcloud.io/component_measures?id=iluwatar_java-design-patterns&selected=iluwatar_java-design-patterns%3Atransaction-script%2Fsrc%2Fmain%2Fjava%2Fcom%2Filuwatar%2Ftransactionscript%2FHotelDaoImpl.java&view=list", "@iluwatar happy to be back again :)\r\nCan I help with this issue?", "I will resolve the report:\r\n\r\nhttps://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AW5RukINqcCiTG-gJi15&resolved=false&severities=CRITICAL", "Ok, assigned @anuragagarwal561994 and @daniel-augusto. Thanks guys!", "@iluwatar Can I help with this issue?", "Sure if @anuragagarwal561994 is no longer working on it?", "No @iluwatar I didn't get time to look into this, you can re-assign", "@iluwatar I will start working on it ", "No problem @anuragagarwal561994 \r\n@kanwarpreet25 you're good to go", "@iluwatar can I help with this and coordinate with @kanwarpreet25 @daniel-augusto ?", "@kanwarpreet25 has no public commits since Jul 28, 2019, [f7e22a1](https://github.com/iluwatar/java-design-patterns/commit/f7e22a1cf6f7664e8790cc5c76285adbcc6ab19d)\r\n@daniel-augusto has no public commits to this repo since Oct 11, 2020 [3a72abb](https://github.com/daniel-augusto/java-design-patterns/pull/1/commits/3a72abba25535b9f3bd90ac71c6cc77c530039d3)\r\n\r\nAre you guys working on this know? ", "Thanks for helping out @joseosuna-engineer. I'm looking forward to your pull request!", "Thank you. I'm going to begin with this.", "@iluwatar @ohbus \r\nI have added this project to my own CircleCI and SonarCloud accounts to run SonarCloud before create a pull request.\r\n\r\n**My accounts:**\r\n![image](https://user-images.githubusercontent.com/2281302/113358032-669e9100-931b-11eb-8d05-5b3dbf3c0b7b.png)\r\n\r\n\r\nI **changed two config files**, :scream: **.circleci/config.yml** and **pom.xml** (my fork, another branch) \r\nI'm sure @iluwatar @ohbus that we can find a better approach using environment vars or some characteristic of \r\nCircleCI 2.1 [Youtube](https://www.youtube.com/watch?v=etXD9sCFxIU)\r\n\r\nMy strategy is: \r\n- to use this branch **A** only in my fork.\r\n- to create another branch **B** to commit my code.\r\n- to merge **B** to **A** and run CircleCI + SonarCloud\r\n- when code is okay create a pull request from **B** (that has original config files) to master\r\n\r\n![image](https://user-images.githubusercontent.com/2281302/113358878-fbee5500-931c-11eb-8cbf-caeeca0a0d52.png)\r\n\r\n![image](https://user-images.githubusercontent.com/2281302/113358940-1c1e1400-931d-11eb-940f-a744b88f4a75.png)\r\n\r\n\r\n\r\n\r\n", "I think the general approach presented above is going to work, but as pointed out there are chances to streamline the workflow. @joseosuna-engineer feel free to create another issue where you point out the exact spots we should change.", "@iluwatar I have created issue [1697](https://github.com/iluwatar/java-design-patterns/issues/1697)", "> \r\n> \r\n> The project is using SonarCloud static code analysis. The latest results are showing that it has found several blocker and critical severity code smells (major, minor and info level we ignore). In this task those are fixed or marked as false positives. To mark false positives, SuppressWarnings annotation should be used in code as explained in the linked documentation.\r\n> \r\n> Links:\r\n> [Blocker and critical severity code smells in SonarCloud](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL&types=CODE_SMELL)\r\n> [Sonar false positives](https://docs.sonarqube.org/latest/analysis/languages/java/#JavaFAQ-HowtoremoveFalse-Positiveissues)\r\n\r\n@iluwatar I want to ask you some things:\r\n1.- This issue (1012) is not about all sonarcloud issues. is it?\r\n2.- major, minor and info issues are not included here\r\n3.- it is only about (blocker and critical) + code smell issues\r\n\r\n![image](https://user-images.githubusercontent.com/2281302/113944874-3ea7a580-97d3-11eb-8c10-097e2e03a933.png)\r\n\r\n4.- Do you want I add **@java.lang.SuppressWarnings(\"squid:some-number\")** annotation for **all** in question number 3? or Do I have to do something like [ykayacan](https://github.com/ykayacan/java-design-patterns/commit/d5ed1a1f22467d396c1f61f4ac18ded662591ccb): suppress false positives (test by example) and fix number 3 issues?\r\n", "@joseosuna-engineer \r\n\r\n1. No, it's about blocker and critical level issues only\r\n2. Yes\r\n3. Yes\r\n4. For false positives we can suppress the warnings as you suggested\r\n", "@iluwatar Thank you! ", "Can I help to fix this issue? Has anyone solved this one? https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AW3G0WaAwB6UiZzQNqwC&resolved=false&severities=BLOCKER", "@samuelpsouza Yes. Feel free to colaborate. @iluwatar I'm so sorry. I'm studying for a couple of certification test.", "> @samuelpsouza Yes. Feel free to collaborate. @iluwatar I'm so sorry. I'm studying for a couple of certification tests.\r\n\r\nPlease @joseosuna-engineer, no need for an apology here.\r\n\r\nYou can mention a timeline for when you will be able to make the contributions or let us know in [Gitter](https://gitter.im/iluwatar/java-design-patterns) about the same as well.\r\n\r\nAnd all the very best for your examinations! May you ace them ⭐ ", "> Can I help to fix this issue? Has anyone solved this one? https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AW3G0WaAwB6UiZzQNqwC&resolved=false&severities=BLOCKER\r\n\r\nThank you so much for your interest in our project @samuelpsouza through #1784", "Raised a PR for the following two Critical Code Smells: [#1831](https://github.com/iluwatar/java-design-patterns/pull/1831)\r\n\r\n1. https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AXhD5LIoXfseSECKkezl&resolved=false&severities=CRITICAL&types=CODE_SMELL\r\n2. https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AXhD5LIoXfseSECKkezm&resolved=false&severities=CRITICAL&types=CODE_SMELL\r\n\r\nFirst time contributing to open source software. Please review and provide your feedback.", "> Raised a PR for the following two Critical Code Smells: [#1831](https://github.com/iluwatar/java-design-patterns/pull/1831)\r\n> \r\n> 1. https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AXhD5LIoXfseSECKkezl&resolved=false&severities=CRITICAL&types=CODE_SMELL\r\n> 2. https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AXhD5LIoXfseSECKkezm&resolved=false&severities=CRITICAL&types=CODE_SMELL\r\n> \r\n> First time contributing to open source software. Please review and provide your feedback.\r\n\r\nPlease also review https://github.com/iluwatar/java-design-patterns/pull/1833 and https://github.com/iluwatar/java-design-patterns/pull/1832", "I would like to work on this issue and resolve some of the code smells/ critical issues in Sonar. Can I take this up? @iluwatar", "Sure @parulagg27, go ahead", "We need assistance to resolve the remaining blocker and critical level SonarCloud issues", "I have resolved 1 blocker & 5 critical Sonar issues using [this PR](https://github.com/iluwatar/java-design-patterns/pull/1899). Kindly review and merge.\r\n<img width=\"1730\" alt=\"Screenshot 2021-10-30 at 11 27 15 PM\" src=\"https://user-images.githubusercontent.com/18613127/139554128-d1b1d1f6-0d95-4663-b3bf-096aa31b8b26.png\">\r\n<img width=\"1728\" alt=\"Screenshot 2021-10-30 at 11 26 50 PM\" src=\"https://user-images.githubusercontent.com/18613127/139554131-468ada1a-d34c-4cb9-8c71-2a77a3fe1195.png\">\r\n\r\n\r\n", "- **Resolved** 1 blocker & 5 critical Sonar issues \r\n\r\n- **Old sonar report** :- [here](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER&types=CODE_SMELL)\r\n\r\n- **Code Cov**: Added an extensive test cases for Commander pattern.\r\n\r\n- **PR Quality Gate** is also [green](https://sonarcloud.io/summary/new_code?id=iluwatar_java-design-patterns&pullRequest=1899)\r\n\r\n@iluwatar @ohbus \r\nKindly review and merge [this PR](https://github.com/iluwatar/java-design-patterns/pull/1899)", "hey can i work on this issue :)", "Ok, go ahead @ShivanshCharak ", "Raised a pr for the following Critical code smell\r\nhttps://github.com/iluwatar/java-design-patterns/pull/1960\r\n\r\nplease also review\r\na minor code smell\r\nhttps://github.com/iluwatar/java-design-patterns/pull/1959#issue-1118731779", "Can I help? ", "Ok @S7sRuss, thanks for the help" ]
[]
"2022-10-26T09:58:11Z"
[ "type: bug", "info: good first issue", "type: refactoring", "epic: code quality" ]
SonarCloud reports issues
The project is using SonarCloud static code analysis. The latest results are showing that it has found several blockers and critical severity code smells (major, minor, and info level we ignore). In this task, those are fixed or marked as false positives. To mark false positives, SuppressWarnings annotation should be used in code as explained in the linked documentation. Links: [Blocker and critical severity code smells in SonarCloud](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL&types=CODE_SMELL) [Sonar false positives](https://docs.sonarqube.org/latest/analysis/languages/java/#JavaFAQ-HowtoremoveFalse-Positiveissues) *** Note: When Submitting a PR please provide a **hyperlinked** list of all the issues that you are issuing a fix for. [_See this example_](https://github.com/iluwatar/java-design-patterns/pull/1833#issue-1015516036)
[ "composite-view/src/main/java/com/iluwatar/compositeview/AppServlet.java" ]
[ "composite-view/src/main/java/com/iluwatar/compositeview/AppServlet.java" ]
[]
diff --git a/composite-view/src/main/java/com/iluwatar/compositeview/AppServlet.java b/composite-view/src/main/java/com/iluwatar/compositeview/AppServlet.java index 02aeab1b3497..7de1982a31bb 100644 --- a/composite-view/src/main/java/com/iluwatar/compositeview/AppServlet.java +++ b/composite-view/src/main/java/com/iluwatar/compositeview/AppServlet.java @@ -38,6 +38,7 @@ */ public final class AppServlet extends HttpServlet { + private static final String CONTENT_TYPE = "text/html"; private String msgPartOne = "<h1>This Server Doesn't Support"; private String msgPartTwo = "Requests</h1>\n" + "<h2>Use a GET request with boolean values for the following parameters<h2>\n" @@ -61,7 +62,7 @@ public void doGet(HttpServletRequest req, HttpServletResponse resp) @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - resp.setContentType("text/html"); + resp.setContentType(CONTENT_TYPE); try (PrintWriter out = resp.getWriter()) { out.println(msgPartOne + " Post " + msgPartTwo); } @@ -71,7 +72,7 @@ public void doPost(HttpServletRequest req, HttpServletResponse resp) @Override public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - resp.setContentType("text/html"); + resp.setContentType(CONTENT_TYPE); try (PrintWriter out = resp.getWriter()) { out.println(msgPartOne + " Delete " + msgPartTwo); } @@ -80,7 +81,7 @@ public void doDelete(HttpServletRequest req, HttpServletResponse resp) @Override public void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - resp.setContentType("text/html"); + resp.setContentType(CONTENT_TYPE); try (PrintWriter out = resp.getWriter()) { out.println(msgPartOne + " Put " + msgPartTwo); }
null
test
val
2022-10-23T15:29:49
"2019-10-15T17:54:46Z"
iluwatar
train
iluwatar/java-design-patterns/1012_2176
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1012
iluwatar/java-design-patterns/2176
[ "timestamp(timedelta=320.0, similarity=0.8876821951891944)", "keyword_pr_to_issue" ]
4108f86177254b72cec4f05c3c2e0dab35e63536
6f21b1060767e6cbc222430f6f4eb5af3fd24226
[ "Can I take this issue?", "Sure @ykayacan ", "This issue is free for taking again.", "I would like to take this issue.", "Through out checking the files causing issues on SonarCloud, I've encountered test cases that are not properly named to the functionality that they are to be tested against. \r\n\r\nExample`\r\n\r\nIn-correct naming convention of a test method.\r\n> ` @Test\r\n> void test() throws Exception {\r\n> App.main(new String[]{});\r\n> }`\r\n\r\nCorrect naming convention of a test method.\r\n\r\n> `@Test\r\n> public void shouldExecuteAppWithoutException() {\r\n> assertDoesNotThrow(() -> App.main(null));\r\n> }`\r\n\r\nA test method should describe what its testing directly in the naming, I will rename the test cases that I find throughout the refactoring process to match proper convention rules, if the test case is understandable as to what it's testing, but I would encourage that these test cases be looked at and properly named for other contributors making changes to certain files that the test cases test against, otherwise it causes a lot of confusion as to whether said contributor is testing the right thing.", "Ok @ToxicDreamz, assigned to you. I agree with your comment regarding test naming.", "I've already finished with the issue. \r\n\r\nRequest to run another SonarCloud report after merging, to see what else remains, and whether or not they can be modified so issues do not come up again.", "13 blockers and 24 criticals remaining: https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL", "`HotelDaoImpl.java` seems to be one of the hotspots we should fix: https://sonarcloud.io/component_measures?id=iluwatar_java-design-patterns&selected=iluwatar_java-design-patterns%3Atransaction-script%2Fsrc%2Fmain%2Fjava%2Fcom%2Filuwatar%2Ftransactionscript%2FHotelDaoImpl.java&view=list", "@iluwatar happy to be back again :)\r\nCan I help with this issue?", "I will resolve the report:\r\n\r\nhttps://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AW5RukINqcCiTG-gJi15&resolved=false&severities=CRITICAL", "Ok, assigned @anuragagarwal561994 and @daniel-augusto. Thanks guys!", "@iluwatar Can I help with this issue?", "Sure if @anuragagarwal561994 is no longer working on it?", "No @iluwatar I didn't get time to look into this, you can re-assign", "@iluwatar I will start working on it ", "No problem @anuragagarwal561994 \r\n@kanwarpreet25 you're good to go", "@iluwatar can I help with this and coordinate with @kanwarpreet25 @daniel-augusto ?", "@kanwarpreet25 has no public commits since Jul 28, 2019, [f7e22a1](https://github.com/iluwatar/java-design-patterns/commit/f7e22a1cf6f7664e8790cc5c76285adbcc6ab19d)\r\n@daniel-augusto has no public commits to this repo since Oct 11, 2020 [3a72abb](https://github.com/daniel-augusto/java-design-patterns/pull/1/commits/3a72abba25535b9f3bd90ac71c6cc77c530039d3)\r\n\r\nAre you guys working on this know? ", "Thanks for helping out @joseosuna-engineer. I'm looking forward to your pull request!", "Thank you. I'm going to begin with this.", "@iluwatar @ohbus \r\nI have added this project to my own CircleCI and SonarCloud accounts to run SonarCloud before create a pull request.\r\n\r\n**My accounts:**\r\n![image](https://user-images.githubusercontent.com/2281302/113358032-669e9100-931b-11eb-8d05-5b3dbf3c0b7b.png)\r\n\r\n\r\nI **changed two config files**, :scream: **.circleci/config.yml** and **pom.xml** (my fork, another branch) \r\nI'm sure @iluwatar @ohbus that we can find a better approach using environment vars or some characteristic of \r\nCircleCI 2.1 [Youtube](https://www.youtube.com/watch?v=etXD9sCFxIU)\r\n\r\nMy strategy is: \r\n- to use this branch **A** only in my fork.\r\n- to create another branch **B** to commit my code.\r\n- to merge **B** to **A** and run CircleCI + SonarCloud\r\n- when code is okay create a pull request from **B** (that has original config files) to master\r\n\r\n![image](https://user-images.githubusercontent.com/2281302/113358878-fbee5500-931c-11eb-8cbf-caeeca0a0d52.png)\r\n\r\n![image](https://user-images.githubusercontent.com/2281302/113358940-1c1e1400-931d-11eb-940f-a744b88f4a75.png)\r\n\r\n\r\n\r\n\r\n", "I think the general approach presented above is going to work, but as pointed out there are chances to streamline the workflow. @joseosuna-engineer feel free to create another issue where you point out the exact spots we should change.", "@iluwatar I have created issue [1697](https://github.com/iluwatar/java-design-patterns/issues/1697)", "> \r\n> \r\n> The project is using SonarCloud static code analysis. The latest results are showing that it has found several blocker and critical severity code smells (major, minor and info level we ignore). In this task those are fixed or marked as false positives. To mark false positives, SuppressWarnings annotation should be used in code as explained in the linked documentation.\r\n> \r\n> Links:\r\n> [Blocker and critical severity code smells in SonarCloud](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL&types=CODE_SMELL)\r\n> [Sonar false positives](https://docs.sonarqube.org/latest/analysis/languages/java/#JavaFAQ-HowtoremoveFalse-Positiveissues)\r\n\r\n@iluwatar I want to ask you some things:\r\n1.- This issue (1012) is not about all sonarcloud issues. is it?\r\n2.- major, minor and info issues are not included here\r\n3.- it is only about (blocker and critical) + code smell issues\r\n\r\n![image](https://user-images.githubusercontent.com/2281302/113944874-3ea7a580-97d3-11eb-8c10-097e2e03a933.png)\r\n\r\n4.- Do you want I add **@java.lang.SuppressWarnings(\"squid:some-number\")** annotation for **all** in question number 3? or Do I have to do something like [ykayacan](https://github.com/ykayacan/java-design-patterns/commit/d5ed1a1f22467d396c1f61f4ac18ded662591ccb): suppress false positives (test by example) and fix number 3 issues?\r\n", "@joseosuna-engineer \r\n\r\n1. No, it's about blocker and critical level issues only\r\n2. Yes\r\n3. Yes\r\n4. For false positives we can suppress the warnings as you suggested\r\n", "@iluwatar Thank you! ", "Can I help to fix this issue? Has anyone solved this one? https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AW3G0WaAwB6UiZzQNqwC&resolved=false&severities=BLOCKER", "@samuelpsouza Yes. Feel free to colaborate. @iluwatar I'm so sorry. I'm studying for a couple of certification test.", "> @samuelpsouza Yes. Feel free to collaborate. @iluwatar I'm so sorry. I'm studying for a couple of certification tests.\r\n\r\nPlease @joseosuna-engineer, no need for an apology here.\r\n\r\nYou can mention a timeline for when you will be able to make the contributions or let us know in [Gitter](https://gitter.im/iluwatar/java-design-patterns) about the same as well.\r\n\r\nAnd all the very best for your examinations! May you ace them ⭐ ", "> Can I help to fix this issue? Has anyone solved this one? https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AW3G0WaAwB6UiZzQNqwC&resolved=false&severities=BLOCKER\r\n\r\nThank you so much for your interest in our project @samuelpsouza through #1784", "Raised a PR for the following two Critical Code Smells: [#1831](https://github.com/iluwatar/java-design-patterns/pull/1831)\r\n\r\n1. https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AXhD5LIoXfseSECKkezl&resolved=false&severities=CRITICAL&types=CODE_SMELL\r\n2. https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AXhD5LIoXfseSECKkezm&resolved=false&severities=CRITICAL&types=CODE_SMELL\r\n\r\nFirst time contributing to open source software. Please review and provide your feedback.", "> Raised a PR for the following two Critical Code Smells: [#1831](https://github.com/iluwatar/java-design-patterns/pull/1831)\r\n> \r\n> 1. https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AXhD5LIoXfseSECKkezl&resolved=false&severities=CRITICAL&types=CODE_SMELL\r\n> 2. https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&open=AXhD5LIoXfseSECKkezm&resolved=false&severities=CRITICAL&types=CODE_SMELL\r\n> \r\n> First time contributing to open source software. Please review and provide your feedback.\r\n\r\nPlease also review https://github.com/iluwatar/java-design-patterns/pull/1833 and https://github.com/iluwatar/java-design-patterns/pull/1832", "I would like to work on this issue and resolve some of the code smells/ critical issues in Sonar. Can I take this up? @iluwatar", "Sure @parulagg27, go ahead", "We need assistance to resolve the remaining blocker and critical level SonarCloud issues", "I have resolved 1 blocker & 5 critical Sonar issues using [this PR](https://github.com/iluwatar/java-design-patterns/pull/1899). Kindly review and merge.\r\n<img width=\"1730\" alt=\"Screenshot 2021-10-30 at 11 27 15 PM\" src=\"https://user-images.githubusercontent.com/18613127/139554128-d1b1d1f6-0d95-4663-b3bf-096aa31b8b26.png\">\r\n<img width=\"1728\" alt=\"Screenshot 2021-10-30 at 11 26 50 PM\" src=\"https://user-images.githubusercontent.com/18613127/139554131-468ada1a-d34c-4cb9-8c71-2a77a3fe1195.png\">\r\n\r\n\r\n", "- **Resolved** 1 blocker & 5 critical Sonar issues \r\n\r\n- **Old sonar report** :- [here](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER&types=CODE_SMELL)\r\n\r\n- **Code Cov**: Added an extensive test cases for Commander pattern.\r\n\r\n- **PR Quality Gate** is also [green](https://sonarcloud.io/summary/new_code?id=iluwatar_java-design-patterns&pullRequest=1899)\r\n\r\n@iluwatar @ohbus \r\nKindly review and merge [this PR](https://github.com/iluwatar/java-design-patterns/pull/1899)", "hey can i work on this issue :)", "Ok, go ahead @ShivanshCharak ", "Raised a pr for the following Critical code smell\r\nhttps://github.com/iluwatar/java-design-patterns/pull/1960\r\n\r\nplease also review\r\na minor code smell\r\nhttps://github.com/iluwatar/java-design-patterns/pull/1959#issue-1118731779", "Can I help? ", "Ok @S7sRuss, thanks for the help" ]
[]
"2022-10-26T10:49:10Z"
[ "type: bug", "info: good first issue", "type: refactoring", "epic: code quality" ]
SonarCloud reports issues
The project is using SonarCloud static code analysis. The latest results are showing that it has found several blockers and critical severity code smells (major, minor, and info level we ignore). In this task, those are fixed or marked as false positives. To mark false positives, SuppressWarnings annotation should be used in code as explained in the linked documentation. Links: [Blocker and critical severity code smells in SonarCloud](https://sonarcloud.io/project/issues?id=iluwatar_java-design-patterns&resolved=false&severities=BLOCKER%2CCRITICAL&types=CODE_SMELL) [Sonar false positives](https://docs.sonarqube.org/latest/analysis/languages/java/#JavaFAQ-HowtoremoveFalse-Positiveissues) *** Note: When Submitting a PR please provide a **hyperlinked** list of all the issues that you are issuing a fix for. [_See this example_](https://github.com/iluwatar/java-design-patterns/pull/1833#issue-1015516036)
[ "special-case/src/main/java/com/iluwatar/specialcase/App.java" ]
[ "special-case/src/main/java/com/iluwatar/specialcase/App.java" ]
[]
diff --git a/special-case/src/main/java/com/iluwatar/specialcase/App.java b/special-case/src/main/java/com/iluwatar/specialcase/App.java index 43157d9ab395..5c6a10602543 100644 --- a/special-case/src/main/java/com/iluwatar/specialcase/App.java +++ b/special-case/src/main/java/com/iluwatar/specialcase/App.java @@ -37,6 +37,13 @@ public class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + private static final String LOGGER_STRING = "[REQUEST] User: {} buy product: {}"; + private static final String TEST_USER_1 = "ignite1771"; + private static final String TEST_USER_2 = "abc123"; + private static final String ITEM_TV = "tv"; + private static final String ITEM_CAR = "car"; + private static final String ITEM_COMPUTER = "computer"; + /** * Program entry point. */ @@ -44,28 +51,28 @@ public static void main(String[] args) { // DB seeding LOGGER.info("Db seeding: " + "1 user: {\"ignite1771\", amount = 1000.0}, " + "2 products: {\"computer\": price = 800.0, \"car\": price = 20000.0}"); - Db.getInstance().seedUser("ignite1771", 1000.0); - Db.getInstance().seedItem("computer", 800.0); - Db.getInstance().seedItem("car", 20000.0); + Db.getInstance().seedUser(TEST_USER_1, 1000.0); + Db.getInstance().seedItem(ITEM_COMPUTER, 800.0); + Db.getInstance().seedItem(ITEM_CAR, 20000.0); final var applicationServices = new ApplicationServicesImpl(); ReceiptViewModel receipt; - LOGGER.info("[REQUEST] User: " + "abc123" + " buy product: " + "tv"); - receipt = applicationServices.loggedInUserPurchase("abc123", "tv"); + LOGGER.info(LOGGER_STRING, TEST_USER_2, ITEM_TV); + receipt = applicationServices.loggedInUserPurchase(TEST_USER_2, ITEM_TV); receipt.show(); MaintenanceLock.getInstance().setLock(false); - LOGGER.info("[REQUEST] User: " + "abc123" + " buy product: " + "tv"); - receipt = applicationServices.loggedInUserPurchase("abc123", "tv"); + LOGGER.info(LOGGER_STRING, TEST_USER_2, ITEM_TV); + receipt = applicationServices.loggedInUserPurchase(TEST_USER_2, ITEM_TV); receipt.show(); - LOGGER.info("[REQUEST] User: " + "ignite1771" + " buy product: " + "tv"); - receipt = applicationServices.loggedInUserPurchase("ignite1771", "tv"); + LOGGER.info(LOGGER_STRING, TEST_USER_1, ITEM_TV); + receipt = applicationServices.loggedInUserPurchase(TEST_USER_1, ITEM_TV); receipt.show(); - LOGGER.info("[REQUEST] User: " + "ignite1771" + " buy product: " + "car"); - receipt = applicationServices.loggedInUserPurchase("ignite1771", "car"); + LOGGER.info(LOGGER_STRING, TEST_USER_1, ITEM_CAR); + receipt = applicationServices.loggedInUserPurchase(TEST_USER_1, ITEM_CAR); receipt.show(); - LOGGER.info("[REQUEST] User: " + "ignite1771" + " buy product: " + "computer"); - receipt = applicationServices.loggedInUserPurchase("ignite1771", "computer"); + LOGGER.info(LOGGER_STRING, TEST_USER_1, ITEM_COMPUTER); + receipt = applicationServices.loggedInUserPurchase(TEST_USER_1, ITEM_COMPUTER); receipt.show(); } }
null
val
val
2022-10-23T15:29:49
"2019-10-15T17:54:46Z"
iluwatar
train
iluwatar/java-design-patterns/2141_2186
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2141
iluwatar/java-design-patterns/2186
[ "keyword_issue_to_pr" ]
3dcda6f2457b27e4b0652ddd9f07e9c6b5b6d4c1
370d851ab0c9b5fb8448088c631953dbe1768699
[ "Ok @m-inh ", "Hi @iluwatar , I have opened a PR #2186 to close this issue, pls take a look when you have time, thanks", "Subtask of #2288", "This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.\n" ]
[]
"2022-10-27T16:46:14Z"
[ "info: good first issue", "status: stale", "epic: documentation" ]
Translate abstract-factory pattern to Vietnamese
I would like to translate `abstract-factory` pattern to Vietnamese and add it under `/localization/vi/` folder.
[]
[ "localization/vi/abstract-factory/README.md" ]
[]
diff --git a/localization/vi/abstract-factory/README.md b/localization/vi/abstract-factory/README.md new file mode 100644 index 000000000000..25be6d86f860 --- /dev/null +++ b/localization/vi/abstract-factory/README.md @@ -0,0 +1,230 @@ +--- +title: Abstract Factory +category: Creational +language: vi +tags: + - Gang of Four +--- + +## Còn được biết đến như + +Kit + +## Mục tiêu + +Cung cấp giao diện (interface) để khởi tạo các đối tượng liên quan +hoặc có phụ thuộc mà không cần chỉ định các lớp cụ thể của chúng. + +## Giải thích + +Nhà Máy Trừu Tượng (thuật ngữ tiếng Anh: Abstract Factory). + +Ví dụ thực tế + +> Để tạo ra một vương quốc, chúng ta cần các đối tượng có chủ đề chung. Vương quốc Elf cần một vị vua Elf, lâu đài Elf và quân đội Elf trong khi vương quốc Orc cần một vị vua Orc, lâu đài Orc và quân đội Orc. Các đối tượng trong vương quốc phụ thuộc lẫn nhau. + +Một cách đơn giản + +> Một nhà máy của nhiều nhà máy; một nhà máy nhóm các nhà máy riêng lẻ nhưng có liên quan hoặc phụ thuộc lại với nhau mà không chỉ định các lớp cụ thể của chúng. + +Wikipedia viết (tạm dịch) + +> Mẫu Nhà Máy Trừu Tượng cung cấp cách làm để đóng gói một nhóm các nhà máy riêng lẻ có chủ đề chung mà không cần chỉ định các lớp cụ thể của chúng + +**Chương trình ví dụ** + +Sử dụng ví dụ về vương quốc đã nêu ở trên. +Trước hết, chúng ta có một số giao diện (interface) và lớp (class) được hiện thực hóa cho các đối tượng trong vương quốc. + +```java +public interface Castle { + String getDescription(); +} + +public interface King { + String getDescription(); +} + +public interface Army { + String getDescription(); +} + +// Hiện thực hóa tộc Elf -> +public class ElfCastle implements Castle { + static final String DESCRIPTION = "This is the elven castle!"; + @Override + public String getDescription() { + return DESCRIPTION; + } +} +public class ElfKing implements King { + static final String DESCRIPTION = "This is the elven king!"; + @Override + public String getDescription() { + return DESCRIPTION; + } +} +public class ElfArmy implements Army { + static final String DESCRIPTION = "This is the elven Army!"; + @Override + public String getDescription() { + return DESCRIPTION; + } +} + +// Tương tự, hiện thực hóa tộc Orc -> ... + +``` + +Sau đó, chúng ta có trừu tượng hóa và hiện thực hóa cho nhà máy vương quốc. + +```java +public interface KingdomFactory { + Castle createCastle(); + King createKing(); + Army createArmy(); +} + +public class ElfKingdomFactory implements KingdomFactory { + + @Override + public Castle createCastle() { + return new ElfCastle(); + } + + @Override + public King createKing() { + return new ElfKing(); + } + + @Override + public Army createArmy() { + return new ElfArmy(); + } +} + +public class OrcKingdomFactory implements KingdomFactory { + + @Override + public Castle createCastle() { + return new OrcCastle(); + } + + @Override + public King createKing() { + return new OrcKing(); + } + + @Override + public Army createArmy() { + return new OrcArmy(); + } +} +``` + +Bây giờ, chúng ta có Nhà Máy Trừu Tượng cho phép chúng ta tạo một nhóm các đối tượng liên quan, tức là nhà máy vương quốc Elf tạo ra lâu đài, vua và quân đội của tộc Elf, v.v. + +```java +var factory = new ElfKingdomFactory(); +var castle = factory.createCastle(); +var king = factory.createKing(); +var army = factory.createArmy(); + +castle.getDescription(); +king.getDescription(); +army.getDescription(); +``` + +Đầu ra khi chạy chương trình: + +```java +This is the elven castle! +This is the elven king! +This is the elven Army! +``` + +Bây giờ, chúng ta có thể thiết kế một nhà máy cho các nhà máy vương quốc khác nhau. Trong ví dụ này, chúng tôi đã tạo `FactoryMaker`, chịu trách nhiệm trả về một thể hiện của` ElfKingdomFactory` hoặc `OrcKingdomFactory`. +Người dùng có thể sử dụng `FactoryMaker` để tạo ra nhà máy mà họ mong muốn, sau đó, `FactoryMaker` sẽ tạo ra các đối tượng cụ thể (là dẫn xuất của `Army`, `King`, `Castle`). +Trong ví dụ này, chúng tôi cũng sử dụng một enum để tham số hóa các loại nhà máy vương quốc mà khách hàng sẽ yêu cầu. + +```java +public static class FactoryMaker { + + public enum KingdomType { + ELF, ORC + } + + public static KingdomFactory makeFactory(KingdomType type) { + switch (type) { + case ELF: + return new ElfKingdomFactory(); + case ORC: + return new OrcKingdomFactory(); + default: + throw new IllegalArgumentException("KingdomType not supported."); + } + } +} + +public static void main(String[] args) { + var app = new App(); + + LOGGER.info("Elf Kingdom"); + app.createKingdom(FactoryMaker.makeFactory(KingdomType.ELF)); + LOGGER.info(app.getArmy().getDescription()); + LOGGER.info(app.getCastle().getDescription()); + LOGGER.info(app.getKing().getDescription()); + + LOGGER.info("Orc Kingdom"); + app.createKingdom(FactoryMaker.makeFactory(KingdomType.ORC)); + -- Tương tự với nhà máy Orc +} +``` + +## Sơ đồ lớp + +![alt text](../../../abstract-factory/etc/abstract-factory.urm.png "Abstract Factory class diagram") + +## Ứng dụng +Sử dụng mẫu Nhà Máy Trừu Tượng khi + +* Hệ thống nên độc lập với cách mà nó khởi tạo/kết hợp/trình bày sản phẩm của nó. +* Hệ thống nên được cấu hình với một trong các họ sản phẩm. +* Họ của các đối tượng sản phẩm được thiết kế để sử dụng cùng nhau, và bạn cần áp đặt ràng buộc này. +* Bạn muốn cung cấp một thư viện lớp các sản phẩm, và bạn chỉ muốn tiết lộ giao diện (interface), ẩn giấu hiện thực hóa của chúng. +* Thời gian tồn tại của đối tượng phụ thuộc thì ngắn hơn thời gian tồn tại của đối tượng sử dụng. +* Bạn cần một/vài giá trị trong lúc chạy để khởi tạo một/vài đối tượng phụ thuộc cụ thể. +* Bạn muốn quyết định sản phẩm nào được gọi từ một họ trong lúc chạy. +* Bạn cần tính nhất quán giữa các sản phẩm. +* Bạn không muốn sửa mã nguồn khi thêm những sản phẩm mới hoặc họ của các sản phẩm vào chương trình. + +Ví dụ về ca sử dụng + +* Lựa chọn để gọi đến hiện thực hóa phù hợp của FileSystemAcmeService hoặc DatabaseAcmeService hoặc NetworkAcmeService trong lúc thực thi. +* Kiểm thử đơn vị trở nên cực kì dễ dàng. +* Công cụ giao diện cho các hệ điều hành khác nhau. + +## Hệ quả + +* Sự tiêm phụ thuộc (dependency injection) trong Java che đậy các lớp dịch vụ phụ thuộc nên nó có thể dẫn tới lỗi trong quá trình thực thi, điều mà lẽ ra có thể bắt được trong quá trình biên dịch. +* Trong khi mẫu này sử dụng hiệu quả với các đối tượng đã được định nghĩa sẵn, thêm một/vài đối tượng mới có thể sẽ khó khăn. +* Mã nguồn trở nên phức tạp hơn do nó có thêm giao diện (interface) và lớp (class) được giới thiệu đi kèm theo mẫu. + +## Hướng dẫn + +* [Abstract Factory Pattern Tutorial](https://www.journaldev.com/1418/abstract-factory-design-pattern-in-java) + +## Thông dụng + +* [javax.xml.parsers.DocumentBuilderFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/parsers/DocumentBuilderFactory.html) +* [javax.xml.transform.TransformerFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/transform/TransformerFactory.html#newInstance--) +* [javax.xml.xpath.XPathFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/xpath/XPathFactory.html#newInstance--) + +## Mẫu liên quan + +* [Factory Method](https://java-design-patterns.com/patterns/factory-method/) +* [Factory Kit](https://java-design-patterns.com/patterns/factory-kit/) + +## Tham khảo +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b)
null
test
val
2022-10-26T19:43:25
"2022-10-22T11:23:53Z"
m-inh
train
iluwatar/java-design-patterns/2187_2188
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2187
iluwatar/java-design-patterns/2188
[ "timestamp(timedelta=2.0, similarity=0.9880140783072036)", "keyword_pr_to_issue" ]
3dcda6f2457b27e4b0652ddd9f07e9c6b5b6d4c1
3fde35ac77467c98c0ec4e89ed6638a18d95035d
[ "Ok @burno1 " ]
[]
"2022-10-27T23:55:17Z"
[ "info: good first issue", "type: refactoring", "epic: code quality" ]
Add lombok to MVC pattern
The pattern currently runs without lombok, I'm adding it so we can have the code more similar to new generation code
[ "model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java", "model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantModel.java", "model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java", "model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java" ]
[ "model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java", "model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantModel.java", "model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java", "model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java" ]
[]
diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java index 0cf9941ce4c3..00cced2407a2 100644 --- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java +++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java @@ -24,9 +24,12 @@ */ package com.iluwatar.model.view.controller; +import lombok.AllArgsConstructor; + /** * Fatigue enumeration. */ +@AllArgsConstructor public enum Fatigue { ALERT("alert"), TIRED("tired"), @@ -34,9 +37,6 @@ public enum Fatigue { private final String title; - Fatigue(String title) { - this.title = title; - } @Override public String toString() { diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantModel.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantModel.java index e6206e065626..3de47cdcba6d 100644 --- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantModel.java +++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantModel.java @@ -24,47 +24,26 @@ */ package com.iluwatar.model.view.controller; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + /** * GiantModel contains the giant data. */ +@Getter +@Setter +@Builder +@AllArgsConstructor +@NoArgsConstructor public class GiantModel { private Health health; private Fatigue fatigue; private Nourishment nourishment; - /** - * Instantiates a new GiantModel. - */ - public GiantModel(Health health, Fatigue fatigue, Nourishment nourishment) { - this.health = health; - this.fatigue = fatigue; - this.nourishment = nourishment; - } - - public Health getHealth() { - return health; - } - - public void setHealth(Health health) { - this.health = health; - } - - public Fatigue getFatigue() { - return fatigue; - } - - public void setFatigue(Fatigue fatigue) { - this.fatigue = fatigue; - } - - public Nourishment getNourishment() { - return nourishment; - } - - public void setNourishment(Nourishment nourishment) { - this.nourishment = nourishment; - } @Override public String toString() { diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java index 75b50a3486ea..0f54f5cd3825 100644 --- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java +++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java @@ -24,9 +24,12 @@ */ package com.iluwatar.model.view.controller; +import lombok.AllArgsConstructor; + /** * Health enumeration. */ +@AllArgsConstructor public enum Health { HEALTHY("healthy"), WOUNDED("wounded"), @@ -34,9 +37,6 @@ public enum Health { private final String title; - Health(String title) { - this.title = title; - } @Override public String toString() { diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java index e8ec91cf5710..f08a9c5bced3 100644 --- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java +++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java @@ -24,9 +24,12 @@ */ package com.iluwatar.model.view.controller; +import lombok.AllArgsConstructor; + /** * Nourishment enumeration. */ +@AllArgsConstructor public enum Nourishment { SATURATED("saturated"), HUNGRY("hungry"), @@ -34,9 +37,6 @@ public enum Nourishment { private final String title; - Nourishment(String title) { - this.title = title; - } @Override public String toString() {
null
train
val
2022-10-26T19:43:25
"2022-10-27T23:53:54Z"
burno1
train
iluwatar/java-design-patterns/2269_2270
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2269
iluwatar/java-design-patterns/2270
[ "keyword_pr_to_issue", "timestamp(timedelta=1.0, similarity=0.8840390487492057)" ]
e4990df5816ca6c9f016e9a1414fe5d01f033183
f8a3d93f33b5c4150af4483db937ae7c05a2a545
[]
[]
"2022-10-29T20:55:02Z"
[ "type: task" ]
Integrate stale bot
There is a handy [stale bot](https://github.com/probot/stale) that can monitor issues and pull requests and mark them as stale when nothing happens for a period of time. Let's integrate it in this issue. Acceptance criteria - Stale bot has been integrated into the repository
[]
[ ".github/stale.yml" ]
[]
diff --git a/.github/stale.yml b/.github/stale.yml new file mode 100644 index 000000000000..f756aa30a3d0 --- /dev/null +++ b/.github/stale.yml @@ -0,0 +1,59 @@ +# Configuration for probot-stale - https://github.com/probot/stale + +# Number of days of inactivity before an Issue or Pull Request becomes stale +daysUntilStale: 30 + +# Number of days of inactivity before an Issue or Pull Request with the stale label is closed. +# Set to false to disable. If disabled, issues still need to be closed manually, but will remain marked as stale. +daysUntilClose: false + +# Only issues or pull requests with all of these labels are check if stale. Defaults to `[]` (disabled) +onlyLabels: [] + +# Issues or Pull Requests with these labels will never be considered stale. Set to `[]` to disable +exemptLabels: + - "info: help wanted" + +# Set to true to ignore issues in a project (defaults to false) +exemptProjects: false + +# Set to true to ignore issues in a milestone (defaults to false) +exemptMilestones: false + +# Set to true to ignore issues with an assignee (defaults to false) +exemptAssignees: false + +# Label to use when marking as stale +staleLabel: "status: stale" + +# Comment to post when marking as stale. Set to `false` to disable +markComment: > + This issue has been automatically marked as stale because it has not had + recent activity. It will be closed if no further activity occurs. Thank you + for your contributions. + +# Comment to post when removing the stale label. +# unmarkComment: > +# Your comment here. + +# Comment to post when closing a stale Issue or Pull Request. +# closeComment: > +# Your comment here. + +# Limit the number of actions per hour, from 1-30. Default is 30 +limitPerRun: 30 + +# Limit to only `issues` or `pulls` +# only: issues + +# Optionally, specify configuration settings that are specific to just 'issues' or 'pulls': +# pulls: +# daysUntilStale: 30 +# markComment: > +# This pull request has been automatically marked as stale because it has not had +# recent activity. It will be closed if no further activity occurs. Thank you +# for your contributions. + +# issues: +# exemptLabels: +# - confirmed \ No newline at end of file
null
val
val
2022-10-29T08:31:41
"2022-10-29T20:35:32Z"
iluwatar
train
iluwatar/java-design-patterns/1842_2271
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1842
iluwatar/java-design-patterns/2271
[ "timestamp(timedelta=0.0, similarity=0.8620750919234087)", "keyword_pr_to_issue" ]
0793c50363d67851f88316e38f9b43144cec5ad7
7be2828c8ac7747e91107d71606cc82484039e92
[ "There is a concrete example about currying in Java on Baeldung's website: https://www.baeldung.com/java-currying", "hi @iluwatar , can I work on this issue for Hacktoberfest?", "Sure @januslinhc, it's now assigned to you", "Hey @iluwatar, could I work on this issue?", "All right @hkattt, you're free to proceed", "This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.\n", "@hkattt is still working on this" ]
[ "Please implement the yaml frontmatter according to https://github.com/iluwatar/java-design-patterns/wiki/01.-How-to-contribute", "Use Lombok to reduce boilerplate", "Doesn't look useful" ]
"2022-10-29T22:21:03Z"
[ "epic: pattern", "type: feature" ]
Currying
I's a functional programming design pattern. As far as I understand you call a function with less parameters than usual and it can be used to defer processing when it has many steps involved. UML example ``` @startuml 'https://plantuml.com/class-diagram interface BiFunction <ParamType1, ParamType2, ResultType>{ } interface Curried<ParamType1, ParamType2 extends Simple> { +ParamType2 apply(final ParamType1 a); } interface Simple<ParamType1, ParamType2, ResultType> extends BiFunction { +ResultType apply(final ParamType1 a, final ParamType2 b); } @enduml ``` ![image](https://user-images.githubusercontent.com/1063901/136424980-f7ab35e9-5654-419e-8f7d-6a1257e12585.png) With the curried version you can do stuff like: ``` System.out.println(curriedAdd.apply(4).apply(5)); Function1<Integer, Integer> adder5 = curriedAdd.apply(5); //some complicate and time consuming process here System.out.println(adder5.apply(4)); System.out.println(adder5.apply(6)); ```
[ "pom.xml" ]
[ "currying/README.md", "currying/etc/currying.urm.puml", "currying/pom.xml", "currying/src/main/java/com/iluwatar/currying/App.java", "currying/src/main/java/com/iluwatar/currying/Book.java", "currying/src/main/java/com/iluwatar/currying/Genre.java", "pom.xml" ]
[ "currying/src/test/java/com/iluwatar/currying/AppTest.java", "currying/src/test/java/com/iluwatar/currying/BookCurryingTest.java" ]
diff --git a/currying/README.md b/currying/README.md new file mode 100644 index 000000000000..72e0e89d46df --- /dev/null +++ b/currying/README.md @@ -0,0 +1,191 @@ +--- +title: Currying +category: Functional +language: en +tag: +- Decoupling +--- + +## Name / classification +Currying + +## Intent +Currying decomposes a function that takes multiple arguments into a sequence of functions that each take a single argument. +Curried functions are useful since they can be used to create new functions with lower arity to perform more specialised tasks +in a concise and readable manner. This is done via partial application. + +## Explanation +Real-world example +> Consider a librarian who wants to populate their library with books. The librarian wants functions which can create +> books corresponding to specific genres and authors. Currying makes this possible by writing a curried book builder +> function and utilising partial application. + +In plain words +> Decompose a function that take multiple arguments into multiple functions that take a single argument. + +Wikipedia says +> Currying is the technique of converting a function that takes multiple arguments into a sequence of functions that +> each take a single argument. Given a function $f:(X \times Y) \rightarrow Z$, currying constructs a new function +> $h:X \rightarrow (Y\rightarrow Z)$. $h$ takes an argument from $X$ and returns a function which maps $Y$ to $Z$. Hence, +> $h(x)(y) = f(x, y)$. + +Programmatic example +We have a `Book` class and `Genre` enum. +```java +public class Book { + private final Genre genre; + private final String author; + private final String title; + private final LocalDate publicationDate; + + Book(Genre genre, String author, String title, LocalDate publicationDate) { + this.genre = genre; + this.author = author; + this.title = title; + this.publicationDate = publicationDate; + } +} + +public enum Genre { + FANTASY, + HORROR, + SCI_FI; +} +``` +We could easily create a `Book` object with the following method: +```java +Book createBook(Genre genre, String author, String title, LocalDate publicationDate) { + return new Book(genre, author, title, publicationDate); +} +``` +However, what if we only wanted to create books from the `FANTASY` genre? We could pass in the `FANTASY` parameter on each method call; however, this is repetitive. We could define a new method specifically for creating `FANTASY` books; however, it is infeasible to create a new method for each book genre. The solution is to create a curried function. +```java +static Function<Genre, Function<String, Function<String, Function<LocalDate, Book>>>> book_creator + = genre + -> author + -> title + -> publicationDate + -> new Book(genre, author, title, publicationDate); +``` +Note that the order of the parameters is important. `genre` must come before `author`, `author` must come before `title` and so on. We must be considerate of this when writing curried functions to take full advantage of partial application. Using the above function, we can define a new function `fantasyBookFunc`, to generate `FANTASY` books as follows: +```java +Function<String, Function<String, Function<LocalDate, Book>>> fantasyBookFunc = Book.book_creator.apply(Genre.FANTASY); +``` +Unfortunately, the type signature of `BOOK_CREATOR` and `fantasyBookFunc` are difficult to read and understand. We can improve this by using the [builder pattern](https://java-design-patterns.com/patterns/builder/) and [functional interfaces](https://www.geeksforgeeks.org/functional-interfaces-java/#:~:text=A%20functional%20interface%20is%20an,any%20number%20of%20default%20methods). +```java +public static AddGenre builder() { + return genre + -> author + -> title + -> publicationDate + -> new Book(genre, author, title, publicationDate); +} + +public interface AddGenre { +Book.AddAuthor withGenre(Genre genre); +} + +public interface AddAuthor { +Book.AddTitle withAuthor(String author); +} + +public interface AddTitle { +Book.AddPublicationDate withTitle(String title); +} + +public interface AddPublicationDate { +Book withPublicationDate(LocalDate publicationDate); +} +``` +The semantics of the `builder` function can easily be understood. The `builder` function returns a function `AddGenre`, which adds the genre to the book. Similarity, the `AddGenre` function returns another function `AddTitle`, which adds the title to the book and so on, until the `AddPublicationDate` function returns a `Book`. +For example, we could create a `Book` as follows: +```java +Book book = Book.builder().withGenre(Genre.FANTAST) + .withAuthor("Author") + .withTitle("Title") + .withPublicationDate(LocalDate.of(2000, 7, 2)); +``` +The below example demonstrates how partial application can be used with the `builder` function to create specialised book builder functions. +```java +public static void main(String[] args) { + LOGGER.info("Librarian begins their work."); + + // Defining genre book functions + Book.AddAuthor fantasyBookFunc = Book.builder().withGenre(Genre.FANTASY); + Book.AddAuthor horrorBookFunc = Book.builder().withGenre(Genre.HORROR); + Book.AddAuthor scifiBookFunc = Book.builder().withGenre(Genre.SCI_FI); + + // Defining author book functions + Book.AddTitle kingFantasyBooksFunc = fantasyBookFunc.withAuthor("Stephen King"); + Book.AddTitle kingHorrorBooksFunc = horrorBookFunc.withAuthor("Stephen King"); + Book.AddTitle rowlingFantasyBooksFunc = fantasyBookFunc.withAuthor("J.K. Rowling"); + + // Creates books by Stephen King (horror and fantasy genres) + Book shining = kingHorrorBooksFunc.withTitle("The Shining") + .withPublicationDate(LocalDate.of(1977, 1, 28)); + Book darkTower = kingFantasyBooksFunc.withTitle("The Dark Tower: Gunslinger") + .withPublicationDate(LocalDate.of(1982, 6, 10)); + + // Creates fantasy books by J.K. Rowling + Book chamberOfSecrets = rowlingFantasyBooksFunc.withTitle("Harry Potter and the Chamber of Secrets") + .withPublicationDate(LocalDate.of(1998, 7, 2)); + + // Create sci-fi books + Book dune = scifiBookFunc.withAuthor("Frank Herbert") + .withTitle("Dune") + .withPublicationDate(LocalDate.of(1965, 8, 1)); + Book foundation = scifiBookFunc.withAuthor("Isaac Asimov") + .withTitle("Foundation") + .withPublicationDate(LocalDate.of(1942, 5, 1)); + + LOGGER.info("Stephen King Books:"); + LOGGER.info(shining.toString()); + LOGGER.info(darkTower.toString()); + + LOGGER.info("J.K. Rowling Books:"); + LOGGER.info(chamberOfSecrets.toString()); + + LOGGER.info("Sci-fi Books:"); + LOGGER.info(dune.toString()); + LOGGER.info(foundation.toString()); +} +``` +Program output: +``` +Librarian begins their work. +Stephen King Books: +Book{genre=HORROR, author='Stephen King', title='The Shining', publicationDate=1977-01-28} +Book{genre=FANTASY, author='Stephen King', title='The Dark Tower: Gunslinger', publicationDate=1982-06-10} +J.K. Rowling Books: +Book{genre=FANTASY, author='J.K. Rowling', title='Harry Potter and the Chamber of Secrets', publicationDate=1998-07-02} +Sci-fi Books: +Book{genre=SCI_FI, author='Frank Herbert', title='Dune', publicationDate=1965-08-01} +Book{genre=SCI_FI, author='Isaac Asimov', title='Foundation', publicationDate=1942-05-01} +``` + +## Class diagram +![currying-uml](./etc/currying.urm.png) + +## Applicability +A curried function which has only been passed some of its arguments is called a partial application. Partial application +allows for the creation of functions with some pre-defined data in their scope, since partial application can be used to +create specialised functions with lower arity. This abstraction can help keep code readable and concise. Therefore, currying is useful when frequently calling functions with fixed parameters. + +## Known uses +Most functional programming languages support curried functions. A popular example is [Haskell](https://www.haskell.org/), in which all functions are considered curried. + +## Consequences +Pros +* Currying allows for partial application, which can be used to create specialised functions concisely. + +Cons +* The order of the parameters in a curried function is important since we want to take advantage of partial application. It is best to input the most general parameters first and input specific parameters last. +* As shown in the programmatic example above, curried functions with several parameters have a cumbersome type signature (in Java). + +## Related patterns +* [Builder patter](https://java-design-patterns.com/patterns/builder/) + +## Credits +* [Currying in Java](https://www.baeldung.com/java-currying) +* [What Is Currying in Programming](https://towardsdatascience.com/what-is-currying-in-programming-56fd57103431#:~:text=Currying%20is%20helpful%20when%20you,concise%2C%20and%20more%20readable%20solution.) +* [Why the fudge should I use currying?](https://medium.com/dailyjs/why-the-fudge-should-i-use-currying-84e4000c8743) \ No newline at end of file diff --git a/currying/etc/currying.urm.puml b/currying/etc/currying.urm.puml new file mode 100644 index 000000000000..9b336ff90828 --- /dev/null +++ b/currying/etc/currying.urm.puml @@ -0,0 +1,39 @@ +@startuml +package com.iluwatar.currying { + class App { + + App() + + main(args : String[]) {static} + } + class Book { + ~ BOOK_CREATOR : Function<Genre, Function<String, Function<String, Function<LocalDate, Book>>>> {static} + - author : String + - genre : Genre + - publicationDate : LocalDate + - title : String + ~ Book(genre : Genre, author : String, title : String, publicationDate : LocalDate) + + builder() : AddGenre {static} + } + interface AddAuthor { + + withAuthor(String) : AddTitle {abstract} + } + interface AddGenre { + + withGenre(Genre) : AddAuthor {abstract} + } + interface AddPublicationDate { + + withPublicationDate(LocalDate) : Book {abstract} + } + interface AddTitle { + + withTitle(String) : AddPublicationDate {abstract} + } + enum Genre { + + FANTASY {static} + + HORROR {static} + + SCI_FI {static} + } +} +Book --> "-genre" Genre +AddPublicationDate ..+ Book +AddAuthor ..+ Book +AddTitle ..+ Book +AddGenre ..+ Book +@enduml \ No newline at end of file diff --git a/currying/pom.xml b/currying/pom.xml new file mode 100644 index 000000000000..5b5385c45a59 --- /dev/null +++ b/currying/pom.xml @@ -0,0 +1,66 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + + This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + + The MIT License + Copyright © 2014-2022 Ilkka Seppälä + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + +--> +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>com.iluwatar</groupId> + <artifactId>java-design-patterns</artifactId> + <version>1.26.0-SNAPSHOT</version> + </parent> + <artifactId>currying</artifactId> + <dependencies> + <dependency> + <groupId>org.junit.jupiter</groupId> + <artifactId>junit-jupiter-engine</artifactId> + <scope>test</scope> + </dependency> + </dependencies> + <build> + <plugins> + <!-- Maven assembly plugin is invoked with default setting which we have + in parent pom and specifying the class having main method --> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-assembly-plugin</artifactId> + <executions> + <execution> + <configuration> + <archive> + <manifest> + <mainClass>com.iluwatar.currying.App</mainClass> + </manifest> + </archive> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> +</project> \ No newline at end of file diff --git a/currying/src/main/java/com/iluwatar/currying/App.java b/currying/src/main/java/com/iluwatar/currying/App.java new file mode 100644 index 000000000000..d3ca262b56c4 --- /dev/null +++ b/currying/src/main/java/com/iluwatar/currying/App.java @@ -0,0 +1,86 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.currying; + +import java.time.LocalDate; +import lombok.extern.slf4j.Slf4j; + +/** +* Currying decomposes a function with multiple arguments in multiple functions that +* take a single argument. A curried function which has only been passed some of its +* arguments is called a partial application. Partial application is useful since it can +* be used to create specialised functions in a concise way. +* +* <p>In this example, a librarian uses a curried book builder function create books belonging to +* desired genres and written by specific authors. +*/ +@Slf4j +public class App { + /** + * Main entry point of the program. + */ + public static void main(String[] args) { + LOGGER.info("Librarian begins their work."); + + // Defining genre book functions + Book.AddAuthor fantasyBookFunc = Book.builder().withGenre(Genre.FANTASY); + Book.AddAuthor horrorBookFunc = Book.builder().withGenre(Genre.HORROR); + Book.AddAuthor scifiBookFunc = Book.builder().withGenre(Genre.SCIFI); + + // Defining author book functions + Book.AddTitle kingFantasyBooksFunc = fantasyBookFunc.withAuthor("Stephen King"); + Book.AddTitle kingHorrorBooksFunc = horrorBookFunc.withAuthor("Stephen King"); + Book.AddTitle rowlingFantasyBooksFunc = fantasyBookFunc.withAuthor("J.K. Rowling"); + + // Creates books by Stephen King (horror and fantasy genres) + Book shining = kingHorrorBooksFunc.withTitle("The Shining") + .withPublicationDate(LocalDate.of(1977, 1, 28)); + Book darkTower = kingFantasyBooksFunc.withTitle("The Dark Tower: Gunslinger") + .withPublicationDate(LocalDate.of(1982, 6, 10)); + + // Creates fantasy books by J.K. Rowling + Book chamberOfSecrets = rowlingFantasyBooksFunc.withTitle("Harry Potter and the Chamber of Secrets") + .withPublicationDate(LocalDate.of(1998, 7, 2)); + + // Create sci-fi books + Book dune = scifiBookFunc.withAuthor("Frank Herbert") + .withTitle("Dune") + .withPublicationDate(LocalDate.of(1965, 8, 1)); + Book foundation = scifiBookFunc.withAuthor("Isaac Asimov") + .withTitle("Foundation") + .withPublicationDate(LocalDate.of(1942, 5, 1)); + + LOGGER.info("Stephen King Books:"); + LOGGER.info(shining.toString()); + LOGGER.info(darkTower.toString()); + + LOGGER.info("J.K. Rowling Books:"); + LOGGER.info(chamberOfSecrets.toString()); + + LOGGER.info("Sci-fi Books:"); + LOGGER.info(dune.toString()); + LOGGER.info(foundation.toString()); + } +} \ No newline at end of file diff --git a/currying/src/main/java/com/iluwatar/currying/Book.java b/currying/src/main/java/com/iluwatar/currying/Book.java new file mode 100644 index 000000000000..f9b7be05138a --- /dev/null +++ b/currying/src/main/java/com/iluwatar/currying/Book.java @@ -0,0 +1,117 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.currying; + +import java.time.LocalDate; +import java.util.Objects; +import java.util.function.Function; +import lombok.AllArgsConstructor; + +/** + * Book class. + */ +@AllArgsConstructor +public class Book { + private final Genre genre; + private final String author; + private final String title; + private final LocalDate publicationDate; + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Book book = (Book) o; + return Objects.equals(author, book.author) + && Objects.equals(genre, book.genre) + && Objects.equals(title, book.title) + && Objects.equals(publicationDate, book.publicationDate); + } + + @Override + public int hashCode() { + return Objects.hash(author, genre, title, publicationDate); + } + + @Override + public String toString() { + return "Book{" + "genre=" + genre + ", author='" + author + '\'' + + ", title='" + title + '\'' + ", publicationDate=" + publicationDate + '}'; + } + + /** + * Curried book builder/creator function. + */ + static Function<Genre, Function<String, Function<String, Function<LocalDate, Book>>>> book_creator + = bookGenre + -> bookAuthor + -> bookTitle + -> bookPublicationDate + -> new Book(bookGenre, bookAuthor, bookTitle, bookPublicationDate); + + /** + * Implements the builder pattern using functional interfaces to create a more readable book + * creator function. This function is equivalent to the BOOK_CREATOR function. + */ + public static AddGenre builder() { + return genre + -> author + -> title + -> publicationDate + -> new Book(genre, author, title, publicationDate); + } + + /** + * Functional interface which adds the genre to a book. + */ + public interface AddGenre { + Book.AddAuthor withGenre(Genre genre); + } + + /** + * Functional interface which adds the author to a book. + */ + public interface AddAuthor { + Book.AddTitle withAuthor(String author); + } + + /** + * Functional interface which adds the title to a book. + */ + public interface AddTitle { + Book.AddPublicationDate withTitle(String title); + } + + /** + * Functional interface which adds the publication date to a book. + */ + public interface AddPublicationDate { + Book withPublicationDate(LocalDate publicationDate); + } +} \ No newline at end of file diff --git a/currying/src/main/java/com/iluwatar/currying/Genre.java b/currying/src/main/java/com/iluwatar/currying/Genre.java new file mode 100644 index 000000000000..58e639f4ce3c --- /dev/null +++ b/currying/src/main/java/com/iluwatar/currying/Genre.java @@ -0,0 +1,34 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.currying; + +/** + * Enum representing different book genres. + */ +public enum Genre { + FANTASY, + HORROR, + SCIFI; +} diff --git a/pom.xml b/pom.xml index b75a4551ff13..be6a09f4c9cc 100644 --- a/pom.xml +++ b/pom.xml @@ -200,6 +200,7 @@ <module>composite-view</module> <module>metadata-mapping</module> <module>service-to-worker</module> + <module>currying</module> <module>serialized-entity</module> <module>identity-map</module> <module>component</module>
diff --git a/currying/src/test/java/com/iluwatar/currying/AppTest.java b/currying/src/test/java/com/iluwatar/currying/AppTest.java new file mode 100644 index 000000000000..83fd99363e52 --- /dev/null +++ b/currying/src/test/java/com/iluwatar/currying/AppTest.java @@ -0,0 +1,39 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.currying; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +/** + * Tests that the App can be run without throwing any exceptions. + */ +class AppTest { + @Test + void executesWithoutExceptions() { + assertDoesNotThrow(() -> App.main(new String[]{})); + } +} diff --git a/currying/src/test/java/com/iluwatar/currying/BookCurryingTest.java b/currying/src/test/java/com/iluwatar/currying/BookCurryingTest.java new file mode 100644 index 000000000000..437941583618 --- /dev/null +++ b/currying/src/test/java/com/iluwatar/currying/BookCurryingTest.java @@ -0,0 +1,83 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.currying; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.time.LocalDate; + +/** + * Unit tests for the Book class + */ +class BookCurryingTest { + private static Book expectedBook; + + @BeforeAll + public static void initialiseBook() { + expectedBook = new Book(Genre.FANTASY, + "Dave", + "Into the Night", + LocalDate.of(2002, 4, 7)); + } + + /** + * Tests that the expected book can be created via curried functions + */ + @Test + void createsExpectedBook() { + Book builderCurriedBook = Book.builder() + .withGenre(Genre.FANTASY) + .withAuthor("Dave") + .withTitle("Into the Night") + .withPublicationDate(LocalDate.of(2002, 4, 7)); + + Book funcCurriedBook = Book.book_creator + .apply(Genre.FANTASY) + .apply("Dave") + .apply("Into the Night") + .apply(LocalDate.of(2002, 4, 7)); + + assertEquals(expectedBook, builderCurriedBook); + assertEquals(expectedBook, funcCurriedBook); + } + + /** + * Tests that an intermediate curried function can be used to create the expected book + */ + @Test + void functionCreatesExpectedBook() { + Book.AddTitle daveFantasyBookFunc = Book.builder() + .withGenre(Genre.FANTASY) + .withAuthor("Dave"); + + Book curriedBook = daveFantasyBookFunc.withTitle("Into the Night") + .withPublicationDate(LocalDate.of(2002, 4, 7)); + + assertEquals(expectedBook, curriedBook); + } +}
val
val
2022-12-03T19:46:22
"2021-10-07T16:29:23Z"
javatlacati
train
iluwatar/java-design-patterns/2242_2302
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2242
iluwatar/java-design-patterns/2302
[ "timestamp(timedelta=2101.0, similarity=0.9059112988313126)" ]
cfeee239570226f50b857770676686bc65b495df
24bd93999d1acd583fc4c866b41dd363b2cb1616
[ "@iluwatar Raised PR# https://github.com/iluwatar/java-design-patterns/pull/2302 Kindly review.\r\nThanks" ]
[]
"2022-11-01T12:23:56Z"
[ "type: feature", "epic: documentation" ]
Explanation for Model-View-Controller
In this issue, let's add a proper explanation for the pattern. Acceptance criteria - The pattern's README.md has been amended with an explanation - The explanation consists of - Real world example - In plain words - Wikipedia says - Programmatic example
[ "model-view-controller/README.md" ]
[ "model-view-controller/README.md" ]
[]
diff --git a/model-view-controller/README.md b/model-view-controller/README.md index a94fb56c12b1..f4d2be8d8471 100644 --- a/model-view-controller/README.md +++ b/model-view-controller/README.md @@ -12,6 +12,132 @@ the model, the view and the controller. Let the model manage the data, the view display the data and the controller mediate updating the data and redrawing the display. +## Explanation + +Real-world example + +> Consider ICU room in hospital which displays the patients health information on device displays which +> are taking input from sensors connected to patient. Here, display's job is to display the data that +> it receives from the controller which in turn gets update from sensor model. + +In plain words + +> MVC separates the business logic from user interface by mediating Controller between Model & View. + +Wikipedia says + +> Model–view–controller (MVC) is commonly used for developing user interfaces that divide the +> related program logic into three interconnected elements. This is done to separate internal +> representations of information from the ways information is presented to and accepted from the user. + +**Programmatic Example** + +Consider following `GiantModel` model class that provides the health, fatigue & nourishment information. + +```java +public class GiantModel { + + private Health health; + private Fatigue fatigue; + private Nourishment nourishment; + + /** + * Instantiates a new GiantModel. + */ + public GiantModel(Health health, Fatigue fatigue, Nourishment nourishment) { + this.health = health; + this.fatigue = fatigue; + this.nourishment = nourishment; + } + + public Health getHealth() { + return health; + } + + public void setHealth(Health health) { + this.health = health; + } + + public Fatigue getFatigue() { + return fatigue; + } + + public void setFatigue(Fatigue fatigue) { + this.fatigue = fatigue; + } + + public Nourishment getNourishment() { + return nourishment; + } + + public void setNourishment(Nourishment nourishment) { + this.nourishment = nourishment; + } + + @Override + public String toString() { + return String.format("The giant looks %s, %s and %s.", health, fatigue, nourishment); + } +} +``` + +`GiantView` class to display received patient data. + +```java +public class GiantView { + + public void displayGiant(GiantModel giant) { + LOGGER.info(giant.toString()); + } +} +``` + +And `GiantController` class that takes updates from `GiantModel` & sends to `GiantView` for display. + +```java +public class GiantController { + + private final GiantModel giant; + private final GiantView view; + + public GiantController(GiantModel giant, GiantView view) { + this.giant = giant; + this.view = view; + } + + @SuppressWarnings("UnusedReturnValue") + public Health getHealth() { + return giant.getHealth(); + } + + public void setHealth(Health health) { + this.giant.setHealth(health); + } + + @SuppressWarnings("UnusedReturnValue") + public Fatigue getFatigue() { + return giant.getFatigue(); + } + + public void setFatigue(Fatigue fatigue) { + this.giant.setFatigue(fatigue); + } + + @SuppressWarnings("UnusedReturnValue") + public Nourishment getNourishment() { + return giant.getNourishment(); + } + + public void setNourishment(Nourishment nourishment) { + this.giant.setNourishment(nourishment); + } + + public void updateView() { + this.view.displayGiant(giant); + } +} +``` + ## Class diagram ![alt text](./etc/model-view-controller.png "Model-View-Controller")
null
test
val
2022-10-30T21:26:27
"2022-10-29T19:59:49Z"
iluwatar
train
iluwatar/java-design-patterns/2243_2302
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2243
iluwatar/java-design-patterns/2302
[ "timestamp(timedelta=2170.0, similarity=0.8789116389588582)" ]
cfeee239570226f50b857770676686bc65b495df
24bd93999d1acd583fc4c866b41dd363b2cb1616
[ "@iluwatar Raised PR https://github.com/iluwatar/java-design-patterns/pull/2303 . Kindly review.\r\n\r\nThanks" ]
[]
"2022-11-01T12:23:56Z"
[ "type: feature", "epic: documentation" ]
Explanation for Model-View-Presenter
In this issue, let's add a proper explanation for the pattern. Acceptance criteria - The pattern's README.md has been amended with an explanation - The explanation consists of - Real world example - In plain words - Wikipedia says - Programmatic example
[ "model-view-controller/README.md" ]
[ "model-view-controller/README.md" ]
[]
diff --git a/model-view-controller/README.md b/model-view-controller/README.md index a94fb56c12b1..f4d2be8d8471 100644 --- a/model-view-controller/README.md +++ b/model-view-controller/README.md @@ -12,6 +12,132 @@ the model, the view and the controller. Let the model manage the data, the view display the data and the controller mediate updating the data and redrawing the display. +## Explanation + +Real-world example + +> Consider ICU room in hospital which displays the patients health information on device displays which +> are taking input from sensors connected to patient. Here, display's job is to display the data that +> it receives from the controller which in turn gets update from sensor model. + +In plain words + +> MVC separates the business logic from user interface by mediating Controller between Model & View. + +Wikipedia says + +> Model–view–controller (MVC) is commonly used for developing user interfaces that divide the +> related program logic into three interconnected elements. This is done to separate internal +> representations of information from the ways information is presented to and accepted from the user. + +**Programmatic Example** + +Consider following `GiantModel` model class that provides the health, fatigue & nourishment information. + +```java +public class GiantModel { + + private Health health; + private Fatigue fatigue; + private Nourishment nourishment; + + /** + * Instantiates a new GiantModel. + */ + public GiantModel(Health health, Fatigue fatigue, Nourishment nourishment) { + this.health = health; + this.fatigue = fatigue; + this.nourishment = nourishment; + } + + public Health getHealth() { + return health; + } + + public void setHealth(Health health) { + this.health = health; + } + + public Fatigue getFatigue() { + return fatigue; + } + + public void setFatigue(Fatigue fatigue) { + this.fatigue = fatigue; + } + + public Nourishment getNourishment() { + return nourishment; + } + + public void setNourishment(Nourishment nourishment) { + this.nourishment = nourishment; + } + + @Override + public String toString() { + return String.format("The giant looks %s, %s and %s.", health, fatigue, nourishment); + } +} +``` + +`GiantView` class to display received patient data. + +```java +public class GiantView { + + public void displayGiant(GiantModel giant) { + LOGGER.info(giant.toString()); + } +} +``` + +And `GiantController` class that takes updates from `GiantModel` & sends to `GiantView` for display. + +```java +public class GiantController { + + private final GiantModel giant; + private final GiantView view; + + public GiantController(GiantModel giant, GiantView view) { + this.giant = giant; + this.view = view; + } + + @SuppressWarnings("UnusedReturnValue") + public Health getHealth() { + return giant.getHealth(); + } + + public void setHealth(Health health) { + this.giant.setHealth(health); + } + + @SuppressWarnings("UnusedReturnValue") + public Fatigue getFatigue() { + return giant.getFatigue(); + } + + public void setFatigue(Fatigue fatigue) { + this.giant.setFatigue(fatigue); + } + + @SuppressWarnings("UnusedReturnValue") + public Nourishment getNourishment() { + return giant.getNourishment(); + } + + public void setNourishment(Nourishment nourishment) { + this.giant.setNourishment(nourishment); + } + + public void updateView() { + this.view.displayGiant(giant); + } +} +``` + ## Class diagram ![alt text](./etc/model-view-controller.png "Model-View-Controller")
null
train
val
2022-10-30T21:26:27
"2022-10-29T19:59:52Z"
iluwatar
train
iluwatar/java-design-patterns/2297_2317
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2297
iluwatar/java-design-patterns/2317
[ "timestamp(timedelta=1.0, similarity=0.8465203046542189)" ]
e6f5b691df3033ad3a73c14f6ad9671efa49bb03
c4307db0a60c7b4612397ab1e1b911e0a78ccf13
[ "@iluwatar , is solution is to update the version of H2 database or something else .\r\nAbove issue is also mentioned here officially in H2 database repo [issue](https://github.com/h2database/h2database/issues/3195).", "Yes, update the version (see the acceptance criteria). Would you like to try it @bhati00 ?", "yes sure @iluwatar , i would like to try.", "Sir , where i can find the details about this project , how is it developed and its architecture .\r\n Why we use the H2 database, is it only for the testing purpose . ?", "Sir, i did updated the version of H2 database by changing the version of H2\nin pom.xml . But it failed the test case.\n\nOn Mon, Oct 31, 2022, 23:57 Ilkka Seppälä ***@***.***> wrote:\n\n> Yes, update the version (see the acceptance criteria). Would you like to\n> try it @bhati00 <https://github.com/bhati00> ?\n>\n> —\n> Reply to this email directly, view it on GitHub\n> <https://github.com/iluwatar/java-design-patterns/issues/2297#issuecomment-1297497804>,\n> or unsubscribe\n> <https://github.com/notifications/unsubscribe-auth/AS5DWKN77YZSK3PD5GHLZ6LWGAFRNANCNFSM6AAAAAARSMVNKY>\n> .\n> You are receiving this because you were mentioned.Message ID:\n> ***@***.***>\n>\n", "After changing the H2 version, you need to fix everything so that the CI build works again @bhati00 That's the difficulty in this task.", "Hello @iluwatar , can you please specify a bit that, what kind of changes should i made to in order to fix everything .I've read this article for [migrate to hibernate 2.0](https://www.h2database.com/html/migration-to-v2.html#:~:text=your%20own%20risk.-,Upgrading,of%20this%20command%20for%20details.) , and one another thing , where we did specify the details about the h2 database , in rest api we use application.properties. ", "Hmm I didn't get any errors after the upgrade. Could you just create the pull request with the updated dependency and we can check if it's just your workstation?", "@iluwatar , i've made the [pull request ](https://github.com/iluwatar/java-design-patterns/pull/2298), it solves two issues , since previous one was'nt merged that's why i've commited to same branch. \r\nI'm not getting error in my workstation Sir, its circle.ci which shows the error , **maven build failed** .", "I previous tried to upgrade the H2 database but failed with some strange error message that need non-trivial investigation.", "@robertvolkmann , did you just simply added the dependency or also made some another changes for upgrading the database.", "I simply pumped the version and it failed. Therefore I expect some additional changes.", "wow , great @robertvolkmann , you've solved the issue .\r\ni was seacrching in the project , where did the database created , @robertvolkmann , why did we created it in domain-modal . And why did you droped the table according to their dependency . ", "@bhati00, the H2 database is automatically created if absent.\r\nYou have to drop the tables according to their dependency. In our case, we cannot drop the table CUSTOMERS before PURCHASES because the latter still has a reference to CUSTOMERS." ]
[]
"2022-11-06T19:24:21Z"
[ "epic: dependencies" ]
Security vulnerability in H2 database
The currently used H2 database version 1.4.190 has multiple security vulnerabilities. To mention a few: 1. - H2 Console before 2.1.210 allows remote attackers to execute arbitrary code via a jdbc:h2:mem JDBC URL containing the IGNORE_UNKNOWN_SETTINGS=TRUE;FORBID_CREATION=FALSE;INIT=RUNSCRIPT substring, a different vulnerability than https://github.com/advisories/GHSA-h376-j262-vhq6 2. - H2 Console in versions since 1.1.100 (2008-10-14) to 2.0.204 (2021-12-21) inclusive allows loading of custom classes from remote servers through JNDI. 3. - The package com.h2database:h2 from 0 and before 2.0.202 are vulnerable to XML External Entity (XXE) Injection via the org.h2.jdbc.JdbcSQLXML class object, when it receives parsed string data from org.h2.jdbc.JdbcResultSet.getSQLXML() method. If it executes the getSource() method when the parameter is DOMSource.class it will trigger the vulnerability. Acceptance criteria - H2 database has been upgraded to the latest version
[ "domain-model/src/main/java/com/iluwatar/domainmodel/App.java", "metadata-mapping/README.md", "metadata-mapping/src/main/java/com/iluwatar/metamapping/utils/DatabaseUtil.java", "metadata-mapping/src/main/resources/com/iluwatar/metamapping/model/User.hbm.xml", "pom.xml", "transaction-script/src/main/java/com/iluwatar/transactionscript/RoomSchemaSql.java" ]
[ "domain-model/src/main/java/com/iluwatar/domainmodel/App.java", "metadata-mapping/README.md", "metadata-mapping/src/main/java/com/iluwatar/metamapping/utils/DatabaseUtil.java", "metadata-mapping/src/main/resources/com/iluwatar/metamapping/model/User.hbm.xml", "pom.xml", "transaction-script/src/main/java/com/iluwatar/transactionscript/RoomSchemaSql.java" ]
[]
diff --git a/domain-model/src/main/java/com/iluwatar/domainmodel/App.java b/domain-model/src/main/java/com/iluwatar/domainmodel/App.java index 80058fb89a7a..681e7c4fc72a 100644 --- a/domain-model/src/main/java/com/iluwatar/domainmodel/App.java +++ b/domain-model/src/main/java/com/iluwatar/domainmodel/App.java @@ -60,8 +60,8 @@ public class App { + "customer_name varchar references CUSTOMERS(name));"; public static final String DELETE_SCHEMA_SQL = - "DROP TABLE CUSTOMERS IF EXISTS;" - + "DROP TABLE PURCHASES IF EXISTS;" + "DROP TABLE PURCHASES IF EXISTS;" + + "DROP TABLE CUSTOMERS IF EXISTS;" + "DROP TABLE PRODUCTS IF EXISTS;"; /** diff --git a/metadata-mapping/README.md b/metadata-mapping/README.md index 4cea6b10f84f..612188cbe267 100644 --- a/metadata-mapping/README.md +++ b/metadata-mapping/README.md @@ -26,14 +26,14 @@ Wikipedia says **Programmatic Example** -We give an example about visiting the information of `USER` table in `h2` database. Firstly, we create `USER` table with `h2`: +We give an example about visiting the information of `user_account` table in `h2` database. Firstly, we create `user_account` table with `h2`: ```java @Slf4j public class DatabaseUtil { private static final String DB_URL = "jdbc:h2:mem:metamapping"; - private static final String CREATE_SCHEMA_SQL = "DROP TABLE IF EXISTS `user`;" - + "CREATE TABLE `user` (\n" + private static final String CREATE_SCHEMA_SQL = "DROP TABLE IF EXISTS `user_account`;" + + "CREATE TABLE `user_account` (\n" + " `id` int(11) NOT NULL AUTO_INCREMENT,\n" + " `username` varchar(255) NOT NULL,\n" + " `password` varchar(255) NOT NULL,\n" @@ -88,7 +88,7 @@ Then we write a `xml` file to show the mapping between the table and the object: "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> - <class name="com.iluwatar.metamapping.model.User" table="user"> + <class name="com.iluwatar.metamapping.model.User" table="user_account"> <id name="id" type="java.lang.Integer" column="id"> <generator class="native"/> </id> diff --git a/metadata-mapping/src/main/java/com/iluwatar/metamapping/utils/DatabaseUtil.java b/metadata-mapping/src/main/java/com/iluwatar/metamapping/utils/DatabaseUtil.java index 55f06ed9a794..048f470aebf4 100644 --- a/metadata-mapping/src/main/java/com/iluwatar/metamapping/utils/DatabaseUtil.java +++ b/metadata-mapping/src/main/java/com/iluwatar/metamapping/utils/DatabaseUtil.java @@ -34,8 +34,8 @@ @Slf4j public class DatabaseUtil { private static final String DB_URL = "jdbc:h2:mem:metamapping"; - private static final String CREATE_SCHEMA_SQL = "DROP TABLE IF EXISTS `user`;" - + "CREATE TABLE `user` (\n" + private static final String CREATE_SCHEMA_SQL = "DROP TABLE IF EXISTS `user_account`;" + + "CREATE TABLE `user_account` (\n" + " `id` int(11) NOT NULL AUTO_INCREMENT,\n" + " `username` varchar(255) NOT NULL,\n" + " `password` varchar(255) NOT NULL,\n" diff --git a/metadata-mapping/src/main/resources/com/iluwatar/metamapping/model/User.hbm.xml b/metadata-mapping/src/main/resources/com/iluwatar/metamapping/model/User.hbm.xml index cd63c552d65d..38862c67a3f4 100644 --- a/metadata-mapping/src/main/resources/com/iluwatar/metamapping/model/User.hbm.xml +++ b/metadata-mapping/src/main/resources/com/iluwatar/metamapping/model/User.hbm.xml @@ -4,7 +4,7 @@ "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> - <class name="com.iluwatar.metamapping.model.User" table="user"> + <class name="com.iluwatar.metamapping.model.User" table="user_account"> <id name="id" type="java.lang.Integer" column="id"> <generator class="native"/> </id> diff --git a/pom.xml b/pom.xml index fd1193bc15aa..ed94116b65cb 100644 --- a/pom.xml +++ b/pom.xml @@ -38,7 +38,6 @@ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <sonar-maven-plugin.version>3.8.0.2131</sonar-maven-plugin.version> <spring-boot.version>2.7.5</spring-boot.version> - <h2.version>1.4.190</h2.version> <jacoco.version>0.8.8</jacoco.version> <commons-dbcp.version>1.4</commons-dbcp.version> <camel.version>2.25.1</camel.version> @@ -246,11 +245,6 @@ <type>pom</type> <scope>import</scope> </dependency> - <dependency> - <groupId>com.h2database</groupId> - <artifactId>h2</artifactId> - <version>${h2.version}</version> - </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> diff --git a/transaction-script/src/main/java/com/iluwatar/transactionscript/RoomSchemaSql.java b/transaction-script/src/main/java/com/iluwatar/transactionscript/RoomSchemaSql.java index acb96930ebf8..29cad58620ef 100644 --- a/transaction-script/src/main/java/com/iluwatar/transactionscript/RoomSchemaSql.java +++ b/transaction-script/src/main/java/com/iluwatar/transactionscript/RoomSchemaSql.java @@ -30,7 +30,7 @@ public final class RoomSchemaSql { public static final String CREATE_SCHEMA_SQL = - "CREATE TABLE ROOMS (ID NUMBER, ROOM_TYPE VARCHAR(100), PRICE INT(100), BOOKED VARCHAR(100))"; + "CREATE TABLE ROOMS (ID NUMBER, ROOM_TYPE VARCHAR(100), PRICE INT, BOOKED VARCHAR(100))"; public static final String DELETE_SCHEMA_SQL = "DROP TABLE ROOMS IF EXISTS"; private RoomSchemaSql() {
null
test
val
2022-11-06T14:36:50
"2022-10-30T18:10:05Z"
iluwatar
train
iluwatar/java-design-patterns/2326_2327
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2326
iluwatar/java-design-patterns/2327
[ "keyword_pr_to_issue" ]
dd456d4440406b920492485549e79fbc324a9382
a05cf33643dffdfbd624186dc98ab7aee4327c87
[]
[]
"2022-11-10T23:06:05Z"
[ "type: refactoring", "epic: code quality" ]
Minor enchancements to flyweight
Minor enhancements to flyweight: - AlchemistShopTest : line 59: use a Set<>(potions).size() than streaming - PotionFactory - small refactoring to reduce code duplication by adding the potion after each siwtch case.
[ "feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/UserGroup.java", "flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java" ]
[ "feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/UserGroup.java", "flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java" ]
[ "flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java" ]
diff --git a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/UserGroup.java b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/UserGroup.java index 91b75f548655..d01c5735d19e 100644 --- a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/UserGroup.java +++ b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/UserGroup.java @@ -48,7 +48,7 @@ public class UserGroup { */ public static void addUserToFreeGroup(final User user) throws IllegalArgumentException { if (paidGroup.contains(user)) { - throw new IllegalArgumentException("User all ready member of paid group."); + throw new IllegalArgumentException("User already member of paid group."); } else { if (!freeGroup.contains(user)) { freeGroup.add(user); @@ -65,7 +65,7 @@ public static void addUserToFreeGroup(final User user) throws IllegalArgumentExc */ public static void addUserToPaidGroup(final User user) throws IllegalArgumentException { if (freeGroup.contains(user)) { - throw new IllegalArgumentException("User all ready member of free group."); + throw new IllegalArgumentException("User already member of free group."); } else { if (!paidGroup.contains(user)) { paidGroup.add(user); diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java b/flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java index a05d99798604..814131732d62 100644 --- a/flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java +++ b/flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java @@ -46,27 +46,25 @@ Potion createPotion(PotionType type) { switch (type) { case HEALING: potion = new HealingPotion(); - potions.put(type, potion); break; case HOLY_WATER: potion = new HolyWaterPotion(); - potions.put(type, potion); break; case INVISIBILITY: potion = new InvisibilityPotion(); - potions.put(type, potion); break; case POISON: potion = new PoisonPotion(); - potions.put(type, potion); break; case STRENGTH: potion = new StrengthPotion(); - potions.put(type, potion); break; default: break; } + if (potion != null) { + potions.put(type, potion); + } } return potion; }
diff --git a/flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java b/flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java index 0448554384d3..79a70611ea95 100644 --- a/flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java +++ b/flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java @@ -28,6 +28,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.ArrayList; +import java.util.HashSet; import org.junit.jupiter.api.Test; /** @@ -55,8 +56,6 @@ void testShop() { // There are 13 potion instances, but only 5 unique instance types assertEquals(13, allPotions.size()); - assertEquals(5, allPotions.stream().map(System::identityHashCode).distinct().count()); - + assertEquals(5, new HashSet<>(allPotions).size()); } - }
train
val
2022-11-09T21:03:04
"2022-11-10T23:00:31Z"
StefanelStan
train
iluwatar/java-design-patterns/2325_2327
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2325
iluwatar/java-design-patterns/2327
[ "keyword_pr_to_issue" ]
dd456d4440406b920492485549e79fbc324a9382
a05cf33643dffdfbd624186dc98ab7aee4327c87
[]
[]
"2022-11-10T23:06:05Z"
[ "type: bug", "info: good first issue", "epic: documentation" ]
Feature Toggle mispelled comments
A small typo error: all ready (incorrect) instead of already
[ "feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/UserGroup.java", "flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java" ]
[ "feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/UserGroup.java", "flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java" ]
[ "flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java" ]
diff --git a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/UserGroup.java b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/UserGroup.java index 91b75f548655..d01c5735d19e 100644 --- a/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/UserGroup.java +++ b/feature-toggle/src/main/java/com/iluwatar/featuretoggle/user/UserGroup.java @@ -48,7 +48,7 @@ public class UserGroup { */ public static void addUserToFreeGroup(final User user) throws IllegalArgumentException { if (paidGroup.contains(user)) { - throw new IllegalArgumentException("User all ready member of paid group."); + throw new IllegalArgumentException("User already member of paid group."); } else { if (!freeGroup.contains(user)) { freeGroup.add(user); @@ -65,7 +65,7 @@ public static void addUserToFreeGroup(final User user) throws IllegalArgumentExc */ public static void addUserToPaidGroup(final User user) throws IllegalArgumentException { if (freeGroup.contains(user)) { - throw new IllegalArgumentException("User all ready member of free group."); + throw new IllegalArgumentException("User already member of free group."); } else { if (!paidGroup.contains(user)) { paidGroup.add(user); diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java b/flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java index a05d99798604..814131732d62 100644 --- a/flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java +++ b/flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java @@ -46,27 +46,25 @@ Potion createPotion(PotionType type) { switch (type) { case HEALING: potion = new HealingPotion(); - potions.put(type, potion); break; case HOLY_WATER: potion = new HolyWaterPotion(); - potions.put(type, potion); break; case INVISIBILITY: potion = new InvisibilityPotion(); - potions.put(type, potion); break; case POISON: potion = new PoisonPotion(); - potions.put(type, potion); break; case STRENGTH: potion = new StrengthPotion(); - potions.put(type, potion); break; default: break; } + if (potion != null) { + potions.put(type, potion); + } } return potion; }
diff --git a/flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java b/flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java index 0448554384d3..79a70611ea95 100644 --- a/flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java +++ b/flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java @@ -28,6 +28,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.ArrayList; +import java.util.HashSet; import org.junit.jupiter.api.Test; /** @@ -55,8 +56,6 @@ void testShop() { // There are 13 potion instances, but only 5 unique instance types assertEquals(13, allPotions.size()); - assertEquals(5, allPotions.stream().map(System::identityHashCode).distinct().count()); - + assertEquals(5, new HashSet<>(allPotions).size()); } - }
train
val
2022-11-09T21:03:04
"2022-11-10T22:43:59Z"
StefanelStan
train
iluwatar/java-design-patterns/2035_2331
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2035
iluwatar/java-design-patterns/2331
[ "keyword_pr_to_issue", "timestamp(timedelta=1.0, similarity=0.9820342106713623)" ]
10fb952d85e93386a5b79e3b898fbd7361d5de4d
37bfecce30969c25a519d939eafcbff8023f60a7
[ "@iluwatar ,\r\nCan I work on this", "Yes, go ahead @harikesh409 ", "Is this already fixed in master branch? I've built the current state against JDK17 and have no errors.", "For me, it fails during naked objects integration tests", "@iluwatar Could I work on this?", "@harikesh409 I'll assign @robertvolkmann to this issue as well. This is high priority and would like to see it completed soon." ]
[]
"2022-11-13T09:01:02Z"
[ "info: good first issue", "epic: build issue", "type: feature" ]
Build with JDK 17
This task is part of the transition plan at https://github.com/iluwatar/java-design-patterns/wiki/19.-Java-17-transition. Here we address the issues that come up when building the project with JDK 17 using language level Java 11. Acceptance criteria - Build the project with JDK 17 while keeping the maven-compiler-plugin language level at 11 - Fix the errors that come up during the build
[ ".circleci/config.yml", ".github/workflows/maven-ci.yml", ".github/workflows/maven-pr-builder.yml" ]
[ ".circleci/config.yml", ".github/workflows/maven-ci.yml", ".github/workflows/maven-pr-builder.yml" ]
[]
diff --git a/.circleci/config.yml b/.circleci/config.yml index dad7997a8699..714bd108889a 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -26,14 +26,14 @@ version: 2 jobs: sonar-pr: docker: - - image: cimg/openjdk:11.0-node + - image: cimg/openjdk:17.0-node steps: - checkout - restore_cache: key: jdp-sonar-pr-{{ checksum "pom.xml" }} - run: | sudo apt-get update - sudo apt-get install -y openjdk-11-jdk xvfb + sudo apt-get install -y openjdk-17-jdk xvfb if [ -n "${CIRCLE_PR_NUMBER}" ]; then MAVEN_OPTS="-Xmx3000m" xvfb-run ./mvnw -B clean verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar \ -Dsonar.pullrequest.key=${CIRCLE_PR_NUMBER} \ diff --git a/.github/workflows/maven-ci.yml b/.github/workflows/maven-ci.yml index 1f490cf31be8..f9d8b063dd9c 100644 --- a/.github/workflows/maven-ci.yml +++ b/.github/workflows/maven-ci.yml @@ -39,7 +39,7 @@ jobs: # This Workflow Job will build this project and run Sonar analysis using JDK 11.0.3 build-and-analyze: - name: Build and Run Sonar analysis on JDK 11.0.3 + name: Build and Run Sonar analysis on JDK 17 runs-on: ubuntu-20.04 steps: @@ -49,11 +49,11 @@ jobs: # Disabling shallow clone for improving relevancy of SonarQube reporting fetch-depth: 0 - - name: Set up JDK 11.0.3 + - name: Set up JDK 17 uses: actions/setup-java@v3 with: - java-version: 11.0.3 - distribution: 'zulu' + java-version: '17' + distribution: 'temurin' cache: 'maven' # Cache Sonar packages which as used to run anaylysis and collect metrics @@ -79,18 +79,18 @@ jobs: # This Workflow Job is going to build the project on the latest stable JDK 11 build: - name: Build and Test on JDK 11 + name: Build and Test on JDK 17 runs-on: ubuntu-20.04 steps: - name: Checkout Code uses: actions/checkout@v3 - - name: Set up JDK 11 (Latest) + - name: Set up JDK 17 uses: actions/setup-java@v3 with: - java-version: 11 - distribution: 'zulu' + java-version: '17' + distribution: 'temurin' cache: 'maven' # Some tests need screen access diff --git a/.github/workflows/maven-pr-builder.yml b/.github/workflows/maven-pr-builder.yml index 66d39d40df7a..62664d614ea0 100644 --- a/.github/workflows/maven-pr-builder.yml +++ b/.github/workflows/maven-pr-builder.yml @@ -34,21 +34,18 @@ on: jobs: build: - name: Build JDP + name: Build on JDK 17 runs-on: ubuntu-20.04 - strategy: - matrix: - java-version: [ 11.0.3, 11 ] steps: - name: Checkout Code uses: actions/checkout@v3 - - name: Set up JDK ${{ matrix.java-version }} + - name: Set up JDK 17 uses: actions/setup-java@v3 with: - java-version: ${{ matrix.java-version }} - distribution: 'zulu' + java-version: '17' + distribution: 'temurin' cache: 'maven' # Some tests need screen access
null
val
val
2022-11-21T17:59:09
"2022-09-28T16:31:17Z"
iluwatar
train
iluwatar/java-design-patterns/2036_2331
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2036
iluwatar/java-design-patterns/2331
[ "timestamp(timedelta=132693.0, similarity=0.9544008291454945)" ]
10fb952d85e93386a5b79e3b898fbd7361d5de4d
37bfecce30969c25a519d939eafcbff8023f60a7
[ " I want to help in this issue\r\n ", "Ok @ArinCodes ", "Can I help in this isssue ..?\r\n", "\r\nI want to help in this issue\r\n\r\n", "@iluwatar Could I work on this?", "@ArinCodes I'll assign this issue to @robertvolkmann as well since this is high priority." ]
[]
"2022-11-13T09:01:02Z"
[ "info: good first issue", "epic: build issue", "type: feature" ]
Run with Java 17
This is part of the transition plan at https://github.com/iluwatar/java-design-patterns/wiki/19.-Java-17-transition. In this issue, we build the project using JDK 11 and try to run it with Java 17 runtime. Acceptance criteria - The project is built with JDK 11 - The pattern examples are executed with Java 17 runtime e.g. `java -jar proxy.jar` - The errors that come up in the testing are fixed
[ ".circleci/config.yml", ".github/workflows/maven-ci.yml", ".github/workflows/maven-pr-builder.yml" ]
[ ".circleci/config.yml", ".github/workflows/maven-ci.yml", ".github/workflows/maven-pr-builder.yml" ]
[]
diff --git a/.circleci/config.yml b/.circleci/config.yml index dad7997a8699..714bd108889a 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -26,14 +26,14 @@ version: 2 jobs: sonar-pr: docker: - - image: cimg/openjdk:11.0-node + - image: cimg/openjdk:17.0-node steps: - checkout - restore_cache: key: jdp-sonar-pr-{{ checksum "pom.xml" }} - run: | sudo apt-get update - sudo apt-get install -y openjdk-11-jdk xvfb + sudo apt-get install -y openjdk-17-jdk xvfb if [ -n "${CIRCLE_PR_NUMBER}" ]; then MAVEN_OPTS="-Xmx3000m" xvfb-run ./mvnw -B clean verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar \ -Dsonar.pullrequest.key=${CIRCLE_PR_NUMBER} \ diff --git a/.github/workflows/maven-ci.yml b/.github/workflows/maven-ci.yml index 1f490cf31be8..f9d8b063dd9c 100644 --- a/.github/workflows/maven-ci.yml +++ b/.github/workflows/maven-ci.yml @@ -39,7 +39,7 @@ jobs: # This Workflow Job will build this project and run Sonar analysis using JDK 11.0.3 build-and-analyze: - name: Build and Run Sonar analysis on JDK 11.0.3 + name: Build and Run Sonar analysis on JDK 17 runs-on: ubuntu-20.04 steps: @@ -49,11 +49,11 @@ jobs: # Disabling shallow clone for improving relevancy of SonarQube reporting fetch-depth: 0 - - name: Set up JDK 11.0.3 + - name: Set up JDK 17 uses: actions/setup-java@v3 with: - java-version: 11.0.3 - distribution: 'zulu' + java-version: '17' + distribution: 'temurin' cache: 'maven' # Cache Sonar packages which as used to run anaylysis and collect metrics @@ -79,18 +79,18 @@ jobs: # This Workflow Job is going to build the project on the latest stable JDK 11 build: - name: Build and Test on JDK 11 + name: Build and Test on JDK 17 runs-on: ubuntu-20.04 steps: - name: Checkout Code uses: actions/checkout@v3 - - name: Set up JDK 11 (Latest) + - name: Set up JDK 17 uses: actions/setup-java@v3 with: - java-version: 11 - distribution: 'zulu' + java-version: '17' + distribution: 'temurin' cache: 'maven' # Some tests need screen access diff --git a/.github/workflows/maven-pr-builder.yml b/.github/workflows/maven-pr-builder.yml index 66d39d40df7a..62664d614ea0 100644 --- a/.github/workflows/maven-pr-builder.yml +++ b/.github/workflows/maven-pr-builder.yml @@ -34,21 +34,18 @@ on: jobs: build: - name: Build JDP + name: Build on JDK 17 runs-on: ubuntu-20.04 - strategy: - matrix: - java-version: [ 11.0.3, 11 ] steps: - name: Checkout Code uses: actions/checkout@v3 - - name: Set up JDK ${{ matrix.java-version }} + - name: Set up JDK 17 uses: actions/setup-java@v3 with: - java-version: ${{ matrix.java-version }} - distribution: 'zulu' + java-version: '17' + distribution: 'temurin' cache: 'maven' # Some tests need screen access
null
val
val
2022-11-21T17:59:09
"2022-09-28T16:36:33Z"
iluwatar
train
iluwatar/java-design-patterns/2329_2332
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2329
iluwatar/java-design-patterns/2332
[ "keyword_pr_to_issue" ]
df735cb956a9a3c6555ded781e714fcbe24f24db
40fb6dda74f742298468f8952ba26ad774d973bf
[]
[]
"2022-11-13T10:18:32Z"
[ "type: bug", "info: help wanted", "epic: pattern" ]
Fix pattern categories
Some patterns have a small defect in the yaml frontmatter (README.md). Categories key should be renamed to category so that everything shows up correctly on the website. Acceptance criteria - The pattern yaml frontmatters have been checked to conform with https://github.com/iluwatar/java-design-patterns/wiki/01.-How-to-contribute
[ "identity-map/README.md", "intercepting-filter/README.md", "interpreter/README.md", "iterator/README.md" ]
[ "identity-map/README.md", "intercepting-filter/README.md", "interpreter/README.md", "iterator/README.md" ]
[]
diff --git a/identity-map/README.md b/identity-map/README.md index a5bb4d38695a..6594f54eda9e 100644 --- a/identity-map/README.md +++ b/identity-map/README.md @@ -1,6 +1,6 @@ --- title: Identity Map -categories: Behavioral +category: Behavioral language: en tags: - Performance diff --git a/intercepting-filter/README.md b/intercepting-filter/README.md index f5aef5d03032..aef71f4f5a76 100644 --- a/intercepting-filter/README.md +++ b/intercepting-filter/README.md @@ -1,6 +1,6 @@ --- title: Intercepting Filter -categories: Behavioral +category: Behavioral language: en tags: - Decoupling diff --git a/interpreter/README.md b/interpreter/README.md index 61bf7501abbc..99d3c30e50ed 100644 --- a/interpreter/README.md +++ b/interpreter/README.md @@ -1,6 +1,6 @@ --- title: Interpreter -categories: Behavioral +category: Behavioral language: en tags: - Gang of Four diff --git a/iterator/README.md b/iterator/README.md index 3f36d0070167..b49151eab125 100644 --- a/iterator/README.md +++ b/iterator/README.md @@ -1,6 +1,6 @@ --- title: Iterator -categories: Behavioral +category: Behavioral language: en tags: - Gang of Four
null
train
val
2022-11-13T08:46:45
"2022-11-13T07:37:14Z"
iluwatar
train
iluwatar/java-design-patterns/2335_2338
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2335
iluwatar/java-design-patterns/2338
[ "timestamp(timedelta=29.0, similarity=0.9406253421342035)" ]
ab81f7e3d128c28ffbf5fa75b60da7845c4d371b
8596d38ebaecb99654f3660714b01935f8da4a91
[]
[ "The yaml frontmatter keys are not supposed to be translated, only values. ", "```suggestion\r\ntitle: Aggregator Microservices\r\n```", "```suggestion\r\ncategory: Architectural\r\n```", "```suggestion\r\n- Cloud distributed\r\n```", "```suggestion\r\n- Decoupling\r\n```", "```suggestion\r\n- Microservices\r\n```" ]
"2022-11-16T12:01:10Z"
[ "type: feature", "epic: translation" ]
Translate the aggregator-microservices readme to Spanish
Hi all! Following [01.-How to contribute document](https://github.com/iluwatar/java-design-patterns/wiki/01.-How-to-contribute) I create this issue because I want to contribute to actually open issue #2277 translating [aggregator-microservices/README.md](https://github.com/iluwatar/java-design-patterns/blob/master/aggregator-microservices/README.md) I will save it in a new repository fork from my account in [localization/es](https://github.com/iluwatar/java-design-patterns/tree/master/localization/es) ./aggregator-microservices new subfolder and will make a new Pull Request for be merged soon.
[]
[ "localization/es/aggregator-microservices/README.md" ]
[]
diff --git a/localization/es/aggregator-microservices/README.md b/localization/es/aggregator-microservices/README.md new file mode 100644 index 000000000000..2c1c6aab8ce0 --- /dev/null +++ b/localization/es/aggregator-microservices/README.md @@ -0,0 +1,107 @@ +--- +title: Aggregator Microservices +category: Architectural +language: es +tag: +- Cloud distributed +- Decoupling +- Microservices +--- + +## Intención + +El usuario realiza una sola llamada al servicio del agregador y, a continuación, el agregador llama a cada microservicio relevante. + +## Explicación + +ejemplo del mundo real + +> Nuestro mercado web necesita información sobre los productos y su inventario actual. Hace una llamada a un agregador +> servicio que a su vez llama al microservicio de información del producto y al microservicio de inventario del producto que devuelve la +> información combinada. + +En palabras sencillas + +> Aggregator Microservice recopila datos de varios microservicios y devuelve un agregado para su procesamiento. + +StackOverflow dice + +> Aggregator Microservice invoca múltiples servicios para lograr la funcionalidad requerida por la aplicación. + +**Ejemplo programático** + +Empecemos por el modelo de datos. Aquí está nuestro `Product`. + +```java +public class Product { + private String title; + private int productInventories; + // getters and setters -> + ... +} +``` + +A continuación, podemos presentar nuestro microservicio `Aggregator` (Agregador de microservicios). Contiene el `ProductInformationClient` (Información del producto del cliente) y el +`ProductInventoryClient` (Inventario del producto del cliente) de los clientes para llamar a los respectivos microservicios. + +```java +@RestController +public class Aggregator { + + @Resource + private ProductInformationClient informationClient; + + @Resource + private ProductInventoryClient inventoryClient; + + @RequestMapping(path = "/product", method = RequestMethod.GET) + public Product getProduct() { + + var product = new Product(); + var productTitle = informationClient.getProductTitle(); + var productInventory = inventoryClient.getProductInventories(); + + //Fallback to error message + product.setTitle(requireNonNullElse(productTitle, "Error: Fetching Product Title Failed")); + + //Fallback to default error inventory + product.setProductInventories(requireNonNullElse(productInventory, -1)); + + return product; + } +} +``` + +Esta es la esencia de la implementación de microservicios de información. El microservicio de inventario es similar, simplemente regresa +recuentos de inventario. + +```java +@RestController +public class InformationController { + @RequestMapping(value = "/information", method = RequestMethod.GET) + public String getProductTitle() { + return "The Product Title."; + } +} +``` + +Ahora llamando a nuestra REST API `Aggregator` devuelve la información del producto. + +```bash +curl http://localhost:50004/product +{"title":"The Product Title.","productInventories":5} +``` + +## Diagrama de clase + +![alt text](./aggregator-service/etc/aggregator-service.png "Aggregator Microservice") + +## Aplicabilidad + +Utilice el patrón Agregador de microservicios (Aggregator Microservices) cuando necesite una API unificada para varios microservicios, independientemente del dispositivo cliente. + +## Créditos + +* [Patrones de diseño de microservicios] (http://web.archive.org/web/20190705163602/http://blog.arungupta.me/microservice-design-patterns/) +* [Patrones de microservicios: Con ejemplos en Java](https://www.amazon.com/gp/product/1617294543/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1617294543&linkId=8b4e570267bc5fb8b8189917b461dc60) +* [Patrones de arquitectura: Descubra patrones esenciales en el ámbito más indispensable de la arquitectura empresarial](https://www.amazon.com/gp/product/B077T7V8RC/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=B077T7V8RC&linkId=c34d204bfe1b277914b420189f09c1a4)
null
train
val
2022-12-29T12:07:01
"2022-11-15T12:01:11Z"
KarmaTashiCat
train
iluwatar/java-design-patterns/2037_2357
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2037
iluwatar/java-design-patterns/2357
[ "keyword_pr_to_issue" ]
2d309b89283e824f3e9e252b99f7537e975e3642
9181210f8144ff7730938aa2d343b8e8923ba856
[ "Hi I am interested in your project \r\nPlease Hire me", "I would like to work on this issue . Please assign it to me\r\n", "I can work on this issue. Assign it to me", "To be fair, @akhilpamwani expressed interest first", "Hey, its been 9 days since... do we have any upgrade ? . If not then I would like to work on this one. ", "Hello Sir,\r\nI would like to contribute to this project,\r\nI am new to hacktoctoberfest and this would be a great beginning.\r\nThank you...", "@iluwatar could you assign it to me?", "Assigned to you @robertvolkmann " ]
[]
"2022-11-20T20:54:37Z"
[ "info: good first issue", "epic: build issue", "epic: dependencies", "type: feature" ]
Upgrade dependencies to support Java 17
This issue is a part of the transition plan at https://github.com/iluwatar/java-design-patterns/wiki/19.-Java-17-transition. Here we upgrade the dependencies so that they support Java 17. Acceptance criteria - Project dependencies have been upgraded so that each of them supports Java 17
[ "pom.xml" ]
[ "pom.xml" ]
[]
diff --git a/pom.xml b/pom.xml index ee3465ca3cfe..74e54db37856 100644 --- a/pom.xml +++ b/pom.xml @@ -41,7 +41,8 @@ <jacoco.version>0.8.8</jacoco.version> <commons-dbcp.version>1.4</commons-dbcp.version> <htmlunit.version>2.66.0</htmlunit.version> - <guice.version>4.0</guice.version> + <gson.version>2.10</gson.version> + <guice.version>5.1.0</guice.version> <system-lambda.version>1.1.0</system-lambda.version> <urm.version>2.0.0</urm.version> <maven-surefire-plugin.version>3.0.0-M5</maven-surefire-plugin.version> @@ -230,7 +231,7 @@ <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> - <version>2.10</version> + <version>${gson.version}</version> </dependency> <dependency> <groupId>com.google.inject</groupId> @@ -414,4 +415,4 @@ </plugin> </plugins> </build> -</project> \ No newline at end of file +</project>
null
train
val
2022-12-04T10:25:57
"2022-09-28T16:38:59Z"
iluwatar
train
iluwatar/java-design-patterns/2037_2358
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2037
iluwatar/java-design-patterns/2358
[ "keyword_pr_to_issue" ]
10fb952d85e93386a5b79e3b898fbd7361d5de4d
cececd4f6402a96ee1b830d5695fbb00580cc226
[ "Hi I am interested in your project \r\nPlease Hire me", "I would like to work on this issue . Please assign it to me\r\n", "I can work on this issue. Assign it to me", "To be fair, @akhilpamwani expressed interest first", "Hey, its been 9 days since... do we have any upgrade ? . If not then I would like to work on this one. ", "Hello Sir,\r\nI would like to contribute to this project,\r\nI am new to hacktoctoberfest and this would be a great beginning.\r\nThank you...", "@iluwatar could you assign it to me?", "Assigned to you @robertvolkmann " ]
[ "Need to import this package com.google.gson.JsonParser.parseReader(reader)and can be used \r\n JsonParser.parseReader(reader);", "Works only if I rename the class `JsonParser` otherwise we have a name conflict.", "Is there any other solution to fix it. Because, it is not looks good as per code readability." ]
"2022-11-22T16:09:18Z"
[ "info: good first issue", "epic: build issue", "epic: dependencies", "type: feature" ]
Upgrade dependencies to support Java 17
This issue is a part of the transition plan at https://github.com/iluwatar/java-design-patterns/wiki/19.-Java-17-transition. Here we upgrade the dependencies so that they support Java 17. Acceptance criteria - Project dependencies have been upgraded so that each of them supports Java 17
[ "event-sourcing/pom.xml", "pom.xml", "typeobjectpattern/pom.xml", "typeobjectpattern/src/main/java/com/iluwatar/typeobject/App.java", "typeobjectpattern/src/main/java/com/iluwatar/typeobject/CellPool.java", "typeobjectpattern/src/main/java/com/iluwatar/typeobject/JsonParser.java", "typeobjectpattern/src/main/java/com/iluwatar/typeobject/candy.json" ]
[ "event-sourcing/pom.xml", "pom.xml", "typeobjectpattern/pom.xml", "typeobjectpattern/src/main/java/com/iluwatar/typeobject/App.java", "typeobjectpattern/src/main/java/com/iluwatar/typeobject/CellPool.java", "typeobjectpattern/src/main/java/com/iluwatar/typeobject/JsonParser.java", "typeobjectpattern/src/main/resources/candy.json" ]
[]
diff --git a/event-sourcing/pom.xml b/event-sourcing/pom.xml index 047c1ea0d293..ae609d67e76b 100644 --- a/event-sourcing/pom.xml +++ b/event-sourcing/pom.xml @@ -39,11 +39,9 @@ <artifactId>junit-jupiter-engine</artifactId> <scope>test</scope> </dependency> - <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> - <version>2.8.9</version> </dependency> </dependencies> <build> diff --git a/pom.xml b/pom.xml index 95247640c84f..ad1bd20560de 100644 --- a/pom.xml +++ b/pom.xml @@ -254,6 +254,11 @@ <artifactId>htmlunit</artifactId> <version>${htmlunit.version}</version> </dependency> + <dependency> + <groupId>com.google.code.gson</groupId> + <artifactId>gson</artifactId> + <version>2.10</version> + </dependency> <dependency> <groupId>com.google.inject</groupId> <artifactId>guice</artifactId> diff --git a/typeobjectpattern/pom.xml b/typeobjectpattern/pom.xml index 00aedd506bc7..6fe65fee84a9 100644 --- a/typeobjectpattern/pom.xml +++ b/typeobjectpattern/pom.xml @@ -35,9 +35,8 @@ <artifactId>typeobjectpattern</artifactId> <dependencies> <dependency> - <groupId>com.googlecode.json-simple</groupId> - <artifactId>json-simple</artifactId> - <version>1.1.1</version> + <groupId>com.google.code.gson</groupId> + <artifactId>gson</artifactId> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> diff --git a/typeobjectpattern/src/main/java/com/iluwatar/typeobject/App.java b/typeobjectpattern/src/main/java/com/iluwatar/typeobject/App.java index de2837b71885..d120baca0f2c 100644 --- a/typeobjectpattern/src/main/java/com/iluwatar/typeobject/App.java +++ b/typeobjectpattern/src/main/java/com/iluwatar/typeobject/App.java @@ -24,9 +24,7 @@ */ package com.iluwatar.typeobject; -import java.io.IOException; import lombok.extern.slf4j.Slf4j; -import org.json.simple.parser.ParseException; /** * <p>Type object pattern is the pattern we use when the OOP concept of creating a base class and @@ -54,7 +52,7 @@ public class App { * * @param args command line args */ - public static void main(String[] args) throws IOException, ParseException { + public static void main(String[] args) { var givenTime = 50; //50ms var toWin = 500; //points var pointsWon = 0; diff --git a/typeobjectpattern/src/main/java/com/iluwatar/typeobject/CellPool.java b/typeobjectpattern/src/main/java/com/iluwatar/typeobject/CellPool.java index 7dd423af67a8..94f8ec6632b1 100644 --- a/typeobjectpattern/src/main/java/com/iluwatar/typeobject/CellPool.java +++ b/typeobjectpattern/src/main/java/com/iluwatar/typeobject/CellPool.java @@ -24,13 +24,12 @@ */ package com.iluwatar.typeobject; +import com.google.gson.JsonParseException; import com.iluwatar.typeobject.Candy.Type; -import java.io.IOException; import java.security.SecureRandom; import java.util.ArrayList; import java.util.List; -import org.json.simple.parser.ParseException; /** * The CellPool class allows the reuse of crushed cells instead of creation of new cells each time. @@ -80,7 +79,7 @@ void addNewCell(Cell c) { pointer++; } - Candy[] assignRandomCandytypes() throws IOException, ParseException { + Candy[] assignRandomCandytypes() throws JsonParseException { var jp = new JsonParser(); jp.parse(); var randomCode = new Candy[jp.candies.size() - 2]; //exclude generic types 'fruit' and 'candy' diff --git a/typeobjectpattern/src/main/java/com/iluwatar/typeobject/JsonParser.java b/typeobjectpattern/src/main/java/com/iluwatar/typeobject/JsonParser.java index b9db69eb716d..da0588aa2607 100644 --- a/typeobjectpattern/src/main/java/com/iluwatar/typeobject/JsonParser.java +++ b/typeobjectpattern/src/main/java/com/iluwatar/typeobject/JsonParser.java @@ -24,17 +24,13 @@ */ package com.iluwatar.typeobject; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; import com.iluwatar.typeobject.Candy.Type; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.Hashtable; -import java.util.List; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; +import java.io.InputStreamReader; +import java.util.Hashtable; /** * The JsonParser class helps parse the json file candy.json to get all the different candies. @@ -47,23 +43,21 @@ public class JsonParser { this.candies = new Hashtable<>(); } - void parse() throws IOException, ParseException { - var parser = new JSONParser(); - var workingDirectory = new File("").getAbsolutePath(); - var filePath = List.of("src", "main", "java", "com", "iluwatar", "typeobject", "candy.json"); - var absolutePath = workingDirectory + File.separator + String.join(File.separator, filePath); - var jo = (JSONObject) parser.parse(new FileReader(absolutePath)); - var a = (JSONArray) jo.get("candies"); - for (var o : a) { - var candy = (JSONObject) o; - var name = (String) candy.get("name"); - var parentName = (String) candy.get("parent"); - var t = (String) candy.get("type"); + void parse() throws JsonParseException { + var is = this.getClass().getClassLoader().getResourceAsStream("candy.json"); + var reader = new InputStreamReader(is); + var json = (JsonObject) com.google.gson.JsonParser.parseReader(reader); + var array = (JsonArray) json.get("candies"); + for (var item : array) { + var candy = (JsonObject) item; + var name = candy.get("name").getAsString(); + var parentName = candy.get("parent").getAsString(); + var t = candy.get("type").getAsString(); var type = Type.CRUSHABLE_CANDY; if (t.equals("rewardFruit")) { type = Type.REWARD_FRUIT; } - var points = Integer.parseInt((String) candy.get("points")); + var points = candy.get("points").getAsInt(); var c = new Candy(name, parentName, type, points); this.candies.put(name, c); } diff --git a/typeobjectpattern/src/main/java/com/iluwatar/typeobject/candy.json b/typeobjectpattern/src/main/resources/candy.json similarity index 82% rename from typeobjectpattern/src/main/java/com/iluwatar/typeobject/candy.json rename to typeobjectpattern/src/main/resources/candy.json index 74430c318d72..61c5fd4c3eb3 100644 --- a/typeobjectpattern/src/main/java/com/iluwatar/typeobject/candy.json +++ b/typeobjectpattern/src/main/resources/candy.json @@ -3,43 +3,43 @@ "name" : "fruit", "parent" : "null", "type" : "rewardFruit", - "points" : "20" + "points" : 20 }, { "name" : "candy", "parent" : "null", "type" : "crushableCandy", - "points" : "10" + "points" : 10 }, { "name" : "cherry", "parent" : "fruit", "type" : "rewardFruit", - "points" : "0" + "points" : 0 }, { "name" : "mango", "parent" : "fruit", "type" : "rewardFruit", - "points" : "0" + "points" : 0 }, { "name" : "purple popsicle", "parent" : "candy", "type" : "crushableCandy", - "points" : "0" + "points" : 0 }, { "name" : "green jellybean", "parent" : "candy", "type" : "crushableCandy", - "points" : "0" + "points" : 0 }, { "name" : "orange gum", "parent" : "candy", "type" : "crushableCandy", - "points" : "0" + "points" : 0 } ] }
null
train
val
2022-11-21T17:59:09
"2022-09-28T16:38:59Z"
iluwatar
train
iluwatar/java-design-patterns/2037_2359
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2037
iluwatar/java-design-patterns/2359
[ "keyword_pr_to_issue" ]
10fb952d85e93386a5b79e3b898fbd7361d5de4d
9600a69b1e20419524c1661eea5cc21965a9c3c5
[ "Hi I am interested in your project \r\nPlease Hire me", "I would like to work on this issue . Please assign it to me\r\n", "I can work on this issue. Assign it to me", "To be fair, @akhilpamwani expressed interest first", "Hey, its been 9 days since... do we have any upgrade ? . If not then I would like to work on this one. ", "Hello Sir,\r\nI would like to contribute to this project,\r\nI am new to hacktoctoberfest and this would be a great beginning.\r\nThank you...", "@iluwatar could you assign it to me?", "Assigned to you @robertvolkmann " ]
[]
"2022-11-22T16:28:40Z"
[ "info: good first issue", "epic: build issue", "epic: dependencies", "type: feature" ]
Upgrade dependencies to support Java 17
This issue is a part of the transition plan at https://github.com/iluwatar/java-design-patterns/wiki/19.-Java-17-transition. Here we upgrade the dependencies so that they support Java 17. Acceptance criteria - Project dependencies have been upgraded so that each of them supports Java 17
[ "acyclic-visitor/pom.xml" ]
[ "acyclic-visitor/pom.xml" ]
[]
diff --git a/acyclic-visitor/pom.xml b/acyclic-visitor/pom.xml index 34f16caa06ef..52604048e127 100644 --- a/acyclic-visitor/pom.xml +++ b/acyclic-visitor/pom.xml @@ -33,19 +33,7 @@ <version>1.26.0-SNAPSHOT</version> </parent> <artifactId>acyclic-visitor</artifactId> - <properties> - <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> - <maven.compiler.source>1.8</maven.compiler.source> - <maven.compiler.target>1.8</maven.compiler.target> - </properties> <dependencies> - <!-- https://mvnrepository.com/artifact/uk.org.lidalia/slf4j-test --> - <dependency> - <groupId>uk.org.lidalia</groupId> - <artifactId>slf4j-test</artifactId> - <version>1.2.0</version> - <scope>test</scope> - </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId>
diff --git a/acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor/ConfigureForDosVisitorTest.java b/acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor/ConfigureForDosVisitorTest.java deleted file mode 100644 index c6aec8bef971..000000000000 --- a/acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor/ConfigureForDosVisitorTest.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.acyclicvisitor; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static uk.org.lidalia.slf4jext.Level.INFO; - -import com.google.common.collect.ImmutableList; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import uk.org.lidalia.slf4jtest.LoggingEvent; -import uk.org.lidalia.slf4jtest.TestLogger; -import uk.org.lidalia.slf4jtest.TestLoggerFactory; - -/** - * ConfigureForDosVisitor test class - */ -class ConfigureForDosVisitorTest { - - private final TestLogger logger = TestLoggerFactory.getTestLogger(ConfigureForDosVisitor.class); - - @Test - void testVisitForZoom() { - var conDos = new ConfigureForDosVisitor(); - var zoom = new Zoom(); - - conDos.visit(zoom); - - ImmutableList<LoggingEvent> loggingEvents = logger.getLoggingEvents(); - assertEquals(1, loggingEvents.size()); - for (LoggingEvent loggingEvent : loggingEvents) { - assertEquals(INFO, loggingEvent.getLevel()); - assertEquals(zoom + " used with Dos configurator.", loggingEvent.getMessage()); - } - } - - @Test - void testVisitForHayes() { - var conDos = new ConfigureForDosVisitor(); - var hayes = new Hayes(); - - conDos.visit(hayes); - - ImmutableList<LoggingEvent> loggingEvents = logger.getLoggingEvents(); - assertEquals(1, loggingEvents.size()); - for (LoggingEvent loggingEvent : loggingEvents) { - assertEquals(INFO, loggingEvent.getLevel()); - assertEquals(hayes + " used with Dos configurator.", loggingEvent.getMessage()); - } - } - - @BeforeEach - @AfterEach - void clearLoggers() { - TestLoggerFactory.clear(); - } -} diff --git a/acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor/ConfigureForUnixVisitorTest.java b/acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor/ConfigureForUnixVisitorTest.java deleted file mode 100644 index 587b82911f81..000000000000 --- a/acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor/ConfigureForUnixVisitorTest.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). - * - * The MIT License - * Copyright © 2014-2022 Ilkka Seppälä - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package com.iluwatar.acyclicvisitor; - -import com.google.common.collect.ImmutableList; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import uk.org.lidalia.slf4jtest.LoggingEvent; -import uk.org.lidalia.slf4jtest.TestLogger; -import uk.org.lidalia.slf4jtest.TestLoggerFactory; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static uk.org.lidalia.slf4jext.Level.INFO; - -/** - * ConfigureForUnixVisitor test class - */ -class ConfigureForUnixVisitorTest { - - private static final TestLogger LOGGER = TestLoggerFactory.getTestLogger(ConfigureForUnixVisitor.class); - - @BeforeEach - @AfterEach - void clearLoggers() { - TestLoggerFactory.clear(); - } - - @Test - void testVisitForZoom() { - var conUnix = new ConfigureForUnixVisitor(); - var zoom = new Zoom(); - - conUnix.visit(zoom); - - ImmutableList<LoggingEvent> loggingEvents = LOGGER.getLoggingEvents(); - assertEquals(1, loggingEvents.size()); - for (LoggingEvent loggingEvent : loggingEvents) { - assertEquals(INFO, loggingEvent.getLevel()); - assertEquals(zoom + " used with Unix configurator.", loggingEvent.getMessage()); - } - } -}
val
val
2022-11-21T17:59:09
"2022-09-28T16:38:59Z"
iluwatar
train
iluwatar/java-design-patterns/2369_2370
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2369
iluwatar/java-design-patterns/2370
[ "keyword_pr_to_issue", "timestamp(timedelta=1.0, similarity=0.8499777834642155)" ]
37bfecce30969c25a519d939eafcbff8023f60a7
7a3d61776971236688b73bd59d5c5609a4dffd37
[]
[]
"2022-11-30T21:19:37Z"
[ "info: help wanted", "epic: build issue", "type: refactoring" ]
Reduce build logging
Currrently, the build with tests enabled produces a zipped log file of about 65MB. This is a bit too large to analyze effectively. Let's try to reduce the logging a bit while keeping the most important parts. Acceptance criteria - Build and tests produce more compact logs
[ "monitor/src/main/java/com/iluwatar/monitor/Bank.java", "monitor/src/main/java/com/iluwatar/monitor/Main.java" ]
[ "monitor/src/main/java/com/iluwatar/monitor/Bank.java", "monitor/src/main/java/com/iluwatar/monitor/Main.java", "monitor/src/test/resources/logback.xml" ]
[ "monitor/src/test/java/com/iluwatar/monitor/MainTest.java" ]
diff --git a/monitor/src/main/java/com/iluwatar/monitor/Bank.java b/monitor/src/main/java/com/iluwatar/monitor/Bank.java index 6ff65f28cb9a..3f19e0f593a7 100644 --- a/monitor/src/main/java/com/iluwatar/monitor/Bank.java +++ b/monitor/src/main/java/com/iluwatar/monitor/Bank.java @@ -78,12 +78,14 @@ public synchronized void transfer(int accountA, int accountB, int amount) { if (accounts[accountA] >= amount) { accounts[accountB] += amount; accounts[accountA] -= amount; - LOGGER.info( - "Transferred from account: {} to account: {} , amount: {} , balance: {}", - accountA, - accountB, - amount, - getBalance()); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "Transferred from account: {} to account: {} , amount: {} , balance: {}", + accountA, + accountB, + amount, + getBalance()); + } } } diff --git a/monitor/src/main/java/com/iluwatar/monitor/Main.java b/monitor/src/main/java/com/iluwatar/monitor/Main.java index 8b2e8ab47997..923c720d8ef1 100644 --- a/monitor/src/main/java/com/iluwatar/monitor/Main.java +++ b/monitor/src/main/java/com/iluwatar/monitor/Main.java @@ -25,7 +25,7 @@ package com.iluwatar.monitor; import java.security.SecureRandom; -import java.util.concurrent.ExecutorService; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import lombok.extern.slf4j.Slf4j; @@ -40,20 +40,26 @@ @Slf4j public class Main { + private static final int NUMBER_OF_THREADS = 5; + /** * Runner to perform a bunch of transfers and handle exception. * - * @param bank bank object + * @param bank bank object + * @param latch signal finished execution */ - public static void runner(Bank bank) { + public static void runner(Bank bank, CountDownLatch latch) { try { SecureRandom random = new SecureRandom(); Thread.sleep(random.nextInt(1000)); + LOGGER.info("Start transferring..."); for (int i = 0; i < 1000000; i++) { bank.transfer(random.nextInt(4), random.nextInt(4), random.nextInt()); } + LOGGER.info("Finished transferring."); + latch.countDown(); } catch (InterruptedException e) { - LOGGER.info(e.getMessage()); + LOGGER.error(e.getMessage()); Thread.currentThread().interrupt(); } } @@ -63,12 +69,15 @@ public static void runner(Bank bank) { * * @param args command line args */ - public static void main(String[] args) { + public static void main(String[] args) throws InterruptedException { var bank = new Bank(4, 1000); - Runnable runnable = () -> runner(bank); - ExecutorService executorService = Executors.newFixedThreadPool(5); - for (int i = 0; i < 5; i++) { - executorService.execute(runnable); + var latch = new CountDownLatch(NUMBER_OF_THREADS); + var executorService = Executors.newFixedThreadPool(NUMBER_OF_THREADS); + + for (int i = 0; i < NUMBER_OF_THREADS; i++) { + executorService.execute(() -> runner(bank, latch)); } + + latch.await(); } } diff --git a/monitor/src/test/resources/logback.xml b/monitor/src/test/resources/logback.xml new file mode 100644 index 000000000000..ce9892722558 --- /dev/null +++ b/monitor/src/test/resources/logback.xml @@ -0,0 +1,35 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + + The MIT License + Copyright © 2014-2022 Ilkka Seppälä + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + +--> +<configuration> + <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> + <encoder> + <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> + </encoder> + </appender> + <root level="info"> + <appender-ref ref="STDOUT" /> + </root> +</configuration>
diff --git a/monitor/src/test/java/com/iluwatar/monitor/MainTest.java b/monitor/src/test/java/com/iluwatar/monitor/MainTest.java index 360a897fd6a6..4d1c217372d7 100644 --- a/monitor/src/test/java/com/iluwatar/monitor/MainTest.java +++ b/monitor/src/test/java/com/iluwatar/monitor/MainTest.java @@ -25,6 +25,7 @@ package com.iluwatar.monitor; import org.junit.jupiter.api.Test; +import java.util.concurrent.CountDownLatch; import static org.junit.jupiter.api.Assertions.*; /** Test if the application starts without throwing an exception. */ @@ -38,6 +39,9 @@ void shouldExecuteApplicationWithoutException() { @Test void RunnerExecuteWithoutException() { var bank = new Bank(4, 1000); - assertDoesNotThrow(() -> Main.runner(bank)); + var latch = new CountDownLatch(1); + + assertDoesNotThrow(() -> Main.runner(bank, latch)); + assertEquals(0, latch.getCount()); } }
train
val
2022-11-30T18:02:38
"2022-11-30T17:15:55Z"
iluwatar
train
iluwatar/java-design-patterns/1295_2384
iluwatar/java-design-patterns
iluwatar/java-design-patterns/1295
iluwatar/java-design-patterns/2384
[ "timestamp(timedelta=173.0, similarity=0.9952417275087242)" ]
7d2832f4124a1ccbe1ba67c003330ad78b188207
b2eb312b5e18179051f5dc12bddff27a1c6388fe
[ "Hi can I work on this issue?", "Yes, @kevinjplee. Please proceed!", "Thank you!\r\n\r\n> \r\n> \r\n> Yes, @kevinjplee. Please proceed!\r\n\r\n", "Can I work on this issue?", "Hi, can I take up this issue as a part of an Australian National University group project? Thanks @iluwatar ", "Assigned to @shivu2002a since he was the first. @kiratalreja3 I hope you find something else that interests you", "@iluwatar Thank you for assigning me. What's the deadline to solve this issue?", "I'm not too strict, but if you would like to participate in Hacktoberfest, better do it during this month", "Yeah sure. Thank you.", "@iluwatar Hi. This pattern falls under the Relational-Structural design patterns but this category is not on the list of [categories and tags](https://github.com/iluwatar/java-design-patterns/wiki/07.-Categories-and-Tags), but there is a Structural pattern. I needed your suggestion regarding this and also about the tag that should be mentioned for this pattern. Thank you.", "@shivu2002a I think we can use structural then (close enough)", "@iluwatar #2164 Need to be reviewed ", "This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.\n", "@shivu2002a, please address the review comments", "@iluwatar I've made a commit saying 'adding suggested changes'. \r\n[Here it is](https://github.com/iluwatar/java-design-patterns/pull/2164/commits/904d7997f02fef8e2ee9d971c7698cd54af7d017)\r\nShould I address them separately one by one?" ]
[]
"2022-12-04T11:12:00Z"
[ "epic: pattern", "type: feature" ]
Embedded Value pattern
https://www.youtube.com/watch?v=6n5O5mCdnew
[ "pom.xml" ]
[ "embedded-value/README.md", "embedded-value/etc/embedded-value.urm.puml", "embedded-value/pom.xml", "embedded-value/src/main/java/com/iluwatar/embedded/value/App.java", "embedded-value/src/main/java/com/iluwatar/embedded/value/DataSource.java", "embedded-value/src/main/java/com/iluwatar/embedded/value/DataSourceInterface.java", "embedded-value/src/main/java/com/iluwatar/embedded/value/Order.java", "embedded-value/src/main/java/com/iluwatar/embedded/value/ShippingAddress.java", "pom.xml" ]
[ "embedded-value/src/test/java/com/iluwatar/embedded/value/AppTest.java" ]
diff --git a/embedded-value/README.md b/embedded-value/README.md new file mode 100644 index 000000000000..dc924cb45a0f --- /dev/null +++ b/embedded-value/README.md @@ -0,0 +1,124 @@ +--- +title: Embedded Value +category: Structural +language: en +tag: + - Data Access + - Enterprise Application Pattern +--- + +## Also known as +Aggregate Mapping, Composer + +## Intent +Many small objects make sense in an OO system that don’t make sense as +tables in a database. An Embedded Value maps the values of an object to fields in the record of the object’s owner. + +## Explanation + +Real-world example + +> Examples include currency-aware money objects and date +ranges. Although the default thinking is to save an object as a table, no sane person would want a table of money values. +> Another example would be the online orders which have a shipping address like street, city, state. We map these values of Shipping address object to fields in record of Order object. + +In plain words + +> Embedded value pattern let's you map an object into several fields of another object’s table. + +**Programmatic Example** + +Consider online order's example where we have details of item ordered and shipping address. We have Shipping address embedded in Order object. But in database we map shipping address values in Order record instead of creating a separate table for Shipping address and using foreign key to reference the order object. + +First, we have POJOs `Order` and `ShippingAddress` + +```java +public class Order { + + private int id; + private String item; + private String orderedBy; + private ShippingAddress ShippingAddress; + + public Order(String item, String orderedBy, ShippingAddress ShippingAddress) { + this.item = item; + this.orderedBy = orderedBy; + this.ShippingAddress = ShippingAddress; + } +``` +```java +public class ShippingAddress { + + private String city; + private String state; + private String pincode; + + public ShippingAddress(String city, String state, String pincode) { + this.city = city; + this.state = state; + this.pincode = pincode; + } +} +``` +Now, we have to create only one table for Order along with fields for shipping address attributes. + +```Sql +CREATE TABLE Orders (Id INT AUTO_INCREMENT, item VARCHAR(50) NOT NULL, orderedBy VARCHAR(50) city VARCHAR(50), state VARCHAR(50), pincode CHAR(6) NOT NULL, PRIMARY KEY(Id)) +``` + +While performing the database queries and inserts, we box and unbox shipping address details. + +```java +final String INSERT_ORDER = "INSERT INTO Orders (item, orderedBy, city, state, pincode) VALUES (?, ?, ?, ?, ?)"; + +public boolean insertOrder(Order order) throws Exception { + var insertOrder = new PreparedStatement(INSERT_ORDER); + var address = order.getShippingAddress(); + conn.setAutoCommit(false); + insertIntoOrders.setString(1, order.getItem()); + insertIntoOrders.setString(2, order.getOrderedBy()); + insertIntoOrders.setString(3, address.getCity()); + insertIntoOrders.setString(4, address.getState()); + insertIntoOrders.setString(5, address.getPincode()); + + var affectedRows = insertIntoOrders.executeUpdate(); + if(affectedRows == 1){ + Logger.info("Inserted successfully"); + }else{ + Logger.info("Couldn't insert " + order); + } +} +``` + +## Class diagram +![alt text](./etc/embedded-value.urm.png "Embedded value class diagram") + +## Applicability + +Use the Embedded value pattern when + +* Many small objects make sense in an OO system that don’t make sense as tables in a database. +* The simplest cases for Embedded Value are the clear, simple Value Objects like money and date range. +* If you’re mapping to an existing schema, you can use this pattern when a table contains data that you want to split into more than one object in memory. This can occur when you want to factor out some behaviour in object model. +* In most cases you’ll only use Embedded Value on a reference object when the association between them is single valued at both ends (a one-to-one association). +* It can only be used for fairly simple dependents. A solitary dependent, or a few separated dependents, works well. + +## Tutorials + +* [Dzone](https://dzone.com/articles/practical-php-patterns/practical-php-patterns-3) +* [Ram N Java](https://ramj2ee.blogspot.com/2013/08/embedded-value-design-pattern.html) +* [Five's Weblog](https://powerdream5.wordpress.com/2007/10/09/embedded-value/) + +## Consequences + +* The great advantage of Embedded Value is that it allows SQL queries to be made against the values in the dependent object. +* The embedded value object has no persistence behaviour at all. +* While using this, you have to be careful that any change to the dependent marks the owner as dirty—which isn’t an issue with Value Objects that are replaced in the owner. +* Another issue is the loading and saving. If you only load the embedded object memory when you load the owner, that’s an argument for saving both in the same table. +* Another question is whether you’ll want to access the embedded objects' data separately through SQL. This can be important if you’re reporting through SQL and don’t have a separate database for reporting. + + +## Credits + +* [Fowler, Martin - Patterns of enterprise application architecture-Addison-Wesley](https://www.amazon.com/Patterns-Enterprise-Application-Architecture-Martin/dp/0321127420) +* [Ram N Java](https://ramj2ee.blogspot.com/2013/08/embedded-value-design-pattern.html) \ No newline at end of file diff --git a/embedded-value/etc/embedded-value.urm.puml b/embedded-value/etc/embedded-value.urm.puml new file mode 100644 index 000000000000..ed73802792a2 --- /dev/null +++ b/embedded-value/etc/embedded-value.urm.puml @@ -0,0 +1,79 @@ +@startuml +package com.iluwatar.embedded.value { + class App { + - LOGGER : Logger {static} + + App() + + main(args : String[]) {static} + } + class DataSource { + - LOGGER : Logger {static} + - conn : Connection + - createschema : Statement + - deleteschema : Statement + - getschema : Statement + - insertIntoOrders : PreparedStatement + - queryOrders : Statement + - queyOrderByID : PreparedStatement + - removeorder : PreparedStatement + + DataSource() + + createSchema() : boolean + + deleteSchema() : boolean + + getSchema() : String + + insertOrder(order : Order) : boolean + + queryOrder(id : int) : Order + + queryOrders() : Stream<Order> + + removeOrder(id : int) + } + ~interface DataSourceInterface { + + CREATE_SCHEMA : String {static} + + DELETE_SCHEMA : String {static} + + GET_SCHEMA : String {static} + + INSERT_ORDER : String {static} + + JDBC_URL : String {static} + + QUERY_ORDER : String {static} + + QUERY_ORDERS : String {static} + + REMOVE_ORDER : String {static} + + createSchema() : boolean {abstract} + + deleteSchema() : boolean {abstract} + + getSchema() : String {abstract} + + insertOrder(Order) : boolean {abstract} + + queryOrder(int) : Order {abstract} + + queryOrders() : Stream<Order> {abstract} + + removeOrder(int) {abstract} + } + class Order { + - id : int + - item : String + - orderedBy : String + - shippingAddress : ShippingAddress + + Order() + + Order(id : int, item : String, orderedBy : String, shippingAddress : ShippingAddress) + + Order(item : String, orderedBy : String, shippingAddress : ShippingAddress) + + getId() : int + + getItem() : String + + getOrderedBy() : String + + getShippingAddress() : ShippingAddress + + setId(id : int) + + setItem(item : String) + + setOrderedBy(orderedBy : String) + + setShippingAddress(shippingAddress : ShippingAddress) + + toString() : String + } + class ShippingAddress { + - city : String + - pincode : String + - state : String + + ShippingAddress() + + ShippingAddress(city : String, state : String, pincode : String) + + getCity() : String + + getPincode() : String + + getState() : String + + setCity(city : String) + + setPincode(pincode : String) + + setState(state : String) + + toString() : String + } +} +Order --> "-shippingAddress" ShippingAddress +DataSource ..|> DataSourceInterface +@enduml \ No newline at end of file diff --git a/embedded-value/pom.xml b/embedded-value/pom.xml new file mode 100644 index 000000000000..ccef450e4bfc --- /dev/null +++ b/embedded-value/pom.xml @@ -0,0 +1,66 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + + This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + + The MIT License + Copyright © 2014-2022 Ilkka Seppälä + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + +--> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>com.iluwatar</groupId> + <artifactId>java-design-patterns</artifactId> + <version>1.26.0-SNAPSHOT</version> + </parent> + <artifactId>embedded-value</artifactId> + <dependencies> + <dependency> + <groupId>com.h2database</groupId> + <artifactId>h2</artifactId> + </dependency> + <dependency> + <groupId>org.junit.jupiter</groupId> + <artifactId>junit-jupiter-engine</artifactId> + <scope>test</scope> + </dependency> + </dependencies> + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-assembly-plugin</artifactId> + <executions> + <execution> + <configuration> + <archive> + <manifest> + <mainClass>com.iluwatar.embedded.value.App</mainClass> + </manifest> + </archive> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> +</project> \ No newline at end of file diff --git a/embedded-value/src/main/java/com/iluwatar/embedded/value/App.java b/embedded-value/src/main/java/com/iluwatar/embedded/value/App.java new file mode 100644 index 000000000000..9e5011c5980e --- /dev/null +++ b/embedded-value/src/main/java/com/iluwatar/embedded/value/App.java @@ -0,0 +1,114 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.embedded.value; + +import java.util.stream.Collectors; + +import lombok.extern.slf4j.Slf4j; + +/* + * Many small objects make sense in an OO system that don’t make sense as + * tables in a database. Examples include currency-aware money objects (amount, currency) and date + * ranges. Although the default thinking is to save an object as a table, no sane + * person would want a table of money values. + * + * An Embedded Value maps the values of an object to fields in the record of + * the object’s owner. In this implementation we have an Order object with links to an + * ShippingAddress object. In the resulting table the fields in the ShippingAddress + * object map to fields in the Order table rather than make new records + * themselves. + */ + +@Slf4j +public class App { + + /** + * Program entry point. + * + * @param args command line args. + * @throws Exception if any error occurs. + * + */ + public static void main(String[] args) throws Exception { + final var dataSource = new DataSource(); + + // Orders to insert into database + final var order1 = new Order("JBL headphone", "Ram", + new ShippingAddress("Bangalore", "Karnataka", "560040")); + final var order2 = new Order("MacBook Pro", "Manjunath", + new ShippingAddress("Bangalore", "Karnataka", "581204")); + final var order3 = new Order("Carrie Soto is Back", "Shiva", + new ShippingAddress("Bangalore", "Karnataka", "560004")); + + /** + * Create table for orders - Orders(id, name, orderedBy, city, state, pincode). + * We can see that table is different from the Order object we have. + * We're mapping ShippingAddress into city, state, pincode colummns of the database and not creating a separate table. + */ + if (dataSource.createSchema()) { + LOGGER.info("TABLE CREATED"); + LOGGER.info("Table \"Orders\" schema:\n" + dataSource.getSchema()); + } else { + //If not able to create table, there's nothing we can do further. + LOGGER.error("Error creating table"); + System.exit(0); + } + + // Initially, database is empty + LOGGER.info("Orders Query: {}", dataSource.queryOrders().collect(Collectors.toList())); + + //Insert orders where shippingAddress is mapped to different columns of the same table + dataSource.insertOrder(order1); + dataSource.insertOrder(order2); + dataSource.insertOrder(order3); + + /** + * Query orders + * We'll create ShippingAddress object from city, state, pincode values from the table + * and add it to Order object + */ + LOGGER.info("Orders Query: {}", dataSource.queryOrders().collect(Collectors.toList()) + "\n"); + + //Query order by given id + LOGGER.info("Query Order with id=2: {}", dataSource.queryOrder(2)); + + /** + * Remove order by given id. + * Since we'd mapped address in the same table, deleting order will also take + * out the shipping address details + */ + LOGGER.info("Remove Order with id=1"); + dataSource.removeOrder(1); + LOGGER.info("\nOrders Query: {}", dataSource.queryOrders().collect(Collectors.toList()) + "\n"); + + //After successfull demonstration of the pattern, drop the table + if (dataSource.deleteSchema()) { + LOGGER.info("TABLE DROPPED"); + } else { + //If there's a potential error while dropping table + LOGGER.error("Error deleting table"); + } + } +} diff --git a/embedded-value/src/main/java/com/iluwatar/embedded/value/DataSource.java b/embedded-value/src/main/java/com/iluwatar/embedded/value/DataSource.java new file mode 100644 index 000000000000..e2ec2ed7c023 --- /dev/null +++ b/embedded-value/src/main/java/com/iluwatar/embedded/value/DataSource.java @@ -0,0 +1,217 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.embedded.value; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.stream.Stream; + +import lombok.extern.slf4j.Slf4j; +/* + * Communicates with H2 database with the help of JDBC API + * + * Inherits the SQL queries and methods from @link AbstractDataSource class + */ + +@Slf4j +public class DataSource implements DataSourceInterface { + private Connection conn; + + /** + * Statements are objects which are used to execute queries which will not be + * repeated. + */ + private Statement getschema; + private Statement deleteschema; + private Statement queryOrders; + + /* + * PreparedStatements are used to execute queries which will be repeated. + */ + private PreparedStatement insertIntoOrders; + private PreparedStatement removeorder; + private PreparedStatement queyOrderByID; + + /** + * {@summary} + * Establish connection to database. + */ + public DataSource() { + try { + conn = DriverManager.getConnection(JDBC_URL); + LOGGER.info("Connected to H2 in-memory database: " + conn.getCatalog()); + } catch (SQLException e) { + LOGGER.error(e.getLocalizedMessage(), e.getCause()); + } + } + + @Override + public boolean createSchema() { + try (Statement createschema = conn.createStatement()) { + createschema.execute(CREATE_SCHEMA); + insertIntoOrders = conn.prepareStatement(INSERT_ORDER, PreparedStatement.RETURN_GENERATED_KEYS); + getschema = conn.createStatement(); + queryOrders = conn.createStatement(); + removeorder = conn.prepareStatement(REMOVE_ORDER); + queyOrderByID = conn.prepareStatement(QUERY_ORDER); + deleteschema = conn.createStatement(); + } catch (SQLException e) { + LOGGER.error(e.getLocalizedMessage(), e.getCause()); + return false; + } + return true; + } + + @Override + public String getSchema() { + try { + var resultSet = getschema.executeQuery(GET_SCHEMA); + var sb = new StringBuilder(); + while (resultSet.next()) { + sb.append("Col name: " + resultSet.getString(1) + ", Col type: " + resultSet.getString(2) + "\n"); + } + getschema.close(); + return sb.toString(); + } catch (Exception e) { + LOGGER.error("Error in retrieving schema: {}", e.getLocalizedMessage(), e.getCause()); + } + return "Schema unavailable"; + } + + @Override + public boolean insertOrder(Order order) { + try { + conn.setAutoCommit(false); + insertIntoOrders.setString(1, order.getItem()); + insertIntoOrders.setString(2, order.getOrderedBy()); + var address = order.getShippingAddress(); + insertIntoOrders.setString(3, address.getCity()); + insertIntoOrders.setString(4, address.getState()); + insertIntoOrders.setString(5, address.getPincode()); + var affectedRows = insertIntoOrders.executeUpdate(); + if (affectedRows == 1) { + var rs = insertIntoOrders.getGeneratedKeys(); + rs.last(); + var insertedAddress = new ShippingAddress(address.getCity(), address.getState(), address.getPincode()); + var insertedOrder = new Order(rs.getInt(1), order.getItem(), order.getOrderedBy(), + insertedAddress); + conn.commit(); + LOGGER.info("Inserted: {}", insertedOrder); + } else { + conn.rollback(); + } + } catch (Exception e) { + LOGGER.error(e.getLocalizedMessage()); + } finally { + try { + conn.setAutoCommit(true); + } catch (SQLException e) { + LOGGER.error(e.getLocalizedMessage()); + } + } + return true; + } + + @Override + public Stream<Order> queryOrders() { + var ordersList = new ArrayList<Order>(); + try (var rSet = queryOrders.executeQuery(QUERY_ORDERS)) { + while (rSet.next()) { + var order = new Order(rSet.getInt(1), rSet.getString(2), rSet.getString(3), + new ShippingAddress(rSet.getString(4), rSet.getString(5), + rSet.getString(6))); + ordersList.add(order); + } + rSet.close(); + } catch (SQLException e) { + LOGGER.error(e.getMessage(), e.getCause()); + } + return ordersList.stream(); + } + + /** + * {@summary} + * Query order by given id. + * @param id as the parameter + * @return Order objct + * @throws SQLException in case of unexpected events + */ + + @Override + public Order queryOrder(int id) throws SQLException { + Order order = null; + queyOrderByID.setInt(1, id); + try (var rSet = queyOrderByID.executeQuery()) { + queyOrderByID.setInt(1, id); + if (rSet.next()) { + var address = new ShippingAddress(rSet.getString(4), + rSet.getString(5), rSet.getString(6)); + order = new Order(rSet.getInt(1), rSet.getString(2), rSet.getString(3), address); + } + rSet.close(); + } catch (Exception e) { + LOGGER.error(e.getLocalizedMessage(), e.getCause()); + } + return order; + } + + @Override + public void removeOrder(int id) throws Exception { + try { + conn.setAutoCommit(false); + removeorder.setInt(1, id); + if (removeorder.executeUpdate() == 1) { + LOGGER.info("Order with id " + id + " successfully removed"); + } else { + LOGGER.info("Order with id " + id + " unavailable."); + } + } catch (Exception e) { + LOGGER.error(e.getLocalizedMessage(), e.getCause()); + conn.rollback(); + } finally { + conn.setAutoCommit(true); + } + } + + @Override + public boolean deleteSchema() throws Exception { + try { + deleteschema.execute(DELETE_SCHEMA); + queryOrders.close(); + queyOrderByID.close(); + deleteschema.close(); + insertIntoOrders.close(); + conn.close(); + return true; + } catch (Exception e) { + LOGGER.error(e.getLocalizedMessage(), e.getCause()); + } + return false; + } +} diff --git a/embedded-value/src/main/java/com/iluwatar/embedded/value/DataSourceInterface.java b/embedded-value/src/main/java/com/iluwatar/embedded/value/DataSourceInterface.java new file mode 100644 index 000000000000..deddf55b93ac --- /dev/null +++ b/embedded-value/src/main/java/com/iluwatar/embedded/value/DataSourceInterface.java @@ -0,0 +1,69 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.embedded.value; + +import java.sql.SQLException; +import java.util.stream.Stream; + +/* + * Abstract class which contains the required SQL queries and basic methods declaration. + * + * The main thing to consider is that the ShippingAddress object doesn't have it's own class + * but it's values are stored into the Orders table as city, state, pincode + * + */ +interface DataSourceInterface { + + final String JDBC_URL = "jdbc:h2:mem:Embedded-Value"; + + final String CREATE_SCHEMA = "CREATE TABLE Orders (Id INT AUTO_INCREMENT, item VARCHAR(50) NOT NULL, orderedBy VARCHAR(50)" + + ", city VARCHAR(50), state VARCHAR(50), pincode CHAR(6) NOT NULL, PRIMARY KEY(Id))"; + + final String GET_SCHEMA = "SHOW COLUMNS FROM Orders"; + + final String INSERT_ORDER = "INSERT INTO Orders (item, orderedBy, city, state, pincode) VALUES(?, ?, ?, ?, ?)"; + + final String QUERY_ORDERS = "SELECT * FROM Orders"; + + final String QUERY_ORDER = QUERY_ORDERS + " WHERE Id = ?"; + + final String REMOVE_ORDER = "DELETE FROM Orders WHERE Id = ?"; + + final String DELETE_SCHEMA = "DROP TABLE Orders"; + + boolean createSchema() throws SQLException; + + String getSchema() throws SQLException; + + boolean insertOrder(Order order) throws SQLException; + + Stream<Order> queryOrders() throws SQLException; + + Order queryOrder(int id) throws SQLException; + + void removeOrder(int id) throws Exception; + + boolean deleteSchema() throws Exception; +} diff --git a/embedded-value/src/main/java/com/iluwatar/embedded/value/Order.java b/embedded-value/src/main/java/com/iluwatar/embedded/value/Order.java new file mode 100644 index 000000000000..9c87a83f6ec0 --- /dev/null +++ b/embedded-value/src/main/java/com/iluwatar/embedded/value/Order.java @@ -0,0 +1,61 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.embedded.value; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; +/* + * A POJO which represents the Order object. + */ +@ToString +@Setter +@Getter +public class Order { + + private int id; + private String item; + private String orderedBy; + private ShippingAddress shippingAddress; + + /** + * Constructor for Item object. + * @param item item name + * @param orderedBy item orderer + * @param shippingAddress shipping address details + */ + + public Order(String item, String orderedBy, ShippingAddress shippingAddress) { + this.item = item; + this.orderedBy = orderedBy; + this.shippingAddress = shippingAddress; + } + + public Order(int id, String item, String orderedBy, ShippingAddress shippingAddress) { + this(item, orderedBy, shippingAddress); + this.id = id; + } + +} diff --git a/embedded-value/src/main/java/com/iluwatar/embedded/value/ShippingAddress.java b/embedded-value/src/main/java/com/iluwatar/embedded/value/ShippingAddress.java new file mode 100644 index 000000000000..9b04519dd17e --- /dev/null +++ b/embedded-value/src/main/java/com/iluwatar/embedded/value/ShippingAddress.java @@ -0,0 +1,54 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.embedded.value; + +import lombok.Getter; +import lombok.ToString; + +/** + * Another POJO which wraps the Shipping details of order into Object. + */ +@ToString +@Getter +public class ShippingAddress { + + private String city; + private String state; + private String pincode; + + /** + * Constructor for Shipping Address object. + * @param city City name + * @param state State name + * @param pincode Pin code of the city + * + */ + public ShippingAddress(String city, String state, String pincode) { + this.city = city; + this.state = state; + this.pincode = pincode; + } +} + diff --git a/pom.xml b/pom.xml index 68714e28a007..3f491033a80a 100644 --- a/pom.xml +++ b/pom.xml @@ -198,6 +198,7 @@ <module>composite-view</module> <module>metadata-mapping</module> <module>service-to-worker</module> + <module>embedded-value</module> <module>currying</module> <module>serialized-entity</module> <module>identity-map</module>
diff --git a/embedded-value/src/test/java/com/iluwatar/embedded/value/AppTest.java b/embedded-value/src/test/java/com/iluwatar/embedded/value/AppTest.java new file mode 100644 index 000000000000..1e97bfabc36f --- /dev/null +++ b/embedded-value/src/test/java/com/iluwatar/embedded/value/AppTest.java @@ -0,0 +1,41 @@ +/* + * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). + * + * The MIT License + * Copyright © 2014-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.embedded.value; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.junit.jupiter.api.Test; + +/** + * Check whether the execution of the main method in {@link App} + * throws an exception. +*/ +public class AppTest { + + @Test + public void doesNotThrowException() { + assertDoesNotThrow(() -> App.main(new String[] {})); + } +}
val
val
2022-12-04T10:53:17
"2020-07-07T17:33:47Z"
iluwatar
train
iluwatar/java-design-patterns/2399_2400
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2399
iluwatar/java-design-patterns/2400
[ "keyword_pr_to_issue" ]
9a92930dfae8945c6a3ba61e73ee147296e825b3
3be7664dd463c9ba7bc41cc55b05bba9152ca341
[ "Kind of works, see https://github.com/iluwatar/java-design-patterns/pull/2398, but maybe we can improve it" ]
[]
"2022-12-17T20:41:11Z"
[ "type: bug", "epic: build issue" ]
Project not found. Please check the 'sonar.projectKey' and 'sonar.organization' properties
When you try to build the project using `./mvnw clean verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonarit` gives the following error: ### Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.8.0.2131:sonar (default-cli) on project java-design-patterns: Project not found. Please check the 'sonar.projectKey' and 'sonar.organization' properties, the 'SONAR_TOKEN' environment variable, or contact the project administrator Both in local and when you try to do the pull request. If the project is no longer in the sonarcloud, it can be a suggestion to remove the following dependencies: ``` <sonar.host.url>https://sonarcloud.io</sonar.host.url> <sonar.organization>iluwatar</sonar.organization> <sonar.projectKey>iluwatar_java-design-patterns</sonar.projectKey> <sonar.moduleKey>${project.artifactId}</sonar.moduleKey> <sonar.projectName>Java Design Patterns</sonar.projectName> ``` and to build using: `./mvnw clean verify` In order to continue to build the project and do pull request without building errors.
[ ".github/workflows/maven-pr-builder.yml" ]
[ ".github/workflows/maven-pr-builder.yml" ]
[]
diff --git a/.github/workflows/maven-pr-builder.yml b/.github/workflows/maven-pr-builder.yml index 51ffbbcb9089..f2699a9c9c93 100644 --- a/.github/workflows/maven-pr-builder.yml +++ b/.github/workflows/maven-pr-builder.yml @@ -28,6 +28,7 @@ name: Java PR Builder on: pull_request: + pull_request_target: branches: [ master ] types: [ opened, reopened, synchronize ]
null
train
val
2022-12-10T15:56:47
"2022-12-17T14:07:33Z"
girolamo-giordano
train
iluwatar/java-design-patterns/2399_2402
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2399
iluwatar/java-design-patterns/2402
[ "keyword_pr_to_issue" ]
3be7664dd463c9ba7bc41cc55b05bba9152ca341
9262dc52b400845fae37e08ce17382de6f53ca75
[ "Kind of works, see https://github.com/iluwatar/java-design-patterns/pull/2398, but maybe we can improve it" ]
[]
"2022-12-18T13:18:32Z"
[ "type: bug", "epic: build issue" ]
Project not found. Please check the 'sonar.projectKey' and 'sonar.organization' properties
When you try to build the project using `./mvnw clean verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonarit` gives the following error: ### Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.8.0.2131:sonar (default-cli) on project java-design-patterns: Project not found. Please check the 'sonar.projectKey' and 'sonar.organization' properties, the 'SONAR_TOKEN' environment variable, or contact the project administrator Both in local and when you try to do the pull request. If the project is no longer in the sonarcloud, it can be a suggestion to remove the following dependencies: ``` <sonar.host.url>https://sonarcloud.io</sonar.host.url> <sonar.organization>iluwatar</sonar.organization> <sonar.projectKey>iluwatar_java-design-patterns</sonar.projectKey> <sonar.moduleKey>${project.artifactId}</sonar.moduleKey> <sonar.projectName>Java Design Patterns</sonar.projectName> ``` and to build using: `./mvnw clean verify` In order to continue to build the project and do pull request without building errors.
[ ".github/workflows/maven-pr-builder.yml" ]
[ ".github/workflows/maven-pr-builder.yml" ]
[]
diff --git a/.github/workflows/maven-pr-builder.yml b/.github/workflows/maven-pr-builder.yml index f2699a9c9c93..fb1fdbe84f7d 100644 --- a/.github/workflows/maven-pr-builder.yml +++ b/.github/workflows/maven-pr-builder.yml @@ -27,7 +27,6 @@ name: Java PR Builder on: - pull_request: pull_request_target: branches: [ master ] types: [ opened, reopened, synchronize ]
null
val
val
2022-12-17T22:25:09
"2022-12-17T14:07:33Z"
girolamo-giordano
train
iluwatar/java-design-patterns/2421_2429
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2421
iluwatar/java-design-patterns/2429
[ "timestamp(timedelta=76.0, similarity=0.9296612699032656)" ]
6205f7dd82098bc4bb2102dec3ec8747abe1fa59
95203520bc910fd7b4e261d30d8bc17f8d86104a
[ "Subtask of https://github.com/iluwatar/java-design-patterns/issues/2282" ]
[]
"2023-01-05T12:40:00Z"
[ "type: feature", "epic: translation" ]
Translate event-driven-architecture readme file into Korean
I wanna translate `event-driven-architecture` readme file into Korean, if possible.
[]
[ "localization/ko/event-driven-architecture/README.md" ]
[]
diff --git a/localization/ko/event-driven-architecture/README.md b/localization/ko/event-driven-architecture/README.md new file mode 100644 index 000000000000..0296076db582 --- /dev/null +++ b/localization/ko/event-driven-architecture/README.md @@ -0,0 +1,33 @@ +--- +title: Event Driven Architecture +category: Architectural +language: ko +tag: +- Reactive +--- + +## 의도 +이벤트 드리븐 아키텍처를 사용하는 다른 어플리케이션에 특정 객체의 상태 변화를 알리고 관련 이벤트를 발송할 수 있습니다. + +## 클래스 다이어그램 +![alt text](./etc/eda.png "Event Driven Architecture") + +## 적용 가능성 +아래와 같은 상황에서 이벤트 드리븐 아키텍처를 사용할 수 있습니다. + +* 느슨하게 연결된 시스템을 구축하고자 하는 경우 +* 반응형 시스템을 구축하고자 하는 경우 +* 확장성을 갖춘 시스템을 구축하고자 하는 경우 + +## 실제 적용 사례 + +* Chargify라는 결제 API에서는 다양한 이벤트를 통해 결제 활동을 드러냅니다. (https://docs.chargify.com/api-events) +* Amazon의 AWS Lambda에서는 Amazon S3 버킷에서의 변경, Amazon DynamoDB 테이블에서의 수정이나 어플리케이션 및 기기에서 발생한 커스텀 이벤트에 대응하여 코드를 실행할 수 있습니다. (https://aws.amazon.com/lambda) +* MySQL은 데이터베이스 테이블에서 발생하는 삽입이나 수정 이벤트를 기반으로 트리거를 실행합니다. + +## 크레딧 + +* [이벤트 드리븐 아키텍처 - 위키피디아](https://en.wikipedia.org/wiki/Event-driven_architecture) +* [이벤트 드리븐 아키텍처는 무엇인가?](https://aws.amazon.com/event-driven-architecture/) +* [실제 적용 사례/이벤트 드리븐 아키텍처](https://wiki.haskell.org/Real_World_Applications/Event_Driven_Applications) +* [이벤트 드리븐 아키텍처의 정의](http://searchsoa.techtarget.com/definition/event-driven-architecture)
null
train
val
2023-01-05T17:20:56
"2023-01-04T14:15:19Z"
hwan33
train
iluwatar/java-design-patterns/2428_2430
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2428
iluwatar/java-design-patterns/2430
[ "timestamp(timedelta=113.0, similarity=0.8610188056997489)" ]
6205f7dd82098bc4bb2102dec3ec8747abe1fa59
acf55c934f88a577d4ab2ba2297da3ab16bc9c23
[]
[]
"2023-01-05T12:40:23Z"
[ "type: bug", "epic: documentation" ]
Typo in javadoc of event-driven-architecture
I found some typos in javadoc. It's such a minor things, but I want to correct them.
[ "event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserCreatedEvent.java", "event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserUpdatedEvent.java", "event-driven-architecture/src/main/java/com/iluwatar/eda/framework/EventDispatcher.java", "event-driven-architecture/src/main/java/com/iluwatar/eda/framework/Handler.java" ]
[ "event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserCreatedEvent.java", "event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserUpdatedEvent.java", "event-driven-architecture/src/main/java/com/iluwatar/eda/framework/EventDispatcher.java", "event-driven-architecture/src/main/java/com/iluwatar/eda/framework/Handler.java" ]
[ "event-driven-architecture/src/test/java/com/iluwatar/eda/AppTest.java" ]
diff --git a/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserCreatedEvent.java b/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserCreatedEvent.java index f7be8cb6cb0e..245f79b4cbca 100644 --- a/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserCreatedEvent.java +++ b/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserCreatedEvent.java @@ -29,9 +29,9 @@ import lombok.RequiredArgsConstructor; /** - * The {@link UserCreatedEvent} should should be dispatched whenever a user has been created. This - * class can be extended to contain details about the user has been created. In this example, the - * entire {@link User} object is passed on as data with the event. + * The {@link UserCreatedEvent} should be dispatched whenever a user has been created. + * This class can be extended to contain details about the user has been created. + * In this example, the entire {@link User} object is passed on as data with the event. */ @RequiredArgsConstructor @Getter diff --git a/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserUpdatedEvent.java b/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserUpdatedEvent.java index 57a5e4586e40..6fa1832cb4f9 100644 --- a/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserUpdatedEvent.java +++ b/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserUpdatedEvent.java @@ -29,9 +29,9 @@ import lombok.RequiredArgsConstructor; /** - * The {@link UserUpdatedEvent} should should be dispatched whenever a user has been updated. This - * class can be extended to contain details about the user has been updated. In this example, the - * entire {@link User} object is passed on as data with the event. + * The {@link UserUpdatedEvent} should be dispatched whenever a user has been updated. + * This class can be extended to contain details about the user has been updated. + * In this example, the entire {@link User} object is passed on as data with the event. */ @RequiredArgsConstructor @Getter diff --git a/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/EventDispatcher.java b/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/EventDispatcher.java index e5edd780a654..1d0fab9d5da7 100644 --- a/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/EventDispatcher.java +++ b/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/EventDispatcher.java @@ -53,7 +53,7 @@ public <E extends Event> void registerHandler( } /** - * Dispatches an {@link Event} depending on it's type. + * Dispatches an {@link Event} depending on its type. * * @param event The {@link Event} to be dispatched */ @@ -65,4 +65,4 @@ public <E extends Event> void dispatch(E event) { } } -} \ No newline at end of file +} diff --git a/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/Handler.java b/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/Handler.java index d81a5c04fcd0..8eb56ca0cb0b 100644 --- a/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/Handler.java +++ b/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/Handler.java @@ -34,7 +34,7 @@ public interface Handler<E extends Event> { /** * The onEvent method should implement and handle behavior related to the event. This can be as - * simple as calling another service to handle the event on publishing the event on a queue to be + * simple as calling another service to handle the event on publishing the event in a queue to be * consumed by other sub systems. * * @param event the {@link Event} object to be handled.
diff --git a/event-driven-architecture/src/test/java/com/iluwatar/eda/AppTest.java b/event-driven-architecture/src/test/java/com/iluwatar/eda/AppTest.java index f4d1f18a8d43..17f3bddaa4a2 100644 --- a/event-driven-architecture/src/test/java/com/iluwatar/eda/AppTest.java +++ b/event-driven-architecture/src/test/java/com/iluwatar/eda/AppTest.java @@ -35,7 +35,7 @@ class AppTest { /** * Issue: Add at least one assertion to this test case. - * + * <p> * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])} * throws an exception. */
train
val
2023-01-05T17:20:56
"2023-01-05T12:31:18Z"
hwan33
train
iluwatar/java-design-patterns/2438_2439
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2438
iluwatar/java-design-patterns/2439
[ "timestamp(timedelta=83.0, similarity=0.9618551908347523)" ]
919d7d0339d7717ad01a307c3d6f0374383910db
2263e248bde25c3be7549058fd489c46497b7f41
[]
[ "remove the extra newline", "Sorry. I'll check it more carefully next time 🤗" ]
"2023-01-06T14:39:09Z"
[ "type: feature", "epic: translation" ]
Translate event-sourcing readme file into Korean
I'll translate.
[]
[ "localization/ko/event-sourcing/README.md" ]
[]
diff --git a/localization/ko/event-sourcing/README.md b/localization/ko/event-sourcing/README.md new file mode 100644 index 000000000000..1d3bd584061c --- /dev/null +++ b/localization/ko/event-sourcing/README.md @@ -0,0 +1,36 @@ +--- +title: Event Sourcing +category: Architectural +language: ko +tag: +- Performance +- Cloud distributed + +--- + +## 의도 + +데이터의 현재 상태만 도메인에 저장하는 대신, 추가 전용 저장소를 사용하여 해당 데이터에 수행된 전체 작업을 기록하십시오. 저장소는 기록 시스템으로서의 역할을 하며 도메인 객체를 구체화하는데 사용할 수 있습니다. 따라서 데이터 모델과 비지니스 도메인을 동기화할 필요가 없고 성능, 확장성 및 응답성이 향상되어 복잡한 도메인에서의 작업을 단순화할 수 있습니다. +또한, 트랜잭션 데이터에 대한 일관성을 제공하고, 보상 작업을 수행할 수 있는 전체 감사용 기록과 히스토리를 유지 관리할 수 있습니다. + +## 클래스 다이어그램 + +![alt text](./etc/event-sourcing.png "Event Sourcing") + +## 적용 가능성 +아래와 같은 상황에서 이벤트 소싱 패턴을 사용할 수 있습니다. + +* 관계형 데이터 구조가 복잡한 어플리케이션 상태를 유지하기 위해 매우 높은 성능이 필요한 경우 +* 어플리케이션 상태의 변경 사항과 특정 시점의 상태를 복원할 수 있는 기능에 대한 로그가 필요한 경우 +* 과거에 발생한 이벤트를 다시 적용하여 프로덕션 문제를 디버깅하는 경우 + +## 실제 적용 사례 + +* [Lmax 아키텍처](https://martinfowler.com/articles/lmax.html) + +## 크레딧 + +* [마틴 파울러 - 이벤트 소싱](https://martinfowler.com/eaaDev/EventSourcing.html) +* [이벤트 소싱에 대한 마이크로소프트의 문서](https://docs.microsoft.com/en-us/azure/architecture/patterns/event-sourcing) +* [레퍼런스 3: 이벤트 소싱에 대한 소개](https://msdn.microsoft.com/en-us/library/jj591559.aspx) +* [이벤트 소싱 패턴](https://docs.microsoft.com/en-us/azure/architecture/patterns/event-sourcing)
null
val
val
2023-01-06T11:34:08
"2023-01-06T12:54:39Z"
hwan33
train
iluwatar/java-design-patterns/2441_2442
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2441
iluwatar/java-design-patterns/2442
[ "timestamp(timedelta=37.0, similarity=0.9219567665722146)" ]
6ba6988d5ee225b6e1b9796bb2587fad4003b8d9
186b5b6ff284c1c232072b19372620a0e6e493cd
[]
[]
"2023-01-07T13:35:26Z"
[ "type: feature", "epic: documentation" ]
Fix typos in javadocs of Event sourcing
I'll correct typos and grammatical errors suggested by ide or sonarlint :)
[ "event-sourcing/README.md", "event-sourcing/src/main/java/com/iluwatar/event/sourcing/app/App.java", "event-sourcing/src/main/java/com/iluwatar/event/sourcing/domain/Account.java", "event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/AccountCreateEvent.java", "event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyDepositEvent.java", "event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyTransferEvent.java", "event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/JsonFileJournal.java" ]
[ "event-sourcing/README.md", "event-sourcing/src/main/java/com/iluwatar/event/sourcing/app/App.java", "event-sourcing/src/main/java/com/iluwatar/event/sourcing/domain/Account.java", "event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/AccountCreateEvent.java", "event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyDepositEvent.java", "event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyTransferEvent.java", "event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/JsonFileJournal.java" ]
[ "event-sourcing/src/test/java/IntegrationTest.java" ]
diff --git a/event-sourcing/README.md b/event-sourcing/README.md index 8bec3c52a4e8..423f892cb24a 100644 --- a/event-sourcing/README.md +++ b/event-sourcing/README.md @@ -16,7 +16,7 @@ Instead of storing just the current state of the data in a domain, use an append ## Applicability Use the Event Sourcing pattern when -* You need very high performance on persisting your application state even your application state have a complex relational data structure +* You need very high performance on persisting your application state even your application state has a complex relational data structure * You need log of changes of your application state and ability to restore a state of any moment in time. * You need to debug production problems by replaying the past events. diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/app/App.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/app/App.java index ac11782cf7d7..d356a8b99f8a 100644 --- a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/app/App.java +++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/app/App.java @@ -34,7 +34,7 @@ import lombok.extern.slf4j.Slf4j; /** - * Event Sourcing : Instead of storing just the current state of the data in a domain, use an + * Event Sourcing: Instead of storing just the current state of the data in a domain, use an * append-only store to record the full series of actions taken on that data. The store acts as the * system of record and can be used to materialize the domain objects. This can simplify tasks in * complex domains, by avoiding the need to synchronize the data model and the business domain, @@ -42,11 +42,11 @@ * transactional data, and maintain full audit trails and history that can enable compensating * actions. * - * <p>This App class is an example usage of Event Sourcing pattern. As an example, two bank account - * is created, then some money deposit and transfer actions are taken so a new state of accounts is - * created. At that point, state is cleared in order to represent a system shot down. After the shot - * down, system state is recovered by re-creating the past events from event journal. Then state is - * printed so a user can view the last state is same with the state before system shot down. + * <p>This App class is an example usage of an Event Sourcing pattern. As an example, two bank accounts + * are created, then some money deposit and transfer actions are taken, so a new state of accounts is + * created. At that point, state is cleared in order to represent a system shut-down. After the shut-down, + * system state is recovered by re-creating the past events from event journals. Then state is + * printed so a user can view the last state is same with the state before a system shut-down. * * <p>Created by Serdar Hamzaogullari on 06.08.2017. */ diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/domain/Account.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/domain/Account.java index 429fd61d262b..177348be86a3 100644 --- a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/domain/Account.java +++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/domain/Account.java @@ -115,7 +115,7 @@ public void handleEvent(MoneyDepositEvent moneyDepositEvent) { /** * Handles the AccountCreateEvent. * - * @param accountCreateEvent the account create event + * @param accountCreateEvent the account created event */ public void handleEvent(AccountCreateEvent accountCreateEvent) { AccountAggregate.putAccount(this); diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/AccountCreateEvent.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/AccountCreateEvent.java index 71ea65ca3419..9e6b40e62ee0 100644 --- a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/AccountCreateEvent.java +++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/AccountCreateEvent.java @@ -29,8 +29,9 @@ import lombok.Getter; /** - * This is the class that implements account create event. Holds the necessary info for an account - * create event. Implements the process function that finds the event related domain objects and + * This is the class that implements account created event. + * Holds the necessary info for an account created event. + * Implements the process function that finds the event-related domain objects and * calls the related domain object's handle event functions * * <p>Created by Serdar Hamzaogullari on 06.08.2017. @@ -42,7 +43,7 @@ public class AccountCreateEvent extends DomainEvent { private final String owner; /** - * Instantiates a new Account create event. + * Instantiates a new Account created event. * * @param sequenceId the sequence id * @param createdTime the created time diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyDepositEvent.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyDepositEvent.java index f094e8f6b61e..96afd4640012 100644 --- a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyDepositEvent.java +++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyDepositEvent.java @@ -31,7 +31,7 @@ /** * This is the class that implements money deposit event. Holds the necessary info for a money - * deposit event. Implements the process function that finds the event related domain objects and + * deposit event. Implements the process function that finds the event-related domain objects and * calls the related domain object's handle event functions * * <p>Created by Serdar Hamzaogullari on 06.08.2017. diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyTransferEvent.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyTransferEvent.java index 2f0a0cb52fdd..18d98cded008 100644 --- a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyTransferEvent.java +++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyTransferEvent.java @@ -31,7 +31,7 @@ /** * This is the class that implements money transfer event. Holds the necessary info for a money - * transfer event. Implements the process function that finds the event related domain objects and + * transfer event. Implements the process function that finds the event-related domain objects and * calls the related domain object's handle event functions * * <p>Created by Serdar Hamzaogullari on 06.08.2017. diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/JsonFileJournal.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/JsonFileJournal.java index 42283c460e64..048e270e2eaa 100644 --- a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/JsonFileJournal.java +++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/JsonFileJournal.java @@ -91,7 +91,7 @@ public void write(DomainEvent domainEvent) { } else if (domainEvent instanceof MoneyTransferEvent) { jsonElement = gson.toJsonTree(domainEvent, MoneyTransferEvent.class); } else { - throw new RuntimeException("Journal Event not recegnized"); + throw new RuntimeException("Journal Event not recognized"); } try (var output = new BufferedWriter( @@ -113,7 +113,7 @@ public void reset() { /** - * Read next domain event. + * Read the next domain event. * * @return the domain event */
diff --git a/event-sourcing/src/test/java/IntegrationTest.java b/event-sourcing/src/test/java/IntegrationTest.java index 6d30a89fc582..9e15a2163bcc 100644 --- a/event-sourcing/src/test/java/IntegrationTest.java +++ b/event-sourcing/src/test/java/IntegrationTest.java @@ -37,7 +37,7 @@ import org.junit.jupiter.api.Test; /** - * Intergartion Test for Event Sourcing state recovery + * Integration Test for Event-Sourcing state recovery * <p> * Created by Serdar Hamzaogullari on 19.08.2017. */ @@ -95,4 +95,4 @@ void testStateRecovery() { assertEquals(accountOfJonBeforeShotDown.getMoney(), accountOfJonAfterShotDown.getMoney()); } -} \ No newline at end of file +}
test
test
2023-01-06T18:30:02
"2023-01-07T13:33:55Z"
hwan33
train
iluwatar/java-design-patterns/2281_2444
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2281
iluwatar/java-design-patterns/2444
[ "keyword_pr_to_issue" ]
42ba121977da2961b990512bba1de2de6c426629
4da36e7826ea418909924a113bbfe11ddbe6044d
[ "Hi @iluwatar, I will work on this because I'm Japanese! It seems there are fewer materials that were translated into Japanese compared to other languages..." ]
[ "Could you check that the image is found in this location? I think it currently resides in `localization/ja/decorator/decorator.urm.png`", "@iluwatar \r\nOops... Sorry about that. I moved the image under `etc` directory\r\n\r\nhttps://github.com/iluwatar/java-design-patterns/pull/2444/commits/2832ffa4461868153178a7969f036f689ce56cc1" ]
"2023-01-08T10:08:06Z"
[ "info: help wanted", "type: feature", "epic: documentation" ]
Translate to Japanese
This task tracks the translation of the patterns. More information about the translation process is available at https://github.com/iluwatar/java-design-patterns/wiki/15.-Support-for-multiple-languages Acceptance criteria - The patterns have been translated - The patterns can be browsed in Github and on the website https://java-design-patterns.com
[]
[ "localization/ja/decorator/README.md" ]
[]
diff --git a/localization/ja/decorator/README.md b/localization/ja/decorator/README.md new file mode 100644 index 000000000000..d67bfb805459 --- /dev/null +++ b/localization/ja/decorator/README.md @@ -0,0 +1,160 @@ +--- +title: Decorator +category: Structural +language: ja +tag: + - Gang of Four + - Extensibility +--- + +## 別名 + +Wrapper + +## 目的 + +オブジェクトに責任を動的に追加する。 +Decorator パターンは、サブクラス化よりも柔軟な機能拡張方法を提供する。 + +## 説明 + +実世界の例 + +> 近くの丘に住む怒ったトロールがいる。大抵は素手だが、たまに武器を持っている。トロールに武器を持たせるためには、新しいトロールを作る必要はなく、適切な武器を動的に装飾すればいい。 + +分かりやすい説明 + +> Decorator パターンを用いると、decorator クラスのオブジェクトにラップすることで、オブジェクトの振る舞いを実行時間で動的に変更することができる。 + +Wikipedia の説明 + +> オブジェクト指向プログラミングにおいて、Decorator パターンは、同じクラスの別のオブジェクトの振る舞いに影響を与えることなく、静的もしくは動的に、個別のオブジェクトに振る舞いを加えることができるデザインパターンである。Decorator パターンは、単一責任の原則を遵守するためにしばしば便利である。なぜなら、クラスの機能性を変更せずに拡張することで、開放/閉鎖原則などの関心事の特異な分野を元に、クラスの間で機能性を分割することができるためである。 + +**サンプルコード** + +トロールを例として使用する。まず、Troll のインターフェイスを実装する SimpleTroll クラスを作る。 + +```java +public interface Troll { + void attack(); + int getAttackPower(); + void fleeBattle(); +} + +@Slf4j +public class SimpleTroll implements Troll { + + @Override + public void attack() { + LOGGER.info("The troll tries to grab you!"); + } + + @Override + public int getAttackPower() { + return 10; + } + + @Override + public void fleeBattle() { + LOGGER.info("The troll shrieks in horror and runs away!"); + } +} +``` + +次に、トロールに対してこん棒を追加する。decorator を使い、動的に追加することが可能である。 + +```java +@Slf4j +public class ClubbedTroll implements Troll { + + private final Troll decorated; + + public ClubbedTroll(Troll decorated) { + this.decorated = decorated; + } + + @Override + public void attack() { + decorated.attack(); + LOGGER.info("The troll swings at you with a club!"); + } + + @Override + public int getAttackPower() { + return decorated.getAttackPower() + 10; + } + + @Override + public void fleeBattle() { + decorated.fleeBattle(); + } +} +``` + +以下がトロールの動き。 + +```java +// simple troll +LOGGER.info("A simple looking troll approaches."); +var troll = new SimpleTroll(); +troll.attack(); +troll.fleeBattle(); +LOGGER.info("Simple troll power: {}.\n", troll.getAttackPower()); + +// change the behavior of the simple troll by adding a decorator +LOGGER.info("A troll with huge club surprises you."); +var clubbedTroll = new ClubbedTroll(troll); +clubbedTroll.attack(); +clubbedTroll.fleeBattle(); +LOGGER.info("Clubbed troll power: {}.\n", clubbedTroll.getAttackPower()); +``` + +アウトプット + +```java +A simple looking troll approaches. +The troll tries to grab you! +The troll shrieks in horror and runs away! +Simple troll power: 10. + +A troll with huge club surprises you. +The troll tries to grab you! +The troll swings at you with a club! +The troll shrieks in horror and runs away! +Clubbed troll power: 20. +``` + +## クラス図 + +![alt text](./etc/decorator.urm.png "Decorator pattern class diagram") + +## 適用可能性 + +次のような場合に Decorator パターンを利用する。 + +* 個々のオブジェクトに責任を動的、かつ透明に(すなわち、他のオブジェクトに影響を与えないように)追加する場合。 +* 責任を取りはずすことができるようにする場合。 +* サブクラス化による拡張が非現実的な場合。非常に多くの独立した拡張が起こり得ることがある。このような場合、サブクラス化により全ての組み合わせの拡張に対応しようとすると、莫大な数のサブクラスが必要になるだろう。また、クラス定義が隠蔽されている場合や入手できない場合にも、このパターンを利用できる。 + +## チュートリアル + +* [Decorator Pattern Tutorial](https://www.journaldev.com/1540/decorator-design-pattern-in-java-example) + +## 使用例 + + * [java.io.InputStream](http://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html), [java.io.OutputStream](http://docs.oracle.com/javase/8/docs/api/java/io/OutputStream.html), + [java.io.Reader](http://docs.oracle.com/javase/8/docs/api/java/io/Reader.html) and [java.io.Writer](http://docs.oracle.com/javase/8/docs/api/java/io/Writer.html) + * [java.util.Collections#synchronizedXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#synchronizedCollection-java.util.Collection-) + * [java.util.Collections#unmodifiableXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#unmodifiableCollection-java.util.Collection-) + * [java.util.Collections#checkedXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#checkedCollection-java.util.Collection-java.lang.Class-) + + +## クレジット + +* [オブジェクト指向における再利用のためのデザインパターン](https://www.amazon.co.jp/%E3%82%AA%E3%83%96%E3%82%B8%E3%82%A7%E3%82%AF%E3%83%88%E6%8C%87%E5%90%91%E3%81%AB%E3%81%8A%E3%81%91%E3%82%8B%E5%86%8D%E5%88%A9%E7%94%A8%E3%81%AE%E3%81%9F%E3%82%81%E3%81%AE%E3%83%87%E3%82%B6%E3%82%A4%E3%83%B3%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3-%E3%82%A8%E3%83%AA%E3%83%83%E3%82%AF-%E3%82%AC%E3%83%B3%E3%83%9E/dp/4797311126) +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59) +* [Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions](https://www.amazon.com/gp/product/1937785467/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1937785467&linkCode=as2&tag=javadesignpat-20&linkId=7e4e2fb7a141631491534255252fd08b) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=48d37c67fb3d845b802fa9b619ad8f31) +* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b) +* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7) +* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=f27d2644fbe5026ea448791a8ad09c94)
null
test
test
2023-01-08T09:15:59
"2022-10-30T08:12:02Z"
iluwatar
train
iluwatar/java-design-patterns/2451_2455
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2451
iluwatar/java-design-patterns/2455
[ "timestamp(timedelta=765.0, similarity=0.8822402075876062)" ]
fb7ec9b37533df8a84c233d0d7ad5f91080eff96
c741814b367f004787ef2f87665cc00b5f07b35e
[ "@iluwatar \r\nHere is a PR that I started:\r\n[https://github.com/iluwatar/java-design-patterns/pull/2464](https://github.com/iluwatar/java-design-patterns/pull/2464)\r\n\r\nNo new source code added from my side. Just the code/class name/method formatting as per checkstyle and respective changes in pom.xml and suppressions.xml \r\n\r\nCan you review it?\r\n\r\n\r\n" ]
[]
"2023-01-16T22:00:51Z"
[ "type: enhancement", "epic: build issue", "epic: dependencies" ]
Update Checkstyle to 3.2.0
The project currently uses Checkstyle 3.1.0, but there is a newer version 3.2.0 available. According to dependabot's pull request https://github.com/iluwatar/java-design-patterns/pull/2449, the upgrade is not straightforward. Acceptance criteria - Checkstyle upgraded to 3.2.0 - Any build issues that arise have been resolved
[ "pom.xml" ]
[ "pom.xml" ]
[]
diff --git a/pom.xml b/pom.xml index 8405ac144b2b..6ea0d2bbdb61 100644 --- a/pom.xml +++ b/pom.xml @@ -45,7 +45,7 @@ <guice.version>5.1.0</guice.version> <system-lambda.version>1.1.0</system-lambda.version> <maven-surefire-plugin.version>3.0.0-M8</maven-surefire-plugin.version> - <maven-checkstyle-plugin.version>3.2.0</maven-checkstyle-plugin.version> + <maven-checkstyle-plugin.version>3.2.1</maven-checkstyle-plugin.version> <license-maven-plugin.version>4.1</license-maven-plugin.version> <urm-maven-plugin.version>2.1.1</urm-maven-plugin.version> <!-- SonarCloud -->
null
train
test
2023-02-04T18:20:54
"2023-01-14T06:42:17Z"
iluwatar
train
iluwatar/java-design-patterns/2453_2456
iluwatar/java-design-patterns
iluwatar/java-design-patterns/2453
iluwatar/java-design-patterns/2456
[ "timestamp(timedelta=95.0, similarity=0.9512614915718197)" ]
13d0416045261c98fbd7adb5309daee06e87f2fa
6b0a90ee61fcc5c3bd02af1810fbb66492b5d13f
[ "Related to https://github.com/iluwatar/java-design-patterns/issues/2277" ]
[]
"2023-01-16T23:58:51Z"
[ "type: feature", "epic: translation" ]
Translate: Translate the ambassador readme to Spanish (Task of issue #2277 )
Hi again, I will follow with next pattern, ambassador readme translation to Spanish, with this issue related PR
[]
[ "localization/es/ambassador/README.md" ]
[]
diff --git a/localization/es/ambassador/README.md b/localization/es/ambassador/README.md new file mode 100644 index 000000000000..fcc63208e54e --- /dev/null +++ b/localization/es/ambassador/README.md @@ -0,0 +1,208 @@ +--- +title: Ambassador +category: Structural +language: es +tag: + - Decoupling + - Cloud distributed +--- + +## Motivo + +Proporcionar una instancia de servicio auxiliar a un cliente y delegar en ella las funcionalidades comunes de un recurso compartido. + +## Explicación + +Ejemplo real + +> Un servicio remoto tiene muchos clientes accediendo a una función que este servicio proporciona. El servicio es una aplicación heredada y +> es imposible actualizarla. Un gran número de solicitudes por parte de los usuarios están causando problemas de conectividad. Nuevas reglas +> respecto a la frecuencia de solicitudes deberían implementarse junto con comprobaciones de latencia y registros del lado del cliente. + +En otras palabras + +> Con el patrón Ambassador, podemos implementar una menor frecuencia en solicitudes de clientes junto con comprobaciones de latencia y +> registros. + +Según la Documentación de Microsoft + +> Un servicio de Ambassador puede considerarse como un proxy fuera de proceso que coexiste con el cliente. +> +> Este patrón puede ser útil para la descarga de tareas comunes de conectividad de cliente, como la supervisión, el registro, el enrutamiento, +> la seguridad (por ejemplo, TLS) y los patrones de resistencia(*) de una manera independiente del lenguaje. A menudo se utiliza con aplicaciones heredadas, +> u otras aplicaciones que son difíciles de modificar, con el fin de ampliar sus capacidades de red. También puede +> habilitar un equipo especializado para implementar esas características. + +**Código de ejemplo** + +Con la introducción anterior en mente vamos a imitar su funcionalidad en el siguiente ejemplo. Tenemos una interface implementada +por el servicio remoto así como el servicio ambassador: + +```java +interface RemoteServiceInterface { + long doRemoteFunction(int value) throws Exception; +} +``` + +Un servicio remoto representado como un singleton (Instancia única). + +```java +@Slf4j +public class RemoteService implements RemoteServiceInterface { + private static RemoteService service = null; + + static synchronized RemoteService getRemoteService() { + if (service == null) { + service = new RemoteService(); + } + return service; + } + + private RemoteService() {} + + @Override + public long doRemoteFunction(int value) { + long waitTime = (long) Math.floor(Math.random() * 1000); + + try { + sleep(waitTime); + } catch (InterruptedException e) { + LOGGER.error("Thread sleep interrupted", e); + } + + return waitTime >= 200 ? value * 10 : -1; + } +} +``` + +Un servicio ambassador añadiendo funcionalidades adicionales como registros, comprobación de latencia + +```java +@Slf4j +public class ServiceAmbassador implements RemoteServiceInterface { + private static final int RETRIES = 3; + private static final int DELAY_MS = 3000; + + ServiceAmbassador() { + } + + @Override + public long doRemoteFunction(int value) { + return safeCall(value); + } + + private long checkLatency(int value) { + var startTime = System.currentTimeMillis(); + var result = RemoteService.getRemoteService().doRemoteFunction(value); + var timeTaken = System.currentTimeMillis() - startTime; + + LOGGER.info("Time taken (ms): " + timeTaken); + return result; + } + + private long safeCall(int value) { + var retries = 0; + var result = (long) FAILURE; + + for (int i = 0; i < RETRIES; i++) { + if (retries >= RETRIES) { + return FAILURE; + } + + if ((result = checkLatency(value)) == FAILURE) { + LOGGER.info("Failed to reach remote: (" + (i + 1) + ")"); + retries++; + try { + sleep(DELAY_MS); + } catch (InterruptedException e) { + LOGGER.error("Thread sleep state interrupted", e); + } + } else { + break; + } + } + return result; + } +} +``` + +Un cliente tiene un servicio ambassador local usado para interactuar con el servicio remoto: + +```java +@Slf4j +public class Client { + private final ServiceAmbassador serviceAmbassador = new ServiceAmbassador(); + + long useService(int value) { + var result = serviceAmbassador.doRemoteFunction(value); + LOGGER.info("Service result: " + result); + return result; + } +} +``` + +A continuación dos clientes usando el servicio. + +```java +public class App { + public static void main(String[] args) { + var host1 = new Client(); + var host2 = new Client(); + host1.useService(12); + host2.useService(73); + } +} +``` + +Esta es la salida que obtendremos tras ejecutar el ejemplo: + +```java +Time taken (ms): 111 +Service result: 120 +Time taken (ms): 931 +Failed to reach remote: (1) +Time taken (ms): 665 +Failed to reach remote: (2) +Time taken (ms): 538 +Failed to reach remote: (3) +Service result: -1 +``` + +## Diagrama de clase + +![alt text](/ambassador/etc/ambassador.urm.png "Ambassador class diagram") + +## Aplicaciones + +Ambassador es aplicable cuando trabajamos con un servicio remoto heredado que no puede ser modificado o que sería extremamente +difícil de modificar. Las características de conectividad pueden implementarse en el cliente sin necesidad de realizar cambios en el servicio +remoto. + +* Ambassador proporciona una interface local para un servicio remoto. +* Ambassador proporciona registros, interrupción de circuitos, reintentos y seguridad en el cliente. + +## Casos de uso típicos + +* Control de acceso a otro objeto +* Implementación de registros o logs +* Implementación de interrupciones de circuito +* Delegar tareas de servicios remotos +* Facilitar la conexión a la red + +## Usos conocidos + +* [Pasarela API Kubernetes-native para microservicios](https://github.com/datawire/ambassador) + +## Patrones relacionados + +* [Proxy](https://java-design-patterns.com/patterns/proxy/) + +## Créditos + +* [Ambassador Pattern (Documentación de Microsoft en inglés)](https://docs.microsoft.com/en-us/azure/architecture/patterns/ambassador) +* [Designing Distributed Systems: Patterns and Paradigms for Scalable, Reliable Services](https://www.amazon.com/s?k=designing+distributed+systems&sprefix=designing+distri%2Caps%2C156&linkCode=ll2&tag=javadesignpat-20&linkId=a12581e625462f9038557b01794e5341&language=en_US&ref_=as_li_ss_tl) + +## Notas del traductor +(*) La versión original en inglés de la documentación de Microsoft hace referencia al término resiliencia y +en su traducción al español lo traduce como resistencia, aunque enlaza al apartado patrones de confiabilidad. Véase: +* [Versión de la Documentación para el Patrón Ambassador de Microsoft en español.](https://learn.microsoft.com/es-es/azure/architecture/patterns/ambassador)
null
test
test
2023-01-15T09:35:28
"2023-01-16T18:57:03Z"
KarmaTashiCat
train