From 6762557f1ec4e0731aa8291d02b8e93ce91b966a Mon Sep 17 00:00:00 2001 From: fejera Date: Sun, 17 Nov 2019 15:04:03 +0100 Subject: [PATCH 01/47] added live-all profile to root pom --- pom.xml | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/pom.xml b/pom.xml index bc4c38f386..63561cb65e 100644 --- a/pom.xml +++ b/pom.xml @@ -1671,6 +1671,39 @@ + + + live-all + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/SpringContextTest.java + **/*UnitTest.java + **/*IntegrationTest.java + **/*IntTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/*JdbcTest.java + + + **/*LiveTest.java + + + + + + + + + + + + From ae8ef36227de957b2696acf94bb782941dcefe1a Mon Sep 17 00:00:00 2001 From: fejera Date: Sun, 17 Nov 2019 15:05:58 +0100 Subject: [PATCH 02/47] added live-test resources --- persistence-modules/spring-data-mongodb/live-test.sh | 11 +++++++++++ .../spring-data-mongodb/live-test/Dockerfile | 8 ++++++++ .../spring-data-mongodb/live-test/init-session.js | 1 + 3 files changed, 20 insertions(+) create mode 100755 persistence-modules/spring-data-mongodb/live-test.sh create mode 100644 persistence-modules/spring-data-mongodb/live-test/Dockerfile create mode 100644 persistence-modules/spring-data-mongodb/live-test/init-session.js diff --git a/persistence-modules/spring-data-mongodb/live-test.sh b/persistence-modules/spring-data-mongodb/live-test.sh new file mode 100755 index 0000000000..bb513a90bb --- /dev/null +++ b/persistence-modules/spring-data-mongodb/live-test.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +docker image build -t spring-data-mongodb:live-test live-test/ + +docker run -p 27017:27017 --name spring-data-mongodb-live-test -it spring-data-mongodb:live-test +#wait + +mvn clean compile test -P live-all + +docker stop spring-data-mongodb-live-test +docker rm spring-data-mongodb-live-test diff --git a/persistence-modules/spring-data-mongodb/live-test/Dockerfile b/persistence-modules/spring-data-mongodb/live-test/Dockerfile new file mode 100644 index 0000000000..9e3634feb0 --- /dev/null +++ b/persistence-modules/spring-data-mongodb/live-test/Dockerfile @@ -0,0 +1,8 @@ +FROM mongo:4.2.1 + +COPY init-session.js /docker-entrypoint-initdb.d/ + +EXPOSE 27017 + +HEALTHCHECK --interval=5s --timeout=3s --start-period=10s CMD mongo db.stats() +CMD ["mongod", "--replSet", "rs0"] diff --git a/persistence-modules/spring-data-mongodb/live-test/init-session.js b/persistence-modules/spring-data-mongodb/live-test/init-session.js new file mode 100644 index 0000000000..2e968884cc --- /dev/null +++ b/persistence-modules/spring-data-mongodb/live-test/init-session.js @@ -0,0 +1 @@ +rs.initiate(); From 23fb4ae451fef29cb5a81d486542e32cb4d5b979 Mon Sep 17 00:00:00 2001 From: fejera Date: Sun, 24 Nov 2019 12:42:59 +0100 Subject: [PATCH 03/47] cleaned up and documented live testing script usage --- persistence-modules/spring-data-mongodb/LIVE-TEST.md | 9 +++++++++ .../spring-data-mongodb/live-test-setup.sh | 5 +++++ .../spring-data-mongodb/live-test-teardown.sh | 4 ++++ persistence-modules/spring-data-mongodb/live-test.sh | 8 -------- 4 files changed, 18 insertions(+), 8 deletions(-) create mode 100644 persistence-modules/spring-data-mongodb/LIVE-TEST.md create mode 100644 persistence-modules/spring-data-mongodb/live-test-setup.sh create mode 100644 persistence-modules/spring-data-mongodb/live-test-teardown.sh diff --git a/persistence-modules/spring-data-mongodb/LIVE-TEST.md b/persistence-modules/spring-data-mongodb/LIVE-TEST.md new file mode 100644 index 0000000000..9da1ea249e --- /dev/null +++ b/persistence-modules/spring-data-mongodb/LIVE-TEST.md @@ -0,0 +1,9 @@ +========= + +## Spring Data MongoDB Live Testing + + +There are 3 scripts to simplify running live tests: +1. `live-test-setup.sh` builds a docker image with the necessary setup and runs it. The environment is ready, when the log stops - it takes approximately 30 seconds. +2. `live-test.sh` runs the live tests (but no other tests). +3. `live-test-setup.sh` stops and removes the docker image. diff --git a/persistence-modules/spring-data-mongodb/live-test-setup.sh b/persistence-modules/spring-data-mongodb/live-test-setup.sh new file mode 100644 index 0000000000..37e6c48dbd --- /dev/null +++ b/persistence-modules/spring-data-mongodb/live-test-setup.sh @@ -0,0 +1,5 @@ +#!/bin/bash + +docker image build -t spring-data-mongodb:live-test live-test/ + +docker run -p 27017:27017 --name spring-data-mongodb-live-test spring-data-mongodb:live-test diff --git a/persistence-modules/spring-data-mongodb/live-test-teardown.sh b/persistence-modules/spring-data-mongodb/live-test-teardown.sh new file mode 100644 index 0000000000..a29163bc7a --- /dev/null +++ b/persistence-modules/spring-data-mongodb/live-test-teardown.sh @@ -0,0 +1,4 @@ +#!/bin/bash + +docker stop spring-data-mongodb-live-test +docker rm spring-data-mongodb-live-test diff --git a/persistence-modules/spring-data-mongodb/live-test.sh b/persistence-modules/spring-data-mongodb/live-test.sh index bb513a90bb..5a079bdac8 100755 --- a/persistence-modules/spring-data-mongodb/live-test.sh +++ b/persistence-modules/spring-data-mongodb/live-test.sh @@ -1,11 +1,3 @@ #!/bin/bash -docker image build -t spring-data-mongodb:live-test live-test/ - -docker run -p 27017:27017 --name spring-data-mongodb-live-test -it spring-data-mongodb:live-test -#wait - mvn clean compile test -P live-all - -docker stop spring-data-mongodb-live-test -docker rm spring-data-mongodb-live-test From 1afd7a40e20ba55edd147e2f95c873f46c3b8539 Mon Sep 17 00:00:00 2001 From: fejera Date: Mon, 2 Dec 2019 10:18:42 +0100 Subject: [PATCH 04/47] moved live test resources to src/live-test/resources --- persistence-modules/spring-data-mongodb/live-test-setup.sh | 2 +- .../{live-test => src/live-test/resources}/Dockerfile | 0 .../{live-test => src/live-test/resources}/init-session.js | 0 3 files changed, 1 insertion(+), 1 deletion(-) rename persistence-modules/spring-data-mongodb/{live-test => src/live-test/resources}/Dockerfile (100%) rename persistence-modules/spring-data-mongodb/{live-test => src/live-test/resources}/init-session.js (100%) diff --git a/persistence-modules/spring-data-mongodb/live-test-setup.sh b/persistence-modules/spring-data-mongodb/live-test-setup.sh index 37e6c48dbd..e8e0437083 100644 --- a/persistence-modules/spring-data-mongodb/live-test-setup.sh +++ b/persistence-modules/spring-data-mongodb/live-test-setup.sh @@ -1,5 +1,5 @@ #!/bin/bash -docker image build -t spring-data-mongodb:live-test live-test/ +docker image build -t spring-data-mongodb:live-test src/live-test/resources/ docker run -p 27017:27017 --name spring-data-mongodb-live-test spring-data-mongodb:live-test diff --git a/persistence-modules/spring-data-mongodb/live-test/Dockerfile b/persistence-modules/spring-data-mongodb/src/live-test/resources/Dockerfile similarity index 100% rename from persistence-modules/spring-data-mongodb/live-test/Dockerfile rename to persistence-modules/spring-data-mongodb/src/live-test/resources/Dockerfile diff --git a/persistence-modules/spring-data-mongodb/live-test/init-session.js b/persistence-modules/spring-data-mongodb/src/live-test/resources/init-session.js similarity index 100% rename from persistence-modules/spring-data-mongodb/live-test/init-session.js rename to persistence-modules/spring-data-mongodb/src/live-test/resources/init-session.js From 0a5fbbe0e7626062cf5810970b07e65c1472bcbe Mon Sep 17 00:00:00 2001 From: Greg Martin Date: Mon, 16 Mar 2020 16:55:14 -0400 Subject: [PATCH 05/47] Moved NullAwayExample.java to libraries-3. Updated the libraries-3 README --- libraries-3/README.md | 1 + .../src/main/java/com/baeldung/nullaway/NullAwayExample.java | 0 2 files changed, 1 insertion(+) rename {libraries => libraries-3}/src/main/java/com/baeldung/nullaway/NullAwayExample.java (100%) diff --git a/libraries-3/README.md b/libraries-3/README.md index 404045e6b1..2692d606f3 100644 --- a/libraries-3/README.md +++ b/libraries-3/README.md @@ -12,3 +12,4 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m - [Guide to the Cactoos Library](https://www.baeldung.com/java-cactoos) - [Parsing Command-Line Parameters with Airline](https://www.baeldung.com/java-airline) - [Introduction to cache2k](https://www.baeldung.com/java-cache2k) +- [Using NullAway to Avoid NullPointerExceptions](https://www.baeldung.com/java-nullaway) diff --git a/libraries/src/main/java/com/baeldung/nullaway/NullAwayExample.java b/libraries-3/src/main/java/com/baeldung/nullaway/NullAwayExample.java similarity index 100% rename from libraries/src/main/java/com/baeldung/nullaway/NullAwayExample.java rename to libraries-3/src/main/java/com/baeldung/nullaway/NullAwayExample.java From 159370411205f46ecbe50ad765c9efb586c1d65d Mon Sep 17 00:00:00 2001 From: Greg Martin Date: Tue, 17 Mar 2020 09:58:23 -0400 Subject: [PATCH 06/47] Added dependencies and plugins for NullAway example --- libraries-3/pom.xml | 57 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/libraries-3/pom.xml b/libraries-3/pom.xml index a438d423e2..dbe6dd194f 100644 --- a/libraries-3/pom.xml +++ b/libraries-3/pom.xml @@ -104,6 +104,23 @@ velocity-engine-core ${velocity-engine-core.version} + + com.uber.nullaway + nullaway + 0.3.0 + + + org.codehaus.plexus + plexus-compiler-javac-errorprone + 2.8 + + + + com.google.errorprone + error_prone_core + 2.1.3 + @@ -139,6 +156,46 @@ ${aspectjweaver.version} + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5 + + javac-with-errorprone + true + 1.8 + 1.8 + true + + + com.uber.nullaway + nullaway + 0.3.0 + + + + + + -XepExcludedPaths:(.*)/test/.*|(.*)/streamex/.* + -XepOpt:NullAway:AnnotatedPackages=com.baeldung.nullaway + + + + + org.codehaus.plexus + plexus-compiler-javac-errorprone + 2.8 + + + + com.google.errorprone + error_prone_core + 2.1.3 + + From 5861ebd6337f574226da2fcadb878401d9da4635 Mon Sep 17 00:00:00 2001 From: Greg Date: Tue, 17 Mar 2020 10:47:54 -0400 Subject: [PATCH 07/47] Update pom.xml --- libraries-3/pom.xml | 86 ++++++++++++++++++++++----------------------- 1 file changed, 43 insertions(+), 43 deletions(-) diff --git a/libraries-3/pom.xml b/libraries-3/pom.xml index dbe6dd194f..fe007dfc4d 100644 --- a/libraries-3/pom.xml +++ b/libraries-3/pom.xml @@ -104,23 +104,23 @@ velocity-engine-core ${velocity-engine-core.version} - - com.uber.nullaway - nullaway - 0.3.0 - - - org.codehaus.plexus - plexus-compiler-javac-errorprone - 2.8 - - - - com.google.errorprone - error_prone_core - 2.1.3 - + + com.uber.nullaway + nullaway + 0.3.0 + + + org.codehaus.plexus + plexus-compiler-javac-errorprone + 2.8 + + + + com.google.errorprone + error_prone_core + 2.1.3 + @@ -158,32 +158,32 @@ - - org.apache.maven.plugins - maven-compiler-plugin - 3.5 - - javac-with-errorprone - true - 1.8 - 1.8 - true - - - com.uber.nullaway - nullaway - 0.3.0 - - - - - - -XepExcludedPaths:(.*)/test/.*|(.*)/streamex/.* - -XepOpt:NullAway:AnnotatedPackages=com.baeldung.nullaway - - - - + + org.apache.maven.plugins + maven-compiler-plugin + 3.5 + + javac-with-errorprone + true + 1.8 + 1.8 + true + + + com.uber.nullaway + nullaway + 0.3.0 + + + + + + -XepExcludedPaths:(.*)/test/.*|(.*)/streamex/.* + -XepOpt:NullAway:AnnotatedPackages=com.baeldung.nullaway + + + + org.codehaus.plexus plexus-compiler-javac-errorprone 2.8 From f95c25d461a4abdb3e303404e7e8f965990d0c02 Mon Sep 17 00:00:00 2001 From: Greg Martin Date: Wed, 18 Mar 2020 16:01:52 -0400 Subject: [PATCH 08/47] Added com.baeldung.distinct.Person to libraries-3 --- .../java/com/baeldung/distinct/Person.java | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 libraries-3/src/main/java/com/baeldung/distinct/Person.java diff --git a/libraries-3/src/main/java/com/baeldung/distinct/Person.java b/libraries-3/src/main/java/com/baeldung/distinct/Person.java new file mode 100644 index 0000000000..8a2a5f7a45 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/distinct/Person.java @@ -0,0 +1,65 @@ +package com.baeldung.distinct; + +public class Person { + int age; + String name; + String email; + + public Person(int age, String name, String email) { + super(); + this.age = age; + this.name = name; + this.email = email; + } + + public int getAge() { + return age; + } + + public String getName() { + return name; + } + + public String getEmail() { + return email; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Person [age="); + builder.append(age); + builder.append(", name="); + builder.append(name); + builder.append(", email="); + builder.append(email); + builder.append("]"); + return builder.toString(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((email == null) ? 0 : email.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Person other = (Person) obj; + if (email == null) { + if (other.email != null) + return false; + } else if (!email.equals(other.email)) + return false; + return true; + } + +} From 4cd3cc23361cc1d9f70a4179a8050c8cb7b49bf6 Mon Sep 17 00:00:00 2001 From: Greg Martin Date: Thu, 19 Mar 2020 07:04:24 -0400 Subject: [PATCH 09/47] Updated error_prone_core version to 2.3.4. --- libraries-3/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries-3/pom.xml b/libraries-3/pom.xml index fe007dfc4d..5c373b88dc 100644 --- a/libraries-3/pom.xml +++ b/libraries-3/pom.xml @@ -193,7 +193,7 @@ com.google.errorprone error_prone_core - 2.1.3 + 2.3.4 From d16ed66dcc3e7e03ad7f5a225f25d5b4f606b6bf Mon Sep 17 00:00:00 2001 From: Greg Martin Date: Thu, 19 Mar 2020 09:18:23 -0400 Subject: [PATCH 10/47] Updated pom to tell errorprone to excluude the jcabi directory. --- libraries-3/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries-3/pom.xml b/libraries-3/pom.xml index 5c373b88dc..8e0a93c982 100644 --- a/libraries-3/pom.xml +++ b/libraries-3/pom.xml @@ -178,7 +178,7 @@ - -XepExcludedPaths:(.*)/test/.*|(.*)/streamex/.* + -XepExcludedPaths:(.*)/test/.*|(.*)/streamex/.*|(.*)/jcabi/.* -XepOpt:NullAway:AnnotatedPackages=com.baeldung.nullaway From c1b13d09314f92424cddca0c00171fc4ad87e139 Mon Sep 17 00:00:00 2001 From: Kirill Vlasov Date: Fri, 10 Apr 2020 20:21:01 +0500 Subject: [PATCH 11/47] BAEL-3969 Spring Security - Custom Logout Handler --- .../LogoutDemoApplication.java | 13 +++ .../customlogouthandler/MvcConfiguration.java | 51 +++++++++ .../services/UserCache.java | 33 ++++++ .../customlogouthandler/user/User.java | 61 ++++++++++ .../customlogouthandler/user/UserUtils.java | 13 +++ .../web/CustomLogoutHandler.java | 27 +++++ .../web/UserController.java | 30 +++++ ...application-customlogouthandler.properties | 5 + .../CustomLogoutHandlerIntegrationTest.java | 106 ++++++++++++++++++ .../resources/customlogouthandler/after.sql | 1 + .../application.properties | 5 + .../resources/customlogouthandler/before.sql | 1 + 12 files changed, 346 insertions(+) create mode 100644 spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/LogoutDemoApplication.java create mode 100644 spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/MvcConfiguration.java create mode 100644 spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/services/UserCache.java create mode 100644 spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/user/User.java create mode 100644 spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/user/UserUtils.java create mode 100644 spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/web/CustomLogoutHandler.java create mode 100644 spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/web/UserController.java create mode 100644 spring-security-modules/spring-security-mvc-boot-2/src/main/resources/application-customlogouthandler.properties create mode 100644 spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/customlogouthandler/CustomLogoutHandlerIntegrationTest.java create mode 100644 spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/after.sql create mode 100644 spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/application.properties create mode 100644 spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/before.sql diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/LogoutDemoApplication.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/LogoutDemoApplication.java new file mode 100644 index 0000000000..027334dd6b --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/LogoutDemoApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.customlogouthandler; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class LogoutDemoApplication { + + public static void main(String[] args) { + SpringApplication.run(LogoutDemoApplication.class, args); + } + +} diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/MvcConfiguration.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/MvcConfiguration.java new file mode 100644 index 0000000000..36de049a31 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/MvcConfiguration.java @@ -0,0 +1,51 @@ +package com.baeldung.customlogouthandler; + +import com.baeldung.customlogouthandler.web.CustomLogoutHandler; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +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.web.authentication.logout.HttpStatusReturningLogoutSuccessHandler; + +import javax.sql.DataSource; + +@Configuration +@EnableWebSecurity +public class MvcConfiguration extends WebSecurityConfigurerAdapter { + + @Autowired + private DataSource dataSource; + + @Autowired + private CustomLogoutHandler logoutHandler; + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .httpBasic().and() + .authorizeRequests() + .antMatchers(HttpMethod.GET, "/user/**").hasRole("USER") + .and() + .logout() + .logoutUrl("/user/logout") + .addLogoutHandler(logoutHandler) + .logoutSuccessHandler((new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK))) + .permitAll() + .and() + .csrf().disable() + .formLogin().disable(); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.jdbcAuthentication() + .dataSource(dataSource) + .usersByUsernameQuery("select login, password, true from users where login=?") + .authoritiesByUsernameQuery("select login, role from users where login=?"); + } + +} diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/services/UserCache.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/services/UserCache.java new file mode 100644 index 0000000000..56c4d1e7c9 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/services/UserCache.java @@ -0,0 +1,33 @@ +package com.baeldung.customlogouthandler.services; + +import com.baeldung.customlogouthandler.user.User; +import org.springframework.stereotype.Service; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +@Service +public class UserCache { + + @PersistenceContext + private EntityManager entityManager; + + private final ConcurrentMap store = new ConcurrentHashMap<>(256); + + public User getByLogin(String login) { + return store.computeIfAbsent(login, k -> entityManager.createQuery("from User where login=:login", User.class) + .setParameter("login", k) + .getSingleResult()); + } + + public void evictUser(String login) { + store.remove(login); + } + + public int size() { + return this.store.size(); + } + +} diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/user/User.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/user/User.java new file mode 100644 index 0000000000..ca3a998c5c --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/user/User.java @@ -0,0 +1,61 @@ +package com.baeldung.customlogouthandler.user; + +import javax.persistence.*; + +@Entity +@Table(name = "users") +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + @Column(unique = true) + private String login; + + private String password; + + private String role; + + private String language; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getLogin() { + return login; + } + + public void setLogin(String login) { + this.login = login; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getRole() { + return role; + } + + public void setRole(String role) { + this.role = role; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } +} diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/user/UserUtils.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/user/UserUtils.java new file mode 100644 index 0000000000..195497f7ba --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/user/UserUtils.java @@ -0,0 +1,13 @@ +package com.baeldung.customlogouthandler.user; + +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; + +public class UserUtils { + + public static String getAuthenticatedUserLogin() { + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + return auth != null ? ((org.springframework.security.core.userdetails.User) auth.getPrincipal()).getUsername() : null; + } + +} diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/web/CustomLogoutHandler.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/web/CustomLogoutHandler.java new file mode 100644 index 0000000000..2a335cd122 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/web/CustomLogoutHandler.java @@ -0,0 +1,27 @@ +package com.baeldung.customlogouthandler.web; + +import com.baeldung.customlogouthandler.services.UserCache; +import com.baeldung.customlogouthandler.user.UserUtils; +import org.springframework.security.core.Authentication; +import org.springframework.security.web.authentication.logout.LogoutHandler; +import org.springframework.stereotype.Service; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@Service +public class CustomLogoutHandler implements LogoutHandler { + + private final UserCache userCache; + + public CustomLogoutHandler(UserCache userCache) { + this.userCache = userCache; + } + + @Override + public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { + String login = UserUtils.getAuthenticatedUserLogin(); + userCache.evictUser(login); + } + +} diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/web/UserController.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/web/UserController.java new file mode 100644 index 0000000000..18cd8dda98 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/web/UserController.java @@ -0,0 +1,30 @@ +package com.baeldung.customlogouthandler.web; + +import com.baeldung.customlogouthandler.services.UserCache; +import com.baeldung.customlogouthandler.user.User; +import com.baeldung.customlogouthandler.user.UserUtils; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + + +@Controller +@RequestMapping(path = "/user") +public class UserController { + + private final UserCache userCache; + + public UserController(UserCache userCache) { + this.userCache = userCache; + } + + @GetMapping(path = "/language") + @ResponseBody + public String getLanguage() { + String login = UserUtils.getAuthenticatedUserLogin(); + User user = userCache.getByLogin(login); + return user.getLanguage(); + } + +} diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/application-customlogouthandler.properties b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/application-customlogouthandler.properties new file mode 100644 index 0000000000..2cb766378d --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/application-customlogouthandler.properties @@ -0,0 +1,5 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/test +spring.datasource.username=test +spring.datasource.password=test + +spring.jpa.hibernate.ddl-auto=create \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/customlogouthandler/CustomLogoutHandlerIntegrationTest.java b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/customlogouthandler/CustomLogoutHandlerIntegrationTest.java new file mode 100644 index 0000000000..3c325a2006 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/customlogouthandler/CustomLogoutHandlerIntegrationTest.java @@ -0,0 +1,106 @@ +package com.baeldung.customlogouthandler; + +import com.baeldung.customlogouthandler.services.UserCache; +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.jdbc.Sql; +import org.springframework.test.context.jdbc.SqlGroup; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = {LogoutDemoApplication.class, MvcConfiguration.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@SqlGroup({ + @Sql(value = "classpath:customlogouthandler/before.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD), + @Sql(value = "classpath:customlogouthandler/after.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) +}) +class CustomLogoutHandlerIntegrationTest { + + @Autowired + private TestRestTemplate restTemplate; + + @Autowired + private UserCache userCache; + + @LocalServerPort + private int port; + + @Test + public void whenLogin_thenUseUserCache() throws Exception { + // User cache should be empty on start + assertThat(userCache.size()).isEqualTo(0); + + // Request using first login + ResponseEntity response = restTemplate + .withBasicAuth("user", "pass") + .getForEntity(getLanguageUrl(), String.class); + + assertThat(response.getBody()).contains("english"); + + // User cache must contain the user + assertThat(userCache.size()).isEqualTo(1); + + // Getting the session cookie + HttpHeaders requestHeaders = new HttpHeaders(); + requestHeaders.add("Cookie", response.getHeaders().getFirst(HttpHeaders.SET_COOKIE)); + + // Request with the session cookie + response = restTemplate + .exchange(getLanguageUrl(), HttpMethod.GET, new HttpEntity(requestHeaders), String.class); + assertThat(response.getBody()).contains("english"); + + // Logging out using the session cookies + response = restTemplate.exchange(getLogoutUrl(), HttpMethod.GET, new HttpEntity(requestHeaders), String.class); + assertThat(response.getStatusCode().value()).isEqualTo(200); + } + + @Test + public void whenLogout_thenCacheIsEmpty() throws Exception { + // User cache should be empty on start + assertThat(userCache.size()).isEqualTo(0); + + // Request using first login + ResponseEntity response = restTemplate + .withBasicAuth("user", "pass") + .getForEntity(getLanguageUrl(), String.class); + + assertThat(response.getBody()).contains("english"); + + // User cache must contain the user + assertThat(userCache.size()).isEqualTo(1); + + // Getting the session cookie + HttpHeaders requestHeaders = new HttpHeaders(); + requestHeaders.add("Cookie", response.getHeaders().getFirst(HttpHeaders.SET_COOKIE)); + + // Logging out using the session cookies + response = restTemplate.exchange(getLogoutUrl(), HttpMethod.GET, new HttpEntity(requestHeaders), String.class); + assertThat(response.getStatusCode().value()).isEqualTo(200); + + // User cache must be empty now + // this is the reaction on custom logout filter execution + assertThat(userCache.size()).isEqualTo(0); + + // Assert unathorized request + response = restTemplate.exchange(getLanguageUrl(), HttpMethod.GET, new HttpEntity(requestHeaders), String.class); + assertThat(response.getStatusCode().value()).isEqualTo(401); + } + + private String getLanguageUrl() { + return "http://localhost:" + port + "/user/language"; + } + + private String getLogoutUrl() { + return "http://localhost:" + port + "/user/logout"; + } + +} diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/after.sql b/spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/after.sql new file mode 100644 index 0000000000..df6f312987 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/after.sql @@ -0,0 +1 @@ +delete from users; \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/application.properties b/spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/application.properties new file mode 100644 index 0000000000..8b6d47ebe9 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/application.properties @@ -0,0 +1,5 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/develop +spring.datasource.username=develop +spring.datasource.password=develop + +spring.jpa.hibernate.ddl-auto=create diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/before.sql b/spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/before.sql new file mode 100644 index 0000000000..bb0a85f613 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/before.sql @@ -0,0 +1 @@ +insert into users (login, password, role, language) values ('user', '{noop}pass', 'ROLE_USER', 'english'); \ No newline at end of file From 07b5c1f01020dfbd7a3dfa17054f21347d451c65 Mon Sep 17 00:00:00 2001 From: Kirill Vlasov Date: Sun, 12 Apr 2020 16:16:36 +0500 Subject: [PATCH 12/47] Code review fixes --- ...tion.java => CustomLogoutApplication.java} | 8 +- .../customlogouthandler/MvcConfiguration.java | 30 ++-- .../services/UserCache.java | 24 ++-- .../customlogouthandler/user/UserUtils.java | 5 +- .../web/CustomLogoutHandler.java | 13 +- .../web/UserController.java | 10 +- .../CustomLogoutHandlerIntegrationTest.java | 132 +++++++++--------- .../application.properties | 6 +- 8 files changed, 119 insertions(+), 109 deletions(-) rename spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/{LogoutDemoApplication.java => CustomLogoutApplication.java} (54%) diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/LogoutDemoApplication.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/CustomLogoutApplication.java similarity index 54% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/LogoutDemoApplication.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/CustomLogoutApplication.java index 027334dd6b..39d867b1f4 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/LogoutDemoApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/CustomLogoutApplication.java @@ -4,10 +4,10 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication -public class LogoutDemoApplication { +public class CustomLogoutApplication { - public static void main(String[] args) { - SpringApplication.run(LogoutDemoApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(CustomLogoutApplication.class, args); + } } diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/MvcConfiguration.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/MvcConfiguration.java index 36de049a31..3e17a7c397 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/MvcConfiguration.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/MvcConfiguration.java @@ -1,6 +1,7 @@ package com.baeldung.customlogouthandler; -import com.baeldung.customlogouthandler.web.CustomLogoutHandler; +import javax.sql.DataSource; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; @@ -11,7 +12,7 @@ import org.springframework.security.config.annotation.web.configuration.EnableWe import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.authentication.logout.HttpStatusReturningLogoutSuccessHandler; -import javax.sql.DataSource; +import com.baeldung.customlogouthandler.web.CustomLogoutHandler; @Configuration @EnableWebSecurity @@ -25,27 +26,30 @@ public class MvcConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { - http - .httpBasic().and() + http.httpBasic() + .and() .authorizeRequests() - .antMatchers(HttpMethod.GET, "/user/**").hasRole("USER") - .and() - .logout() + .antMatchers(HttpMethod.GET, "/user/**") + .hasRole("USER") + .and() + .logout() .logoutUrl("/user/logout") .addLogoutHandler(logoutHandler) .logoutSuccessHandler((new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK))) .permitAll() - .and() - .csrf().disable() - .formLogin().disable(); + .and() + .csrf() + .disable() + .formLogin() + .disable(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.jdbcAuthentication() - .dataSource(dataSource) - .usersByUsernameQuery("select login, password, true from users where login=?") - .authoritiesByUsernameQuery("select login, role from users where login=?"); + .dataSource(dataSource) + .usersByUsernameQuery("select login, password, true from users where login=?") + .authoritiesByUsernameQuery("select login, role from users where login=?"); } } diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/services/UserCache.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/services/UserCache.java index 56c4d1e7c9..b86edc0dee 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/services/UserCache.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/services/UserCache.java @@ -1,12 +1,14 @@ package com.baeldung.customlogouthandler.services; -import com.baeldung.customlogouthandler.user.User; -import org.springframework.stereotype.Service; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; + +import org.springframework.stereotype.Service; + +import com.baeldung.customlogouthandler.user.User; @Service public class UserCache { @@ -16,18 +18,18 @@ public class UserCache { private final ConcurrentMap store = new ConcurrentHashMap<>(256); - public User getByLogin(String login) { - return store.computeIfAbsent(login, k -> entityManager.createQuery("from User where login=:login", User.class) - .setParameter("login", k) - .getSingleResult()); + public User getByUserName(String userName) { + return store.computeIfAbsent(userName, k -> entityManager.createQuery("from User where login=:login", User.class) + .setParameter("login", k) + .getSingleResult()); } - public void evictUser(String login) { - store.remove(login); + public void evictUser(String userName) { + store.remove(userName); } public int size() { - return this.store.size(); + return store.size(); } } diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/user/UserUtils.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/user/UserUtils.java index 195497f7ba..aa9a521b01 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/user/UserUtils.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/user/UserUtils.java @@ -5,8 +5,9 @@ import org.springframework.security.core.context.SecurityContextHolder; public class UserUtils { - public static String getAuthenticatedUserLogin() { - Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + public static String getAuthenticatedUserName() { + Authentication auth = SecurityContextHolder.getContext() + .getAuthentication(); return auth != null ? ((org.springframework.security.core.userdetails.User) auth.getPrincipal()).getUsername() : null; } diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/web/CustomLogoutHandler.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/web/CustomLogoutHandler.java index 2a335cd122..a89c9a570d 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/web/CustomLogoutHandler.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/web/CustomLogoutHandler.java @@ -1,13 +1,14 @@ package com.baeldung.customlogouthandler.web; -import com.baeldung.customlogouthandler.services.UserCache; -import com.baeldung.customlogouthandler.user.UserUtils; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.logout.LogoutHandler; import org.springframework.stereotype.Service; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import com.baeldung.customlogouthandler.services.UserCache; +import com.baeldung.customlogouthandler.user.UserUtils; @Service public class CustomLogoutHandler implements LogoutHandler { @@ -20,8 +21,8 @@ public class CustomLogoutHandler implements LogoutHandler { @Override public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { - String login = UserUtils.getAuthenticatedUserLogin(); - userCache.evictUser(login); + String userName = UserUtils.getAuthenticatedUserName(); + userCache.evictUser(userName); } } diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/web/UserController.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/web/UserController.java index 18cd8dda98..b2d332a1bb 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/web/UserController.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/web/UserController.java @@ -1,13 +1,13 @@ package com.baeldung.customlogouthandler.web; -import com.baeldung.customlogouthandler.services.UserCache; -import com.baeldung.customlogouthandler.user.User; -import com.baeldung.customlogouthandler.user.UserUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; +import com.baeldung.customlogouthandler.services.UserCache; +import com.baeldung.customlogouthandler.user.User; +import com.baeldung.customlogouthandler.user.UserUtils; @Controller @RequestMapping(path = "/user") @@ -22,8 +22,8 @@ public class UserController { @GetMapping(path = "/language") @ResponseBody public String getLanguage() { - String login = UserUtils.getAuthenticatedUserLogin(); - User user = userCache.getByLogin(login); + String userName = UserUtils.getAuthenticatedUserName(); + User user = userCache.getByUserName(userName); return user.getLanguage(); } diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/customlogouthandler/CustomLogoutHandlerIntegrationTest.java b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/customlogouthandler/CustomLogoutHandlerIntegrationTest.java index 3c325a2006..cd8a1a72d6 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/customlogouthandler/CustomLogoutHandlerIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/customlogouthandler/CustomLogoutHandlerIntegrationTest.java @@ -1,6 +1,7 @@ package com.baeldung.customlogouthandler; -import com.baeldung.customlogouthandler.services.UserCache; +import static org.assertj.core.api.Assertions.assertThat; + import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -11,96 +12,97 @@ import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; +import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.context.jdbc.SqlGroup; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.assertj.core.api.Assertions.assertThat; +import com.baeldung.customlogouthandler.services.UserCache; @RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = {LogoutDemoApplication.class, MvcConfiguration.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@SqlGroup({ - @Sql(value = "classpath:customlogouthandler/before.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD), - @Sql(value = "classpath:customlogouthandler/after.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) -}) +@SpringBootTest(classes = { CustomLogoutApplication.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@SqlGroup({ @Sql(value = "classpath:customlogouthandler/before.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD), @Sql(value = "classpath:customlogouthandler/after.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) }) +@TestPropertySource(locations="classpath:customlogouthandler/application.properties") class CustomLogoutHandlerIntegrationTest { - @Autowired - private TestRestTemplate restTemplate; + @Autowired + private TestRestTemplate restTemplate; - @Autowired - private UserCache userCache; + @Autowired + private UserCache userCache; - @LocalServerPort - private int port; + @LocalServerPort + private int port; - @Test - public void whenLogin_thenUseUserCache() throws Exception { - // User cache should be empty on start - assertThat(userCache.size()).isEqualTo(0); + @Test + public void whenLogin_thenUseUserCache() { + // User cache should be empty on start + assertThat(userCache.size()).isEqualTo(0); - // Request using first login - ResponseEntity response = restTemplate - .withBasicAuth("user", "pass") - .getForEntity(getLanguageUrl(), String.class); + // Request using first login + ResponseEntity response = restTemplate.withBasicAuth("user", "pass") + .getForEntity(getLanguageUrl(), String.class); - assertThat(response.getBody()).contains("english"); + assertThat(response.getBody()).contains("english"); - // User cache must contain the user - assertThat(userCache.size()).isEqualTo(1); + // User cache must contain the user + assertThat(userCache.size()).isEqualTo(1); - // Getting the session cookie - HttpHeaders requestHeaders = new HttpHeaders(); - requestHeaders.add("Cookie", response.getHeaders().getFirst(HttpHeaders.SET_COOKIE)); + // Getting the session cookie + HttpHeaders requestHeaders = new HttpHeaders(); + requestHeaders.add("Cookie", response.getHeaders() + .getFirst(HttpHeaders.SET_COOKIE)); - // Request with the session cookie - response = restTemplate - .exchange(getLanguageUrl(), HttpMethod.GET, new HttpEntity(requestHeaders), String.class); - assertThat(response.getBody()).contains("english"); + // Request with the session cookie + response = restTemplate.exchange(getLanguageUrl(), HttpMethod.GET, new HttpEntity(requestHeaders), String.class); + assertThat(response.getBody()).contains("english"); - // Logging out using the session cookies - response = restTemplate.exchange(getLogoutUrl(), HttpMethod.GET, new HttpEntity(requestHeaders), String.class); - assertThat(response.getStatusCode().value()).isEqualTo(200); - } + // Logging out using the session cookies + response = restTemplate.exchange(getLogoutUrl(), HttpMethod.GET, new HttpEntity(requestHeaders), String.class); + assertThat(response.getStatusCode() + .value()).isEqualTo(200); + } - @Test - public void whenLogout_thenCacheIsEmpty() throws Exception { - // User cache should be empty on start - assertThat(userCache.size()).isEqualTo(0); + @Test + public void whenLogout_thenCacheIsEmpty() { + // User cache should be empty on start + assertThat(userCache.size()).isEqualTo(0); - // Request using first login - ResponseEntity response = restTemplate - .withBasicAuth("user", "pass") - .getForEntity(getLanguageUrl(), String.class); + // Request using first login + ResponseEntity response = restTemplate.withBasicAuth("user", "pass") + .getForEntity(getLanguageUrl(), String.class); - assertThat(response.getBody()).contains("english"); + assertThat(response.getBody()).contains("english"); - // User cache must contain the user - assertThat(userCache.size()).isEqualTo(1); + // User cache must contain the user + assertThat(userCache.size()).isEqualTo(1); - // Getting the session cookie - HttpHeaders requestHeaders = new HttpHeaders(); - requestHeaders.add("Cookie", response.getHeaders().getFirst(HttpHeaders.SET_COOKIE)); + // Getting the session cookie + HttpHeaders requestHeaders = new HttpHeaders(); + requestHeaders.add("Cookie", response.getHeaders() + .getFirst(HttpHeaders.SET_COOKIE)); - // Logging out using the session cookies - response = restTemplate.exchange(getLogoutUrl(), HttpMethod.GET, new HttpEntity(requestHeaders), String.class); - assertThat(response.getStatusCode().value()).isEqualTo(200); + // Logging out using the session cookies + response = restTemplate.exchange(getLogoutUrl(), HttpMethod.GET, new HttpEntity(requestHeaders), String.class); + assertThat(response.getStatusCode() + .value()).isEqualTo(200); - // User cache must be empty now - // this is the reaction on custom logout filter execution - assertThat(userCache.size()).isEqualTo(0); + // User cache must be empty now + // this is the reaction on custom logout filter execution + assertThat(userCache.size()).isEqualTo(0); - // Assert unathorized request - response = restTemplate.exchange(getLanguageUrl(), HttpMethod.GET, new HttpEntity(requestHeaders), String.class); - assertThat(response.getStatusCode().value()).isEqualTo(401); - } + // Assert unauthorized request + response = restTemplate.exchange(getLanguageUrl(), HttpMethod.GET, new HttpEntity(requestHeaders), String.class); + assertThat(response.getStatusCode() + .value()).isEqualTo(401); + } - private String getLanguageUrl() { - return "http://localhost:" + port + "/user/language"; - } + private String getLanguageUrl() { + return "http://localhost:" + port + "/user/language"; + } - private String getLogoutUrl() { - return "http://localhost:" + port + "/user/logout"; - } + private String getLogoutUrl() { + return "http://localhost:" + port + "/user/logout"; + } } diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/application.properties b/spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/application.properties index 8b6d47ebe9..9edd853f2c 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/application.properties +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/application.properties @@ -1,5 +1,5 @@ -spring.datasource.url=jdbc:postgresql://localhost:5432/develop -spring.datasource.username=develop -spring.datasource.password=develop +spring.datasource.url=jdbc:postgresql://localhost:5432/test +spring.datasource.username=test +spring.datasource.password=test spring.jpa.hibernate.ddl-auto=create From 7678f4a0cc7feb670715f7f3c3124bbdebc9bec5 Mon Sep 17 00:00:00 2001 From: Kirill Vlasov Date: Sat, 18 Apr 2020 08:00:52 +0500 Subject: [PATCH 13/47] Code review --- .../java/com/baeldung/customlogouthandler/MvcConfiguration.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/MvcConfiguration.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/MvcConfiguration.java index 3e17a7c397..c363effb4e 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/MvcConfiguration.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/MvcConfiguration.java @@ -35,7 +35,7 @@ public class MvcConfiguration extends WebSecurityConfigurerAdapter { .logout() .logoutUrl("/user/logout") .addLogoutHandler(logoutHandler) - .logoutSuccessHandler((new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK))) + .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK)) .permitAll() .and() .csrf() From 374905467e7ed9769c9cd6d834652a7198a22350 Mon Sep 17 00:00:00 2001 From: Justin Albano Date: Sat, 18 Apr 2020 11:48:26 -0400 Subject: [PATCH 14/47] BAEL-3965: Created examples for instance and static factory methods. --- .../java/com/baeldung/factorymethod/Bar.java | 18 ++++++++++++++ .../java/com/baeldung/factorymethod/Foo.java | 5 ++++ .../factorymethod/InstanceBarFactory.java | 8 +++++++ .../factorymethod/InstanceFooFactory.java | 8 +++++++ .../factorymethod/SingletonBarFactory.java | 11 +++++++++ .../factorymethod/SingletonFooFactory.java | 10 ++++++++ .../InstanceBarFactoryIntegrationTest.java | 24 +++++++++++++++++++ .../InstanceFooFactoryIntegrationTest.java | 22 +++++++++++++++++ .../SingletonBarFactoryIntegrationTest.java | 24 +++++++++++++++++++ .../SingletonFooFactoryIntegrationTest.java | 22 +++++++++++++++++ .../factorymethod/instance-bar-config.xml | 20 ++++++++++++++++ .../factorymethod/instance-foo-config.xml | 18 ++++++++++++++ .../factorymethod/static-bar-config.xml | 20 ++++++++++++++++ .../factorymethod/static-foo-config.xml | 18 ++++++++++++++ 14 files changed, 228 insertions(+) create mode 100644 spring-core-3/src/main/java/com/baeldung/factorymethod/Bar.java create mode 100644 spring-core-3/src/main/java/com/baeldung/factorymethod/Foo.java create mode 100644 spring-core-3/src/main/java/com/baeldung/factorymethod/InstanceBarFactory.java create mode 100644 spring-core-3/src/main/java/com/baeldung/factorymethod/InstanceFooFactory.java create mode 100644 spring-core-3/src/main/java/com/baeldung/factorymethod/SingletonBarFactory.java create mode 100644 spring-core-3/src/main/java/com/baeldung/factorymethod/SingletonFooFactory.java create mode 100644 spring-core-3/src/test/java/com/baeldung/factorymethod/InstanceBarFactoryIntegrationTest.java create mode 100644 spring-core-3/src/test/java/com/baeldung/factorymethod/InstanceFooFactoryIntegrationTest.java create mode 100644 spring-core-3/src/test/java/com/baeldung/factorymethod/SingletonBarFactoryIntegrationTest.java create mode 100644 spring-core-3/src/test/java/com/baeldung/factorymethod/SingletonFooFactoryIntegrationTest.java create mode 100644 spring-core-3/src/test/resources/factorymethod/instance-bar-config.xml create mode 100644 spring-core-3/src/test/resources/factorymethod/instance-foo-config.xml create mode 100644 spring-core-3/src/test/resources/factorymethod/static-bar-config.xml create mode 100644 spring-core-3/src/test/resources/factorymethod/static-foo-config.xml diff --git a/spring-core-3/src/main/java/com/baeldung/factorymethod/Bar.java b/spring-core-3/src/main/java/com/baeldung/factorymethod/Bar.java new file mode 100644 index 0000000000..22ef5b3429 --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/factorymethod/Bar.java @@ -0,0 +1,18 @@ +package com.baeldung.factorymethod; + +public class Bar { + + private String name; + + public Bar(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/spring-core-3/src/main/java/com/baeldung/factorymethod/Foo.java b/spring-core-3/src/main/java/com/baeldung/factorymethod/Foo.java new file mode 100644 index 0000000000..54bd0c9ff4 --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/factorymethod/Foo.java @@ -0,0 +1,5 @@ +package com.baeldung.factorymethod; + +public class Foo { + +} diff --git a/spring-core-3/src/main/java/com/baeldung/factorymethod/InstanceBarFactory.java b/spring-core-3/src/main/java/com/baeldung/factorymethod/InstanceBarFactory.java new file mode 100644 index 0000000000..f834b82aee --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/factorymethod/InstanceBarFactory.java @@ -0,0 +1,8 @@ +package com.baeldung.factorymethod; + +public class InstanceBarFactory { + + public Bar createInstance(String name) { + return new Bar(name); + } +} diff --git a/spring-core-3/src/main/java/com/baeldung/factorymethod/InstanceFooFactory.java b/spring-core-3/src/main/java/com/baeldung/factorymethod/InstanceFooFactory.java new file mode 100644 index 0000000000..c3125d3339 --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/factorymethod/InstanceFooFactory.java @@ -0,0 +1,8 @@ +package com.baeldung.factorymethod; + +public class InstanceFooFactory { + + public Foo createInstance() { + return new Foo(); + } +} diff --git a/spring-core-3/src/main/java/com/baeldung/factorymethod/SingletonBarFactory.java b/spring-core-3/src/main/java/com/baeldung/factorymethod/SingletonBarFactory.java new file mode 100644 index 0000000000..93802819b1 --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/factorymethod/SingletonBarFactory.java @@ -0,0 +1,11 @@ +package com.baeldung.factorymethod; + +public class SingletonBarFactory { + + private static final Bar INSTANCE = new Bar("unnamed"); + + public static Bar createInstance(String name) { + INSTANCE.setName(name); + return INSTANCE; + } +} diff --git a/spring-core-3/src/main/java/com/baeldung/factorymethod/SingletonFooFactory.java b/spring-core-3/src/main/java/com/baeldung/factorymethod/SingletonFooFactory.java new file mode 100644 index 0000000000..77d56cc7f6 --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/factorymethod/SingletonFooFactory.java @@ -0,0 +1,10 @@ +package com.baeldung.factorymethod; + +public class SingletonFooFactory { + + private static final Foo INSTANCE = new Foo(); + + public static Foo createInstance() { + return INSTANCE; + } +} diff --git a/spring-core-3/src/test/java/com/baeldung/factorymethod/InstanceBarFactoryIntegrationTest.java b/spring-core-3/src/test/java/com/baeldung/factorymethod/InstanceBarFactoryIntegrationTest.java new file mode 100644 index 0000000000..b5728316e7 --- /dev/null +++ b/spring-core-3/src/test/java/com/baeldung/factorymethod/InstanceBarFactoryIntegrationTest.java @@ -0,0 +1,24 @@ +package com.baeldung.factorymethod; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("/factorymethod/instance-bar-config.xml") +public class InstanceBarFactoryIntegrationTest { + + @Autowired + private Bar instance; + + @Test + public void givenValidInstanceFactoryConfig_whenCreateInstance_thenNameIsCorrect() { + assertNotNull(instance); + assertEquals("someName", instance.getName()); + } +} diff --git a/spring-core-3/src/test/java/com/baeldung/factorymethod/InstanceFooFactoryIntegrationTest.java b/spring-core-3/src/test/java/com/baeldung/factorymethod/InstanceFooFactoryIntegrationTest.java new file mode 100644 index 0000000000..6b1857c2f2 --- /dev/null +++ b/spring-core-3/src/test/java/com/baeldung/factorymethod/InstanceFooFactoryIntegrationTest.java @@ -0,0 +1,22 @@ +package com.baeldung.factorymethod; + +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("/factorymethod/instance-foo-config.xml") +public class InstanceFooFactoryIntegrationTest { + + @Autowired + private Foo foo; + + @Test + public void givenValidInstanceFactoryConfig_whenCreateFooInstance_thenInstanceIsNotNull() { + assertNotNull(foo); + } +} diff --git a/spring-core-3/src/test/java/com/baeldung/factorymethod/SingletonBarFactoryIntegrationTest.java b/spring-core-3/src/test/java/com/baeldung/factorymethod/SingletonBarFactoryIntegrationTest.java new file mode 100644 index 0000000000..403b46156b --- /dev/null +++ b/spring-core-3/src/test/java/com/baeldung/factorymethod/SingletonBarFactoryIntegrationTest.java @@ -0,0 +1,24 @@ +package com.baeldung.factorymethod; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("/factorymethod/static-bar-config.xml") +public class SingletonBarFactoryIntegrationTest { + + @Autowired + private Bar instance; + + @Test + public void givenValidStaticFactoryConfig_whenCreateInstance_thenNameIsCorrect() { + assertNotNull(instance); + assertEquals("someName", instance.getName()); + } +} diff --git a/spring-core-3/src/test/java/com/baeldung/factorymethod/SingletonFooFactoryIntegrationTest.java b/spring-core-3/src/test/java/com/baeldung/factorymethod/SingletonFooFactoryIntegrationTest.java new file mode 100644 index 0000000000..52154b81ab --- /dev/null +++ b/spring-core-3/src/test/java/com/baeldung/factorymethod/SingletonFooFactoryIntegrationTest.java @@ -0,0 +1,22 @@ +package com.baeldung.factorymethod; + +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("/factorymethod/static-foo-config.xml") +public class SingletonFooFactoryIntegrationTest { + + @Autowired + private Foo singleton; + + @Test + public void givenValidStaticFactoryConfig_whenCreateInstance_thenInstanceIsNotNull() { + assertNotNull(singleton); + } +} diff --git a/spring-core-3/src/test/resources/factorymethod/instance-bar-config.xml b/spring-core-3/src/test/resources/factorymethod/instance-bar-config.xml new file mode 100644 index 0000000000..40d2f33683 --- /dev/null +++ b/spring-core-3/src/test/resources/factorymethod/instance-bar-config.xml @@ -0,0 +1,20 @@ + + + + + + + + + + \ No newline at end of file diff --git a/spring-core-3/src/test/resources/factorymethod/instance-foo-config.xml b/spring-core-3/src/test/resources/factorymethod/instance-foo-config.xml new file mode 100644 index 0000000000..c45bef6a85 --- /dev/null +++ b/spring-core-3/src/test/resources/factorymethod/instance-foo-config.xml @@ -0,0 +1,18 @@ + + + + + + + + \ No newline at end of file diff --git a/spring-core-3/src/test/resources/factorymethod/static-bar-config.xml b/spring-core-3/src/test/resources/factorymethod/static-bar-config.xml new file mode 100644 index 0000000000..4d1befc645 --- /dev/null +++ b/spring-core-3/src/test/resources/factorymethod/static-bar-config.xml @@ -0,0 +1,20 @@ + + + + + + + + \ No newline at end of file diff --git a/spring-core-3/src/test/resources/factorymethod/static-foo-config.xml b/spring-core-3/src/test/resources/factorymethod/static-foo-config.xml new file mode 100644 index 0000000000..83e61a656c --- /dev/null +++ b/spring-core-3/src/test/resources/factorymethod/static-foo-config.xml @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file From 95578f92ea2e77deca0d76a08be98675943df8db Mon Sep 17 00:00:00 2001 From: "amit.pandey" Date: Sun, 19 Apr 2020 18:09:24 +0530 Subject: [PATCH 15/47] update pom version from RC to GA --- core-java-modules/core-java-time-measurements/pom.xml | 2 +- jhipster/jhipster-uaa/gateway/pom.xml | 2 +- jhipster/jhipster-uaa/quotes/pom.xml | 2 +- jhipster/jhipster-uaa/uaa/pom.xml | 2 +- persistence-modules/java-jpa-2/pom.xml | 2 +- persistence-modules/java-jpa/pom.xml | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/core-java-modules/core-java-time-measurements/pom.xml b/core-java-modules/core-java-time-measurements/pom.xml index 71a012ca2b..b751cc0d74 100644 --- a/core-java-modules/core-java-time-measurements/pom.xml +++ b/core-java-modules/core-java-time-measurements/pom.xml @@ -96,7 +96,7 @@ 3.6.1 1.8.9 - 2.0.0-RC.4 + 2.0.0 1.44 2.22.1 diff --git a/jhipster/jhipster-uaa/gateway/pom.xml b/jhipster/jhipster-uaa/gateway/pom.xml index 1b85877a9b..b417bd7b57 100644 --- a/jhipster/jhipster-uaa/gateway/pom.xml +++ b/jhipster/jhipster-uaa/gateway/pom.xml @@ -1013,7 +1013,7 @@ 1.0.0 - 0.24.0-RC.0 + 0.24.0 3.0.0 1.8 diff --git a/jhipster/jhipster-uaa/quotes/pom.xml b/jhipster/jhipster-uaa/quotes/pom.xml index aacc6f8e36..f088ad2fd1 100644 --- a/jhipster/jhipster-uaa/quotes/pom.xml +++ b/jhipster/jhipster-uaa/quotes/pom.xml @@ -910,6 +910,6 @@ ${project.basedir}/src/test/ - 0.24.0-RC.0 + 0.24.0 diff --git a/jhipster/jhipster-uaa/uaa/pom.xml b/jhipster/jhipster-uaa/uaa/pom.xml index 27a056820d..f9c1f226bb 100644 --- a/jhipster/jhipster-uaa/uaa/pom.xml +++ b/jhipster/jhipster-uaa/uaa/pom.xml @@ -835,7 +835,7 @@ 1.0.0 - 0.24.0-RC.0 + 0.24.0 3.0.0 1.8 diff --git a/persistence-modules/java-jpa-2/pom.xml b/persistence-modules/java-jpa-2/pom.xml index f79f6f1633..76b1033dac 100644 --- a/persistence-modules/java-jpa-2/pom.xml +++ b/persistence-modules/java-jpa-2/pom.xml @@ -111,7 +111,7 @@ 5.4.0.Final - 2.7.4-RC1 + 2.7.4 42.2.5 2.2 3.11.1 diff --git a/persistence-modules/java-jpa/pom.xml b/persistence-modules/java-jpa/pom.xml index 762c541d96..3601721dac 100644 --- a/persistence-modules/java-jpa/pom.xml +++ b/persistence-modules/java-jpa/pom.xml @@ -106,7 +106,7 @@ 5.4.0.Final - 2.7.4-RC1 + 2.7.4 42.2.5 2.2 3.3.3 From ffc79e7edd3d9825ce3f9ab3aaedd73efb15564b Mon Sep 17 00:00:00 2001 From: dupirefr Date: Fri, 17 Apr 2020 21:25:03 +0200 Subject: [PATCH 16/47] [JAVA-630] vavr-2 module * Creation * Moved https://www.baeldung.com/vavr-either code * Moved https://www.baeldung.com/java-vavr code --- pom.xml | 6 +++-- vavr-2/README.md | 8 ++++++ vavr-2/pom.xml | 27 +++++++++++++++++++ .../com/baeldung/vavr/either/EitherDemo.java | 0 .../baeldung/vavr/either/EitherUnitTest.java | 0 .../CollectionsInteroperabilityUnitTest.java | 0 vavr/README.md | 3 +-- 7 files changed, 40 insertions(+), 4 deletions(-) create mode 100644 vavr-2/README.md create mode 100644 vavr-2/pom.xml rename {vavr => vavr-2}/src/main/java/com/baeldung/vavr/either/EitherDemo.java (100%) rename {vavr => vavr-2}/src/test/java/com/baeldung/vavr/either/EitherUnitTest.java (100%) rename {vavr => vavr-2}/src/test/java/com/baeldung/vavr/interoperability/CollectionsInteroperabilityUnitTest.java (100%) diff --git a/pom.xml b/pom.xml index 02d1ab6cd2..1b3c98994f 100644 --- a/pom.xml +++ b/pom.xml @@ -812,7 +812,8 @@ libraries vaadin - vavr + vavr + vavr-2 @@ -1310,7 +1311,8 @@ libraries vaadin - vavr + vavr + vavr-2 diff --git a/vavr-2/README.md b/vavr-2/README.md new file mode 100644 index 0000000000..71814a08fd --- /dev/null +++ b/vavr-2/README.md @@ -0,0 +1,8 @@ +## Vavr + +This module contains articles about Vavr. + +### Relevant Articles: +- [Introduction to Vavr’s Either](https://www.baeldung.com/vavr-either) +- [Interoperability Between Java and Vavr](https://www.baeldung.com/java-vavr) +- [[<-- prev]](/vavr) diff --git a/vavr-2/pom.xml b/vavr-2/pom.xml new file mode 100644 index 0000000000..d20dd9afef --- /dev/null +++ b/vavr-2/pom.xml @@ -0,0 +1,27 @@ + + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + 4.0.0 + + vavr-2 + vavr-2 + jar + + + + io.vavr + vavr-test + ${vavr.version} + + + + + 0.9.1 + + \ No newline at end of file diff --git a/vavr/src/main/java/com/baeldung/vavr/either/EitherDemo.java b/vavr-2/src/main/java/com/baeldung/vavr/either/EitherDemo.java similarity index 100% rename from vavr/src/main/java/com/baeldung/vavr/either/EitherDemo.java rename to vavr-2/src/main/java/com/baeldung/vavr/either/EitherDemo.java diff --git a/vavr/src/test/java/com/baeldung/vavr/either/EitherUnitTest.java b/vavr-2/src/test/java/com/baeldung/vavr/either/EitherUnitTest.java similarity index 100% rename from vavr/src/test/java/com/baeldung/vavr/either/EitherUnitTest.java rename to vavr-2/src/test/java/com/baeldung/vavr/either/EitherUnitTest.java diff --git a/vavr/src/test/java/com/baeldung/vavr/interoperability/CollectionsInteroperabilityUnitTest.java b/vavr-2/src/test/java/com/baeldung/vavr/interoperability/CollectionsInteroperabilityUnitTest.java similarity index 100% rename from vavr/src/test/java/com/baeldung/vavr/interoperability/CollectionsInteroperabilityUnitTest.java rename to vavr-2/src/test/java/com/baeldung/vavr/interoperability/CollectionsInteroperabilityUnitTest.java diff --git a/vavr/README.md b/vavr/README.md index 2b8bb25356..e04e02069f 100644 --- a/vavr/README.md +++ b/vavr/README.md @@ -13,5 +13,4 @@ This module contains articles about Vavr. - [Guide to Collections API in Vavr](https://www.baeldung.com/vavr-collections) - [Collection Factory Methods for Vavr](https://www.baeldung.com/vavr-collection-factory-methods) - [Introduction to Future in Vavr](https://www.baeldung.com/vavr-future) -- [Introduction to Vavr’s Either](https://www.baeldung.com/vavr-either) -- [Interoperability Between Java and Vavr](https://www.baeldung.com/java-vavr) +- [[next -->]](/vavr-2) From 1639ead274ffbb256016ec36f6fa6f7a1c08cd58 Mon Sep 17 00:00:00 2001 From: Donato Rimenti Date: Mon, 20 Apr 2020 19:36:51 +0200 Subject: [PATCH 17/47] [BAEL-3489] Added Java-R integration examples. --- libraries-data-2/pom.xml | 43 +++++++++++++++++++ .../main/java/com/baeldung/r/FastRMean.java | 28 ++++++++++++ .../main/java/com/baeldung/r/RCallerMean.java | 36 ++++++++++++++++ .../src/main/java/com/baeldung/r/RUtils.java | 30 +++++++++++++ .../main/java/com/baeldung/r/RenjinMean.java | 36 ++++++++++++++++ .../main/java/com/baeldung/r/RserveMean.java | 29 +++++++++++++ .../com/baeldung/r/FastRMeanUnitTest.java | 29 +++++++++++++ .../r/RCallerMeanIntegrationTest.java | 37 ++++++++++++++++ .../com/baeldung/r/RenjinMeanUnitTest.java | 37 ++++++++++++++++ libraries-data-2/src/test/resources/script.R | 3 ++ 10 files changed, 308 insertions(+) create mode 100644 libraries-data-2/src/main/java/com/baeldung/r/FastRMean.java create mode 100644 libraries-data-2/src/main/java/com/baeldung/r/RCallerMean.java create mode 100644 libraries-data-2/src/main/java/com/baeldung/r/RUtils.java create mode 100644 libraries-data-2/src/main/java/com/baeldung/r/RenjinMean.java create mode 100644 libraries-data-2/src/main/java/com/baeldung/r/RserveMean.java create mode 100644 libraries-data-2/src/test/java/com/baeldung/r/FastRMeanUnitTest.java create mode 100644 libraries-data-2/src/test/java/com/baeldung/r/RCallerMeanIntegrationTest.java create mode 100644 libraries-data-2/src/test/java/com/baeldung/r/RenjinMeanUnitTest.java create mode 100644 libraries-data-2/src/test/resources/script.R diff --git a/libraries-data-2/pom.xml b/libraries-data-2/pom.xml index e6106c0fe3..ce15ef6c07 100644 --- a/libraries-data-2/pom.xml +++ b/libraries-data-2/pom.xml @@ -128,6 +128,24 @@ ${awaitility.version} test + + + org.rosuda.REngine + Rserve + ${rserve.version} + + + + com.github.jbytecode + RCaller + ${rcaller.version} + + + + org.renjin + renjin-script-engine + ${renjin.version} + @@ -137,6 +155,13 @@ http://repo.numericalmethod.com/maven/ default + + + + bedatadriven + bedatadriven public repo + https://nexus.bedatadriven.com/content/groups/public/ + @@ -153,6 +178,24 @@ 3.6.2 1.7.25 3.0.0 + RELEASE + 3.0 + 1.8.1 + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + com/baeldung/r/FastRMean.java + + + + + + \ No newline at end of file diff --git a/libraries-data-2/src/main/java/com/baeldung/r/FastRMean.java b/libraries-data-2/src/main/java/com/baeldung/r/FastRMean.java new file mode 100644 index 0000000000..52fb2d1506 --- /dev/null +++ b/libraries-data-2/src/main/java/com/baeldung/r/FastRMean.java @@ -0,0 +1,28 @@ +package com.baeldung.r; + +import java.io.IOException; +import java.net.URISyntaxException; + +/** + * FastR showcase. + * + * @author Donato Rimenti + */ +public class FastRMean { + + /** + * Invokes the customMean R function passing the given values as arguments. + * + * @param values the input to the mean script + * @return the result of the R script + */ + public double mean(int[] values) { + Context polyglot = Context.newBuilder().allowAllAccess(true).build(); + String meanScriptContent = RUtils.getMeanScriptContent(); + polyglot.eval("R", meanScriptContent); + Value rBindings = polyglot.getBindings("R"); + Value rInput = rBindings.getMember("c").execute(values); + return rBindings.getMember("customMean").execute(rInput).asDouble(); + } + +} \ No newline at end of file diff --git a/libraries-data-2/src/main/java/com/baeldung/r/RCallerMean.java b/libraries-data-2/src/main/java/com/baeldung/r/RCallerMean.java new file mode 100644 index 0000000000..53e0ab9e31 --- /dev/null +++ b/libraries-data-2/src/main/java/com/baeldung/r/RCallerMean.java @@ -0,0 +1,36 @@ +package com.baeldung.r; + +import java.io.IOException; +import java.net.URISyntaxException; + +import com.github.rcaller.rstuff.RCaller; +import com.github.rcaller.rstuff.RCallerOptions; +import com.github.rcaller.rstuff.RCode; + +/** + * RCaller showcase. + * + * @author Donato Rimenti + */ +public class RCallerMean { + + /** + * Invokes the customMean R function passing the given values as arguments. + * + * @param values the input to the mean script + * @return the result of the R script + * @throws IOException if any error occurs + * @throws URISyntaxException if any error occurs + */ + public double mean(int[] values) throws IOException, URISyntaxException { + String fileContent = RUtils.getMeanScriptContent(); + RCode code = RCode.create(); + code.addRCode(fileContent); + code.addIntArray("input", values); + code.addRCode("result <- customMean(input)"); + RCaller caller = RCaller.create(code, RCallerOptions.create()); + caller.runAndReturnResult("result"); + return caller.getParser().getAsDoubleArray("result")[0]; + } + +} \ No newline at end of file diff --git a/libraries-data-2/src/main/java/com/baeldung/r/RUtils.java b/libraries-data-2/src/main/java/com/baeldung/r/RUtils.java new file mode 100644 index 0000000000..ad16fd5602 --- /dev/null +++ b/libraries-data-2/src/main/java/com/baeldung/r/RUtils.java @@ -0,0 +1,30 @@ +package com.baeldung.r; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.stream.Collectors; + +/** + * Utility class for loading the script.R content. + * + * @author Donato Rimenti + */ +public class RUtils { + + /** + * Loads the script.R and returns its content as a string. + * + * @return the script.R content as a string + * @throws IOException if any error occurs + * @throws URISyntaxException if any error occurs + */ + static String getMeanScriptContent() throws IOException, URISyntaxException { + URI rScriptUri = RUtils.class.getClassLoader().getResource("script.R").toURI(); + Path inputScript = Paths.get(rScriptUri); + return Files.lines(inputScript).collect(Collectors.joining()); + } +} \ No newline at end of file diff --git a/libraries-data-2/src/main/java/com/baeldung/r/RenjinMean.java b/libraries-data-2/src/main/java/com/baeldung/r/RenjinMean.java new file mode 100644 index 0000000000..befb7d522f --- /dev/null +++ b/libraries-data-2/src/main/java/com/baeldung/r/RenjinMean.java @@ -0,0 +1,36 @@ +package com.baeldung.r; + +import java.io.IOException; +import java.net.URISyntaxException; + +import javax.script.ScriptException; + +import org.renjin.script.RenjinScriptEngine; +import org.renjin.sexp.DoubleArrayVector; + +/** + * Renjin showcase. + * + * @author Donato Rimenti + */ +public class RenjinMean { + + /** + * Invokes the customMean R function passing the given values as arguments. + * + * @param values the input to the mean script + * @return the result of the R script + * @throws IOException if any error occurs + * @throws URISyntaxException if any error occurs + * @throws ScriptException if any error occurs + */ + public double mean(int[] values) throws IOException, URISyntaxException, ScriptException { + RenjinScriptEngine engine = new RenjinScriptEngine(); + String meanScriptContent = RUtils.getMeanScriptContent(); + engine.put("input", values); + engine.eval(meanScriptContent); + DoubleArrayVector result = (DoubleArrayVector) engine.eval("customMean(input)"); + return result.asReal(); + } + +} \ No newline at end of file diff --git a/libraries-data-2/src/main/java/com/baeldung/r/RserveMean.java b/libraries-data-2/src/main/java/com/baeldung/r/RserveMean.java new file mode 100644 index 0000000000..51aaa90648 --- /dev/null +++ b/libraries-data-2/src/main/java/com/baeldung/r/RserveMean.java @@ -0,0 +1,29 @@ +package com.baeldung.r; + +import org.rosuda.REngine.REXPMismatchException; +import org.rosuda.REngine.REngineException; +import org.rosuda.REngine.Rserve.RConnection; + +/** + * Rserve showcase. + * + * @author Donato Rimenti + */ +public class RserveMean { + + /** + * Connects to the Rserve istance listening on 127.0.0.1:6311 and invokes the + * customMean R function passing the given values as arguments. + * + * @param values the input to the mean script + * @return the result of the R script + * @throws REngineException if any error occurs + * @throws REXPMismatchException if any error occurs + */ + public double mean(int[] values) throws REngineException, REXPMismatchException { + RConnection c = new RConnection(); + c.assign("input", values); + return c.eval("customMean(input)").asDouble(); + } + +} \ No newline at end of file diff --git a/libraries-data-2/src/test/java/com/baeldung/r/FastRMeanUnitTest.java b/libraries-data-2/src/test/java/com/baeldung/r/FastRMeanUnitTest.java new file mode 100644 index 0000000000..5cf8c63a56 --- /dev/null +++ b/libraries-data-2/src/test/java/com/baeldung/r/FastRMeanUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.r; + +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Test for {@link FastRMean}. + * + * @author Donato Rimenti + */ +@Ignore +public class FastRMeanUnitTest { + + /** + * Object to test. + */ + private FastRMean fastrMean = new FastRMean(); + + /** + * Test for {@link FastRMeanUnitTest#mean(int[])}. + */ + @Test + public void givenValues_whenMean_thenCorrect() { + int[] input = { 1, 2, 3, 4, 5 }; + double result = fastrMean.mean(input); + Assert.assertEquals(3.0, result, 0.000001); + } +} \ No newline at end of file diff --git a/libraries-data-2/src/test/java/com/baeldung/r/RCallerMeanIntegrationTest.java b/libraries-data-2/src/test/java/com/baeldung/r/RCallerMeanIntegrationTest.java new file mode 100644 index 0000000000..b68f259edd --- /dev/null +++ b/libraries-data-2/src/test/java/com/baeldung/r/RCallerMeanIntegrationTest.java @@ -0,0 +1,37 @@ +package com.baeldung.r; + +import java.io.IOException; +import java.net.URISyntaxException; + +import javax.script.ScriptException; + +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Test for {@link RCallerMean}. + * + * @author Donato Rimenti + */ +@Ignore +public class RCallerMeanIntegrationTest { + + /** + * Object to test. + */ + private RCallerMean rcallerMean = new RCallerMean(); + + /** + * Test for {@link RCallerMeanIntegrationTest#mean(int[])}. + * + * @throws ScriptException if an error occurs + * @throws URISyntaxException if an error occurs + */ + @Test + public void givenValues_whenMean_thenCorrect() throws IOException, URISyntaxException { + int[] input = { 1, 2, 3, 4, 5 }; + double result = rcallerMean.mean(input); + Assert.assertEquals(3.0, result, 0.000001); + } +} \ No newline at end of file diff --git a/libraries-data-2/src/test/java/com/baeldung/r/RenjinMeanUnitTest.java b/libraries-data-2/src/test/java/com/baeldung/r/RenjinMeanUnitTest.java new file mode 100644 index 0000000000..e364d54632 --- /dev/null +++ b/libraries-data-2/src/test/java/com/baeldung/r/RenjinMeanUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.r; + +import java.io.IOException; +import java.net.URISyntaxException; + +import javax.script.ScriptException; + +import org.junit.Test; + +import org.junit.Assert; + +/** + * Test for {@link RenjinMean}. + * + * @author Donato Rimenti + */ +public class RenjinMeanUnitTest { + + /** + * Object to test. + */ + private RenjinMean renjinMean = new RenjinMean(); + + /** + * Test for {@link RenjinMeanUnitTest#mean(int[])}. + * + * @throws ScriptException if an error occurs + * @throws URISyntaxException if an error occurs + * @throws IOException if an error occurs + */ + @Test + public void givenValues_whenMean_thenCorrect() throws IOException, URISyntaxException, ScriptException { + int[] input = { 1, 2, 3, 4, 5 }; + double result = renjinMean.mean(input); + Assert.assertEquals(3.0, result, 0.000001); + } +} \ No newline at end of file diff --git a/libraries-data-2/src/test/resources/script.R b/libraries-data-2/src/test/resources/script.R new file mode 100644 index 0000000000..08f859cc3d --- /dev/null +++ b/libraries-data-2/src/test/resources/script.R @@ -0,0 +1,3 @@ +customMean <- function(vector) { + mean(vector) +} \ No newline at end of file From 16ca52363cef9a05a32113654ae290854cb27866 Mon Sep 17 00:00:00 2001 From: Donato Rimenti Date: Mon, 20 Apr 2020 20:11:06 +0200 Subject: [PATCH 18/47] Fixed test exclusions and added missing tests. --- libraries-data-2/pom.xml | 5 ++- .../baeldung/r/RserveMeanIntegrationTest.java | 34 +++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 libraries-data-2/src/test/java/com/baeldung/r/RserveMeanIntegrationTest.java diff --git a/libraries-data-2/pom.xml b/libraries-data-2/pom.xml index ce15ef6c07..0dadcbd8d4 100644 --- a/libraries-data-2/pom.xml +++ b/libraries-data-2/pom.xml @@ -189,10 +189,13 @@ org.apache.maven.plugins maven-compiler-plugin - + com/baeldung/r/FastRMean.java + + com/baeldung/r/FastRMeanUnitTest.java + diff --git a/libraries-data-2/src/test/java/com/baeldung/r/RserveMeanIntegrationTest.java b/libraries-data-2/src/test/java/com/baeldung/r/RserveMeanIntegrationTest.java new file mode 100644 index 0000000000..95b344cb02 --- /dev/null +++ b/libraries-data-2/src/test/java/com/baeldung/r/RserveMeanIntegrationTest.java @@ -0,0 +1,34 @@ +package com.baeldung.r; + +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; +import org.rosuda.REngine.REXPMismatchException; +import org.rosuda.REngine.REngineException; + +/** + * Test for {@link RserveMean}. + * + * @author Donato Rimenti + */ +@Ignore +public class RserveMeanIntegrationTest { + + /** + * Object to test. + */ + private RserveMean rserveMean = new RserveMean(); + + /** + * Test for {@link RserveMeanIntegrationTest#mean(int[])}. + * + * @throws REXPMismatchException if an error occurs + * @throws REngineException if an error occurs + */ + @Test + public void givenValues_whenMean_thenCorrect() throws REngineException, REXPMismatchException { + int[] input = { 1, 2, 3, 4, 5 }; + double result = rserveMean.mean(input); + Assert.assertEquals(3.0, result, 0.000001); + } +} \ No newline at end of file From 64e47e7f77a887e29da95cc1443d66cddc9c73c6 Mon Sep 17 00:00:00 2001 From: Michael Pratt Date: Tue, 21 Apr 2020 10:25:27 -0600 Subject: [PATCH 19/47] BAEL-3972: check user roles in Java --- .../app/controller/TaskController.java | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/spring-security-modules/spring-security-core/src/main/java/com/baeldung/app/controller/TaskController.java b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/app/controller/TaskController.java index a084f14eca..95f855c1e5 100644 --- a/spring-security-modules/spring-security-core/src/main/java/com/baeldung/app/controller/TaskController.java +++ b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/app/controller/TaskController.java @@ -1,8 +1,15 @@ package com.baeldung.app.controller; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @@ -10,6 +17,8 @@ import org.springframework.web.bind.annotation.RequestMethod; import com.baeldung.app.entity.Task; import com.baeldung.app.service.TaskService; +import javax.servlet.http.HttpServletRequest; + @Controller @RequestMapping("api/tasks") public class TaskController { @@ -17,6 +26,9 @@ public class TaskController { @Autowired private TaskService taskService; + @Autowired(required = false) + private UserDetailsService userDetailsService; + @RequestMapping(method = RequestMethod.GET) public ResponseEntity> findAllTasks() { Iterable tasks = taskService.findAll(); @@ -30,4 +42,66 @@ public class TaskController { return ResponseEntity.ok().body(tasks); } + + /** + * Example of restricting specific endpoints to specific roles using @PreAuthorize. + */ + @GetMapping("/manager") + @PreAuthorize("hasRole('ROLE_MANAGER')") + public ResponseEntity> getAlManagerTasks() + { + Iterable tasks = taskService.findAll(); + + return ResponseEntity.ok().body(tasks); + } + + /** + * Example of restricting specific endpoints to specific roles using SecurityContext. + */ + @GetMapping("/actuator") + public ResponseEntity> getAlActuatorTasks() + { + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + if (auth != null && auth.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ACTUATOR"))) + { + return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); + } + + Iterable tasks = taskService.findAll(); + + return ResponseEntity.ok().body(tasks); + } + + /** + * Example of restricting specific endpoints to specific roles using UserDetailsService. + */ + @GetMapping("/admin") + public ResponseEntity> getAlAdminTasks() + { + if(userDetailsService != null) { + UserDetails details = userDetailsService.loadUserByUsername("pam"); + if (details != null && details.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ADMIN"))) { + return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); + } + } + + Iterable tasks = taskService.findAll(); + + return ResponseEntity.ok().body(tasks); + } + + /** + * Example of restricting specific endpoints to specific roles using HttpServletRequest. + */ + @GetMapping("/admin2") + public ResponseEntity> getAlAdminTasksUsingServlet(HttpServletRequest request) + { + if (!request.isUserInRole("ROLE_ADMIN")) { + return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); + } + + Iterable tasks = taskService.findAll(); + + return ResponseEntity.ok().body(tasks); + } } From 553e4f1a0454f64390e5aeec4de6347a7a354ab7 Mon Sep 17 00:00:00 2001 From: Justin Albano Date: Tue, 21 Apr 2020 14:27:42 -0400 Subject: [PATCH 20/47] BAEL-3965: Moved examples to new spring-core module --- pom.xml | 2 + spring-core-4/README.md | 7 ++ spring-core-4/pom.xml | 88 +++++++++++++++++++ .../java/com/baeldung/factorymethod/Bar.java | 0 .../java/com/baeldung/factorymethod/Foo.java | 0 .../factorymethod/InstanceBarFactory.java | 0 .../factorymethod/InstanceFooFactory.java | 0 .../factorymethod/SingletonBarFactory.java | 0 .../factorymethod/SingletonFooFactory.java | 0 .../InstanceBarFactoryIntegrationTest.java | 0 .../InstanceFooFactoryIntegrationTest.java | 0 .../SingletonBarFactoryIntegrationTest.java | 0 .../SingletonFooFactoryIntegrationTest.java | 0 .../factorymethod/instance-bar-config.xml | 0 .../factorymethod/instance-foo-config.xml | 0 .../factorymethod/static-bar-config.xml | 18 ++-- .../factorymethod/static-foo-config.xml | 0 17 files changed, 106 insertions(+), 9 deletions(-) create mode 100644 spring-core-4/README.md create mode 100644 spring-core-4/pom.xml rename {spring-core-3 => spring-core-4}/src/main/java/com/baeldung/factorymethod/Bar.java (100%) rename {spring-core-3 => spring-core-4}/src/main/java/com/baeldung/factorymethod/Foo.java (100%) rename {spring-core-3 => spring-core-4}/src/main/java/com/baeldung/factorymethod/InstanceBarFactory.java (100%) rename {spring-core-3 => spring-core-4}/src/main/java/com/baeldung/factorymethod/InstanceFooFactory.java (100%) rename {spring-core-3 => spring-core-4}/src/main/java/com/baeldung/factorymethod/SingletonBarFactory.java (100%) rename {spring-core-3 => spring-core-4}/src/main/java/com/baeldung/factorymethod/SingletonFooFactory.java (100%) rename {spring-core-3 => spring-core-4}/src/test/java/com/baeldung/factorymethod/InstanceBarFactoryIntegrationTest.java (100%) rename {spring-core-3 => spring-core-4}/src/test/java/com/baeldung/factorymethod/InstanceFooFactoryIntegrationTest.java (100%) rename {spring-core-3 => spring-core-4}/src/test/java/com/baeldung/factorymethod/SingletonBarFactoryIntegrationTest.java (100%) rename {spring-core-3 => spring-core-4}/src/test/java/com/baeldung/factorymethod/SingletonFooFactoryIntegrationTest.java (100%) rename {spring-core-3 => spring-core-4}/src/test/resources/factorymethod/instance-bar-config.xml (100%) rename {spring-core-3 => spring-core-4}/src/test/resources/factorymethod/instance-foo-config.xml (100%) rename {spring-core-3 => spring-core-4}/src/test/resources/factorymethod/static-bar-config.xml (54%) rename {spring-core-3 => spring-core-4}/src/test/resources/factorymethod/static-foo-config.xml (100%) diff --git a/pom.xml b/pom.xml index 9e3b354d74..ab6870c780 100644 --- a/pom.xml +++ b/pom.xml @@ -651,6 +651,7 @@ spring-core spring-core-2 spring-core-3 + spring-core-4 spring-cucumber spring-data-rest @@ -1155,6 +1156,7 @@ spring-core spring-core-2 spring-core-3 + spring-core-4 spring-cucumber spring-data-rest diff --git a/spring-core-4/README.md b/spring-core-4/README.md new file mode 100644 index 0000000000..f882c77179 --- /dev/null +++ b/spring-core-4/README.md @@ -0,0 +1,7 @@ +## Spring Core + +This module contains articles about core Spring functionality + +## Relevant Articles: + +- More articles: [[<-- prev]](/spring-core-3) diff --git a/spring-core-4/pom.xml b/spring-core-4/pom.xml new file mode 100644 index 0000000000..06598fb41e --- /dev/null +++ b/spring-core-4/pom.xml @@ -0,0 +1,88 @@ + + + 4.0.0 + spring-core-4 + spring-core-4 + + + com.baeldung + parent-spring-5 + 0.0.1-SNAPSHOT + ../parent-spring-5 + + + + + org.springframework + spring-beans + ${spring.version} + + + org.springframework + spring-tx + ${spring.version} + + + org.springframework + spring-jdbc + ${spring.version} + + + org.springframework.boot + spring-boot-starter-web + ${spring.boot.version} + + + org.springframework + spring-context + ${spring.version} + + + org.springframework + spring-core + ${spring.version} + + + javax.annotation + javax.annotation-api + ${annotation-api.version} + + + org.springframework + spring-test + ${spring.version} + test + + + org.junit.jupiter + junit-jupiter-engine + ${junit-jupiter.version} + test + + + org.junit.jupiter + junit-jupiter-api + ${junit-jupiter.version} + test + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven.surefire.version} + + + + + + 2.22.1 + 1.3.2 + 2.2.2.RELEASE + + + \ No newline at end of file diff --git a/spring-core-3/src/main/java/com/baeldung/factorymethod/Bar.java b/spring-core-4/src/main/java/com/baeldung/factorymethod/Bar.java similarity index 100% rename from spring-core-3/src/main/java/com/baeldung/factorymethod/Bar.java rename to spring-core-4/src/main/java/com/baeldung/factorymethod/Bar.java diff --git a/spring-core-3/src/main/java/com/baeldung/factorymethod/Foo.java b/spring-core-4/src/main/java/com/baeldung/factorymethod/Foo.java similarity index 100% rename from spring-core-3/src/main/java/com/baeldung/factorymethod/Foo.java rename to spring-core-4/src/main/java/com/baeldung/factorymethod/Foo.java diff --git a/spring-core-3/src/main/java/com/baeldung/factorymethod/InstanceBarFactory.java b/spring-core-4/src/main/java/com/baeldung/factorymethod/InstanceBarFactory.java similarity index 100% rename from spring-core-3/src/main/java/com/baeldung/factorymethod/InstanceBarFactory.java rename to spring-core-4/src/main/java/com/baeldung/factorymethod/InstanceBarFactory.java diff --git a/spring-core-3/src/main/java/com/baeldung/factorymethod/InstanceFooFactory.java b/spring-core-4/src/main/java/com/baeldung/factorymethod/InstanceFooFactory.java similarity index 100% rename from spring-core-3/src/main/java/com/baeldung/factorymethod/InstanceFooFactory.java rename to spring-core-4/src/main/java/com/baeldung/factorymethod/InstanceFooFactory.java diff --git a/spring-core-3/src/main/java/com/baeldung/factorymethod/SingletonBarFactory.java b/spring-core-4/src/main/java/com/baeldung/factorymethod/SingletonBarFactory.java similarity index 100% rename from spring-core-3/src/main/java/com/baeldung/factorymethod/SingletonBarFactory.java rename to spring-core-4/src/main/java/com/baeldung/factorymethod/SingletonBarFactory.java diff --git a/spring-core-3/src/main/java/com/baeldung/factorymethod/SingletonFooFactory.java b/spring-core-4/src/main/java/com/baeldung/factorymethod/SingletonFooFactory.java similarity index 100% rename from spring-core-3/src/main/java/com/baeldung/factorymethod/SingletonFooFactory.java rename to spring-core-4/src/main/java/com/baeldung/factorymethod/SingletonFooFactory.java diff --git a/spring-core-3/src/test/java/com/baeldung/factorymethod/InstanceBarFactoryIntegrationTest.java b/spring-core-4/src/test/java/com/baeldung/factorymethod/InstanceBarFactoryIntegrationTest.java similarity index 100% rename from spring-core-3/src/test/java/com/baeldung/factorymethod/InstanceBarFactoryIntegrationTest.java rename to spring-core-4/src/test/java/com/baeldung/factorymethod/InstanceBarFactoryIntegrationTest.java diff --git a/spring-core-3/src/test/java/com/baeldung/factorymethod/InstanceFooFactoryIntegrationTest.java b/spring-core-4/src/test/java/com/baeldung/factorymethod/InstanceFooFactoryIntegrationTest.java similarity index 100% rename from spring-core-3/src/test/java/com/baeldung/factorymethod/InstanceFooFactoryIntegrationTest.java rename to spring-core-4/src/test/java/com/baeldung/factorymethod/InstanceFooFactoryIntegrationTest.java diff --git a/spring-core-3/src/test/java/com/baeldung/factorymethod/SingletonBarFactoryIntegrationTest.java b/spring-core-4/src/test/java/com/baeldung/factorymethod/SingletonBarFactoryIntegrationTest.java similarity index 100% rename from spring-core-3/src/test/java/com/baeldung/factorymethod/SingletonBarFactoryIntegrationTest.java rename to spring-core-4/src/test/java/com/baeldung/factorymethod/SingletonBarFactoryIntegrationTest.java diff --git a/spring-core-3/src/test/java/com/baeldung/factorymethod/SingletonFooFactoryIntegrationTest.java b/spring-core-4/src/test/java/com/baeldung/factorymethod/SingletonFooFactoryIntegrationTest.java similarity index 100% rename from spring-core-3/src/test/java/com/baeldung/factorymethod/SingletonFooFactoryIntegrationTest.java rename to spring-core-4/src/test/java/com/baeldung/factorymethod/SingletonFooFactoryIntegrationTest.java diff --git a/spring-core-3/src/test/resources/factorymethod/instance-bar-config.xml b/spring-core-4/src/test/resources/factorymethod/instance-bar-config.xml similarity index 100% rename from spring-core-3/src/test/resources/factorymethod/instance-bar-config.xml rename to spring-core-4/src/test/resources/factorymethod/instance-bar-config.xml diff --git a/spring-core-3/src/test/resources/factorymethod/instance-foo-config.xml b/spring-core-4/src/test/resources/factorymethod/instance-foo-config.xml similarity index 100% rename from spring-core-3/src/test/resources/factorymethod/instance-foo-config.xml rename to spring-core-4/src/test/resources/factorymethod/instance-foo-config.xml diff --git a/spring-core-3/src/test/resources/factorymethod/static-bar-config.xml b/spring-core-4/src/test/resources/factorymethod/static-bar-config.xml similarity index 54% rename from spring-core-3/src/test/resources/factorymethod/static-bar-config.xml rename to spring-core-4/src/test/resources/factorymethod/static-bar-config.xml index 4d1befc645..e709da36a1 100644 --- a/spring-core-3/src/test/resources/factorymethod/static-bar-config.xml +++ b/spring-core-4/src/test/resources/factorymethod/static-bar-config.xml @@ -1,9 +1,9 @@ - - - + + + \ No newline at end of file diff --git a/spring-core-3/src/test/resources/factorymethod/static-foo-config.xml b/spring-core-4/src/test/resources/factorymethod/static-foo-config.xml similarity index 100% rename from spring-core-3/src/test/resources/factorymethod/static-foo-config.xml rename to spring-core-4/src/test/resources/factorymethod/static-foo-config.xml From 56153d65d8134d26ef0f6a2a2759b822b3c6ca9f Mon Sep 17 00:00:00 2001 From: Justin Albano Date: Wed, 22 Apr 2020 06:18:31 -0400 Subject: [PATCH 21/47] BAEL-3965: Corrected XML formatting in code examples --- .../factorymethod/instance-bar-config.xml | 20 +++++++++--------- .../factorymethod/instance-foo-config.xml | 20 +++++++++--------- .../factorymethod/static-bar-config.xml | 21 ++++++++----------- .../factorymethod/static-foo-config.xml | 21 ++++++++----------- 4 files changed, 38 insertions(+), 44 deletions(-) diff --git a/spring-core-4/src/test/resources/factorymethod/instance-bar-config.xml b/spring-core-4/src/test/resources/factorymethod/instance-bar-config.xml index 40d2f33683..a4281aee4e 100644 --- a/spring-core-4/src/test/resources/factorymethod/instance-bar-config.xml +++ b/spring-core-4/src/test/resources/factorymethod/instance-bar-config.xml @@ -1,19 +1,19 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:util="http://www.springframework.org/schema/util" + xsi:schemaLocation=" + http://www.springframework.org/schema/beans + http://www.springframework.org/schema/beans/spring-beans.xsd + http://www.springframework.org/schema/util + http://www.springframework.org/schema/util/spring-util.xsd"> + class="com.baeldung.factorymethod.InstanceBarFactory" /> + factory-bean="instanceBarFactory" + factory-method="createInstance"> diff --git a/spring-core-4/src/test/resources/factorymethod/instance-foo-config.xml b/spring-core-4/src/test/resources/factorymethod/instance-foo-config.xml index c45bef6a85..0f21f06f5a 100644 --- a/spring-core-4/src/test/resources/factorymethod/instance-foo-config.xml +++ b/spring-core-4/src/test/resources/factorymethod/instance-foo-config.xml @@ -1,18 +1,18 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:util="http://www.springframework.org/schema/util" + xsi:schemaLocation=" + http://www.springframework.org/schema/beans + http://www.springframework.org/schema/beans/spring-beans.xsd + http://www.springframework.org/schema/util + http://www.springframework.org/schema/util/spring-util.xsd"> + class="com.baeldung.factorymethod.InstanceFooFactory" /> + factory-bean="instanceFooFactory" + factory-method="createInstance" /> \ No newline at end of file diff --git a/spring-core-4/src/test/resources/factorymethod/static-bar-config.xml b/spring-core-4/src/test/resources/factorymethod/static-bar-config.xml index e709da36a1..2cacc293bc 100644 --- a/spring-core-4/src/test/resources/factorymethod/static-bar-config.xml +++ b/spring-core-4/src/test/resources/factorymethod/static-bar-config.xml @@ -1,19 +1,16 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:util="http://www.springframework.org/schema/util" + xsi:schemaLocation=" + http://www.springframework.org/schema/beans + http://www.springframework.org/schema/beans/spring-beans.xsd + http://www.springframework.org/schema/util + http://www.springframework.org/schema/util/spring-util.xsd"> + class="com.baeldung.factorymethod.SingletonBarFactory" + factory-method="createInstance"> diff --git a/spring-core-4/src/test/resources/factorymethod/static-foo-config.xml b/spring-core-4/src/test/resources/factorymethod/static-foo-config.xml index 83e61a656c..ffe1480638 100644 --- a/spring-core-4/src/test/resources/factorymethod/static-foo-config.xml +++ b/spring-core-4/src/test/resources/factorymethod/static-foo-config.xml @@ -1,18 +1,15 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:util="http://www.springframework.org/schema/util" + xsi:schemaLocation=" + http://www.springframework.org/schema/beans + http://www.springframework.org/schema/beans/spring-beans.xsd + http://www.springframework.org/schema/util + http://www.springframework.org/schema/util/spring-util.xsd"> + class="com.baeldung.factorymethod.SingletonFooFactory" + factory-method="createInstance" /> \ No newline at end of file From 62842f97cf2c1e1ce1ba94c5505d769acb0632a6 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Thu, 23 Apr 2020 13:10:29 +0530 Subject: [PATCH 22/47] JAVA-923: Migrate spring-data-dynamodb to parent-boot-2 --- persistence-modules/spring-data-dynamodb/pom.xml | 8 ++++---- .../spring/data/dynamodb/config/DynamoDBConfig.java | 4 ++-- .../data/dynamodb/repositories/ProductInfoRepository.java | 7 ++++--- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/persistence-modules/spring-data-dynamodb/pom.xml b/persistence-modules/spring-data-dynamodb/pom.xml index fceceb40ba..377e35b635 100644 --- a/persistence-modules/spring-data-dynamodb/pom.xml +++ b/persistence-modules/spring-data-dynamodb/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 @@ -19,7 +19,7 @@ org.springframework.data spring-data-releasetrain - Hopper-SR10 + Lovelace-SR16 pom import @@ -174,7 +174,7 @@ com.baeldung.Application 4.3.4.RELEASE 4.5.2 - 4.4.1 + 5.1.0 1.11.64 3.3.7-1 1.0.392 diff --git a/persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/config/DynamoDBConfig.java b/persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/config/DynamoDBConfig.java index 9278c0a12e..7e97e6b383 100644 --- a/persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/config/DynamoDBConfig.java +++ b/persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/config/DynamoDBConfig.java @@ -44,8 +44,8 @@ public class DynamoDBConfig { return new BasicAWSCredentials(amazonAWSAccessKey, amazonAWSSecretKey); } - @Bean(name = "mvcHandlerMappingIntrospector") - public HandlerMappingIntrospector mvcHandlerMappingIntrospector() { + @Bean(name = "mvcHandlerMappingIntrospectorCustom") + public HandlerMappingIntrospector mvcHandlerMappingIntrospectorCustom() { return new HandlerMappingIntrospector(context); } } diff --git a/persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/repositories/ProductInfoRepository.java b/persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/repositories/ProductInfoRepository.java index da47f033b6..6e8b493c3b 100644 --- a/persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/repositories/ProductInfoRepository.java +++ b/persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/repositories/ProductInfoRepository.java @@ -1,12 +1,13 @@ package com.baeldung.spring.data.dynamodb.repositories; -import com.baeldung.spring.data.dynamodb.model.ProductInfo; +import java.util.Optional; + import org.socialsignin.spring.data.dynamodb.repository.EnableScan; import org.springframework.data.repository.CrudRepository; -import java.util.List; +import com.baeldung.spring.data.dynamodb.model.ProductInfo; @EnableScan public interface ProductInfoRepository extends CrudRepository { - List findById(String id); + Optional findById(String id); } From acf4fa5af9ad36f7273c11ee4be36dbe95434056 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Thu, 23 Apr 2020 22:18:45 +0200 Subject: [PATCH 23/47] JAVA-73: Move scripts under live-test-resources --- persistence-modules/spring-data-mongodb/LIVE-TEST.md | 9 --------- persistence-modules/spring-data-mongodb/README.md | 9 +++++++++ .../{ => src/live-test/resources}/live-test-setup.sh | 2 +- .../{ => src/live-test/resources}/live-test-teardown.sh | 0 .../{ => src/live-test/resources}/live-test.sh | 0 5 files changed, 10 insertions(+), 10 deletions(-) delete mode 100644 persistence-modules/spring-data-mongodb/LIVE-TEST.md rename persistence-modules/spring-data-mongodb/{ => src/live-test/resources}/live-test-setup.sh (58%) rename persistence-modules/spring-data-mongodb/{ => src/live-test/resources}/live-test-teardown.sh (100%) rename persistence-modules/spring-data-mongodb/{ => src/live-test/resources}/live-test.sh (100%) mode change 100755 => 100644 diff --git a/persistence-modules/spring-data-mongodb/LIVE-TEST.md b/persistence-modules/spring-data-mongodb/LIVE-TEST.md deleted file mode 100644 index 9da1ea249e..0000000000 --- a/persistence-modules/spring-data-mongodb/LIVE-TEST.md +++ /dev/null @@ -1,9 +0,0 @@ -========= - -## Spring Data MongoDB Live Testing - - -There are 3 scripts to simplify running live tests: -1. `live-test-setup.sh` builds a docker image with the necessary setup and runs it. The environment is ready, when the log stops - it takes approximately 30 seconds. -2. `live-test.sh` runs the live tests (but no other tests). -3. `live-test-setup.sh` stops and removes the docker image. diff --git a/persistence-modules/spring-data-mongodb/README.md b/persistence-modules/spring-data-mongodb/README.md index c4f21dffc0..381bf83fa8 100644 --- a/persistence-modules/spring-data-mongodb/README.md +++ b/persistence-modules/spring-data-mongodb/README.md @@ -13,3 +13,12 @@ - [Spring Data Annotations](http://www.baeldung.com/spring-data-annotations) - [Spring Data MongoDB Transactions](https://www.baeldung.com/spring-data-mongodb-transactions ) - [ZonedDateTime with Spring Data MongoDB](https://www.baeldung.com/spring-data-mongodb-zoneddatetime) + + +## Spring Data MongoDB Live Testing + + +There are 3 scripts to simplify running live tests: +1. [`live-test-setup.sh`](src/live-test/resources/live-test-setup.sh) builds a docker image with the necessary setup and runs it. The environment is ready, when the log stops - it takes approximately 30 seconds. +2. [`live-test.sh`](src/live-test/resources/live-test.sh) runs the live tests (but no other tests). +3. [`live-test-teardown.sh`](src/live-test/resources/live-test-teardown.sh) stops and removes the docker image. diff --git a/persistence-modules/spring-data-mongodb/live-test-setup.sh b/persistence-modules/spring-data-mongodb/src/live-test/resources/live-test-setup.sh similarity index 58% rename from persistence-modules/spring-data-mongodb/live-test-setup.sh rename to persistence-modules/spring-data-mongodb/src/live-test/resources/live-test-setup.sh index e8e0437083..78968d51aa 100644 --- a/persistence-modules/spring-data-mongodb/live-test-setup.sh +++ b/persistence-modules/spring-data-mongodb/src/live-test/resources/live-test-setup.sh @@ -1,5 +1,5 @@ #!/bin/bash -docker image build -t spring-data-mongodb:live-test src/live-test/resources/ +docker image build -t spring-data-mongodb:live-test . docker run -p 27017:27017 --name spring-data-mongodb-live-test spring-data-mongodb:live-test diff --git a/persistence-modules/spring-data-mongodb/live-test-teardown.sh b/persistence-modules/spring-data-mongodb/src/live-test/resources/live-test-teardown.sh similarity index 100% rename from persistence-modules/spring-data-mongodb/live-test-teardown.sh rename to persistence-modules/spring-data-mongodb/src/live-test/resources/live-test-teardown.sh diff --git a/persistence-modules/spring-data-mongodb/live-test.sh b/persistence-modules/spring-data-mongodb/src/live-test/resources/live-test.sh old mode 100755 new mode 100644 similarity index 100% rename from persistence-modules/spring-data-mongodb/live-test.sh rename to persistence-modules/spring-data-mongodb/src/live-test/resources/live-test.sh From ffa8e0839df894019e1b3cc501728c9c0f5d9aa6 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Thu, 23 Apr 2020 22:38:10 +0200 Subject: [PATCH 24/47] JAVA-73: Fix live-test.sh and cleanup pom.xml --- .../spring-data-mongodb/src/live-test/resources/live-test.sh | 2 +- pom.xml | 5 +---- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/persistence-modules/spring-data-mongodb/src/live-test/resources/live-test.sh b/persistence-modules/spring-data-mongodb/src/live-test/resources/live-test.sh index 5a079bdac8..307a68a3bd 100644 --- a/persistence-modules/spring-data-mongodb/src/live-test/resources/live-test.sh +++ b/persistence-modules/spring-data-mongodb/src/live-test/resources/live-test.sh @@ -1,3 +1,3 @@ #!/bin/bash -mvn clean compile test -P live-all +mvn clean compile test -P live-all -f ../../../pom.xml diff --git a/pom.xml b/pom.xml index f94c89a5c0..314a6a9f43 100644 --- a/pom.xml +++ b/pom.xml @@ -1341,10 +1341,7 @@ - - - - + From b31b84d475f77972c2fb512707489e0354c4169a Mon Sep 17 00:00:00 2001 From: Gergo Petrik Date: Fri, 24 Apr 2020 16:00:30 +0200 Subject: [PATCH 25/47] Mockint objectmapper with mockito (#9017) * Mockint objectmapper with mockito * enforcing naming convention for test classes * removed Spring * removed unattended changes * modified example * simplified call stack in flower validator --- spring-mockito/pom.xml | 2 +- testing-modules/mockito-2/pom.xml | 15 ++++++ .../baeldung/mockito/objectmapper/Flower.java | 32 +++++++++++ .../FlowerJsonStringValidator.java | 17 ++++++ .../FlowerJsonStringValidatorUnitTest.java | 53 +++++++++++++++++++ 5 files changed, 118 insertions(+), 1 deletion(-) create mode 100644 testing-modules/mockito-2/src/main/java/com/baeldung/mockito/objectmapper/Flower.java create mode 100644 testing-modules/mockito-2/src/main/java/com/baeldung/mockito/objectmapper/FlowerJsonStringValidator.java create mode 100644 testing-modules/mockito-2/src/test/java/com/baeldung/mockito/objectmapper/FlowerJsonStringValidatorUnitTest.java diff --git a/spring-mockito/pom.xml b/spring-mockito/pom.xml index f3e0b04808..5d2cd7c445 100644 --- a/spring-mockito/pom.xml +++ b/spring-mockito/pom.xml @@ -28,7 +28,7 @@ - 2.21.0 + 2.24.0 diff --git a/testing-modules/mockito-2/pom.xml b/testing-modules/mockito-2/pom.xml index 76608a3039..340af89c82 100644 --- a/testing-modules/mockito-2/pom.xml +++ b/testing-modules/mockito-2/pom.xml @@ -14,8 +14,23 @@ ../../ + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + org.mockito + mockito-junit-jupiter + ${mockito.version} + test + + + 2.21.0 + 2.10.3 diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/objectmapper/Flower.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/objectmapper/Flower.java new file mode 100644 index 0000000000..bc366a39f9 --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/objectmapper/Flower.java @@ -0,0 +1,32 @@ +package com.baeldung.mockito.objectmapper; + +public class Flower { + + private String name; + private Integer petals; + + public Flower(String name, Integer petals) { + this.name = name; + this.petals = petals; + } + + public Flower() { + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getPetals() { + return petals; + } + + public void setPetals(Integer petals) { + this.petals = petals; + } + +} diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/objectmapper/FlowerJsonStringValidator.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/objectmapper/FlowerJsonStringValidator.java new file mode 100644 index 0000000000..91bad66e6d --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/objectmapper/FlowerJsonStringValidator.java @@ -0,0 +1,17 @@ +package com.baeldung.mockito.objectmapper; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class FlowerJsonStringValidator { + private ObjectMapper objectMapper; + + public FlowerJsonStringValidator(ObjectMapper objectMapper) { + this.objectMapper = objectMapper; + } + + public boolean flowerHasPetals(String jsonFlowerAsString) throws JsonProcessingException { + Flower flower = objectMapper.readValue(jsonFlowerAsString, Flower.class); + return flower.getPetals() > 0; + } +} diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/objectmapper/FlowerJsonStringValidatorUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/objectmapper/FlowerJsonStringValidatorUnitTest.java new file mode 100644 index 0000000000..31c3f0d01d --- /dev/null +++ b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/objectmapper/FlowerJsonStringValidatorUnitTest.java @@ -0,0 +1,53 @@ +package com.baeldung.mockito.objectmapper; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +public class FlowerJsonStringValidatorUnitTest { + + @Mock + private ObjectMapper objectMapper; + + private FlowerJsonStringValidator flowerJsonStringValidator; + + @BeforeEach + public void setUp() { + flowerJsonStringValidator = new FlowerJsonStringValidator(objectMapper); + } + + @Test + public void whenCallingHasPetalsWithPetals_thenReturnsTrue() throws JsonProcessingException { + Flower rose = new Flower("testFlower", 100); + + when(objectMapper.readValue(anyString(), eq(Flower.class))).thenReturn(rose); + + assertTrue(flowerJsonStringValidator.flowerHasPetals("this can be a very long json flower")); + + verify(objectMapper, times(1)).readValue(anyString(), eq(Flower.class)); + } + + @Test + public void whenCallingHasPetalsWithZeroPetal_thenReturnsFalse() throws JsonProcessingException { + Flower rose = new Flower("testFlowerWithoutPetal", 0); + + when(objectMapper.readValue(anyString(), eq(Flower.class))).thenReturn(rose); + + assertFalse(flowerJsonStringValidator.flowerHasPetals("this can be a very long json flower")); + + verify(objectMapper, times(1)).readValue(anyString(), eq(Flower.class)); + } +} From 35f1a3eba55288d0141e6394a616691a6ed1c124 Mon Sep 17 00:00:00 2001 From: Roque Santos Date: Fri, 24 Apr 2020 11:10:44 -0300 Subject: [PATCH 26/47] BAEL-3927 : Encode a String to UTF-8 in Java (#8954) * BAEL-3927 : Encode a String to UTF-8 in Java * Update core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/encode/StringEncodeUnitTest.java Co-Authored-By: KevinGilmore * BAEL-3927 : Applying suggested adjustments * BAEL-3927 : Simplifying the code snippets * BAEL-3927 : Coding styles adjustements * BAEL-3927 : Test adjustements to fit changes in article Co-authored-by: KevinGilmore --- .../encodetoutf8/StringEncodeUnitTest.java | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/encodetoutf8/StringEncodeUnitTest.java diff --git a/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/encodetoutf8/StringEncodeUnitTest.java b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/encodetoutf8/StringEncodeUnitTest.java new file mode 100644 index 0000000000..a73104b234 --- /dev/null +++ b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/encodetoutf8/StringEncodeUnitTest.java @@ -0,0 +1,73 @@ +package com.baeldung.encodetoutf8; + +import static org.junit.Assert.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; + +import org.apache.commons.codec.binary.StringUtils; +import org.junit.Test; + +public class StringEncodeUnitTest { + + @Test + public void givenGermanAsciiString_whenComparing_thenCompareNotEquals() { + String germanString = "Entwickeln Sie mit Vergnügen"; + byte[] germanBytes = germanString.getBytes(); + + String asciiEncodedString = new String(germanBytes, StandardCharsets.US_ASCII); + + assertNotEquals(germanString, asciiEncodedString); + } + + @Test + public void givenUsAsciiString_whenComparing_thenCompareNotEquals() { + String englishString = "Develop with pleasure"; + byte[] englishBytes = englishString.getBytes(); + + String asciiEncondedEnglishString = new String(englishBytes, StandardCharsets.US_ASCII); + + assertEquals(englishString, asciiEncondedEnglishString); + } + + /* + * ApacheCommonsCodecEncode + */ + @Test + public void givenSomeUnencodedString_whenApacheCommonsCodecEncode_thenCompareEquals() { + String rawString = "Entwickeln Sie mit Vergnügen"; + byte[] bytes = StringUtils.getBytesUtf8(rawString); + + String utf8EncodedString = StringUtils.newStringUtf8(bytes); + + assertEquals(rawString, utf8EncodedString); + } + + /* + * CoreJavaEncode + */ + @Test + public void givenSomeUnencodedString_whenCoreJavaEncode_thenCompareEquals() { + String rawString = "Entwickeln Sie mit Vergnügen"; + byte[] bytes = rawString.getBytes(StandardCharsets.UTF_8); + + String utf8EncodedString = new String(bytes, StandardCharsets.UTF_8); + + assertEquals(rawString, utf8EncodedString); + } + + /* + * Java7StandardCharsetsEncode + */ + @Test + public void givenSomeUnencodedString_whenJava7StandardCharsetsEncode_thenCompareEquals() { + String rawString = "Entwickeln Sie mit Vergnügen"; + ByteBuffer buffer = StandardCharsets.UTF_8.encode(rawString); + + String utf8EncodedString = StandardCharsets.UTF_8.decode(buffer) + .toString(); + + assertEquals(rawString, utf8EncodedString); + } +} From 7d6e096d28e9c1585f52bb464e9150ebbd2ca3b1 Mon Sep 17 00:00:00 2001 From: Donato Rimenti Date: Fri, 24 Apr 2020 16:51:50 +0200 Subject: [PATCH 27/47] Fixed whitespace formatting. --- libraries-data-2/pom.xml | 77 +++++++++---------- .../main/java/com/baeldung/r/FastRMean.java | 33 ++++---- .../main/java/com/baeldung/r/RCallerMean.java | 37 ++++----- .../src/main/java/com/baeldung/r/RUtils.java | 27 ++++--- .../main/java/com/baeldung/r/RenjinMean.java | 34 ++++---- .../main/java/com/baeldung/r/RserveMean.java | 29 +++---- .../com/baeldung/r/FastRMeanUnitTest.java | 26 +++---- .../r/RCallerMeanIntegrationTest.java | 32 ++++---- .../com/baeldung/r/RenjinMeanUnitTest.java | 34 ++++---- .../baeldung/r/RserveMeanIntegrationTest.java | 32 ++++---- 10 files changed, 184 insertions(+), 177 deletions(-) diff --git a/libraries-data-2/pom.xml b/libraries-data-2/pom.xml index 0dadcbd8d4..73c5452f77 100644 --- a/libraries-data-2/pom.xml +++ b/libraries-data-2/pom.xml @@ -128,24 +128,21 @@ ${awaitility.version} test - - - org.rosuda.REngine - Rserve - ${rserve.version} - - - - com.github.jbytecode - RCaller - ${rcaller.version} - - - - org.renjin - renjin-script-engine - ${renjin.version} - + + org.rosuda.REngine + Rserve + ${rserve.version} + + + com.github.jbytecode + RCaller + ${rcaller.version} + + + org.renjin + renjin-script-engine + ${renjin.version} + @@ -157,11 +154,11 @@ - - bedatadriven - bedatadriven public repo - https://nexus.bedatadriven.com/content/groups/public/ - + + bedatadriven + bedatadriven public repo + https://nexus.bedatadriven.com/content/groups/public/ + @@ -183,22 +180,22 @@ 1.8.1 - - - - org.apache.maven.plugins - maven-compiler-plugin - - - - com/baeldung/r/FastRMean.java - - - com/baeldung/r/FastRMeanUnitTest.java - - - - - + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + com/baeldung/r/FastRMean.java + + + com/baeldung/r/FastRMeanUnitTest.java + + + + + \ No newline at end of file diff --git a/libraries-data-2/src/main/java/com/baeldung/r/FastRMean.java b/libraries-data-2/src/main/java/com/baeldung/r/FastRMean.java index 52fb2d1506..8348bfa403 100644 --- a/libraries-data-2/src/main/java/com/baeldung/r/FastRMean.java +++ b/libraries-data-2/src/main/java/com/baeldung/r/FastRMean.java @@ -10,19 +10,24 @@ import java.net.URISyntaxException; */ public class FastRMean { - /** - * Invokes the customMean R function passing the given values as arguments. - * - * @param values the input to the mean script - * @return the result of the R script - */ - public double mean(int[] values) { - Context polyglot = Context.newBuilder().allowAllAccess(true).build(); - String meanScriptContent = RUtils.getMeanScriptContent(); - polyglot.eval("R", meanScriptContent); - Value rBindings = polyglot.getBindings("R"); - Value rInput = rBindings.getMember("c").execute(values); - return rBindings.getMember("customMean").execute(rInput).asDouble(); - } + /** + * Invokes the customMean R function passing the given values as arguments. + * + * @param values the input to the mean script + * @return the result of the R script + */ + public double mean(int[] values) { + Context polyglot = Context.newBuilder() + .allowAllAccess(true) + .build(); + String meanScriptContent = RUtils.getMeanScriptContent(); + polyglot.eval("R", meanScriptContent); + Value rBindings = polyglot.getBindings("R"); + Value rInput = rBindings.getMember("c") + .execute(values); + return rBindings.getMember("customMean") + .execute(rInput) + .asDouble(); + } } \ No newline at end of file diff --git a/libraries-data-2/src/main/java/com/baeldung/r/RCallerMean.java b/libraries-data-2/src/main/java/com/baeldung/r/RCallerMean.java index 53e0ab9e31..99edb8c043 100644 --- a/libraries-data-2/src/main/java/com/baeldung/r/RCallerMean.java +++ b/libraries-data-2/src/main/java/com/baeldung/r/RCallerMean.java @@ -14,23 +14,24 @@ import com.github.rcaller.rstuff.RCode; */ public class RCallerMean { - /** - * Invokes the customMean R function passing the given values as arguments. - * - * @param values the input to the mean script - * @return the result of the R script - * @throws IOException if any error occurs - * @throws URISyntaxException if any error occurs - */ - public double mean(int[] values) throws IOException, URISyntaxException { - String fileContent = RUtils.getMeanScriptContent(); - RCode code = RCode.create(); - code.addRCode(fileContent); - code.addIntArray("input", values); - code.addRCode("result <- customMean(input)"); - RCaller caller = RCaller.create(code, RCallerOptions.create()); - caller.runAndReturnResult("result"); - return caller.getParser().getAsDoubleArray("result")[0]; - } + /** + * Invokes the customMean R function passing the given values as arguments. + * + * @param values the input to the mean script + * @return the result of the R script + * @throws IOException if any error occurs + * @throws URISyntaxException if any error occurs + */ + public double mean(int[] values) throws IOException, URISyntaxException { + String fileContent = RUtils.getMeanScriptContent(); + RCode code = RCode.create(); + code.addRCode(fileContent); + code.addIntArray("input", values); + code.addRCode("result <- customMean(input)"); + RCaller caller = RCaller.create(code, RCallerOptions.create()); + caller.runAndReturnResult("result"); + return caller.getParser() + .getAsDoubleArray("result")[0]; + } } \ No newline at end of file diff --git a/libraries-data-2/src/main/java/com/baeldung/r/RUtils.java b/libraries-data-2/src/main/java/com/baeldung/r/RUtils.java index ad16fd5602..a9393cdcc2 100644 --- a/libraries-data-2/src/main/java/com/baeldung/r/RUtils.java +++ b/libraries-data-2/src/main/java/com/baeldung/r/RUtils.java @@ -15,16 +15,19 @@ import java.util.stream.Collectors; */ public class RUtils { - /** - * Loads the script.R and returns its content as a string. - * - * @return the script.R content as a string - * @throws IOException if any error occurs - * @throws URISyntaxException if any error occurs - */ - static String getMeanScriptContent() throws IOException, URISyntaxException { - URI rScriptUri = RUtils.class.getClassLoader().getResource("script.R").toURI(); - Path inputScript = Paths.get(rScriptUri); - return Files.lines(inputScript).collect(Collectors.joining()); - } + /** + * Loads the script.R and returns its content as a string. + * + * @return the script.R content as a string + * @throws IOException if any error occurs + * @throws URISyntaxException if any error occurs + */ + static String getMeanScriptContent() throws IOException, URISyntaxException { + URI rScriptUri = RUtils.class.getClassLoader() + .getResource("script.R") + .toURI(); + Path inputScript = Paths.get(rScriptUri); + return Files.lines(inputScript) + .collect(Collectors.joining()); + } } \ No newline at end of file diff --git a/libraries-data-2/src/main/java/com/baeldung/r/RenjinMean.java b/libraries-data-2/src/main/java/com/baeldung/r/RenjinMean.java index befb7d522f..4576ec5fb4 100644 --- a/libraries-data-2/src/main/java/com/baeldung/r/RenjinMean.java +++ b/libraries-data-2/src/main/java/com/baeldung/r/RenjinMean.java @@ -15,22 +15,22 @@ import org.renjin.sexp.DoubleArrayVector; */ public class RenjinMean { - /** - * Invokes the customMean R function passing the given values as arguments. - * - * @param values the input to the mean script - * @return the result of the R script - * @throws IOException if any error occurs - * @throws URISyntaxException if any error occurs - * @throws ScriptException if any error occurs - */ - public double mean(int[] values) throws IOException, URISyntaxException, ScriptException { - RenjinScriptEngine engine = new RenjinScriptEngine(); - String meanScriptContent = RUtils.getMeanScriptContent(); - engine.put("input", values); - engine.eval(meanScriptContent); - DoubleArrayVector result = (DoubleArrayVector) engine.eval("customMean(input)"); - return result.asReal(); - } + /** + * Invokes the customMean R function passing the given values as arguments. + * + * @param values the input to the mean script + * @return the result of the R script + * @throws IOException if any error occurs + * @throws URISyntaxException if any error occurs + * @throws ScriptException if any error occurs + */ + public double mean(int[] values) throws IOException, URISyntaxException, ScriptException { + RenjinScriptEngine engine = new RenjinScriptEngine(); + String meanScriptContent = RUtils.getMeanScriptContent(); + engine.put("input", values); + engine.eval(meanScriptContent); + DoubleArrayVector result = (DoubleArrayVector) engine.eval("customMean(input)"); + return result.asReal(); + } } \ No newline at end of file diff --git a/libraries-data-2/src/main/java/com/baeldung/r/RserveMean.java b/libraries-data-2/src/main/java/com/baeldung/r/RserveMean.java index 51aaa90648..1aaa7fa847 100644 --- a/libraries-data-2/src/main/java/com/baeldung/r/RserveMean.java +++ b/libraries-data-2/src/main/java/com/baeldung/r/RserveMean.java @@ -11,19 +11,20 @@ import org.rosuda.REngine.Rserve.RConnection; */ public class RserveMean { - /** - * Connects to the Rserve istance listening on 127.0.0.1:6311 and invokes the - * customMean R function passing the given values as arguments. - * - * @param values the input to the mean script - * @return the result of the R script - * @throws REngineException if any error occurs - * @throws REXPMismatchException if any error occurs - */ - public double mean(int[] values) throws REngineException, REXPMismatchException { - RConnection c = new RConnection(); - c.assign("input", values); - return c.eval("customMean(input)").asDouble(); - } + /** + * Connects to the Rserve istance listening on 127.0.0.1:6311 and invokes the + * customMean R function passing the given values as arguments. + * + * @param values the input to the mean script + * @return the result of the R script + * @throws REngineException if any error occurs + * @throws REXPMismatchException if any error occurs + */ + public double mean(int[] values) throws REngineException, REXPMismatchException { + RConnection c = new RConnection(); + c.assign("input", values); + return c.eval("customMean(input)") + .asDouble(); + } } \ No newline at end of file diff --git a/libraries-data-2/src/test/java/com/baeldung/r/FastRMeanUnitTest.java b/libraries-data-2/src/test/java/com/baeldung/r/FastRMeanUnitTest.java index 5cf8c63a56..4e7426b75a 100644 --- a/libraries-data-2/src/test/java/com/baeldung/r/FastRMeanUnitTest.java +++ b/libraries-data-2/src/test/java/com/baeldung/r/FastRMeanUnitTest.java @@ -12,18 +12,18 @@ import org.junit.Test; @Ignore public class FastRMeanUnitTest { - /** - * Object to test. - */ - private FastRMean fastrMean = new FastRMean(); + /** + * Object to test. + */ + private FastRMean fastrMean = new FastRMean(); - /** - * Test for {@link FastRMeanUnitTest#mean(int[])}. - */ - @Test - public void givenValues_whenMean_thenCorrect() { - int[] input = { 1, 2, 3, 4, 5 }; - double result = fastrMean.mean(input); - Assert.assertEquals(3.0, result, 0.000001); - } + /** + * Test for {@link FastRMeanUnitTest#mean(int[])}. + */ + @Test + public void givenValues_whenMean_thenCorrect() { + int[] input = { 1, 2, 3, 4, 5 }; + double result = fastrMean.mean(input); + Assert.assertEquals(3.0, result, 0.000001); + } } \ No newline at end of file diff --git a/libraries-data-2/src/test/java/com/baeldung/r/RCallerMeanIntegrationTest.java b/libraries-data-2/src/test/java/com/baeldung/r/RCallerMeanIntegrationTest.java index b68f259edd..ce6b3a4332 100644 --- a/libraries-data-2/src/test/java/com/baeldung/r/RCallerMeanIntegrationTest.java +++ b/libraries-data-2/src/test/java/com/baeldung/r/RCallerMeanIntegrationTest.java @@ -17,21 +17,21 @@ import org.junit.Test; @Ignore public class RCallerMeanIntegrationTest { - /** - * Object to test. - */ - private RCallerMean rcallerMean = new RCallerMean(); + /** + * Object to test. + */ + private RCallerMean rcallerMean = new RCallerMean(); - /** - * Test for {@link RCallerMeanIntegrationTest#mean(int[])}. - * - * @throws ScriptException if an error occurs - * @throws URISyntaxException if an error occurs - */ - @Test - public void givenValues_whenMean_thenCorrect() throws IOException, URISyntaxException { - int[] input = { 1, 2, 3, 4, 5 }; - double result = rcallerMean.mean(input); - Assert.assertEquals(3.0, result, 0.000001); - } + /** + * Test for {@link RCallerMeanIntegrationTest#mean(int[])}. + * + * @throws ScriptException if an error occurs + * @throws URISyntaxException if an error occurs + */ + @Test + public void givenValues_whenMean_thenCorrect() throws IOException, URISyntaxException { + int[] input = { 1, 2, 3, 4, 5 }; + double result = rcallerMean.mean(input); + Assert.assertEquals(3.0, result, 0.000001); + } } \ No newline at end of file diff --git a/libraries-data-2/src/test/java/com/baeldung/r/RenjinMeanUnitTest.java b/libraries-data-2/src/test/java/com/baeldung/r/RenjinMeanUnitTest.java index e364d54632..f52d37d614 100644 --- a/libraries-data-2/src/test/java/com/baeldung/r/RenjinMeanUnitTest.java +++ b/libraries-data-2/src/test/java/com/baeldung/r/RenjinMeanUnitTest.java @@ -16,22 +16,22 @@ import org.junit.Assert; */ public class RenjinMeanUnitTest { - /** - * Object to test. - */ - private RenjinMean renjinMean = new RenjinMean(); + /** + * Object to test. + */ + private RenjinMean renjinMean = new RenjinMean(); - /** - * Test for {@link RenjinMeanUnitTest#mean(int[])}. - * - * @throws ScriptException if an error occurs - * @throws URISyntaxException if an error occurs - * @throws IOException if an error occurs - */ - @Test - public void givenValues_whenMean_thenCorrect() throws IOException, URISyntaxException, ScriptException { - int[] input = { 1, 2, 3, 4, 5 }; - double result = renjinMean.mean(input); - Assert.assertEquals(3.0, result, 0.000001); - } + /** + * Test for {@link RenjinMeanUnitTest#mean(int[])}. + * + * @throws ScriptException if an error occurs + * @throws URISyntaxException if an error occurs + * @throws IOException if an error occurs + */ + @Test + public void givenValues_whenMean_thenCorrect() throws IOException, URISyntaxException, ScriptException { + int[] input = { 1, 2, 3, 4, 5 }; + double result = renjinMean.mean(input); + Assert.assertEquals(3.0, result, 0.000001); + } } \ No newline at end of file diff --git a/libraries-data-2/src/test/java/com/baeldung/r/RserveMeanIntegrationTest.java b/libraries-data-2/src/test/java/com/baeldung/r/RserveMeanIntegrationTest.java index 95b344cb02..23d42bd8e9 100644 --- a/libraries-data-2/src/test/java/com/baeldung/r/RserveMeanIntegrationTest.java +++ b/libraries-data-2/src/test/java/com/baeldung/r/RserveMeanIntegrationTest.java @@ -14,21 +14,21 @@ import org.rosuda.REngine.REngineException; @Ignore public class RserveMeanIntegrationTest { - /** - * Object to test. - */ - private RserveMean rserveMean = new RserveMean(); + /** + * Object to test. + */ + private RserveMean rserveMean = new RserveMean(); - /** - * Test for {@link RserveMeanIntegrationTest#mean(int[])}. - * - * @throws REXPMismatchException if an error occurs - * @throws REngineException if an error occurs - */ - @Test - public void givenValues_whenMean_thenCorrect() throws REngineException, REXPMismatchException { - int[] input = { 1, 2, 3, 4, 5 }; - double result = rserveMean.mean(input); - Assert.assertEquals(3.0, result, 0.000001); - } + /** + * Test for {@link RserveMeanIntegrationTest#mean(int[])}. + * + * @throws REXPMismatchException if an error occurs + * @throws REngineException if an error occurs + */ + @Test + public void givenValues_whenMean_thenCorrect() throws REngineException, REXPMismatchException { + int[] input = { 1, 2, 3, 4, 5 }; + double result = rserveMean.mean(input); + Assert.assertEquals(3.0, result, 0.000001); + } } \ No newline at end of file From 73f96969da098b873415b475f3ad1463dc4f45cd Mon Sep 17 00:00:00 2001 From: Paturi Radhe Sravan Date: Sat, 25 Apr 2020 03:06:41 +0530 Subject: [PATCH 28/47] BAEL-3567 An Introduction to Kaniko (#9150) * BAEL-3597 Cactoos * BAEL-3597 Cactoos * BAEL-3597 Cactoos * BAEL-3597 Cactoos * BAEL-3567 An Introduction to Kaniko * BAEL-3597 Cactoos * BAEL-3597 Cactoos * BAEL-3597 Cactoos * BAEL-3597 Cactoos * BAEL-3567 An Introduction to Kaniko * BAEL-3567 An Introduction to Kaniko --- kaniko/dockerfile | 2 ++ kaniko/pod.yaml | 19 +++++++++++++++++++ kaniko/volume-claim.yaml | 11 +++++++++++ kaniko/volume.yaml | 14 ++++++++++++++ 4 files changed, 46 insertions(+) create mode 100644 kaniko/dockerfile create mode 100644 kaniko/pod.yaml create mode 100644 kaniko/volume-claim.yaml create mode 100644 kaniko/volume.yaml diff --git a/kaniko/dockerfile b/kaniko/dockerfile new file mode 100644 index 0000000000..0290bf16ed --- /dev/null +++ b/kaniko/dockerfile @@ -0,0 +1,2 @@ +FROM ubuntu +ENTRYPOINT ["/bin/bash", "-c", "echo hello"] diff --git a/kaniko/pod.yaml b/kaniko/pod.yaml new file mode 100644 index 0000000000..17f9a81b6d --- /dev/null +++ b/kaniko/pod.yaml @@ -0,0 +1,19 @@ +apiVersion: v1 +kind: Pod +metadata: + name: kaniko +spec: + containers: + - name: kaniko + image: gcr.io/kaniko-project/executor:latest + args: ["--dockerfile=/workspace/dockerfile", + "--context=dir://workspace", + "--no-push"] + volumeMounts: + - name: dockerfile-storage + mountPath: /workspace + restartPolicy: Never + volumes: + - name: dockerfile-storage + persistentVolumeClaim: + claimName: dockerfile-claim diff --git a/kaniko/volume-claim.yaml b/kaniko/volume-claim.yaml new file mode 100644 index 0000000000..7a1abbf05c --- /dev/null +++ b/kaniko/volume-claim.yaml @@ -0,0 +1,11 @@ +kind: PersistentVolumeClaim +apiVersion: v1 +metadata: + name: dockerfile-claim +spec: + accessModes: + - ReadWriteOnce + resources: + requests: + storage: 8Gi + storageClassName: local-storage diff --git a/kaniko/volume.yaml b/kaniko/volume.yaml new file mode 100644 index 0000000000..e44663ec5a --- /dev/null +++ b/kaniko/volume.yaml @@ -0,0 +1,14 @@ +apiVersion: v1 +kind: PersistentVolume +metadata: + name: dockerfile + labels: + type: local +spec: + capacity: + storage: 10Gi + accessModes: + - ReadWriteOnce + storageClassName: local-storage + hostPath: + path: /home/docker/kaniko # Path to the local mount directory that was setup From d090c9b059c5e3d2752a6d7422fe344cca8b1dd5 Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Fri, 24 Apr 2020 22:28:04 -0500 Subject: [PATCH 29/47] BAEL-2893 BAEL-3927 update README files (#9171) * BAEL-3336 BAEL-3058 add links * BAEL-3319: add link * BAEL-3284: add link * BAEL-3198: add link to article * BAEL-3479: add link to article * BAEL-3485: add article link * SCALA-38: move to new package and add link back to article * SCALA-38: add imports back into unit test * BAEL-3908: add link back to article * BAEL-2893 BAEL-3927 add link back to article --- core-java-modules/core-java-string-operations-2/README.md | 1 + testing-modules/mockito-2/README.md | 1 + 2 files changed, 2 insertions(+) diff --git a/core-java-modules/core-java-string-operations-2/README.md b/core-java-modules/core-java-string-operations-2/README.md index 45b02a3e10..2f54aa9467 100644 --- a/core-java-modules/core-java-string-operations-2/README.md +++ b/core-java-modules/core-java-string-operations-2/README.md @@ -11,4 +11,5 @@ This module contains articles about string operations. - [Case-Insensitive String Matching in Java](https://www.baeldung.com/java-case-insensitive-string-matching) - [L-Trim and R-Trim Alternatives in Java](https://www.baeldung.com/java-trim-alternatives) - [Java Convert PDF to Base64](https://www.baeldung.com/java-convert-pdf-to-base64) +- [Encode a String to UTF-8 in Java](https://www.baeldung.com/java-string-encode-utf-8) - More articles: [[<-- prev]](../core-java-string-operations) diff --git a/testing-modules/mockito-2/README.md b/testing-modules/mockito-2/README.md index 064366dfd5..6c9ddee01d 100644 --- a/testing-modules/mockito-2/README.md +++ b/testing-modules/mockito-2/README.md @@ -4,3 +4,4 @@ - [Lazy Verification with Mockito 2](https://www.baeldung.com/mockito-2-lazy-verification) - [Mockito Strict Stubbing and The UnnecessaryStubbingException](https://www.baeldung.com/mockito-unnecessary-stubbing-exception) - [Mockito and Fluent APIs](https://www.baeldung.com/mockito-fluent-apis) +- [Mocking the ObjectMapper readValue() Method](https://www.baeldung.com/mockito-mock-jackson-read-value) From 89fd7872c476c05a1a362f502910f31b59c4a916 Mon Sep 17 00:00:00 2001 From: sasam0320 <63002713+sasam0320@users.noreply.github.com> Date: Sat, 25 Apr 2020 07:32:20 +0200 Subject: [PATCH 30/47] BAEL-3973 (#9061) --- gradle/gradle-employee-app/.gitignore | 3 ++ gradle/gradle-employee-app/build.gradle | 38 +++++++++++++++++++ .../src/main/java/employee/Employee.java | 9 +++++ .../src/main/java/employee/EmployeeApp.java | 16 ++++++++ .../test/java/employee/EmployeeAppTest.java | 31 +++++++++++++++ gradle/settings.gradle | 2 +- 6 files changed, 98 insertions(+), 1 deletion(-) create mode 100644 gradle/gradle-employee-app/.gitignore create mode 100644 gradle/gradle-employee-app/build.gradle create mode 100644 gradle/gradle-employee-app/src/main/java/employee/Employee.java create mode 100644 gradle/gradle-employee-app/src/main/java/employee/EmployeeApp.java create mode 100644 gradle/gradle-employee-app/src/test/java/employee/EmployeeAppTest.java diff --git a/gradle/gradle-employee-app/.gitignore b/gradle/gradle-employee-app/.gitignore new file mode 100644 index 0000000000..d347f664af --- /dev/null +++ b/gradle/gradle-employee-app/.gitignore @@ -0,0 +1,3 @@ +/.idea +/.gradle +/build diff --git a/gradle/gradle-employee-app/build.gradle b/gradle/gradle-employee-app/build.gradle new file mode 100644 index 0000000000..19b80c0c4a --- /dev/null +++ b/gradle/gradle-employee-app/build.gradle @@ -0,0 +1,38 @@ + +plugins { + id 'java-library' + id 'application' +} + +apply plugin: 'application' +mainClassName = 'employee.EmployeeApp' + +java { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 +} + +println 'This is executed during configuration phase' + +task configured { + println 'The project is configured' +} + +task wrapper(type: Wrapper){ + gradleVersion = '5.3.1' +} + +repositories { + jcenter() +} + +dependencies { + + compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.10' + testImplementation('junit:junit:4.13') + testRuntime('junit:junit:4.13') +} +test { + useJUnit() +} + diff --git a/gradle/gradle-employee-app/src/main/java/employee/Employee.java b/gradle/gradle-employee-app/src/main/java/employee/Employee.java new file mode 100644 index 0000000000..6940c8c28c --- /dev/null +++ b/gradle/gradle-employee-app/src/main/java/employee/Employee.java @@ -0,0 +1,9 @@ +package employee; + +public class Employee { + + String name; + String emailAddress; + int yearOfBirth; + +} \ No newline at end of file diff --git a/gradle/gradle-employee-app/src/main/java/employee/EmployeeApp.java b/gradle/gradle-employee-app/src/main/java/employee/EmployeeApp.java new file mode 100644 index 0000000000..48ef9f5d61 --- /dev/null +++ b/gradle/gradle-employee-app/src/main/java/employee/EmployeeApp.java @@ -0,0 +1,16 @@ +package employee; + +public class EmployeeApp { + + public static void main(String[] args){ + + Employee employee = new Employee(); + employee.name = "John"; + employee.emailAddress = "john@baeldung.com"; + employee.yearOfBirth = 1978; + System.out.println("Name: " + employee.name); + System.out.println("Email Address: " + employee.emailAddress); + System.out.println("Year Of Birth:" + employee.yearOfBirth); + } + +} diff --git a/gradle/gradle-employee-app/src/test/java/employee/EmployeeAppTest.java b/gradle/gradle-employee-app/src/test/java/employee/EmployeeAppTest.java new file mode 100644 index 0000000000..013bcc35b6 --- /dev/null +++ b/gradle/gradle-employee-app/src/test/java/employee/EmployeeAppTest.java @@ -0,0 +1,31 @@ +package employee; + +import employee.Employee; +import org.junit.*; +import static org.junit.Assert.*; + +public class EmployeeAppTest { + + @Test + public void testData(){ + + Employee testEmp = this.getEmployeeTest(); + + assertEquals(testEmp.name, "John"); + assertEquals(testEmp.emailAddress, "john@baeldung.com"); + assertEquals(testEmp.yearOfBirth, 1978); + + + } + + private Employee getEmployeeTest(){ + + Employee employee = new Employee(); + employee.name = "John"; + employee.emailAddress = "john@baeldung.com"; + employee.yearOfBirth = 1978; + + return employee; + } + +} \ No newline at end of file diff --git a/gradle/settings.gradle b/gradle/settings.gradle index f1d64de58a..59300f9281 100644 --- a/gradle/settings.gradle +++ b/gradle/settings.gradle @@ -1,10 +1,10 @@ rootProject.name = 'gradletutorial' - include 'greeting-library' include 'greeting-library-java' include 'greeter' include 'gradletaskdemo' include 'junit5' +include 'gradle-employee-app' println 'This will be executed during the initialization phase.' From fab18f2126b26d0dbe8f0e492e4d075f5a49bd57 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sat, 25 Apr 2020 18:12:08 +0530 Subject: [PATCH 31/47] JAVA-926: Migrate spring-boot-custom-starter to parent-boot-2 --- .../test/java/{org => com}/baeldung/SpringContextTest.java | 0 .../greeter-spring-boot-sample-app/pom.xml | 4 ++-- .../test/java/{org => com}/baeldung/SpringContextTest.java | 0 .../spring-boot-custom-starter/greeter/pom.xml | 4 ++-- 4 files changed, 4 insertions(+), 4 deletions(-) rename spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/{org => com}/baeldung/SpringContextTest.java (100%) rename spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/{org => com}/baeldung/SpringContextTest.java (100%) diff --git a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/com/baeldung/SpringContextTest.java similarity index 100% rename from spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/org/baeldung/SpringContextTest.java rename to spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/com/baeldung/SpringContextTest.java diff --git a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml index 818ce5c107..8d328b88be 100644 --- a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml +++ b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml @@ -8,9 +8,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../../parent-boot-1 + ../../../parent-boot-2 diff --git a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/SpringContextTest.java similarity index 100% rename from spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/org/baeldung/SpringContextTest.java rename to spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/SpringContextTest.java diff --git a/spring-boot-modules/spring-boot-custom-starter/greeter/pom.xml b/spring-boot-modules/spring-boot-custom-starter/greeter/pom.xml index 89119e2e99..47296990aa 100644 --- a/spring-boot-modules/spring-boot-custom-starter/greeter/pom.xml +++ b/spring-boot-modules/spring-boot-custom-starter/greeter/pom.xml @@ -8,9 +8,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../../parent-boot-1 + ../../../parent-boot-2 \ No newline at end of file From b7588a7a3335ade294b463b98c6775269701a885 Mon Sep 17 00:00:00 2001 From: Sampada <46674082+sampada07@users.noreply.github.com> Date: Sat, 25 Apr 2020 22:14:35 +0530 Subject: [PATCH 32/47] BAEL-3989: Calling a SOAP web service from Spring (#9174) --- spring-soap/pom.xml | 22 +++ .../springsoap/client/CountryClient.java | 26 ++++ .../client/CountryClientConfig.java | 25 +++ .../springsoap/client/gen/Country.java | 146 ++++++++++++++++++ .../springsoap/client/gen/Currency.java | 47 ++++++ .../client/gen/GetCountryRequest.java | 71 +++++++++ .../client/gen/GetCountryResponse.java | 71 +++++++++ .../springsoap/client/gen/ObjectFactory.java | 63 ++++++++ .../springsoap/client/gen/package-info.java | 9 ++ spring-soap/src/main/resources/countries.wsdl | 74 +++++++++ .../client/CountryClientLiveTest.java | 36 +++++ 11 files changed, 590 insertions(+) create mode 100644 spring-soap/src/main/java/com/baeldung/springsoap/client/CountryClient.java create mode 100644 spring-soap/src/main/java/com/baeldung/springsoap/client/CountryClientConfig.java create mode 100644 spring-soap/src/main/java/com/baeldung/springsoap/client/gen/Country.java create mode 100644 spring-soap/src/main/java/com/baeldung/springsoap/client/gen/Currency.java create mode 100644 spring-soap/src/main/java/com/baeldung/springsoap/client/gen/GetCountryRequest.java create mode 100644 spring-soap/src/main/java/com/baeldung/springsoap/client/gen/GetCountryResponse.java create mode 100644 spring-soap/src/main/java/com/baeldung/springsoap/client/gen/ObjectFactory.java create mode 100644 spring-soap/src/main/java/com/baeldung/springsoap/client/gen/package-info.java create mode 100644 spring-soap/src/main/resources/countries.wsdl create mode 100644 spring-soap/src/test/java/com/baeldung/springsoap/client/CountryClientLiveTest.java diff --git a/spring-soap/pom.xml b/spring-soap/pom.xml index 9403b70636..d0987329c0 100644 --- a/spring-soap/pom.xml +++ b/spring-soap/pom.xml @@ -58,6 +58,28 @@ + + + org.jvnet.jaxb2.maven2 + maven-jaxb2-plugin + 0.14.0 + + + + generate + + + + + WSDL + ${project.basedir}/src/main/java + com.baeldung.springsoap.client.gen + ${project.basedir}/src/main/resources + + countries.wsdl + + + diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/client/CountryClient.java b/spring-soap/src/main/java/com/baeldung/springsoap/client/CountryClient.java new file mode 100644 index 0000000000..e0b9172ece --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/client/CountryClient.java @@ -0,0 +1,26 @@ +package com.baeldung.springsoap.client; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.ws.client.core.support.WebServiceGatewaySupport; + +import com.baeldung.springsoap.client.gen.GetCountryRequest; +import com.baeldung.springsoap.client.gen.GetCountryResponse; + +public class CountryClient extends WebServiceGatewaySupport { + + private static final Logger logger = LoggerFactory.getLogger(CountryClient.class); + + public GetCountryResponse getCountry(String country) { + + GetCountryRequest request = new GetCountryRequest(); + request.setName(country); + + logger.info("Requesting information for " + country); + + GetCountryResponse response = (GetCountryResponse) getWebServiceTemplate().marshalSendAndReceive(request); + + return response; + } + +} \ No newline at end of file diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/client/CountryClientConfig.java b/spring-soap/src/main/java/com/baeldung/springsoap/client/CountryClientConfig.java new file mode 100644 index 0000000000..8dabdbc00d --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/client/CountryClientConfig.java @@ -0,0 +1,25 @@ +package com.baeldung.springsoap.client; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.oxm.jaxb.Jaxb2Marshaller; + +@Configuration +public class CountryClientConfig { + + @Bean + public Jaxb2Marshaller marshaller() { + Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); + marshaller.setContextPath("com.baeldung.springsoap.client.gen"); + return marshaller; + } + + @Bean + public CountryClient countryClient(Jaxb2Marshaller marshaller) { + CountryClient client = new CountryClient(); + client.setDefaultUri("http://localhost:8080/ws"); + client.setMarshaller(marshaller); + client.setUnmarshaller(marshaller); + return client; + } +} \ No newline at end of file diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/Country.java b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/Country.java new file mode 100644 index 0000000000..e17dce55f9 --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/Country.java @@ -0,0 +1,146 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0 +// See https://javaee.github.io/jaxb-v2/ +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2020.04.25 at 03:18:49 PM IST +// + + +package com.baeldung.springsoap.client.gen; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlSchemaType; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for country complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType name="country">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="population" type="{http://www.w3.org/2001/XMLSchema}int"/>
+ *         <element name="capital" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="currency" type="{http://www.baeldung.com/springsoap/gen}currency"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "country", propOrder = { + "name", + "population", + "capital", + "currency" +}) +public class Country { + + @XmlElement(required = true) + protected String name; + protected int population; + @XmlElement(required = true) + protected String capital; + @XmlElement(required = true) + @XmlSchemaType(name = "string") + protected Currency currency; + + /** + * Gets the value of the name property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getName() { + return name; + } + + /** + * Sets the value of the name property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setName(String value) { + this.name = value; + } + + /** + * Gets the value of the population property. + * + */ + public int getPopulation() { + return population; + } + + /** + * Sets the value of the population property. + * + */ + public void setPopulation(int value) { + this.population = value; + } + + /** + * Gets the value of the capital property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getCapital() { + return capital; + } + + /** + * Sets the value of the capital property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setCapital(String value) { + this.capital = value; + } + + /** + * Gets the value of the currency property. + * + * @return + * possible object is + * {@link Currency } + * + */ + public Currency getCurrency() { + return currency; + } + + /** + * Sets the value of the currency property. + * + * @param value + * allowed object is + * {@link Currency } + * + */ + public void setCurrency(Currency value) { + this.currency = value; + } + +} diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/Currency.java b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/Currency.java new file mode 100644 index 0000000000..12fdef58c2 --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/Currency.java @@ -0,0 +1,47 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0 +// See https://javaee.github.io/jaxb-v2/ +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2020.04.25 at 03:18:49 PM IST +// + + +package com.baeldung.springsoap.client.gen; + +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for currency. + * + *

The following schema fragment specifies the expected content contained within this class. + *

+ *

+ * <simpleType name="currency">
+ *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
+ *     <enumeration value="GBP"/>
+ *     <enumeration value="EUR"/>
+ *     <enumeration value="PLN"/>
+ *   </restriction>
+ * </simpleType>
+ * 
+ * + */ +@XmlType(name = "currency") +@XmlEnum +public enum Currency { + + GBP, + EUR, + PLN; + + public String value() { + return name(); + } + + public static Currency fromValue(String v) { + return valueOf(v); + } + +} diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/GetCountryRequest.java b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/GetCountryRequest.java new file mode 100644 index 0000000000..5739ee3b96 --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/GetCountryRequest.java @@ -0,0 +1,71 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0 +// See https://javaee.github.io/jaxb-v2/ +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2020.04.25 at 03:18:49 PM IST +// + + +package com.baeldung.springsoap.client.gen; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for anonymous complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType>
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "name" +}) +@XmlRootElement(name = "getCountryRequest") +public class GetCountryRequest { + + @XmlElement(required = true) + protected String name; + + /** + * Gets the value of the name property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getName() { + return name; + } + + /** + * Sets the value of the name property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setName(String value) { + this.name = value; + } + +} diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/GetCountryResponse.java b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/GetCountryResponse.java new file mode 100644 index 0000000000..ba1ab56cf8 --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/GetCountryResponse.java @@ -0,0 +1,71 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0 +// See https://javaee.github.io/jaxb-v2/ +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2020.04.25 at 03:18:49 PM IST +// + + +package com.baeldung.springsoap.client.gen; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for anonymous complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType>
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="country" type="{http://www.baeldung.com/springsoap/gen}country"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "country" +}) +@XmlRootElement(name = "getCountryResponse") +public class GetCountryResponse { + + @XmlElement(required = true) + protected Country country; + + /** + * Gets the value of the country property. + * + * @return + * possible object is + * {@link Country } + * + */ + public Country getCountry() { + return country; + } + + /** + * Sets the value of the country property. + * + * @param value + * allowed object is + * {@link Country } + * + */ + public void setCountry(Country value) { + this.country = value; + } + +} diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/ObjectFactory.java b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/ObjectFactory.java new file mode 100644 index 0000000000..88b27245be --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/ObjectFactory.java @@ -0,0 +1,63 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0 +// See https://javaee.github.io/jaxb-v2/ +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2020.04.25 at 03:18:49 PM IST +// + + +package com.baeldung.springsoap.client.gen; + +import javax.xml.bind.annotation.XmlRegistry; + + +/** + * This object contains factory methods for each + * Java content interface and Java element interface + * generated in the com.baeldung.springsoap.client.gen package. + *

An ObjectFactory allows you to programatically + * construct new instances of the Java representation + * for XML content. The Java representation of XML + * content can consist of schema derived interfaces + * and classes representing the binding of schema + * type definitions, element declarations and model + * groups. Factory methods for each of these are + * provided in this class. + * + */ +@XmlRegistry +public class ObjectFactory { + + + /** + * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.baeldung.springsoap.client.gen + * + */ + public ObjectFactory() { + } + + /** + * Create an instance of {@link GetCountryRequest } + * + */ + public GetCountryRequest createGetCountryRequest() { + return new GetCountryRequest(); + } + + /** + * Create an instance of {@link GetCountryResponse } + * + */ + public GetCountryResponse createGetCountryResponse() { + return new GetCountryResponse(); + } + + /** + * Create an instance of {@link Country } + * + */ + public Country createCountry() { + return new Country(); + } + +} diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/package-info.java b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/package-info.java new file mode 100644 index 0000000000..eefed169a8 --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/package-info.java @@ -0,0 +1,9 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0 +// See https://javaee.github.io/jaxb-v2/ +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2020.04.25 at 03:18:49 PM IST +// + +@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.baeldung.com/springsoap/gen", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) +package com.baeldung.springsoap.client.gen; diff --git a/spring-soap/src/main/resources/countries.wsdl b/spring-soap/src/main/resources/countries.wsdl new file mode 100644 index 0000000000..2a2eaf05bb --- /dev/null +++ b/spring-soap/src/main/resources/countries.wsdl @@ -0,0 +1,74 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-soap/src/test/java/com/baeldung/springsoap/client/CountryClientLiveTest.java b/spring-soap/src/test/java/com/baeldung/springsoap/client/CountryClientLiveTest.java new file mode 100644 index 0000000000..63dbe2a5cf --- /dev/null +++ b/spring-soap/src/test/java/com/baeldung/springsoap/client/CountryClientLiveTest.java @@ -0,0 +1,36 @@ +package com.baeldung.springsoap.client; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.springsoap.client.gen.Currency; +import com.baeldung.springsoap.client.gen.GetCountryResponse; + +//Ensure that the server - com.baeldung.springsoap.Application - is running before executing this test +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = CountryClientConfig.class, loader = AnnotationConfigContextLoader.class) +public class CountryClientLiveTest { + + @Autowired + CountryClient client; + + @Test + public void givenCountryService_whenCountryPoland_thenCapitalIsWarsaw() { + GetCountryResponse response = client.getCountry("Poland"); + assertEquals("Warsaw", response.getCountry() + .getCapital()); + } + + @Test + public void givenCountryService_whenCountrySpain_thenCurrencyEUR() { + GetCountryResponse response = client.getCountry("Spain"); + assertEquals(Currency.EUR, response.getCountry() + .getCurrency()); + } +} From bd9c4945f7c1e96a64c944414f23b055f8e49482 Mon Sep 17 00:00:00 2001 From: Michael Pratt Date: Sat, 25 Apr 2020 11:37:01 -0600 Subject: [PATCH 33/47] BAEL-3972: Fix formatting --- .../com/baeldung/app/controller/TaskController.java | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/spring-security-modules/spring-security-core/src/main/java/com/baeldung/app/controller/TaskController.java b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/app/controller/TaskController.java index 95f855c1e5..67072b5d61 100644 --- a/spring-security-modules/spring-security-core/src/main/java/com/baeldung/app/controller/TaskController.java +++ b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/app/controller/TaskController.java @@ -48,8 +48,7 @@ public class TaskController { */ @GetMapping("/manager") @PreAuthorize("hasRole('ROLE_MANAGER')") - public ResponseEntity> getAlManagerTasks() - { + public ResponseEntity> getAlManagerTasks() { Iterable tasks = taskService.findAll(); return ResponseEntity.ok().body(tasks); @@ -59,8 +58,7 @@ public class TaskController { * Example of restricting specific endpoints to specific roles using SecurityContext. */ @GetMapping("/actuator") - public ResponseEntity> getAlActuatorTasks() - { + public ResponseEntity> getAlActuatorTasks() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null && auth.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ACTUATOR"))) { @@ -76,8 +74,7 @@ public class TaskController { * Example of restricting specific endpoints to specific roles using UserDetailsService. */ @GetMapping("/admin") - public ResponseEntity> getAlAdminTasks() - { + public ResponseEntity> getAlAdminTasks() { if(userDetailsService != null) { UserDetails details = userDetailsService.loadUserByUsername("pam"); if (details != null && details.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ADMIN"))) { @@ -94,8 +91,7 @@ public class TaskController { * Example of restricting specific endpoints to specific roles using HttpServletRequest. */ @GetMapping("/admin2") - public ResponseEntity> getAlAdminTasksUsingServlet(HttpServletRequest request) - { + public ResponseEntity> getAlAdminTasksUsingServlet(HttpServletRequest request) { if (!request.isUserInRole("ROLE_ADMIN")) { return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); } From fd5fcf29c55e234cb26262edf42b2c55ea55e7ef Mon Sep 17 00:00:00 2001 From: Justin Albano Date: Sat, 25 Apr 2020 16:05:50 -0400 Subject: [PATCH 34/47] BAEL-3965: Removed unneeded dependencies --- spring-core-4/pom.xml | 25 ------------------------- 1 file changed, 25 deletions(-) diff --git a/spring-core-4/pom.xml b/spring-core-4/pom.xml index 06598fb41e..53f7ca6912 100644 --- a/spring-core-4/pom.xml +++ b/spring-core-4/pom.xml @@ -14,26 +14,6 @@ - - org.springframework - spring-beans - ${spring.version} - - - org.springframework - spring-tx - ${spring.version} - - - org.springframework - spring-jdbc - ${spring.version} - - - org.springframework.boot - spring-boot-starter-web - ${spring.boot.version} - org.springframework spring-context @@ -44,11 +24,6 @@ spring-core ${spring.version} - - javax.annotation - javax.annotation-api - ${annotation-api.version} - org.springframework spring-test From ee898632d354bfeb972ba3a01217910834517535 Mon Sep 17 00:00:00 2001 From: Aaron Juarez Date: Sat, 25 Apr 2020 16:23:13 -0400 Subject: [PATCH 35/47] BAEL-3966: find object's class in Java (#9118) --- .../com/baeldung/objectclass/Borrower.java | 23 ++++++ .../java/com/baeldung/objectclass/Lender.java | 20 +++++ .../java/com/baeldung/objectclass/User.java | 12 +++ .../objectclass/CreditAppUnitTest.java | 74 +++++++++++++++++++ 4 files changed, 129 insertions(+) create mode 100644 core-java-modules/core-java/src/main/java/com/baeldung/objectclass/Borrower.java create mode 100644 core-java-modules/core-java/src/main/java/com/baeldung/objectclass/Lender.java create mode 100644 core-java-modules/core-java/src/main/java/com/baeldung/objectclass/User.java create mode 100644 core-java-modules/core-java/src/test/java/com/baeldung/objectclass/CreditAppUnitTest.java diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/objectclass/Borrower.java b/core-java-modules/core-java/src/main/java/com/baeldung/objectclass/Borrower.java new file mode 100644 index 0000000000..62062aa7fc --- /dev/null +++ b/core-java-modules/core-java/src/main/java/com/baeldung/objectclass/Borrower.java @@ -0,0 +1,23 @@ +package com.baeldung.objectclass; + +import lombok.Data; + +@Data +public class Borrower extends User { + + private double totalLoanAmount; + + public double requestLoan(double amount) { + totalLoanAmount = amount; + return totalLoanAmount; + } + + public double increaseLoan(double increaseBy) { + return totalLoanAmount + increaseBy; + } + + public double payLoan(double amount) { + return totalLoanAmount - amount; + } + +} diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/objectclass/Lender.java b/core-java-modules/core-java/src/main/java/com/baeldung/objectclass/Lender.java new file mode 100644 index 0000000000..b45272cbb1 --- /dev/null +++ b/core-java-modules/core-java/src/main/java/com/baeldung/objectclass/Lender.java @@ -0,0 +1,20 @@ +package com.baeldung.objectclass; + +public class Lender extends User { + + private double totalInvestmentAmount; + + public double invest(double amount) { + totalInvestmentAmount = amount; + return totalInvestmentAmount; + } + + public double increaseInvestment(double increaseBy) { + return totalInvestmentAmount + increaseBy; + } + + public double collectDividends() { + return totalInvestmentAmount * 0.07; + } + +} diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/objectclass/User.java b/core-java-modules/core-java/src/main/java/com/baeldung/objectclass/User.java new file mode 100644 index 0000000000..b1f3887f2f --- /dev/null +++ b/core-java-modules/core-java/src/main/java/com/baeldung/objectclass/User.java @@ -0,0 +1,12 @@ +package com.baeldung.objectclass; + +import lombok.Data; + +@Data +public class User { + + private String firstName; + private String lastName; + + +} diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/objectclass/CreditAppUnitTest.java b/core-java-modules/core-java/src/test/java/com/baeldung/objectclass/CreditAppUnitTest.java new file mode 100644 index 0000000000..8330ddbac5 --- /dev/null +++ b/core-java-modules/core-java/src/test/java/com/baeldung/objectclass/CreditAppUnitTest.java @@ -0,0 +1,74 @@ +package com.baeldung.objectclass; + +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.Test; + +public class CreditAppUnitTest { + + @Test + public void givenLender_whenInstanceOf_thenReturnTrue() { + User lender = new Lender(); + assertTrue(lender instanceof Lender); + assertTrue(lender instanceof User); + } + + @Test + public void givenUser_whenInstanceOfLender_thenDowncast() { + User user = new Lender(); + Lender lender = null; + + if(user instanceof Lender) { + lender = (Lender) user; + } + + assertNotNull(lender); + } + + @Test + public void givenUser_whenIsInstanceOfLender_thenDowncast() { + User user = new Lender(); + Lender lender = null; + + if(Lender.class.isInstance(user)) { + lender = (Lender) user; + } + + assertNotNull(lender); + } + + @Test + public void givenBorrower_whenLoanAmountIsDouble_thenRequestLoan() { + Borrower borrower = new Borrower(); + double amount = 100.0; + + //if(amount instanceof Double) // Compilation error, no autoboxing + if(Double.class.isInstance(amount)) { + borrower.requestLoan(amount); + } + assertEquals(100, borrower.getTotalLoanAmount()); + } + + @Test + public void givenBorrower_whenLoanAmountIsNotString_thenRequestLoan() { + Borrower borrower = new Borrower(); + Double amount = 100.0; + + //if(amount instanceof String) // Compilation error, incompatible operands + if(!String.class.isInstance(amount)) { + borrower.requestLoan(amount); + } + assertEquals(100, borrower.getTotalLoanAmount()); + } + + @Test + public void givenLender_whenGetClass_thenEqualsLenderType() { + User lender = new Lender(); + assertEquals(Lender.class, lender.getClass()); + assertNotEquals(User.class, lender.getClass()); + } + +} From 0223584fee0d7d6661696a194e63032d6a37acd8 Mon Sep 17 00:00:00 2001 From: "amit.pandey" Date: Sun, 26 Apr 2020 06:41:14 +0530 Subject: [PATCH 36/47] removed duplicate module --- maven-java-11/README.md | 6 -- .../daomodule/pom.xml | 17 ----- .../src/main/java/com/baeldung/dao/Dao.java | 12 ---- .../daomodule/src/main/java/module-info.java | 3 - .../entitiymodule/pom.xml | 22 ------- .../main/java/com/baeldung/entity/User.java | 19 ------ .../src/main/java/module-info.java | 3 - .../mainppmodule/pom.xml | 38 ----------- .../com/baeldung/mainapp/Application.java | 19 ------ .../src/main/java/module-info.java | 6 -- .../multimodule-maven-project/pom.xml | 66 ------------------- .../userdaomodule/pom.xml | 42 ------------ .../java/com/baeldung/userdao/UserDao.java | 32 --------- .../src/main/java/module-info.java | 6 -- .../userdao/test/UserDaoUnitTest.java | 36 ---------- maven-java-11/pom.xml | 27 -------- 16 files changed, 354 deletions(-) delete mode 100644 maven-java-11/README.md delete mode 100644 maven-java-11/multimodule-maven-project/daomodule/pom.xml delete mode 100644 maven-java-11/multimodule-maven-project/daomodule/src/main/java/com/baeldung/dao/Dao.java delete mode 100644 maven-java-11/multimodule-maven-project/daomodule/src/main/java/module-info.java delete mode 100644 maven-java-11/multimodule-maven-project/entitiymodule/pom.xml delete mode 100644 maven-java-11/multimodule-maven-project/entitiymodule/src/main/java/com/baeldung/entity/User.java delete mode 100644 maven-java-11/multimodule-maven-project/entitiymodule/src/main/java/module-info.java delete mode 100644 maven-java-11/multimodule-maven-project/mainppmodule/pom.xml delete mode 100644 maven-java-11/multimodule-maven-project/mainppmodule/src/main/java/com/baeldung/mainapp/Application.java delete mode 100644 maven-java-11/multimodule-maven-project/mainppmodule/src/main/java/module-info.java delete mode 100644 maven-java-11/multimodule-maven-project/pom.xml delete mode 100644 maven-java-11/multimodule-maven-project/userdaomodule/pom.xml delete mode 100644 maven-java-11/multimodule-maven-project/userdaomodule/src/main/java/com/baeldung/userdao/UserDao.java delete mode 100644 maven-java-11/multimodule-maven-project/userdaomodule/src/main/java/module-info.java delete mode 100644 maven-java-11/multimodule-maven-project/userdaomodule/src/test/java/com/baeldung/userdao/test/UserDaoUnitTest.java delete mode 100644 maven-java-11/pom.xml diff --git a/maven-java-11/README.md b/maven-java-11/README.md deleted file mode 100644 index b923518825..0000000000 --- a/maven-java-11/README.md +++ /dev/null @@ -1,6 +0,0 @@ -## Maven and Java 11 - -This module contains articles about Maven with Java 11+. - -### Relevant Articles: - diff --git a/maven-java-11/multimodule-maven-project/daomodule/pom.xml b/maven-java-11/multimodule-maven-project/daomodule/pom.xml deleted file mode 100644 index cbe0b4cb95..0000000000 --- a/maven-java-11/multimodule-maven-project/daomodule/pom.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - 4.0.0 - com.baeldung.daomodule - daomodule - 1.0 - daomodule - jar - - - com.baeldung.multimodule-maven-project - multimodule-maven-project - 1.0 - - - diff --git a/maven-java-11/multimodule-maven-project/daomodule/src/main/java/com/baeldung/dao/Dao.java b/maven-java-11/multimodule-maven-project/daomodule/src/main/java/com/baeldung/dao/Dao.java deleted file mode 100644 index f86ae8abb3..0000000000 --- a/maven-java-11/multimodule-maven-project/daomodule/src/main/java/com/baeldung/dao/Dao.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.dao; - -import java.util.List; -import java.util.Optional; - -public interface Dao { - - Optional findById(int id); - - List findAll(); - -} diff --git a/maven-java-11/multimodule-maven-project/daomodule/src/main/java/module-info.java b/maven-java-11/multimodule-maven-project/daomodule/src/main/java/module-info.java deleted file mode 100644 index 072d7ad007..0000000000 --- a/maven-java-11/multimodule-maven-project/daomodule/src/main/java/module-info.java +++ /dev/null @@ -1,3 +0,0 @@ -module com.baeldung.dao { - exports com.baeldung.dao; -} diff --git a/maven-java-11/multimodule-maven-project/entitiymodule/pom.xml b/maven-java-11/multimodule-maven-project/entitiymodule/pom.xml deleted file mode 100644 index 228619ed74..0000000000 --- a/maven-java-11/multimodule-maven-project/entitiymodule/pom.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - 4.0.0 - com.baeldung.entitymodule - entitymodule - 1.0 - entitymodule - jar - - - com.baeldung.multimodule-maven-project - multimodule-maven-project - 1.0 - - - - 11 - 11 - - - diff --git a/maven-java-11/multimodule-maven-project/entitiymodule/src/main/java/com/baeldung/entity/User.java b/maven-java-11/multimodule-maven-project/entitiymodule/src/main/java/com/baeldung/entity/User.java deleted file mode 100644 index 22022a2e6d..0000000000 --- a/maven-java-11/multimodule-maven-project/entitiymodule/src/main/java/com/baeldung/entity/User.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.entity; - -public class User { - - private final String name; - - public User(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - @Override - public String toString() { - return "User{" + "name=" + name + '}'; - } -} diff --git a/maven-java-11/multimodule-maven-project/entitiymodule/src/main/java/module-info.java b/maven-java-11/multimodule-maven-project/entitiymodule/src/main/java/module-info.java deleted file mode 100644 index 67a3097352..0000000000 --- a/maven-java-11/multimodule-maven-project/entitiymodule/src/main/java/module-info.java +++ /dev/null @@ -1,3 +0,0 @@ -module com.baeldung.entity { - exports com.baeldung.entity; -} diff --git a/maven-java-11/multimodule-maven-project/mainppmodule/pom.xml b/maven-java-11/multimodule-maven-project/mainppmodule/pom.xml deleted file mode 100644 index a4a6575906..0000000000 --- a/maven-java-11/multimodule-maven-project/mainppmodule/pom.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - 4.0.0 - com.baeldung.mainappmodule - mainappmodule - 1.0 - mainappmodule - jar - - - com.baeldung.multimodule-maven-project - multimodule-maven-project - 1.0 - 1.0 - 1.0 - 1.0 - - - - - com.baeldung.entitymodule - entitymodule - ${entitymodule.version} - - - com.baeldung.daomodule - daomodule - ${daomodule.version} - - - com.baeldung.userdaomodule - userdaomodule - ${userdaomodule.version} - - - - diff --git a/maven-java-11/multimodule-maven-project/mainppmodule/src/main/java/com/baeldung/mainapp/Application.java b/maven-java-11/multimodule-maven-project/mainppmodule/src/main/java/com/baeldung/mainapp/Application.java deleted file mode 100644 index 0c0df7461b..0000000000 --- a/maven-java-11/multimodule-maven-project/mainppmodule/src/main/java/com/baeldung/mainapp/Application.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.mainapp; - -import com.baeldung.dao.Dao; -import com.baeldung.entity.User; -import com.baeldung.userdao.UserDao; -import java.util.HashMap; -import java.util.Map; - -public class Application { - - public static void main(String[] args) { - Map users = new HashMap<>(); - users.put(1, new User("Julie")); - users.put(2, new User("David")); - Dao userDao = new UserDao(users); - userDao.findAll().forEach(System.out::println); - } - -} diff --git a/maven-java-11/multimodule-maven-project/mainppmodule/src/main/java/module-info.java b/maven-java-11/multimodule-maven-project/mainppmodule/src/main/java/module-info.java deleted file mode 100644 index c688fcf7de..0000000000 --- a/maven-java-11/multimodule-maven-project/mainppmodule/src/main/java/module-info.java +++ /dev/null @@ -1,6 +0,0 @@ -module com.baeldung.mainapp { - requires com.baeldung.entity; - requires com.baeldung.userdao; - requires com.baeldung.dao; - uses com.baeldung.dao.Dao; -} diff --git a/maven-java-11/multimodule-maven-project/pom.xml b/maven-java-11/multimodule-maven-project/pom.xml deleted file mode 100644 index 65f5b7a814..0000000000 --- a/maven-java-11/multimodule-maven-project/pom.xml +++ /dev/null @@ -1,66 +0,0 @@ - - - 4.0.0 - com.baeldung.multimodule-maven-project - multimodule-maven-project - 1.0 - multimodule-maven-project - pom - - - com.baeldung.maven-java-11 - maven-java-11 - 1.0 - - - - entitymodule - daomodule - userdaomodule - mainappmodule - - - - - - junit - junit - ${junit.version} - test - - - org.assertj - assertj-core - ${assertj.version} - test - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${compiler.plugin.version} - - ${source.version} - ${target.version} - - - - - - - - UTF-8 - 4.12 - 3.12.2 - 3.8.0 - 11 - 11 - - - diff --git a/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml b/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml deleted file mode 100644 index cf6ea85cb5..0000000000 --- a/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - 4.0.0 - com.baeldung.userdaomodule - userdaomodule - 1.0 - userdaomodule - jar - - - com.baeldung.multimodule-maven-project - multimodule-maven-project - 1.0 - - - - - com.baeldung.entitymodule - entitymodule - ${entitymodule.version}1.0 - - - com.baeldung.daomodule - daomodule - ${daomodule.version} - - - junit - junit - test - - - - - 1.0 - 1.0 - - - diff --git a/maven-java-11/multimodule-maven-project/userdaomodule/src/main/java/com/baeldung/userdao/UserDao.java b/maven-java-11/multimodule-maven-project/userdaomodule/src/main/java/com/baeldung/userdao/UserDao.java deleted file mode 100644 index 1f1ea38a60..0000000000 --- a/maven-java-11/multimodule-maven-project/userdaomodule/src/main/java/com/baeldung/userdao/UserDao.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.userdao; - -import com.baeldung.dao.Dao; -import com.baeldung.entity.User; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -public class UserDao implements Dao { - - private final Map users; - - public UserDao() { - users = new HashMap<>(); - } - - public UserDao(Map users) { - this.users = users; - } - - @Override - public List findAll() { - return new ArrayList<>(users.values()); - } - - @Override - public Optional findById(int id) { - return Optional.ofNullable(users.get(id)); - } -} \ No newline at end of file diff --git a/maven-java-11/multimodule-maven-project/userdaomodule/src/main/java/module-info.java b/maven-java-11/multimodule-maven-project/userdaomodule/src/main/java/module-info.java deleted file mode 100644 index f1cb217e23..0000000000 --- a/maven-java-11/multimodule-maven-project/userdaomodule/src/main/java/module-info.java +++ /dev/null @@ -1,6 +0,0 @@ -module com.baeldung.userdao { - requires com.baeldung.entity; - requires com.baeldung.dao; - provides com.baeldung.dao.Dao with com.baeldung.userdao.UserDao; - exports com.baeldung.userdao; -} diff --git a/maven-java-11/multimodule-maven-project/userdaomodule/src/test/java/com/baeldung/userdao/test/UserDaoUnitTest.java b/maven-java-11/multimodule-maven-project/userdaomodule/src/test/java/com/baeldung/userdao/test/UserDaoUnitTest.java deleted file mode 100644 index 191d17ff32..0000000000 --- a/maven-java-11/multimodule-maven-project/userdaomodule/src/test/java/com/baeldung/userdao/test/UserDaoUnitTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.userdao.test; - -import com.baeldung.dao.Dao; -import com.baeldung.entity.User; -import com.baeldung.userdao.UserDao; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import static org.junit.Assert.*; -import static org.hamcrest.CoreMatchers.*; -import org.junit.Before; -import org.junit.Test; - -public class UserDaoUnitTest { - - private Dao userDao; - - @Before - public void setUpUserDaoInstance() { - Map users = new HashMap<>(); - users.put(1, new User("Julie")); - users.put(2, new User("David")); - userDao = new UserDao(users); - } - - @Test - public void givenUserDaoIntance_whenCalledFindById_thenCorrect() { - assertThat(userDao.findById(1), isA(Optional.class)); - } - - @Test - public void givenUserDaoIntance_whenCalledFindAll_thenCorrect() { - assertThat(userDao.findAll(), isA(List.class)); - } -} diff --git a/maven-java-11/pom.xml b/maven-java-11/pom.xml deleted file mode 100644 index 10e80365c8..0000000000 --- a/maven-java-11/pom.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - 4.0.0 - com.baeldung.maven-java-11 - maven-java-11 - 1.0 - maven-java-11 - pom - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - multimodule-maven-project - - - - UTF-8 - 11 - 11 - - - From b8d41e5613457b185324cc39630816d83ac1cf4f Mon Sep 17 00:00:00 2001 From: Vikas Rajput Date: Sun, 26 Apr 2020 11:51:21 +0530 Subject: [PATCH 37/47] Bael 3557 : renamed package name to more unique name - springwithgroovy (#9172) * BAEL-3557: Completed a simple web application in spring boot and groovy * BAEL-3557: renamed packagename from com.baeldung.app to more unique name - com.baeldung.springwithgroovy Co-authored-by: Vikas Ramsingh Rajput --- .../SpringBootGroovyApplication.groovy | 13 +++ .../controller/TodoController.groovy | 48 +++++++++ .../springwithgroovy/entity/Todo.groovy | 23 +++++ .../repository/TodoRepository.groovy | 9 ++ .../service/TodoService.groovy | 16 +++ .../service/impl/TodoServiceImpl.groovy | 40 ++++++++ .../springwithgroovy/TodoAppUnitTest.groovy | 97 +++++++++++++++++++ 7 files changed, 246 insertions(+) create mode 100644 spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/SpringBootGroovyApplication.groovy create mode 100644 spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/controller/TodoController.groovy create mode 100644 spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/entity/Todo.groovy create mode 100644 spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/repository/TodoRepository.groovy create mode 100644 spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/TodoService.groovy create mode 100644 spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/impl/TodoServiceImpl.groovy create mode 100644 spring-boot-groovy/src/test/groovy/com/baeldung/springwithgroovy/TodoAppUnitTest.groovy diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/SpringBootGroovyApplication.groovy b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/SpringBootGroovyApplication.groovy new file mode 100644 index 0000000000..4912b75a66 --- /dev/null +++ b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/SpringBootGroovyApplication.groovy @@ -0,0 +1,13 @@ +package com.baeldung.springwithgroovy + +import org.springframework.boot.SpringApplication +import org.springframework.boot.autoconfigure.SpringBootApplication + +import com.baeldung.springwithgroovy.SpringBootGroovyApplication + +@SpringBootApplication +class SpringBootGroovyApplication { + static void main(String[] args) { + SpringApplication.run SpringBootGroovyApplication, args + } +} diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/controller/TodoController.groovy b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/controller/TodoController.groovy new file mode 100644 index 0000000000..9c6aee20d3 --- /dev/null +++ b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/controller/TodoController.groovy @@ -0,0 +1,48 @@ +package com.baeldung.springwithgroovy.controller + +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.web.bind.annotation.DeleteMapping +import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.bind.annotation.PathVariable +import org.springframework.web.bind.annotation.PostMapping +import org.springframework.web.bind.annotation.PutMapping +import org.springframework.web.bind.annotation.RequestBody +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.web.bind.annotation.RequestMethod +import org.springframework.web.bind.annotation.RestController + +import com.baeldung.springwithgroovy.entity.Todo +import com.baeldung.springwithgroovy.service.TodoService + +@RestController +@RequestMapping('todo') +public class TodoController { + + @Autowired + TodoService todoService + + @GetMapping + List getAllTodoList(){ + todoService.findAll() + } + + @PostMapping + Todo saveTodo(@RequestBody Todo todo){ + todoService.saveTodo todo + } + + @PutMapping + Todo updateTodo(@RequestBody Todo todo){ + todoService.updateTodo todo + } + + @DeleteMapping('/{todoId}') + deleteTodo(@PathVariable Integer todoId){ + todoService.deleteTodo todoId + } + + @GetMapping('/{todoId}') + Todo getTodoById(@PathVariable Integer todoId){ + todoService.findById todoId + } +} \ No newline at end of file diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/entity/Todo.groovy b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/entity/Todo.groovy new file mode 100644 index 0000000000..000d981701 --- /dev/null +++ b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/entity/Todo.groovy @@ -0,0 +1,23 @@ +package com.baeldung.springwithgroovy.entity + +import javax.persistence.Column +import javax.persistence.Entity +import javax.persistence.GeneratedValue +import javax.persistence.GenerationType +import javax.persistence.Id +import javax.persistence.Table + +@Entity +@Table(name = 'todo') +class Todo { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + Integer id + + @Column + String task + + @Column + Boolean isCompleted + +} diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/repository/TodoRepository.groovy b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/repository/TodoRepository.groovy new file mode 100644 index 0000000000..eb58cc0791 --- /dev/null +++ b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/repository/TodoRepository.groovy @@ -0,0 +1,9 @@ +package com.baeldung.springwithgroovy.repository + +import org.springframework.data.jpa.repository.JpaRepository +import org.springframework.stereotype.Repository + +import com.baeldung.springwithgroovy.entity.Todo + +@Repository +interface TodoRepository extends JpaRepository {} \ No newline at end of file diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/TodoService.groovy b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/TodoService.groovy new file mode 100644 index 0000000000..c57af34cde --- /dev/null +++ b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/TodoService.groovy @@ -0,0 +1,16 @@ +package com.baeldung.springwithgroovy.service + +import com.baeldung.springwithgroovy.entity.Todo + +interface TodoService { + + List findAll() + + Todo findById(Integer todoId) + + Todo saveTodo(Todo todo) + + Todo updateTodo(Todo todo) + + Todo deleteTodo(Integer todoId) +} diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/impl/TodoServiceImpl.groovy b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/impl/TodoServiceImpl.groovy new file mode 100644 index 0000000000..943c1c6944 --- /dev/null +++ b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/impl/TodoServiceImpl.groovy @@ -0,0 +1,40 @@ +package com.baeldung.springwithgroovy.service.impl + +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.stereotype.Service + +import com.baeldung.springwithgroovy.entity.Todo +import com.baeldung.springwithgroovy.repository.TodoRepository +import com.baeldung.springwithgroovy.service.TodoService + +@Service +class TodoServiceImpl implements TodoService { + + @Autowired + TodoRepository todoRepository + + @Override + List findAll() { + todoRepository.findAll() + } + + @Override + Todo findById(Integer todoId) { + todoRepository.findById todoId get() + } + + @Override + Todo saveTodo(Todo todo){ + todoRepository.save todo + } + + @Override + Todo updateTodo(Todo todo){ + todoRepository.save todo + } + + @Override + Todo deleteTodo(Integer todoId){ + todoRepository.deleteById todoId + } +} diff --git a/spring-boot-groovy/src/test/groovy/com/baeldung/springwithgroovy/TodoAppUnitTest.groovy b/spring-boot-groovy/src/test/groovy/com/baeldung/springwithgroovy/TodoAppUnitTest.groovy new file mode 100644 index 0000000000..bf8b0ff27f --- /dev/null +++ b/spring-boot-groovy/src/test/groovy/com/baeldung/springwithgroovy/TodoAppUnitTest.groovy @@ -0,0 +1,97 @@ +package com.baeldung.springwithgroovy + +import static org.junit.jupiter.api.Assertions.assertEquals +import static org.junit.jupiter.api.Assertions.assertTrue + +import org.junit.BeforeClass +import org.junit.Test +import org.junit.runner.RunWith +import org.springframework.boot.test.context.SpringBootTest +import org.springframework.http.HttpStatus +import org.springframework.http.MediaType +import org.springframework.test.context.event.annotation.BeforeTestClass +import org.springframework.test.context.junit4.SpringRunner + +import com.baeldung.springwithgroovy.entity.Todo + +import io.restassured.RestAssured +import io.restassured.response.Response + +class TodoAppUnitTest { + static API_ROOT = 'http://localhost:8081/todo' + static readingTodoId + static writingTodoId + + @BeforeClass + static void populateDummyData() { + Todo readingTodo = new Todo(task: 'Reading', isCompleted: false) + Todo writingTodo = new Todo(task: 'Writing', isCompleted: false) + + final Response readingResponse = + RestAssured.given() + .contentType(MediaType.APPLICATION_JSON_VALUE) + .body(readingTodo).post(API_ROOT) + + Todo cookingTodoResponse = readingResponse.as Todo.class + readingTodoId = cookingTodoResponse.getId() + + final Response writingResponse = + RestAssured.given() + .contentType(MediaType.APPLICATION_JSON_VALUE) + .body(writingTodo).post(API_ROOT) + + Todo writingTodoResponse = writingResponse.as Todo.class + writingTodoId = writingTodoResponse.getId() + } + + @Test + void whenGetAllTodoList_thenOk(){ + final Response response = RestAssured.get(API_ROOT) + + assertEquals HttpStatus.OK.value(),response.getStatusCode() + assertTrue response.as(List.class).size() > 0 + } + + @Test + void whenGetTodoById_thenOk(){ + final Response response = + RestAssured.get("$API_ROOT/$readingTodoId") + + assertEquals HttpStatus.OK.value(),response.getStatusCode() + Todo todoResponse = response.as Todo.class + assertEquals readingTodoId,todoResponse.getId() + } + + @Test + void whenUpdateTodoById_thenOk(){ + Todo todo = new Todo(id:readingTodoId, isCompleted: true) + final Response response = + RestAssured.given() + .contentType(MediaType.APPLICATION_JSON_VALUE) + .body(todo).put(API_ROOT) + + assertEquals HttpStatus.OK.value(),response.getStatusCode() + Todo todoResponse = response.as Todo.class + assertTrue todoResponse.getIsCompleted() + } + + @Test + void whenDeleteTodoById_thenOk(){ + final Response response = + RestAssured.given() + .delete("$API_ROOT/$writingTodoId") + + assertEquals HttpStatus.OK.value(),response.getStatusCode() + } + + @Test + void whenSaveTodo_thenOk(){ + Todo todo = new Todo(task: 'Blogging', isCompleted: false) + final Response response = + RestAssured.given() + .contentType(MediaType.APPLICATION_JSON_VALUE) + .body(todo).post(API_ROOT) + + assertEquals HttpStatus.OK.value(),response.getStatusCode() + } +} \ No newline at end of file From d2f60283b8eb3d8633f2bcb5eda3fc69fbff330c Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Sun, 26 Apr 2020 15:46:04 +0200 Subject: [PATCH 38/47] JAVA-73: Remove unused test methods --- .../MongoTransactionalLiveTest.java | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalLiveTest.java index bafcd770ec..6cd9657006 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalLiveTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalLiveTest.java @@ -62,24 +62,6 @@ public class MongoTransactionalLiveTest { } } - @Test(expected = MongoCommandException.class) - @Transactional - public void whenCountDuringMongoTransaction_thenException() { - userRepository.save(new User("John", 30)); - userRepository.save(new User("Ringo", 35)); - userRepository.count(); - } - - @Test - @Transactional - public void whenQueryDuringMongoTransaction_thenSuccess() { - userRepository.save(new User("Jane", 20)); - userRepository.save(new User("Nick", 33)); - List users = mongoTemplate.find(new Query(), User.class); - - assertTrue(users.size() > 1); - } - // ==== Using test instead of before and after due to @transactional doesn't allow list collection @Test From df179d642e3fef9da586f8fe2582fa6719d2fe53 Mon Sep 17 00:00:00 2001 From: Sampada <46674082+sampada07@users.noreply.github.com> Date: Sun, 26 Apr 2020 21:25:43 +0530 Subject: [PATCH 39/47] BAEL-3988: Calling a SOAP web service in Java (#9184) * BAEL-3988: Calling a SOAP web service in Java * BAEL-3988: modified generated class as per wsdl location change --- jee-7/pom.xml | 7 ++-- .../generated/CountryServiceImplService.java | 6 +-- jee-7/src/main/resources/country.wsdl | 40 ------------------- 3 files changed, 6 insertions(+), 47 deletions(-) delete mode 100644 jee-7/src/main/resources/country.wsdl diff --git a/jee-7/pom.xml b/jee-7/pom.xml index 7352c6550a..9077aae1a6 100644 --- a/jee-7/pom.xml +++ b/jee-7/pom.xml @@ -256,10 +256,9 @@ - src/main/resources - - country.wsdl - + + http://localhost:8888/ws/country?wsdl + true com.baeldung.soap.ws.client.generated src/main/java diff --git a/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/CountryServiceImplService.java b/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/CountryServiceImplService.java index 09f4c29202..a6983938f5 100644 --- a/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/CountryServiceImplService.java +++ b/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/CountryServiceImplService.java @@ -12,11 +12,11 @@ import javax.xml.ws.WebServiceFeature; /** * This class was generated by the JAX-WS RI. - * JAX-WS RI 2.3.2 + * JAX-WS RI 2.2.9-b130926.1035 * Generated source version: 2.2 * */ -@WebServiceClient(name = "CountryServiceImplService", targetNamespace = "http://server.ws.soap.baeldung.com/", wsdlLocation = "file:src/main/resources/country.wsdl") +@WebServiceClient(name = "CountryServiceImplService", targetNamespace = "http://server.ws.soap.baeldung.com/", wsdlLocation = "http://localhost:8888/ws/country?wsdl") public class CountryServiceImplService extends Service { private final static URL COUNTRYSERVICEIMPLSERVICE_WSDL_LOCATION; @@ -27,7 +27,7 @@ public class CountryServiceImplService extends Service { URL url = null; WebServiceException e = null; try { - url = new URL("file:src/main/resources/country.wsdl"); + url = new URL("http://localhost:8888/ws/country?wsdl"); } catch (MalformedURLException ex) { e = new WebServiceException(ex); } diff --git a/jee-7/src/main/resources/country.wsdl b/jee-7/src/main/resources/country.wsdl deleted file mode 100644 index 4d41fce322..0000000000 --- a/jee-7/src/main/resources/country.wsdl +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file From c7acf47138c929c59a35e545a3fe66d3225365eb Mon Sep 17 00:00:00 2001 From: "amit.pandey" Date: Sun, 26 Apr 2020 22:24:14 +0530 Subject: [PATCH 40/47] fix junit test cases --- .../batch/understanding/CustomCheckPointUnitTest.java | 9 +++------ .../batch/understanding/JobSequenceUnitTest.java | 6 +++--- .../batch/understanding/SimpleBatchLetUnitTest.java | 9 ++++----- .../batch/understanding/SimpleChunkUnitTest.java | 5 ++--- .../batch/understanding/SimpleErrorChunkUnitTest.java | 11 +++++------ jee-7/src/test/resources/jberet.properties | 1 + 6 files changed, 18 insertions(+), 23 deletions(-) create mode 100644 jee-7/src/test/resources/jberet.properties diff --git a/jee-7/src/test/java/com/baeldung/batch/understanding/CustomCheckPointUnitTest.java b/jee-7/src/test/java/com/baeldung/batch/understanding/CustomCheckPointUnitTest.java index 744bdfc8f5..c607efeb24 100644 --- a/jee-7/src/test/java/com/baeldung/batch/understanding/CustomCheckPointUnitTest.java +++ b/jee-7/src/test/java/com/baeldung/batch/understanding/CustomCheckPointUnitTest.java @@ -1,20 +1,17 @@ package com.baeldung.batch.understanding; -import static org.junit.jupiter.api.Assertions.*; -import java.util.Map; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.Properties; + import javax.batch.operations.JobOperator; import javax.batch.runtime.BatchRuntime; import javax.batch.runtime.BatchStatus; import javax.batch.runtime.JobExecution; -import javax.batch.runtime.Metric; import javax.batch.runtime.StepExecution; -import com.baeldung.batch.understanding.BatchTestHelper; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.Disabled; -@Disabled("Should be fixed in BAEL-3812") class CustomCheckPointUnitTest { @Test public void givenChunk_whenCustomCheckPoint_thenCommitCountIsThree() throws Exception { diff --git a/jee-7/src/test/java/com/baeldung/batch/understanding/JobSequenceUnitTest.java b/jee-7/src/test/java/com/baeldung/batch/understanding/JobSequenceUnitTest.java index 88b981df92..4b27e5f5ec 100644 --- a/jee-7/src/test/java/com/baeldung/batch/understanding/JobSequenceUnitTest.java +++ b/jee-7/src/test/java/com/baeldung/batch/understanding/JobSequenceUnitTest.java @@ -1,6 +1,8 @@ package com.baeldung.batch.understanding; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.List; @@ -13,9 +15,7 @@ import javax.batch.runtime.JobExecution; import javax.batch.runtime.StepExecution; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.Disabled; -@Disabled("Should be fixed in BAEL-3812") class JobSequenceUnitTest { @Test public void givenTwoSteps_thenBatch_CompleteWithSuccess() throws Exception { diff --git a/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleBatchLetUnitTest.java b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleBatchLetUnitTest.java index 3babf9b5aa..788b75eb3e 100644 --- a/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleBatchLetUnitTest.java +++ b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleBatchLetUnitTest.java @@ -1,17 +1,16 @@ package com.baeldung.batch.understanding; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Properties; import javax.batch.operations.JobOperator; import javax.batch.runtime.BatchRuntime; import javax.batch.runtime.BatchStatus; import javax.batch.runtime.JobExecution; -import java.util.Properties; -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; -@Disabled("Should be fixed in BAEL-3812") class SimpleBatchLetUnitTest { @Test public void givenBatchLet_thenBatch_CompleteWithSuccess() throws Exception { diff --git a/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleChunkUnitTest.java b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleChunkUnitTest.java index 5871143fa3..9010c365a2 100644 --- a/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleChunkUnitTest.java +++ b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleChunkUnitTest.java @@ -1,6 +1,7 @@ package com.baeldung.batch.understanding; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; import java.util.Map; @@ -14,9 +15,7 @@ import javax.batch.runtime.Metric; import javax.batch.runtime.StepExecution; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.Disabled; -@Disabled("Should be fixed in BAEL-3812") class SimpleChunkUnitTest { @Test public void givenChunk_thenBatch_CompletesWithSucess() throws Exception { diff --git a/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleErrorChunkUnitTest.java b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleErrorChunkUnitTest.java index c53561a0c0..bc410aec8d 100644 --- a/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleErrorChunkUnitTest.java +++ b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleErrorChunkUnitTest.java @@ -1,19 +1,18 @@ package com.baeldung.batch.understanding; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; +import static org.junit.Assert.assertEquals; + +import java.util.List; +import java.util.Properties; import javax.batch.operations.JobOperator; import javax.batch.runtime.BatchRuntime; import javax.batch.runtime.BatchStatus; import javax.batch.runtime.JobExecution; import javax.batch.runtime.StepExecution; -import java.util.List; -import java.util.Properties; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; -@Disabled("Should be fixed in BAEL-3812") class SimpleErrorChunkUnitTest { @Test diff --git a/jee-7/src/test/resources/jberet.properties b/jee-7/src/test/resources/jberet.properties new file mode 100644 index 0000000000..e8b9907de5 --- /dev/null +++ b/jee-7/src/test/resources/jberet.properties @@ -0,0 +1 @@ +db-url=jdbc:h2:mem:jberet-repo;DB_CLOSE_DELAY=-1 \ No newline at end of file From f1283f2424cc85aa6459898767c3f62be816d01b Mon Sep 17 00:00:00 2001 From: Belma Jakupovic Date: Mon, 27 Apr 2020 06:57:38 +0200 Subject: [PATCH 41/47] bjakupovic - single responsibility principle example (#9191) --- .../java/com/baeldung/s/TextManipulator.java | 35 +++++++++++++++++++ .../main/java/com/baeldung/s/TextPrinter.java | 23 ++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 patterns/solid/src/main/java/com/baeldung/s/TextManipulator.java create mode 100644 patterns/solid/src/main/java/com/baeldung/s/TextPrinter.java diff --git a/patterns/solid/src/main/java/com/baeldung/s/TextManipulator.java b/patterns/solid/src/main/java/com/baeldung/s/TextManipulator.java new file mode 100644 index 0000000000..a6b32a0ff9 --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/s/TextManipulator.java @@ -0,0 +1,35 @@ +package com.baeldung.s; + +public class TextManipulator { + private String text; + + public TextManipulator(String text) { + this.text = text; + } + + public String getText() { + return text; + } + + public void appendText(String newText) { + text = text.concat(newText); + } + + public void findWordAndReplace(String word, String replacementWord) { + if (text.contains(word)) { + text = text.replace(word, replacementWord); + } else System.out.println("Word you want to replace is not found in the text"); + } + + public void findWordAndDelete(String word) { + if (text.contains(word)) { + text = text.replace(word, ""); + } else System.out.println("Word you want to delete is not found in the text"); + } + + /* + * Bad practice when implementing SRP principle, not in the scope of this class + public void printText() { + System.out.println(textManipulator.getText()); + }*/ +} diff --git a/patterns/solid/src/main/java/com/baeldung/s/TextPrinter.java b/patterns/solid/src/main/java/com/baeldung/s/TextPrinter.java new file mode 100644 index 0000000000..d6a413e7ac --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/s/TextPrinter.java @@ -0,0 +1,23 @@ +package com.baeldung.s; + +import java.util.Arrays; + +public class TextPrinter { + TextManipulator textManipulator; + + public TextPrinter(TextManipulator textManipulator) { + this.textManipulator = textManipulator; + } + + public void printText() { + System.out.println(textManipulator.getText()); + } + + public void printOutEachWordOfText() { + System.out.println(Arrays.toString(textManipulator.getText().split(" "))); + } + + public void printRangeOfCharacters(int startingIndex, int endIndex) { + System.out.println(textManipulator.getText().substring(startingIndex, endIndex)); + } +} From e24cc4d7b0a9d34c0c091512f875df24b947b134 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Mon, 27 Apr 2020 11:34:36 +0530 Subject: [PATCH 42/47] JAVA-926: Upgraded spring boot version --- .../greeter-spring-boot-autoconfigure/pom.xml | 2 +- .../greeter-spring-boot-starter/pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml index 0bba2936a7..532f45cf3e 100644 --- a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml +++ b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml @@ -63,7 +63,7 @@ UTF-8 - 1.5.2.RELEASE + 2.2.6.RELEASE 0.0.1-SNAPSHOT diff --git a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-starter/pom.xml b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-starter/pom.xml index ba2b4101e8..0e8fb4cbc9 100644 --- a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-starter/pom.xml +++ b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-starter/pom.xml @@ -51,7 +51,7 @@ UTF-8 0.0.1-SNAPSHOT - 1.5.2.RELEASE + 2.2.6.RELEASE \ No newline at end of file From debb7dace50ee0ebe67e41872c132eafe83d8cbe Mon Sep 17 00:00:00 2001 From: Yevgen Pikus <4037842+gindex@users.noreply.github.com> Date: Mon, 27 Apr 2020 23:25:33 +0200 Subject: [PATCH 43/47] Add fold and reduce examples (#9188) Co-authored-by: Yevgen Pikus --- .../foldvsreduce/FoldAndReduceTest.kt | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/foldvsreduce/FoldAndReduceTest.kt diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/foldvsreduce/FoldAndReduceTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/foldvsreduce/FoldAndReduceTest.kt new file mode 100644 index 0000000000..7b263914c6 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/foldvsreduce/FoldAndReduceTest.kt @@ -0,0 +1,59 @@ +package com.baeldung.foldvsreduce + +import org.junit.Test +import org.junit.jupiter.api.assertThrows +import java.lang.RuntimeException +import kotlin.test.assertEquals + +class FoldAndReduceTest { + + @Test + fun testReduceLimitations() { + val numbers: List = listOf(1, 2, 3) + val sum: Number = numbers.reduce { acc, next -> acc + next } + assertEquals(6, sum) + + val emptyList = listOf() + assertThrows { emptyList.reduce { acc, next -> acc + next } } + + // doesn't compile + // val sum = numbers.reduce { acc, next -> acc.toLong() + next.toLong()} + } + + @Test + fun testFold() { + + val numbers: List = listOf(1, 2, 3) + val sum: Int = numbers.fold(0, { acc, next -> acc + next }) + assertEquals(6, sum) + + //change result type + val sumLong: Long = numbers.fold(0L, { acc, next -> acc + next.toLong() }) + assertEquals(6L, sumLong) + + val emptyList = listOf() + val emptySum = emptyList.fold(0, { acc, next -> acc + next }) + assertEquals(0, emptySum) + + //power of changing result type + val (even, odd) = numbers.fold(Pair(listOf(), listOf()), { acc, next -> + if (next % 2 == 0) Pair(acc.first + next, acc.second) + else Pair(acc.first, acc.second + next) + }) + + assertEquals(listOf(2), even) + assertEquals(listOf(1, 3), odd) + } + + @Test + fun testVariationsOfFold() { + val numbers = listOf(1, 2, 3) + val reversed = numbers.foldRight(listOf(), { next, acc -> acc + next}) + assertEquals(listOf(3,2,1), reversed) + + val reversedIndexes = numbers.foldRightIndexed(listOf(), { i, _, acc -> acc + i }) + assertEquals(listOf(2,1,0), reversedIndexes) + } + + +} \ No newline at end of file From ac794a722f32fbb1252e84f9b75d28586d2ef42a Mon Sep 17 00:00:00 2001 From: Greg Martin Date: Mon, 27 Apr 2020 18:58:15 -0400 Subject: [PATCH 44/47] Resolved Conflicts with master --- libraries-3/pom.xml | 33 --------------------------------- 1 file changed, 33 deletions(-) diff --git a/libraries-3/pom.xml b/libraries-3/pom.xml index a72dbcba50..5334bfba70 100644 --- a/libraries-3/pom.xml +++ b/libraries-3/pom.xml @@ -70,25 +70,6 @@ velocity-engine-core ${velocity-engine-core.version} -<<<<<<< HEAD - - com.uber.nullaway - nullaway - 0.3.0 - - - org.codehaus.plexus - plexus-compiler-javac-errorprone - 2.8 - - - - com.google.errorprone - error_prone_core - 2.1.3 - -======= com.uber.nullaway nullaway @@ -106,7 +87,6 @@ error_prone_core 2.1.3 ->>>>>>> upstream/master @@ -143,20 +123,11 @@ -<<<<<<< HEAD - - - org.apache.maven.plugins - maven-compiler-plugin - 3.5 - -======= org.apache.maven.plugins maven-compiler-plugin 3.5 ->>>>>>> upstream/master javac-with-errorprone true 1.8 @@ -172,11 +143,7 @@ -<<<<<<< HEAD - -XepExcludedPaths:(.*)/test/.*|(.*)/streamex/.*|(.*)/jcabi/.* -======= -XepExcludedPaths:(.*)/test/.*|(.*)/jcabi/.* ->>>>>>> upstream/master -XepOpt:NullAway:AnnotatedPackages=com.baeldung.nullaway From 491e2d84933ee0c876e38c956edd5e888f1398fc Mon Sep 17 00:00:00 2001 From: Greg Martin Date: Mon, 27 Apr 2020 19:02:40 -0400 Subject: [PATCH 45/47] Synced with master --- libraries-3/README.md | 1 - .../java/com/baeldung/distinct/Person.java | 65 ------------------- 2 files changed, 66 deletions(-) delete mode 100644 libraries-3/src/main/java/com/baeldung/distinct/Person.java diff --git a/libraries-3/README.md b/libraries-3/README.md index 922ce1bd1a..ec433960ef 100644 --- a/libraries-3/README.md +++ b/libraries-3/README.md @@ -12,7 +12,6 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m - [Guide to the Cactoos Library](https://www.baeldung.com/java-cactoos) - [Parsing Command-Line Parameters with Airline](https://www.baeldung.com/java-airline) - [Introduction to cache2k](https://www.baeldung.com/java-cache2k) -- [Using NullAway to Avoid NullPointerExceptions](https://www.baeldung.com/java-nullaway) - [Introduction to the jcabi-aspects AOP Annotations Library](https://www.baeldung.com/java-jcabi-aspects) - [Introduction to Takes](https://www.baeldung.com/java-takes) - [Using NullAway to Avoid NullPointerExceptions](https://www.baeldung.com/java-nullaway) diff --git a/libraries-3/src/main/java/com/baeldung/distinct/Person.java b/libraries-3/src/main/java/com/baeldung/distinct/Person.java deleted file mode 100644 index 8a2a5f7a45..0000000000 --- a/libraries-3/src/main/java/com/baeldung/distinct/Person.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.baeldung.distinct; - -public class Person { - int age; - String name; - String email; - - public Person(int age, String name, String email) { - super(); - this.age = age; - this.name = name; - this.email = email; - } - - public int getAge() { - return age; - } - - public String getName() { - return name; - } - - public String getEmail() { - return email; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("Person [age="); - builder.append(age); - builder.append(", name="); - builder.append(name); - builder.append(", email="); - builder.append(email); - builder.append("]"); - return builder.toString(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((email == null) ? 0 : email.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Person other = (Person) obj; - if (email == null) { - if (other.email != null) - return false; - } else if (!email.equals(other.email)) - return false; - return true; - } - -} From 57519b9daebdbb82d6ca96c3f7af87f304c0dbd6 Mon Sep 17 00:00:00 2001 From: Kumar Chandrakant Date: Tue, 28 Apr 2020 09:48:00 +0530 Subject: [PATCH 46/47] Testing multithreading (#9193) --- .../core-java-concurrency-2/README.md | 1 + .../core-java-concurrency-2/pom.xml | 77 +++++++++++++++ .../com/baeldung/concurrent/MyCounter.java | 0 .../concurrent/MyCounterJCStressUnitTest.java | 0 .../MyCounterMultithreadedTCUnitTest.java | 4 +- .../concurrent/MyCounterSimpleUnitTest.java | 7 +- .../MyCounterTempusFugitUnitTest.java | 2 + .../MyCounterThreadWeaverUnitTest.java | 2 + .../core-java-concurrency-testing/README.md | 7 -- .../core-java-concurrency-testing/pom.xml | 93 ------------------- .../src/main/resources/logback.xml | 19 ---- .../src/test/resources/.gitignore | 13 --- 12 files changed, 90 insertions(+), 135 deletions(-) rename core-java-modules/{core-java-concurrency-testing => core-java-concurrency-2}/src/main/java/com/baeldung/concurrent/MyCounter.java (100%) rename core-java-modules/{core-java-concurrency-testing => core-java-concurrency-2}/src/test/java/com/baeldung/concurrent/MyCounterJCStressUnitTest.java (100%) rename core-java-modules/{core-java-concurrency-testing => core-java-concurrency-2}/src/test/java/com/baeldung/concurrent/MyCounterMultithreadedTCUnitTest.java (90%) rename core-java-modules/{core-java-concurrency-testing => core-java-concurrency-2}/src/test/java/com/baeldung/concurrent/MyCounterSimpleUnitTest.java (96%) rename core-java-modules/{core-java-concurrency-testing => core-java-concurrency-2}/src/test/java/com/baeldung/concurrent/MyCounterTempusFugitUnitTest.java (96%) rename core-java-modules/{core-java-concurrency-testing => core-java-concurrency-2}/src/test/java/com/baeldung/concurrent/MyCounterThreadWeaverUnitTest.java (96%) delete mode 100644 core-java-modules/core-java-concurrency-testing/README.md delete mode 100644 core-java-modules/core-java-concurrency-testing/pom.xml delete mode 100644 core-java-modules/core-java-concurrency-testing/src/main/resources/logback.xml delete mode 100644 core-java-modules/core-java-concurrency-testing/src/test/resources/.gitignore diff --git a/core-java-modules/core-java-concurrency-2/README.md b/core-java-modules/core-java-concurrency-2/README.md index 749d174968..ab7eebc26a 100644 --- a/core-java-modules/core-java-concurrency-2/README.md +++ b/core-java-modules/core-java-concurrency-2/README.md @@ -4,4 +4,5 @@ ### Relevant Articles: - [Using a Mutex Object in Java](https://www.baeldung.com/java-mutex) +- [Testing Multi-Threaded Code in Java] (https://www.baeldung.com/java-testing-multithreaded) diff --git a/core-java-modules/core-java-concurrency-2/pom.xml b/core-java-modules/core-java-concurrency-2/pom.xml index a9a01b70f3..dfb5674c8e 100644 --- a/core-java-modules/core-java-concurrency-2/pom.xml +++ b/core-java-modules/core-java-concurrency-2/pom.xml @@ -15,6 +15,38 @@ 0.0.1-SNAPSHOT ../../parent-java + + + + junit + junit + 4.13 + test + + + com.googlecode.thread-weaver + threadweaver + 0.2 + test + + + com.google.code.tempus-fugit + tempus-fugit + 1.1 + test + + + com.googlecode.multithreadedtc + multithreadedtc + 1.01 + test + + + org.openjdk.jcstress + jcstress-core + 0.5 + + core-java-concurrency-2 @@ -24,6 +56,51 @@ true + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + ${javac.target} + ${javac.target} + ${javac.target} + + + + + org.apache.maven.plugins + maven-shade-plugin + 2.2 + + + main + package + + shade + + + jcstress + + + org.openjdk.jcstress.Main + + + META-INF/TestList + + + + + + + + + + 1.8 + diff --git a/core-java-modules/core-java-concurrency-testing/src/main/java/com/baeldung/concurrent/MyCounter.java b/core-java-modules/core-java-concurrency-2/src/main/java/com/baeldung/concurrent/MyCounter.java similarity index 100% rename from core-java-modules/core-java-concurrency-testing/src/main/java/com/baeldung/concurrent/MyCounter.java rename to core-java-modules/core-java-concurrency-2/src/main/java/com/baeldung/concurrent/MyCounter.java diff --git a/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterJCStressUnitTest.java b/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/MyCounterJCStressUnitTest.java similarity index 100% rename from core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterJCStressUnitTest.java rename to core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/MyCounterJCStressUnitTest.java diff --git a/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterMultithreadedTCUnitTest.java b/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/MyCounterMultithreadedTCUnitTest.java similarity index 90% rename from core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterMultithreadedTCUnitTest.java rename to core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/MyCounterMultithreadedTCUnitTest.java index eb4e77cae9..8a0bedf6c2 100644 --- a/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterMultithreadedTCUnitTest.java +++ b/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/MyCounterMultithreadedTCUnitTest.java @@ -1,5 +1,6 @@ package com.baeldung.concurrent; +import org.junit.Ignore; import org.junit.Test; import edu.umd.cs.mtc.MultithreadedTestCase; @@ -25,9 +26,10 @@ public class MyCounterMultithreadedTCUnitTest extends MultithreadedTestCase { @SuppressWarnings("deprecation") @Override public void finish() { - assertEquals(2, counter.getCount()); + assertEquals(2, counter.getCount()); } + @Ignore @Test public void testCounter() throws Throwable { TestFramework.runManyTimes(new MyCounterMultithreadedTCUnitTest(), 1000); diff --git a/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterSimpleUnitTest.java b/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/MyCounterSimpleUnitTest.java similarity index 96% rename from core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterSimpleUnitTest.java rename to core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/MyCounterSimpleUnitTest.java index 4f3409b923..9a405e7e24 100644 --- a/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterSimpleUnitTest.java +++ b/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/MyCounterSimpleUnitTest.java @@ -6,6 +6,7 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import org.junit.Ignore; import org.junit.Test; public class MyCounterSimpleUnitTest { @@ -18,7 +19,8 @@ public class MyCounterSimpleUnitTest { assertEquals(500, counter.getCount()); } - // @Test + @Ignore + @Test public void testCounterWithConcurrency() throws InterruptedException { int numberOfThreads = 100; ExecutorService service = Executors.newFixedThreadPool(10); @@ -34,7 +36,8 @@ public class MyCounterSimpleUnitTest { assertEquals(numberOfThreads, counter.getCount()); } - // @Test + @Ignore + @Test public void testSummationWithConcurrencyAndWait() throws InterruptedException { int numberOfThreads = 2; ExecutorService service = Executors.newFixedThreadPool(10); diff --git a/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterTempusFugitUnitTest.java b/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/MyCounterTempusFugitUnitTest.java similarity index 96% rename from core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterTempusFugitUnitTest.java rename to core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/MyCounterTempusFugitUnitTest.java index 360c61b4f4..36a2031e78 100644 --- a/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterTempusFugitUnitTest.java +++ b/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/MyCounterTempusFugitUnitTest.java @@ -3,6 +3,7 @@ package com.baeldung.concurrent; import static org.junit.Assert.assertEquals; import org.junit.AfterClass; +import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; @@ -20,6 +21,7 @@ public class MyCounterTempusFugitUnitTest { private static MyCounter counter = new MyCounter(); + @Ignore @Test @Concurrent(count = 2) @Repeating(repetition = 10) diff --git a/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterThreadWeaverUnitTest.java b/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/MyCounterThreadWeaverUnitTest.java similarity index 96% rename from core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterThreadWeaverUnitTest.java rename to core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/MyCounterThreadWeaverUnitTest.java index 29b08996cd..e65a963584 100644 --- a/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterThreadWeaverUnitTest.java +++ b/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/MyCounterThreadWeaverUnitTest.java @@ -2,6 +2,7 @@ package com.baeldung.concurrent; import static org.junit.Assert.assertEquals; +import org.junit.Ignore; import org.junit.Test; import com.google.testing.threadtester.AnnotatedTestRunner; @@ -34,6 +35,7 @@ public class MyCounterThreadWeaverUnitTest { assertEquals(2, counter.getCount()); } + @Ignore @Test public void testCounter() { new AnnotatedTestRunner().runTests(this.getClass(), MyCounter.class); diff --git a/core-java-modules/core-java-concurrency-testing/README.md b/core-java-modules/core-java-concurrency-testing/README.md deleted file mode 100644 index fef74a6750..0000000000 --- a/core-java-modules/core-java-concurrency-testing/README.md +++ /dev/null @@ -1,7 +0,0 @@ -========= - -## Core Java Concurrency Testing Examples - -### Relevant Articles: -- [Testing Multi-Threaded Code in Java](https://www.baeldung.com/java-testing-multithreaded) - diff --git a/core-java-modules/core-java-concurrency-testing/pom.xml b/core-java-modules/core-java-concurrency-testing/pom.xml deleted file mode 100644 index 51de83f67c..0000000000 --- a/core-java-modules/core-java-concurrency-testing/pom.xml +++ /dev/null @@ -1,93 +0,0 @@ - - - 4.0.0 - core-java-concurrency-testing - 0.1.0-SNAPSHOT - core-java-concurrency-testing - jar - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java - - - - - junit - junit - 4.13 - test - - - com.googlecode.thread-weaver - threadweaver - 0.2 - test - - - com.google.code.tempus-fugit - tempus-fugit - 1.1 - test - - - com.googlecode.multithreadedtc - multithreadedtc - 1.01 - test - - - org.openjdk.jcstress - jcstress-core - 0.5 - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.1 - - ${javac.target} - ${javac.target} - ${javac.target} - - - - - org.apache.maven.plugins - maven-shade-plugin - 2.2 - - - main - package - - shade - - - jcstress - - - org.openjdk.jcstress.Main - - - META-INF/TestList - - - - - - - - - - diff --git a/core-java-modules/core-java-concurrency-testing/src/main/resources/logback.xml b/core-java-modules/core-java-concurrency-testing/src/main/resources/logback.xml deleted file mode 100644 index 56af2d397e..0000000000 --- a/core-java-modules/core-java-concurrency-testing/src/main/resources/logback.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - - - - - - - \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-testing/src/test/resources/.gitignore b/core-java-modules/core-java-concurrency-testing/src/test/resources/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/core-java-modules/core-java-concurrency-testing/src/test/resources/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file From aec4ed2d5c3939b9c21ff84ff2cd34c0f15f1d54 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Tue, 28 Apr 2020 18:20:23 +0530 Subject: [PATCH 47/47] JAVA-928: Migrate property-exp-default-config to parent-boot-2 --- .../property-exp-custom-config/pom.xml | 8 +++++++- .../java/{org => com}/baeldung/SpringContextTest.java | 0 .../property-exp-default-config/pom.xml | 4 ++-- .../java/{org => com}/baeldung/SpringContextTest.java | 0 4 files changed, 9 insertions(+), 3 deletions(-) rename spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/src/test/java/{org => com}/baeldung/SpringContextTest.java (100%) rename spring-boot-modules/spring-boot-property-exp/property-exp-default-config/src/test/java/{org => com}/baeldung/SpringContextTest.java (100%) diff --git a/spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/pom.xml b/spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/pom.xml index 8ea9c8366d..e38a2742d5 100644 --- a/spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/pom.xml +++ b/spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/pom.xml @@ -24,6 +24,12 @@ spring-boot-starter-test ${spring-boot.version} test + + + org.junit.vintage + junit-vintage-engine + + @@ -72,7 +78,7 @@ - 1.5.10.RELEASE + 2.2.6.RELEASE Custom Property Value 2.7 1.6.0 diff --git a/spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/src/test/java/com/baeldung/SpringContextTest.java similarity index 100% rename from spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/src/test/java/org/baeldung/SpringContextTest.java rename to spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/src/test/java/com/baeldung/SpringContextTest.java diff --git a/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/pom.xml b/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/pom.xml index aa5b8ef34a..79e194a3b5 100644 --- a/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/pom.xml +++ b/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../../parent-boot-1 + ../../../parent-boot-2 diff --git a/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/src/test/java/com/baeldung/SpringContextTest.java similarity index 100% rename from spring-boot-modules/spring-boot-property-exp/property-exp-default-config/src/test/java/org/baeldung/SpringContextTest.java rename to spring-boot-modules/spring-boot-property-exp/property-exp-default-config/src/test/java/com/baeldung/SpringContextTest.java