From e55944b8c14c1475b32148c2558250184a03da77 Mon Sep 17 00:00:00 2001 From: Sandip Singh Date: Tue, 24 Jul 2018 11:23:39 +0530 Subject: [PATCH 01/13] BAEL-1979 Added examples for SnakeYAML Library --- pom.xml | 3 + snakeyaml/pom.xml | 29 ++++ .../com/baeldung/snakeyaml/model/Address.java | 41 ++++++ .../com/baeldung/snakeyaml/model/Contact.java | 25 ++++ .../baeldung/snakeyaml/model/Customer.java | 62 ++++++++ .../JavaToYAMLSerializationUnitTest.java | 51 +++++++ .../YAMLToJavaDeserialisationUnitTest.java | 135 ++++++++++++++++++ snakeyaml/src/test/resources/customer.yaml | 3 + .../customer_with_contact_details.yaml | 7 + ...omer_with_contact_details_and_address.yaml | 18 +++ ...ustomer_with_contact_details_and_tags.yaml | 6 + .../test/resources/customer_with_type.yaml | 4 + snakeyaml/src/test/resources/customers.yaml | 8 ++ 13 files changed, 392 insertions(+) create mode 100644 snakeyaml/pom.xml create mode 100644 snakeyaml/src/main/java/com/baeldung/snakeyaml/model/Address.java create mode 100644 snakeyaml/src/main/java/com/baeldung/snakeyaml/model/Contact.java create mode 100644 snakeyaml/src/main/java/com/baeldung/snakeyaml/model/Customer.java create mode 100644 snakeyaml/src/test/java/com/baeldung/snakeyaml/JavaToYAMLSerializationUnitTest.java create mode 100644 snakeyaml/src/test/java/com/baeldung/snakeyaml/YAMLToJavaDeserialisationUnitTest.java create mode 100644 snakeyaml/src/test/resources/customer.yaml create mode 100644 snakeyaml/src/test/resources/customer_with_contact_details.yaml create mode 100644 snakeyaml/src/test/resources/customer_with_contact_details_and_address.yaml create mode 100644 snakeyaml/src/test/resources/customer_with_contact_details_and_tags.yaml create mode 100644 snakeyaml/src/test/resources/customer_with_type.yaml create mode 100644 snakeyaml/src/test/resources/customers.yaml diff --git a/pom.xml b/pom.xml index 06ec82e5f0..4aad8d43d6 100644 --- a/pom.xml +++ b/pom.xml @@ -550,6 +550,7 @@ spring-reactive-kotlin jnosql testing-modules/junit-abstract + snakeyaml @@ -670,6 +671,7 @@ spring-apache-camel spring-batch testing-modules/junit-abstract + snakeyaml @@ -1076,6 +1078,7 @@ maven-archetype apache-meecrowave testing-modules/junit-abstract + snakeyaml @@ -1077,8 +1075,7 @@ antlr maven-archetype apache-meecrowave - testing-modules/junit-abstract - snakeyaml + testing-modules/junit-abstract - + + + 1.1.2 1.2 1.6.1 2.6.11 + 1.8 diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/HttpsEnabledApplication.java b/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/HttpsEnabledApplication.java new file mode 100644 index 0000000000..70fe30abdc --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/HttpsEnabledApplication.java @@ -0,0 +1,14 @@ +package org.baeldung.ssl; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class HttpsEnabledApplication { + + public static void main(String... args) { + SpringApplication application = new SpringApplication(HttpsEnabledApplication.class); + application.setAdditionalProfiles("ssl"); + application.run(args); + } +} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/SecurityConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/SecurityConfig.java new file mode 100644 index 0000000000..98a59b11bb --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/SecurityConfig.java @@ -0,0 +1,36 @@ +package org.baeldung.ssl; + +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + public void configure(AuthenticationManagerBuilder auth) throws Exception { + + auth.inMemoryAuthentication() + .withUser("memuser") + .password(passwordEncoder().encode("pass")) + .roles("USER"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.httpBasic() + .and() + .authorizeRequests() + .antMatchers("/**") + .authenticated(); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } +} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/WelcomeController.java b/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/WelcomeController.java new file mode 100644 index 0000000000..72ad8abb85 --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/WelcomeController.java @@ -0,0 +1,15 @@ +package org.baeldung.ssl; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +public class WelcomeController { + + @GetMapping("/welcome") + public String welcome() { + return "ssl/welcome"; + } + +} diff --git a/spring-security-mvc-boot/src/main/resources/application-ssl.properties b/spring-security-mvc-boot/src/main/resources/application-ssl.properties new file mode 100644 index 0000000000..090b775d03 --- /dev/null +++ b/spring-security-mvc-boot/src/main/resources/application-ssl.properties @@ -0,0 +1,20 @@ + +http.port=8080 + +server.port=8443 + +security.require-ssl=true + +# The format used for the keystore +server.ssl.key-store-type=PKCS12 +# The path to the keystore containing the certificate +server.ssl.key-store=classpath:keystore/baeldung.p12 +# The password used to generate the certificate +server.ssl.key-store-password=password +# The alias mapped to the certificate +server.ssl.key-alias=baeldung + +#trust store location +trust.store=classpath:keystore/baeldung.p12 +#trust store password +trust.store.password=password diff --git a/spring-security-mvc-boot/src/main/resources/keystore/baeldung.p12 b/spring-security-mvc-boot/src/main/resources/keystore/baeldung.p12 new file mode 100644 index 0000000000000000000000000000000000000000..cd8eb284297009e987aa1a1d6b53c48af587776e GIT binary patch literal 2603 zcmY+EXEYlM8^;r3M9o+w1hFbbqGHbuyEIm+snTk!hO1FpR7GP|aZ6j;auK8UtQAG7 zV$YhT2qmc9Vcsg&`=0l`_uLQ9dCvL$|IhRBhaz(+vH)38WbiCI7!hqAy~_jS08+@{ zK@b_-cZ|DGWH#S_MQko0G8^s~V~@v<{lx#SxVeBV6f)>1iVWICDY0|?A0I!5f`s^3 zu&dJJ6F~Z?bJm7OhKe^z>^=)CfQ|u?L7h6GkAgI65DwJB{KM&_MXKTI9lIqxhN`1} z`A*KRClYJWaEY_s^N|voc6A00ThR7qHjQvZX+gn$-BvCy^h*XXd@(9FFl&uIA(ye3~t$x%OvdtZ6kea z?f2mYKd}#kcfPd2Qj@BWsJYAQV?UWEV$3xr?2MMkh<@aOLyI5fS+HWE`b(`(J^ht} zkR*eWyqT*v5%MaZOvmUzs+mdtjCG$7e zk&q|W%V|!jeWjxuJY*Pp@C-pN0z$3MU$4}90$#HPd)>y0K?<6Y7T0Chq0uke7wbomuc|C+P#-z{m`4c1|1GBI(woGP!Qhl7t_2@B=gTCU}klA|2uD~LA$B|Hf z9?q|vYv$T8RN`JF0)WU?;jGXd*@?42n)lJLP?O%qsJ(!~)+G!#4|R;Q2h*6mO8XIX z_P~j+liPKyQLV85WsE0HQ+2F7!T=w$#*rGM@2eK}v3Xvw^kEK*b_!6)K@Oy{^#nzK zYsydd{?(y@;X^STEU`R(o3B3DQ=gQ{TalEFacTQ$WwZ_3$NLf1A`ue15ske5Gbvrn zMVwpM5 z$^;r{*cZwNsXDeph+W0HFoH3@>rvgs;VhhQP@SeG3Lch{p&iNZS<9O-`k>9`V^$Bvi__Z&f2RwKK4svAZO_QzY-Q+9boQ0)of~0dFq|de&s}-DZ zouW8d&sajPQE^wEim{+NZ&76^e#4I@Eafg)-eAhQByD>`a|b0n*iCC6(-a?G59!K! z%WNH4FA|B~`8ZHpAgsSh=iwt@gM6V;X^Lic=Ze*TrTDT{_smO{wb$xT3!aB9Ix$ zDHJb#IrUW=`ki_aY+ttWxkRR7JPdppxA8pLHc788pN$m`*!udm1)o>{gp13CMePDg z>Tgwoh14K0et;X`2EZNQ1Hc0U0lxt}Q8ND&gw=#V5C?BxcWE^ZbsbGD4K!Lq9j$XL zP=~)u9PGzVH91CSS%84!rTb3;{Fi0f|6^H4*Oa*e3xdCLeiF;!_o?hv z0tk<&E}^>5tfsiw#0xZ84jjfMZW)O9@|xuvB=#S%RSw(YvpJl=fCsPWzeWCMix(mA7RsU@{fe{o=Xy>Pp*}`%+i`nlk|N9x!FxG2)|X4 zEKw@1^=34F&2qQi9j@PN8d^HCdnwkH+SwDtAaoOs>MrPVqq+6GsLWG{iP!raR{296 zn)bo1Ypxj{s&Zq3PJ)r!`Io^PGnnr+kk7{UX+IJgRt#f%T8fU$?%w|Vop*RwEGqa{ z(WG3c0FW|}N4&}s$|j#RGGV2oSE>W{OZ@E-b47trP;YC$ z=vPW$1m1o3sc292)J35Y(%$!P4;0VKD5xumEa}b>FU(NpzSChk7S=$(X973=-bj9{y};Q81=IyKM8_P=YATS4wxXidLc;YHIX!VEoy)KSNh5GdGhbD-AIfz3o9_1@)sB) B#c}`u literal 0 HcmV?d00001 diff --git a/spring-security-mvc-boot/src/main/resources/templates/ssl/welcome.html b/spring-security-mvc-boot/src/main/resources/templates/ssl/welcome.html new file mode 100644 index 0000000000..93b3577f5c --- /dev/null +++ b/spring-security-mvc-boot/src/main/resources/templates/ssl/welcome.html @@ -0,0 +1 @@ +

Welcome to Secured Site

\ No newline at end of file diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java new file mode 100644 index 0000000000..63b421604a --- /dev/null +++ b/spring-security-mvc-boot/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java @@ -0,0 +1,67 @@ +package org.baeldung.web; + +import org.apache.http.client.HttpClient; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.ssl.SSLContextBuilder; +import org.baeldung.ssl.HttpsEnabledApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.core.io.Resource; +import org.springframework.http.*; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.client.RestTemplate; + +import javax.net.ssl.SSLContext; +import java.util.Base64; + +import static org.junit.Assert.assertEquals; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = HttpsEnabledApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +@ActiveProfiles("ssl") +public class HttpsApplicationIntegrationTest { + + private static final String WELCOME_URL = "https://localhost:8443/welcome"; + + @Value("${trust.store}") + private Resource trustStore; + + @Value("${trust.store.password}") + private String trustStorePassword; + + @Test + public void whenGETanHTTPSResource_thenCorrectResponse() throws Exception { + ResponseEntity response = restTemplate().exchange(WELCOME_URL, HttpMethod.GET, new HttpEntity(withAuthorization("memuser", "pass")), String.class); + + assertEquals("

Welcome to Secured Site

", response.getBody()); + assertEquals(HttpStatus.OK, response.getStatusCode()); + } + + RestTemplate restTemplate() throws Exception { + SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(trustStore.getURL(), trustStorePassword.toCharArray()) + .build(); + SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext); + HttpClient httpClient = HttpClients.custom() + .setSSLSocketFactory(socketFactory) + .build(); + HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient); + return new RestTemplate(factory); + } + + HttpHeaders withAuthorization(String userName, String password) { + return new HttpHeaders() { + { + String auth = userName + ":" + password; + String authHeader = "Basic " + new String(Base64.getEncoder() + .encode(auth.getBytes())); + set("Authorization", authHeader); + } + }; + } + +} From 0ee48a7d92d100a6164ee425abdb0dfdde1b4745 Mon Sep 17 00:00:00 2001 From: Sandip Singh Date: Mon, 22 Oct 2018 09:05:47 +0530 Subject: [PATCH 11/13] BAEL-2262 Removed the Basic Authentication from the HttpsEnabledApplication. --- .../java/org/baeldung/ssl/SecurityConfig.java | 26 +++---------------- .../web/HttpsApplicationIntegrationTest.java | 19 +++----------- 2 files changed, 7 insertions(+), 38 deletions(-) diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/SecurityConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/SecurityConfig.java index 98a59b11bb..92f92d8fc7 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/SecurityConfig.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/SecurityConfig.java @@ -1,36 +1,16 @@ package org.baeldung.ssl; -import org.springframework.context.annotation.Bean; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { - @Override - public void configure(AuthenticationManagerBuilder auth) throws Exception { - - auth.inMemoryAuthentication() - .withUser("memuser") - .password(passwordEncoder().encode("pass")) - .roles("USER"); - } - @Override protected void configure(HttpSecurity http) throws Exception { - http.httpBasic() - .and() - .authorizeRequests() - .antMatchers("/**") - .authenticated(); - } - - @Bean - public PasswordEncoder passwordEncoder() { - return new BCryptPasswordEncoder(); + http.authorizeRequests() + .antMatchers("/**") + .permitAll(); } } diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java index 63b421604a..fe7883ec94 100644 --- a/spring-security-mvc-boot/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java +++ b/spring-security-mvc-boot/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java @@ -10,14 +10,15 @@ import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.core.io.Resource; -import org.springframework.http.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.RestTemplate; import javax.net.ssl.SSLContext; -import java.util.Base64; +import java.util.Collections; import static org.junit.Assert.assertEquals; @@ -36,7 +37,7 @@ public class HttpsApplicationIntegrationTest { @Test public void whenGETanHTTPSResource_thenCorrectResponse() throws Exception { - ResponseEntity response = restTemplate().exchange(WELCOME_URL, HttpMethod.GET, new HttpEntity(withAuthorization("memuser", "pass")), String.class); + ResponseEntity response = restTemplate().getForEntity(WELCOME_URL, String.class, Collections.emptyMap()); assertEquals("

Welcome to Secured Site

", response.getBody()); assertEquals(HttpStatus.OK, response.getStatusCode()); @@ -52,16 +53,4 @@ public class HttpsApplicationIntegrationTest { HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient); return new RestTemplate(factory); } - - HttpHeaders withAuthorization(String userName, String password) { - return new HttpHeaders() { - { - String auth = userName + ":" + password; - String authHeader = "Basic " + new String(Base64.getEncoder() - .encode(auth.getBytes())); - set("Authorization", authHeader); - } - }; - } - } From e1b47c72a06d38d8007428589b40abb0fb8b655e Mon Sep 17 00:00:00 2001 From: Sandip Singh Date: Fri, 2 Nov 2018 20:41:50 +0530 Subject: [PATCH 12/13] BAEL-2303 Added sample code to demo how to replace multiple if statements in java. --- .../baeldung/reducingIfElse/AddCommand.java | 19 +++++ .../com/baeldung/reducingIfElse/AddRule.java | 21 +++++ .../com/baeldung/reducingIfElse/Addition.java | 8 ++ .../baeldung/reducingIfElse/Calculator.java | 84 +++++++++++++++++++ .../com/baeldung/reducingIfElse/Command.java | 7 ++ .../com/baeldung/reducingIfElse/Division.java | 7 ++ .../baeldung/reducingIfElse/Expression.java | 26 ++++++ .../com/baeldung/reducingIfElse/Modulo.java | 7 ++ .../reducingIfElse/Multiplication.java | 7 ++ .../baeldung/reducingIfElse/Operation.java | 5 ++ .../com/baeldung/reducingIfElse/Operator.java | 41 +++++++++ .../reducingIfElse/OperatorFactory.java | 21 +++++ .../com/baeldung/reducingIfElse/Rule.java | 8 ++ .../baeldung/reducingIfElse/RuleEngine.java | 20 +++++ .../baeldung/reducingIfElse/Subtraction.java | 7 ++ .../reduceIfelse/RuleEngineUnitTest.java | 27 ++++++ 16 files changed, 315 insertions(+) create mode 100644 core-java-8/src/main/java/com/baeldung/reducingIfElse/AddCommand.java create mode 100644 core-java-8/src/main/java/com/baeldung/reducingIfElse/AddRule.java create mode 100644 core-java-8/src/main/java/com/baeldung/reducingIfElse/Addition.java create mode 100644 core-java-8/src/main/java/com/baeldung/reducingIfElse/Calculator.java create mode 100644 core-java-8/src/main/java/com/baeldung/reducingIfElse/Command.java create mode 100644 core-java-8/src/main/java/com/baeldung/reducingIfElse/Division.java create mode 100644 core-java-8/src/main/java/com/baeldung/reducingIfElse/Expression.java create mode 100644 core-java-8/src/main/java/com/baeldung/reducingIfElse/Modulo.java create mode 100644 core-java-8/src/main/java/com/baeldung/reducingIfElse/Multiplication.java create mode 100644 core-java-8/src/main/java/com/baeldung/reducingIfElse/Operation.java create mode 100644 core-java-8/src/main/java/com/baeldung/reducingIfElse/Operator.java create mode 100644 core-java-8/src/main/java/com/baeldung/reducingIfElse/OperatorFactory.java create mode 100644 core-java-8/src/main/java/com/baeldung/reducingIfElse/Rule.java create mode 100644 core-java-8/src/main/java/com/baeldung/reducingIfElse/RuleEngine.java create mode 100644 core-java-8/src/main/java/com/baeldung/reducingIfElse/Subtraction.java create mode 100644 core-java-8/src/test/java/com/baeldung/reduceIfelse/RuleEngineUnitTest.java diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/AddCommand.java b/core-java-8/src/main/java/com/baeldung/reducingIfElse/AddCommand.java new file mode 100644 index 0000000000..5aa0de7adc --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/reducingIfElse/AddCommand.java @@ -0,0 +1,19 @@ +package com.baeldung.reducingIfElse; + +public class AddCommand implements Command { + + private int a; + private int b; + + @Override + public Integer execute() { + return a + b; + } + + @Override + public Command takeInput(Integer a, Integer b) { + this.a = a; + this.b = b; + return this; + } +} diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/AddRule.java b/core-java-8/src/main/java/com/baeldung/reducingIfElse/AddRule.java new file mode 100644 index 0000000000..871ff1f2d1 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/reducingIfElse/AddRule.java @@ -0,0 +1,21 @@ +package com.baeldung.reducingIfElse; + +public class AddRule implements Rule { + + private int result; + + @Override + public boolean evaluate(Expression expression) { + boolean evalResult = false; + if (expression.getOperator() == Operator.ADD) { + this.result = expression.getX() + expression.getY(); + evalResult = true; + } + return evalResult; + } + + @Override + public int getResult() { + return result; + } +} diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/Addition.java b/core-java-8/src/main/java/com/baeldung/reducingIfElse/Addition.java new file mode 100644 index 0000000000..3174ea558c --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/reducingIfElse/Addition.java @@ -0,0 +1,8 @@ +package com.baeldung.reducingIfElse; + +public class Addition implements Operation { + @Override + public int apply(int a, int b) { + return a + b; + } +} diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/Calculator.java b/core-java-8/src/main/java/com/baeldung/reducingIfElse/Calculator.java new file mode 100644 index 0000000000..9b8cce130f --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/reducingIfElse/Calculator.java @@ -0,0 +1,84 @@ +package com.baeldung.reducingIfElse; + +public class Calculator { + + public int calculate(int a, int b, String operator) { + int result = Integer.MIN_VALUE; + + if ("add".equals(operator)) { + result = a + b; + } else if ("multiply".equals(operator)) { + result = a * b; + } else if ("divide".equals(operator)) { + result = a / b; + } else if ("subtract".equals(operator)) { + result = a - b; + } else if ("modulo".equals(operator)) { + result = a % b; + } + return result; + } + + public int calculateUsingSwitch(int a, int b, String operator) { + int result = 0; + switch (operator) { + case "add": + result = a + b; + break; + case "multiply": + result = a * b; + break; + case "divide": + result = a / b; + break; + case "subtract": + result = a - b; + break; + case "modulo": + result = a % b; + break; + default: + result = Integer.MIN_VALUE; + } + return result; + } + + public int calculateUsingSwitch(int a, int b, Operator operator) { + int result = 0; + switch (operator) { + case ADD: + result = a + b; + break; + case MULTIPLY: + result = a * b; + break; + case DIVIDE: + result = a / b; + break; + case SUBTRACT: + result = a - b; + break; + case MODULO: + result = a % b; + break; + default: + result = Integer.MIN_VALUE; + } + return result; + } + + public int calculate(int a, int b, Operator operator) { + return operator.apply(a, b); + } + + public int calculateUsingFactory(int a, int b, String operation) { + Operation targetOperation = OperatorFactory.getOperation(operation) + .orElseThrow(() -> new IllegalArgumentException("Invalid Operator")); + return targetOperation.apply(a, b); + } + + public int calculate(int a, int b, Command command) { + return command.takeInput(a, b) + .execute(); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/Command.java b/core-java-8/src/main/java/com/baeldung/reducingIfElse/Command.java new file mode 100644 index 0000000000..d9f00e31b4 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/reducingIfElse/Command.java @@ -0,0 +1,7 @@ +package com.baeldung.reducingIfElse; + +public interface Command { + R execute(); + + Command takeInput(A a, B b); +} diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/Division.java b/core-java-8/src/main/java/com/baeldung/reducingIfElse/Division.java new file mode 100644 index 0000000000..75b1297655 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/reducingIfElse/Division.java @@ -0,0 +1,7 @@ +package com.baeldung.reducingIfElse; + +public class Division implements Operation { + @Override public int apply(int a, int b) { + return a / b; + } +} diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/Expression.java b/core-java-8/src/main/java/com/baeldung/reducingIfElse/Expression.java new file mode 100644 index 0000000000..4d3fe1b824 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/reducingIfElse/Expression.java @@ -0,0 +1,26 @@ +package com.baeldung.reducingIfElse; + +public class Expression { + + private Integer x; + private Integer y; + private Operator operator; + + public Expression(Integer x, Integer y, Operator operator) { + this.x = x; + this.y = y; + this.operator = operator; + } + + public Integer getX() { + return x; + } + + public Integer getY() { + return y; + } + + public Operator getOperator() { + return operator; + } +} diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/Modulo.java b/core-java-8/src/main/java/com/baeldung/reducingIfElse/Modulo.java new file mode 100644 index 0000000000..a7a081704c --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/reducingIfElse/Modulo.java @@ -0,0 +1,7 @@ +package com.baeldung.reducingIfElse; + +public class Modulo implements Operation { + @Override public int apply(int a, int b) { + return a % b; + } +} diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/Multiplication.java b/core-java-8/src/main/java/com/baeldung/reducingIfElse/Multiplication.java new file mode 100644 index 0000000000..e1a39b33c4 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/reducingIfElse/Multiplication.java @@ -0,0 +1,7 @@ +package com.baeldung.reducingIfElse; + +public class Multiplication implements Operation { + @Override public int apply(int a, int b) { + return 0; + } +} diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/Operation.java b/core-java-8/src/main/java/com/baeldung/reducingIfElse/Operation.java new file mode 100644 index 0000000000..41241fa810 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/reducingIfElse/Operation.java @@ -0,0 +1,5 @@ +package com.baeldung.reducingIfElse; + +public interface Operation { + int apply(int a, int b); +} diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/Operator.java b/core-java-8/src/main/java/com/baeldung/reducingIfElse/Operator.java new file mode 100644 index 0000000000..831b8fa146 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/reducingIfElse/Operator.java @@ -0,0 +1,41 @@ +package com.baeldung.reducingIfElse; + +public enum Operator { + + ADD { + @Override + public int apply(int a, int b) { + return a + b; + } + }, + + MULTIPLY { + @Override + public int apply(int a, int b) { + return a * b; + } + }, + + SUBTRACT { + @Override + public int apply(int a, int b) { + return a - b; + } + }, + + DIVIDE { + @Override + public int apply(int a, int b) { + return a / b; + } + }, + + MODULO { + @Override + public int apply(int a, int b) { + return a % b; + } + }; + + public abstract int apply(int a, int b); +} diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/OperatorFactory.java b/core-java-8/src/main/java/com/baeldung/reducingIfElse/OperatorFactory.java new file mode 100644 index 0000000000..18ed63adbd --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/reducingIfElse/OperatorFactory.java @@ -0,0 +1,21 @@ +package com.baeldung.reducingIfElse; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +public class OperatorFactory { + + static Map operationMap = new HashMap<>(); + static { + operationMap.put("add", new Addition()); + operationMap.put("divide", new Division()); + operationMap.put("multiply", new Multiplication()); + operationMap.put("subtract", new Subtraction()); + operationMap.put("modulo", new Modulo()); + } + + public static Optional getOperation(String operation) { + return Optional.ofNullable(operationMap.get(operation)); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/Rule.java b/core-java-8/src/main/java/com/baeldung/reducingIfElse/Rule.java new file mode 100644 index 0000000000..202072dd66 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/reducingIfElse/Rule.java @@ -0,0 +1,8 @@ +package com.baeldung.reducingIfElse; + +public interface Rule { + + boolean evaluate(Expression expression); + + int getResult(); +} diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/RuleEngine.java b/core-java-8/src/main/java/com/baeldung/reducingIfElse/RuleEngine.java new file mode 100644 index 0000000000..3af67aff11 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/reducingIfElse/RuleEngine.java @@ -0,0 +1,20 @@ +package com.baeldung.reducingIfElse; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +public class RuleEngine { + + private static List rules = new ArrayList<>(); + + static { + rules.add(new AddRule()); + } + + public List process(Expression expression) { + return rules.stream() + .filter(r -> r.evaluate(expression)) + .collect(Collectors.toList()); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/Subtraction.java b/core-java-8/src/main/java/com/baeldung/reducingIfElse/Subtraction.java new file mode 100644 index 0000000000..948998810e --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/reducingIfElse/Subtraction.java @@ -0,0 +1,7 @@ +package com.baeldung.reducingIfElse; + +public class Subtraction implements Operation { + @Override public int apply(int a, int b) { + return a - b; + } +} diff --git a/core-java-8/src/test/java/com/baeldung/reduceIfelse/RuleEngineUnitTest.java b/core-java-8/src/test/java/com/baeldung/reduceIfelse/RuleEngineUnitTest.java new file mode 100644 index 0000000000..227dd12f0d --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/reduceIfelse/RuleEngineUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.reduceIfelse; + +import com.baeldung.reducingIfElse.Expression; +import com.baeldung.reducingIfElse.Operator; +import com.baeldung.reducingIfElse.Rule; +import com.baeldung.reducingIfElse.RuleEngine; +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +public class RuleEngineUnitTest { + + @Test + public void whenNumbersGivenToRuleEngine_thenReturnCorrectResult() { + Expression expression = new Expression(5, 5, Operator.ADD); + RuleEngine engine = new RuleEngine(); + List rules = engine.process(expression); + + assertNotNull(rules); + assertEquals(1, rules.size()); + assertEquals(10, rules.get(0) + .getResult()); + } +} From 3c558d642798f3f977f7466463649bbfdc65b8a6 Mon Sep 17 00:00:00 2001 From: Sandip Singh Date: Tue, 6 Nov 2018 14:21:19 +0530 Subject: [PATCH 13/13] BAEL-2303 Updated the code as per the review comments. --- .../baeldung/reducingIfElse/AddCommand.java | 14 ++++---- .../com/baeldung/reducingIfElse/AddRule.java | 4 +-- .../baeldung/reducingIfElse/Calculator.java | 5 ++- .../com/baeldung/reducingIfElse/Command.java | 8 ++--- .../com/baeldung/reducingIfElse/Result.java | 13 ++++++++ .../com/baeldung/reducingIfElse/Rule.java | 2 +- .../baeldung/reducingIfElse/RuleEngine.java | 10 ++++-- .../reduceIfelse/CalculatorUnitTest.java | 32 +++++++++++++++++++ .../reduceIfelse/RuleEngineUnitTest.java | 12 +++---- 9 files changed, 70 insertions(+), 30 deletions(-) create mode 100644 core-java-8/src/main/java/com/baeldung/reducingIfElse/Result.java create mode 100644 core-java-8/src/test/java/com/baeldung/reduceIfelse/CalculatorUnitTest.java diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/AddCommand.java b/core-java-8/src/main/java/com/baeldung/reducingIfElse/AddCommand.java index 5aa0de7adc..279a3b2c55 100644 --- a/core-java-8/src/main/java/com/baeldung/reducingIfElse/AddCommand.java +++ b/core-java-8/src/main/java/com/baeldung/reducingIfElse/AddCommand.java @@ -1,19 +1,17 @@ package com.baeldung.reducingIfElse; -public class AddCommand implements Command { +public class AddCommand implements Command { private int a; private int b; + public AddCommand(int a, int b) { + this.a = a; + this.b = b; + } + @Override public Integer execute() { return a + b; } - - @Override - public Command takeInput(Integer a, Integer b) { - this.a = a; - this.b = b; - return this; - } } diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/AddRule.java b/core-java-8/src/main/java/com/baeldung/reducingIfElse/AddRule.java index 871ff1f2d1..f24c973ead 100644 --- a/core-java-8/src/main/java/com/baeldung/reducingIfElse/AddRule.java +++ b/core-java-8/src/main/java/com/baeldung/reducingIfElse/AddRule.java @@ -15,7 +15,7 @@ public class AddRule implements Rule { } @Override - public int getResult() { - return result; + public Result getResult() { + return new Result(result); } } diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/Calculator.java b/core-java-8/src/main/java/com/baeldung/reducingIfElse/Calculator.java index 9b8cce130f..550d92e183 100644 --- a/core-java-8/src/main/java/com/baeldung/reducingIfElse/Calculator.java +++ b/core-java-8/src/main/java/com/baeldung/reducingIfElse/Calculator.java @@ -77,8 +77,7 @@ public class Calculator { return targetOperation.apply(a, b); } - public int calculate(int a, int b, Command command) { - return command.takeInput(a, b) - .execute(); + public int calculate(Command command) { + return command.execute(); } } diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/Command.java b/core-java-8/src/main/java/com/baeldung/reducingIfElse/Command.java index d9f00e31b4..c084fcc6a0 100644 --- a/core-java-8/src/main/java/com/baeldung/reducingIfElse/Command.java +++ b/core-java-8/src/main/java/com/baeldung/reducingIfElse/Command.java @@ -1,7 +1,5 @@ package com.baeldung.reducingIfElse; -public interface Command { - R execute(); - - Command takeInput(A a, B b); -} +public interface Command { + Integer execute(); +} \ No newline at end of file diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/Result.java b/core-java-8/src/main/java/com/baeldung/reducingIfElse/Result.java new file mode 100644 index 0000000000..d5ed12202e --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/reducingIfElse/Result.java @@ -0,0 +1,13 @@ +package com.baeldung.reducingIfElse; + +public class Result { + int value; + + public Result(int value) { + this.value = value; + } + + public int getValue() { + return value; + } +} diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/Rule.java b/core-java-8/src/main/java/com/baeldung/reducingIfElse/Rule.java index 202072dd66..5a6c84b0f9 100644 --- a/core-java-8/src/main/java/com/baeldung/reducingIfElse/Rule.java +++ b/core-java-8/src/main/java/com/baeldung/reducingIfElse/Rule.java @@ -4,5 +4,5 @@ public interface Rule { boolean evaluate(Expression expression); - int getResult(); + Result getResult(); } diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/RuleEngine.java b/core-java-8/src/main/java/com/baeldung/reducingIfElse/RuleEngine.java index 3af67aff11..ac56915dee 100644 --- a/core-java-8/src/main/java/com/baeldung/reducingIfElse/RuleEngine.java +++ b/core-java-8/src/main/java/com/baeldung/reducingIfElse/RuleEngine.java @@ -2,6 +2,7 @@ package com.baeldung.reducingIfElse; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import java.util.stream.Collectors; public class RuleEngine { @@ -12,9 +13,12 @@ public class RuleEngine { rules.add(new AddRule()); } - public List process(Expression expression) { - return rules.stream() + public Result process(Expression expression) { + + Rule rule = rules.stream() .filter(r -> r.evaluate(expression)) - .collect(Collectors.toList()); + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("Expression does not matches any Rule")); + return rule.getResult(); } } diff --git a/core-java-8/src/test/java/com/baeldung/reduceIfelse/CalculatorUnitTest.java b/core-java-8/src/test/java/com/baeldung/reduceIfelse/CalculatorUnitTest.java new file mode 100644 index 0000000000..fa351930d8 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/reduceIfelse/CalculatorUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.reduceIfelse; + +import com.baeldung.reducingIfElse.AddCommand; +import com.baeldung.reducingIfElse.Calculator; +import com.baeldung.reducingIfElse.Operator; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class CalculatorUnitTest { + + @Test + public void whenCalculateUsingStringOperator_thenReturnCorrectResult() { + Calculator calculator = new Calculator(); + int result = calculator.calculate(3, 4, "add"); + assertEquals(7, result); + } + + @Test + public void whenCalculateUsingEnumOperator_thenReturnCorrectResult() { + Calculator calculator = new Calculator(); + int result = calculator.calculate(3, 4, Operator.valueOf("ADD")); + assertEquals(7, result); + } + + @Test + public void whenCalculateUsingCommand_thenReturnCorrectResult() { + Calculator calculator = new Calculator(); + int result = calculator.calculate(new AddCommand(3, 7)); + assertEquals(10, result); + } +} diff --git a/core-java-8/src/test/java/com/baeldung/reduceIfelse/RuleEngineUnitTest.java b/core-java-8/src/test/java/com/baeldung/reduceIfelse/RuleEngineUnitTest.java index 227dd12f0d..4a30b3efac 100644 --- a/core-java-8/src/test/java/com/baeldung/reduceIfelse/RuleEngineUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/reduceIfelse/RuleEngineUnitTest.java @@ -2,12 +2,10 @@ package com.baeldung.reduceIfelse; import com.baeldung.reducingIfElse.Expression; import com.baeldung.reducingIfElse.Operator; -import com.baeldung.reducingIfElse.Rule; +import com.baeldung.reducingIfElse.Result; import com.baeldung.reducingIfElse.RuleEngine; import org.junit.Test; -import java.util.List; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -17,11 +15,9 @@ public class RuleEngineUnitTest { public void whenNumbersGivenToRuleEngine_thenReturnCorrectResult() { Expression expression = new Expression(5, 5, Operator.ADD); RuleEngine engine = new RuleEngine(); - List rules = engine.process(expression); + Result result = engine.process(expression); - assertNotNull(rules); - assertEquals(1, rules.size()); - assertEquals(10, rules.get(0) - .getResult()); + assertNotNull(result); + assertEquals(10, result.getValue()); } }