From ecfb5a2b944a847432b9d53e507a088a3486aabc Mon Sep 17 00:00:00 2001 From: eelhazati Date: Mon, 15 Jul 2019 10:25:50 +0100 Subject: [PATCH 01/84] add module to the main pom, in the profiles default-first and integration-lite-first. --- pom.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 35a7b95095..f9ee6e74c2 100644 --- a/pom.xml +++ b/pom.xml @@ -559,7 +559,7 @@ spring-boot-flowable spring-security-kerberos morphia - + oauth2-framework-impl @@ -1236,6 +1236,7 @@ rsocket rxjava rxjava-2 + oauth2-framework-impl From aba05a929c0d5084d88bf192f15055ac34127825 Mon Sep 17 00:00:00 2001 From: eelhazati Date: Mon, 15 Jul 2019 10:32:04 +0100 Subject: [PATCH 02/84] Replace the 'approbation' term with 'approval'. --- .../authorization/server/api/AuthorizationEndpoint.java | 4 ++-- .../oauth2-authorization-server/src/main/webapp/authorize.jsp | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/AuthorizationEndpoint.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/AuthorizationEndpoint.java index 10e78a2dfd..ba5e1ec359 100644 --- a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/AuthorizationEndpoint.java +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/AuthorizationEndpoint.java @@ -121,8 +121,8 @@ public class AuthorizationEndpoint { String redirectUri = originalParams.getFirst("resolved_redirect_uri"); StringBuilder sb = new StringBuilder(redirectUri); - String approbationStatus = params.getFirst("approbation_status"); - if ("NO".equals(approbationStatus)) { + String approvalStatus = params.getFirst("approval_status"); + if ("NO".equals(approvalStatus)) { URI location = UriBuilder.fromUri(sb.toString()) .queryParam("error", "User doesn't approved the request.") .queryParam("error_description", "User doesn't approved the request.") diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/authorize.jsp b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/authorize.jsp index 1004b5b8b7..41b0582c03 100644 --- a/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/authorize.jsp +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/authorize.jsp @@ -41,8 +41,8 @@ - - + + From ee6012a4decab36c07f4e16bd2e981c559faa528 Mon Sep 17 00:00:00 2001 From: Krzysztof Majewski Date: Wed, 17 Jul 2019 16:34:38 +0200 Subject: [PATCH 03/84] BAEL-2825 --- .../main/java/com/baeldung/jpa/entity/Article.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Article.java diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Article.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Article.java new file mode 100644 index 0000000000..02082c3d92 --- /dev/null +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Article.java @@ -0,0 +1,12 @@ +package com.baeldung.jpa.entity; + +import javax.persistence.Entity; +import javax.persistence.Table; + +@Entity(name = "MyArticle") +@Table(name = Article.TABLE_NAME) +public class Article { + + public static final String TABLE_NAME = "ARTICLES"; + +} From 82f1efaabe55577d9f1df64851213a16e346df9d Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Thu, 18 Jul 2019 18:50:31 +0300 Subject: [PATCH 04/84] Update pom.xml --- pom.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/pom.xml b/pom.xml index e04d9f7bba..9be2971be4 100644 --- a/pom.xml +++ b/pom.xml @@ -556,7 +556,6 @@ tensorflow-java spring-boot-flowable spring-security-kerberos - morphia oauth2-framework-impl From 9978d337fcededcc0fa6e51ba4819dcccde25e8f Mon Sep 17 00:00:00 2001 From: Loredana Date: Sat, 20 Jul 2019 12:09:38 +0300 Subject: [PATCH 05/84] fix envers test --- .../src/main/java/com/baeldung/spring/PersistenceConfig.java | 2 +- .../persistence/audit/EnversFooBarAuditIntegrationTest.java | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceConfig.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceConfig.java index 35e80b81a5..b7cf0fadf2 100644 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceConfig.java +++ b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceConfig.java @@ -47,7 +47,7 @@ import com.google.common.base.Preconditions; @EnableTransactionManagement @EnableJpaRepositories(basePackages = { "com.baeldung.persistence" }, transactionManagerRef = "jpaTransactionManager") @EnableJpaAuditing -@PropertySource({ "classpath:persistence-mysql.properties" }) +@PropertySource({ "classpath:persistence-h2.properties" }) @ComponentScan({ "com.baeldung.persistence" }) public class PersistenceConfig { diff --git a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java b/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java index 2f23a9a532..0530c2a70f 100644 --- a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java +++ b/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java @@ -2,6 +2,7 @@ package com.baeldung.persistence.audit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import java.util.List; @@ -17,6 +18,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @@ -29,6 +31,7 @@ import com.baeldung.spring.config.PersistenceTestConfig; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) +@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) public class EnversFooBarAuditIntegrationTest { private static Logger logger = LoggerFactory.getLogger(EnversFooBarAuditIntegrationTest.class); @@ -118,7 +121,7 @@ public class EnversFooBarAuditIntegrationTest { barRevisionList = barService.getRevisions(); assertNotNull(barRevisionList); - assertEquals(4, barRevisionList.size()); + assertTrue(barRevisionList.size()>=4); assertEquals("BAR", barRevisionList.get(0).getName()); assertEquals("BAR", barRevisionList.get(1).getName()); From 98c537f20f49a720909ca44ea055a64cc44e9050 Mon Sep 17 00:00:00 2001 From: Loredana Date: Sat, 20 Jul 2019 12:11:16 +0300 Subject: [PATCH 06/84] update links --- persistence-modules/spring-data-jpa/README.md | 1 - persistence-modules/spring-hibernate4/README.md | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/spring-data-jpa/README.md b/persistence-modules/spring-data-jpa/README.md index e85d8a8487..4b4a590e10 100644 --- a/persistence-modules/spring-data-jpa/README.md +++ b/persistence-modules/spring-data-jpa/README.md @@ -10,7 +10,6 @@ - [Spring Data Java 8 Support](http://www.baeldung.com/spring-data-java-8) - [A Simple Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging) - [Spring Data Composable Repositories](https://www.baeldung.com/spring-data-composable-repositories) -- [Auditing with JPA, Hibernate, and Spring Data JPA](https://www.baeldung.com/database-auditing-jpa) - [Query Entities by Dates and Times with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-query-by-date) - [DDD Aggregates and @DomainEvents](https://www.baeldung.com/spring-data-ddd) - [Spring Data – CrudRepository save() Method](https://www.baeldung.com/spring-data-crud-repository-save) diff --git a/persistence-modules/spring-hibernate4/README.md b/persistence-modules/spring-hibernate4/README.md index 426944c149..020e867c82 100644 --- a/persistence-modules/spring-hibernate4/README.md +++ b/persistence-modules/spring-hibernate4/README.md @@ -10,6 +10,7 @@ - [Hibernate: save, persist, update, merge, saveOrUpdate](http://www.baeldung.com/hibernate-save-persist-update-merge-saveorupdate) - [Eager/Lazy Loading In Hibernate](http://www.baeldung.com/hibernate-lazy-eager-loading) - [The DAO with Spring and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate) +- [Auditing with JPA, Hibernate, and Spring Data JPA](https://www.baeldung.com/database-auditing-jpa) ### Quick Start From c10619ea207c50d8ac638622a7ad50cedc20873f Mon Sep 17 00:00:00 2001 From: Loredana Date: Sat, 20 Jul 2019 12:13:01 +0300 Subject: [PATCH 07/84] update test --- .../persistence/audit/EnversFooBarAuditIntegrationTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java b/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java index 0530c2a70f..444324dafc 100644 --- a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java +++ b/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java @@ -121,7 +121,7 @@ public class EnversFooBarAuditIntegrationTest { barRevisionList = barService.getRevisions(); assertNotNull(barRevisionList); - assertTrue(barRevisionList.size()>=4); + assertEquals(4, barRevisionList.size()); assertEquals("BAR", barRevisionList.get(0).getName()); assertEquals("BAR", barRevisionList.get(1).getName()); From e81753727d534f8121de19a9008d1c11cebeb90d Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 21 Jul 2019 00:57:41 +0530 Subject: [PATCH 08/84] [BAEL-15959] - Moved article to spring-security-core --- spring-5-mvc/README.md | 1 - .../java/com/baeldung/Spring5Application.java | 32 ------------------- spring-5-mvc/src/main/webapp/WEB-INF/web.xml | 9 ------ spring-security-core/README.md | 1 + .../src/main/java/org/baeldung/app/App.java | 32 +++++++++++++++++++ .../org/baeldung}/filter/CustomFilter.java | 2 +- .../src/main/webapp/WEB-INF/web.xml | 17 ++++++++++ 7 files changed, 51 insertions(+), 43 deletions(-) rename {spring-5-mvc/src/main/java/com/baeldung/spring => spring-security-core/src/main/java/org/baeldung}/filter/CustomFilter.java (96%) create mode 100644 spring-security-core/src/main/webapp/WEB-INF/web.xml diff --git a/spring-5-mvc/README.md b/spring-5-mvc/README.md index 7e83077f54..063945281f 100644 --- a/spring-5-mvc/README.md +++ b/spring-5-mvc/README.md @@ -1,4 +1,3 @@ ### Relevant Articles: - [Spring Boot and Kotlin](http://www.baeldung.com/spring-boot-kotlin) - [Spring MVC Streaming and SSE Request Processing](https://www.baeldung.com/spring-mvc-sse-streams) -- [Overview and Need for DelegatingFilterProxy in Spring](https://www.baeldung.com/spring-delegating-filter-proxy) diff --git a/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java b/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java index 74a348dea6..38b2d943f8 100644 --- a/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java +++ b/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java @@ -1,12 +1,8 @@ package com.baeldung; -import javax.servlet.Filter; - import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; -import org.springframework.web.filter.DelegatingFilterProxy; -import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; @SpringBootApplication( exclude = SecurityAutoConfiguration.class) public class Spring5Application { @@ -14,32 +10,4 @@ public class Spring5Application { public static void main(String[] args) { SpringApplication.run(Spring5Application.class, args); } - - public static class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { - - @Override - protected Class[] getRootConfigClasses() { - return null; - } - - @Override - protected Class[] getServletConfigClasses() { - // TODO Auto-generated method stub - return null; - } - - @Override - protected String[] getServletMappings() { - // TODO Auto-generated method stub - return null; - } - - @Override - protected javax.servlet.Filter[] getServletFilters() { - DelegatingFilterProxy delegateFilterProxy = new DelegatingFilterProxy(); - delegateFilterProxy.setTargetBeanName("loggingFilter"); - return new Filter[] { delegateFilterProxy }; - } - } - } diff --git a/spring-5-mvc/src/main/webapp/WEB-INF/web.xml b/spring-5-mvc/src/main/webapp/WEB-INF/web.xml index 43c7143e5b..ab4d38ce1c 100644 --- a/spring-5-mvc/src/main/webapp/WEB-INF/web.xml +++ b/spring-5-mvc/src/main/webapp/WEB-INF/web.xml @@ -16,14 +16,5 @@ functional / - - loggingFilter - org.springframework.web.filter.DelegatingFilterProxy - - - - loggingFilter - /* - \ No newline at end of file diff --git a/spring-security-core/README.md b/spring-security-core/README.md index b38dc061b4..bc9a8afed7 100644 --- a/spring-security-core/README.md +++ b/spring-security-core/README.md @@ -10,3 +10,4 @@ mvn clean install - [Spring Security – @PreFilter and @PostFilter](http://www.baeldung.com/spring-security-prefilter-postfilter) - [Spring Boot Authentication Auditing Support](http://www.baeldung.com/spring-boot-authentication-audit) - [Introduction to Spring Method Security](http://www.baeldung.com/spring-security-method-security) +- [Overview and Need for DelegatingFilterProxy in Spring](https://www.baeldung.com/spring-delegating-filter-proxy) \ No newline at end of file diff --git a/spring-security-core/src/main/java/org/baeldung/app/App.java b/spring-security-core/src/main/java/org/baeldung/app/App.java index 37d8c34c5a..db0c9135c4 100644 --- a/spring-security-core/src/main/java/org/baeldung/app/App.java +++ b/spring-security-core/src/main/java/org/baeldung/app/App.java @@ -1,11 +1,15 @@ package org.baeldung.app; +import javax.servlet.Filter; + import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.context.annotation.ComponentScan; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.web.filter.DelegatingFilterProxy; +import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; @SpringBootApplication @EnableJpaRepositories("org.baeldung.repository") @@ -15,4 +19,32 @@ public class App extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(App.class, args); } + + public static class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { + + @Override + protected javax.servlet.Filter[] getServletFilters() { + DelegatingFilterProxy delegateFilterProxy = new DelegatingFilterProxy(); + delegateFilterProxy.setTargetBeanName("loggingFilter"); + return new Filter[] { delegateFilterProxy }; + } + + @Override + protected Class[] getRootConfigClasses() { + // TODO Auto-generated method stub + return null; + } + + @Override + protected Class[] getServletConfigClasses() { + // TODO Auto-generated method stub + return null; + } + + @Override + protected String[] getServletMappings() { + // TODO Auto-generated method stub + return null; + } + } } diff --git a/spring-5-mvc/src/main/java/com/baeldung/spring/filter/CustomFilter.java b/spring-security-core/src/main/java/org/baeldung/filter/CustomFilter.java similarity index 96% rename from spring-5-mvc/src/main/java/com/baeldung/spring/filter/CustomFilter.java rename to spring-security-core/src/main/java/org/baeldung/filter/CustomFilter.java index 4aa33cd749..35596eae16 100644 --- a/spring-5-mvc/src/main/java/com/baeldung/spring/filter/CustomFilter.java +++ b/spring-security-core/src/main/java/org/baeldung/filter/CustomFilter.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.filter; +package org.baeldung.filter; import java.io.IOException; diff --git a/spring-security-core/src/main/webapp/WEB-INF/web.xml b/spring-security-core/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..e4954338a9 --- /dev/null +++ b/spring-security-core/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,17 @@ + + + + + loggingFilter + org.springframework.web.filter.DelegatingFilterProxy + + + + loggingFilter + /* + + + \ No newline at end of file From 9fe7b80348854fe6011bb8cffa4c323689d5520e Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 15:54:32 +0800 Subject: [PATCH 09/84] Update README.md --- spring-5-reactive-client/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/spring-5-reactive-client/README.md b/spring-5-reactive-client/README.md index f94bd0b0c1..f03ed7237d 100644 --- a/spring-5-reactive-client/README.md +++ b/spring-5-reactive-client/README.md @@ -4,3 +4,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles + +- [Spring Security 5 for Reactive Applications](https://www.baeldung.com/spring-security-5-reactive) From e4f1ddd488a420dc16d6b9f2a844cabd67509822 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 15:56:00 +0800 Subject: [PATCH 10/84] Update README.md --- spring-groovy/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/spring-groovy/README.md b/spring-groovy/README.md index ff12555376..2aab1b2e18 100644 --- a/spring-groovy/README.md +++ b/spring-groovy/README.md @@ -1 +1,3 @@ ## Relevant articles: + +- [Groovy Bean Definitions](https://www.baeldung.com/spring-groovy-beans) From 01b8b344116403d4b1c9370d32b22afca6612177 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 15:57:07 +0800 Subject: [PATCH 11/84] Delete README.md --- resteasy/bin/README.md | 6 ------ 1 file changed, 6 deletions(-) delete mode 100644 resteasy/bin/README.md diff --git a/resteasy/bin/README.md b/resteasy/bin/README.md deleted file mode 100644 index f4dba1493a..0000000000 --- a/resteasy/bin/README.md +++ /dev/null @@ -1,6 +0,0 @@ -========= - -## A Guide to RESTEasy - - -### Relevant Articles: From 1d4c353cf646b7fcb8bd86187c6f6cb8d5094f5d Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:00:24 +0800 Subject: [PATCH 12/84] Create README.md --- core-java-modules/multimodulemavenproject/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 core-java-modules/multimodulemavenproject/README.md diff --git a/core-java-modules/multimodulemavenproject/README.md b/core-java-modules/multimodulemavenproject/README.md new file mode 100644 index 0000000000..fc4ca60b6b --- /dev/null +++ b/core-java-modules/multimodulemavenproject/README.md @@ -0,0 +1,3 @@ +## Relevant Articles + +- [Multi-Module Maven Application with Java Modules](https://www.baeldung.com/maven-multi-module-project-java-jpms) From 6780457b188610101a609386a4142d3539fd3b74 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:01:53 +0800 Subject: [PATCH 13/84] Create README.md --- spring-security-cors/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 spring-security-cors/README.md diff --git a/spring-security-cors/README.md b/spring-security-cors/README.md new file mode 100644 index 0000000000..2ab5e33ee3 --- /dev/null +++ b/spring-security-cors/README.md @@ -0,0 +1,3 @@ +## Relevant Articles + +- [Fixing 401s with CORS Preflights and Spring Security](https://www.baeldung.com/spring-security-cors-preflight) From 2f04bde63ec5cb901fbe655145f2937ce34e0312 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:03:46 +0800 Subject: [PATCH 14/84] Create README.md --- testing-modules/load-testing-comparison/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 testing-modules/load-testing-comparison/README.md diff --git a/testing-modules/load-testing-comparison/README.md b/testing-modules/load-testing-comparison/README.md new file mode 100644 index 0000000000..bad22e7a49 --- /dev/null +++ b/testing-modules/load-testing-comparison/README.md @@ -0,0 +1,3 @@ +## Relevant Articles + +-[Gatling vs JMeter vs The Grinder: Comparing Load Test Tools](https://www.baeldung.com/gatling-jmeter-grinder-comparison) From f76d67c2489b4db663fce54012c3ca03bcba1714 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:04:00 +0800 Subject: [PATCH 15/84] Update README.md --- testing-modules/load-testing-comparison/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing-modules/load-testing-comparison/README.md b/testing-modules/load-testing-comparison/README.md index bad22e7a49..9823be5369 100644 --- a/testing-modules/load-testing-comparison/README.md +++ b/testing-modules/load-testing-comparison/README.md @@ -1,3 +1,3 @@ ## Relevant Articles --[Gatling vs JMeter vs The Grinder: Comparing Load Test Tools](https://www.baeldung.com/gatling-jmeter-grinder-comparison) +- [Gatling vs JMeter vs The Grinder: Comparing Load Test Tools](https://www.baeldung.com/gatling-jmeter-grinder-comparison) From f574a14badd7cd577a3775e6125a080b6871be36 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:05:12 +0800 Subject: [PATCH 16/84] Create README.md --- testing-modules/parallel-tests-junit/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 testing-modules/parallel-tests-junit/README.md diff --git a/testing-modules/parallel-tests-junit/README.md b/testing-modules/parallel-tests-junit/README.md new file mode 100644 index 0000000000..0b7834c5e7 --- /dev/null +++ b/testing-modules/parallel-tests-junit/README.md @@ -0,0 +1,3 @@ +## Relevant Articles + +- [Running JUnit Tests in Parallel with Maven](https://www.baeldung.com/maven-junit-parallel-tests) From 8b39d2ab37aa6318992a9cff0758529c2a212a10 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:09:53 +0800 Subject: [PATCH 17/84] Create README.md --- jhipster/jhipster-uaa/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 jhipster/jhipster-uaa/README.md diff --git a/jhipster/jhipster-uaa/README.md b/jhipster/jhipster-uaa/README.md new file mode 100644 index 0000000000..3971e3c8c6 --- /dev/null +++ b/jhipster/jhipster-uaa/README.md @@ -0,0 +1,3 @@ +## Relevant Articles + +- [Building a Basic UAA-Secured JHipster Microservice](https://www.baeldung.com/jhipster-uaa-secured-micro-service) From 196289923e97200f10974d5c0b8ab31f219207b0 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:11:32 +0800 Subject: [PATCH 18/84] Update README.md --- jhipster/jhipster-monolithic/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/jhipster/jhipster-monolithic/README.md b/jhipster/jhipster-monolithic/README.md index a2c267b74d..3a44f3f120 100644 --- a/jhipster/jhipster-monolithic/README.md +++ b/jhipster/jhipster-monolithic/README.md @@ -1,5 +1,7 @@ ### Relevant articles +- [Intro to JHipster](https://www.baeldung.com/jhipster) + # baeldung This application was generated using JHipster 4.0.8, you can find documentation and help at [https://jhipster.github.io/documentation-archive/v4.0.8](https://jhipster.github.io/documentation-archive/v4.0.8). From db63ca45ca61c89fe097c98ac4f9cebd1d5a1428 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:11:46 +0800 Subject: [PATCH 19/84] Update README.md --- jhipster/jhipster-monolithic/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jhipster/jhipster-monolithic/README.md b/jhipster/jhipster-monolithic/README.md index 3a44f3f120..15c55118ee 100644 --- a/jhipster/jhipster-monolithic/README.md +++ b/jhipster/jhipster-monolithic/README.md @@ -1,4 +1,4 @@ -### Relevant articles +### Relevant Articles - [Intro to JHipster](https://www.baeldung.com/jhipster) From 51cd7667a59760cdfb5bc144d585a5f552bc63df Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:12:02 +0800 Subject: [PATCH 20/84] Update README.md --- jhipster/jhipster-monolithic/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jhipster/jhipster-monolithic/README.md b/jhipster/jhipster-monolithic/README.md index 15c55118ee..65cc51ad88 100644 --- a/jhipster/jhipster-monolithic/README.md +++ b/jhipster/jhipster-monolithic/README.md @@ -1,4 +1,4 @@ -### Relevant Articles +## Relevant Articles - [Intro to JHipster](https://www.baeldung.com/jhipster) From f9b26474ce4f84cacba083e0ed77136b26e75ea4 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:13:15 +0800 Subject: [PATCH 21/84] Create README.md --- jhipster/jhipster-microservice/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 jhipster/jhipster-microservice/README.md diff --git a/jhipster/jhipster-microservice/README.md b/jhipster/jhipster-microservice/README.md new file mode 100644 index 0000000000..7abe3204c4 --- /dev/null +++ b/jhipster/jhipster-microservice/README.md @@ -0,0 +1,3 @@ +## Relevant Articles + +- [JHipster with a Microservice Architecture](https://www.baeldung.com/jhipster-microservices) From c8ea0b65a90b5f30b4e8d78627d263150574a5e3 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:17:57 +0800 Subject: [PATCH 22/84] Update README.md --- quarkus/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/quarkus/README.md b/quarkus/README.md index 8116d16cb7..3ff08c6f9e 100644 --- a/quarkus/README.md +++ b/quarkus/README.md @@ -1,3 +1,3 @@ -## Relevant articles: +## Relevant Articles: - [Guide to QuarkusIO](https://www.baeldung.com/quarkus-io) From dc65ed87f68de3614a087b4aaa92cebd2835517c Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:20:20 +0800 Subject: [PATCH 23/84] Update README.md --- spring-groovy/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-groovy/README.md b/spring-groovy/README.md index 2aab1b2e18..36404230a9 100644 --- a/spring-groovy/README.md +++ b/spring-groovy/README.md @@ -1,3 +1,3 @@ -## Relevant articles: +## Relevant Articles: - [Groovy Bean Definitions](https://www.baeldung.com/spring-groovy-beans) From 0fa09cf5ae0ff47d566f6aee6172149311d3419f Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:22:09 +0800 Subject: [PATCH 24/84] Update README.md --- core-java-modules/core-java-exceptions/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-exceptions/README.md b/core-java-modules/core-java-exceptions/README.md index 5338789a2f..79e5bad23a 100644 --- a/core-java-modules/core-java-exceptions/README.md +++ b/core-java-modules/core-java-exceptions/README.md @@ -1,3 +1,3 @@ -## Relevant articles: +## Relevant Articles: - [Will an Error Be Caught by Catch Block in Java?](https://www.baeldung.com/java-error-catch) From 9bdd157a48c3565f59e1dce0e75ef83fdea499ed Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:22:48 +0800 Subject: [PATCH 25/84] Update README.md --- core-java-modules/core-java-exceptions/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-exceptions/README.md b/core-java-modules/core-java-exceptions/README.md index 79e5bad23a..4fda36bb44 100644 --- a/core-java-modules/core-java-exceptions/README.md +++ b/core-java-modules/core-java-exceptions/README.md @@ -1,3 +1,3 @@ ## Relevant Articles: -- [Will an Error Be Caught by Catch Block in Java?](https://www.baeldung.com/java-error-catch) + From f66288d9b53e4b33f195652ee48073d6aef1339e Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:23:10 +0800 Subject: [PATCH 26/84] Update README.md --- core-java-modules/core-java-12/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core-java-modules/core-java-12/README.md b/core-java-modules/core-java-12/README.md index 4514fd1a2b..4fda36bb44 100644 --- a/core-java-modules/core-java-12/README.md +++ b/core-java-modules/core-java-12/README.md @@ -1,3 +1,3 @@ -## Relevant articles: +## Relevant Articles: + -- [String API Updates in Java 12](https://www.baeldung.com/java12-string-api) From 340f9656659cea31151b439aba7267b2d5f65c14 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:24:41 +0800 Subject: [PATCH 27/84] Update README.md --- parent-java/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/parent-java/README.md b/parent-java/README.md index ff12555376..729105e3fd 100644 --- a/parent-java/README.md +++ b/parent-java/README.md @@ -1 +1 @@ -## Relevant articles: +## Relevant Articles: From a672639976e1dc5ff815fad63f2cd227216c175a Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:26:13 +0800 Subject: [PATCH 28/84] Update README.md --- video-tutorials/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/video-tutorials/README.md b/video-tutorials/README.md index ff12555376..729105e3fd 100644 --- a/video-tutorials/README.md +++ b/video-tutorials/README.md @@ -1 +1 @@ -## Relevant articles: +## Relevant Articles: From 21c12dcef58a0eb21339af283218d046825feda1 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:26:37 +0800 Subject: [PATCH 29/84] Update README.md --- parent-spring-4/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/parent-spring-4/README.md b/parent-spring-4/README.md index ff12555376..729105e3fd 100644 --- a/parent-spring-4/README.md +++ b/parent-spring-4/README.md @@ -1 +1 @@ -## Relevant articles: +## Relevant Articles: From 474aa7a5eef9d696037443ca152512e8677931cb Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:26:53 +0800 Subject: [PATCH 30/84] Update README.md --- parent-spring-5/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/parent-spring-5/README.md b/parent-spring-5/README.md index ff12555376..729105e3fd 100644 --- a/parent-spring-5/README.md +++ b/parent-spring-5/README.md @@ -1 +1 @@ -## Relevant articles: +## Relevant Articles: From ca10190f5b3174a22ff2dec43a21225c9fa85ce9 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 21 Jul 2019 11:46:51 +0300 Subject: [PATCH 31/84] Update README.md --- core-java-modules/core-java-12/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-12/README.md b/core-java-modules/core-java-12/README.md index 4fda36bb44..6c603e4dea 100644 --- a/core-java-modules/core-java-12/README.md +++ b/core-java-modules/core-java-12/README.md @@ -1,3 +1,4 @@ ## Relevant Articles: +- [String API Updates in Java 12](https://www.baeldung.com/java12-string-api) From 006bb85ca23661a5ef718be368bc8bc7b925b0a8 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 21 Jul 2019 11:47:08 +0300 Subject: [PATCH 32/84] Update README.md --- core-java-modules/core-java-exceptions/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-exceptions/README.md b/core-java-modules/core-java-exceptions/README.md index 4fda36bb44..79e5bad23a 100644 --- a/core-java-modules/core-java-exceptions/README.md +++ b/core-java-modules/core-java-exceptions/README.md @@ -1,3 +1,3 @@ ## Relevant Articles: - +- [Will an Error Be Caught by Catch Block in Java?](https://www.baeldung.com/java-error-catch) From 11836c0626b6a795e790aad88666523b4c8c15dd Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 21 Jul 2019 11:47:24 +0300 Subject: [PATCH 33/84] Update README.md --- spring-5-reactive-client/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-5-reactive-client/README.md b/spring-5-reactive-client/README.md index f03ed7237d..0df2bdd339 100644 --- a/spring-5-reactive-client/README.md +++ b/spring-5-reactive-client/README.md @@ -5,4 +5,3 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles -- [Spring Security 5 for Reactive Applications](https://www.baeldung.com/spring-security-5-reactive) From f5142320bf4809d6dabe6c03fc3108286fd7228e Mon Sep 17 00:00:00 2001 From: priyank-sriv Date: Mon, 22 Jul 2019 00:54:49 +0530 Subject: [PATCH 34/84] first commit - basic test --- patterns/backoff-jitter/pom.xml | 61 ++++++++++++++ .../backoff/jitter/BackoffWithJitterTest.java | 81 +++++++++++++++++++ patterns/pom.xml | 3 +- 3 files changed, 144 insertions(+), 1 deletion(-) create mode 100644 patterns/backoff-jitter/pom.xml create mode 100644 patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java diff --git a/patterns/backoff-jitter/pom.xml b/patterns/backoff-jitter/pom.xml new file mode 100644 index 0000000000..0a48a18abb --- /dev/null +++ b/patterns/backoff-jitter/pom.xml @@ -0,0 +1,61 @@ + + + 4.0.0 + com.baeldung + backoff-jitter + 1.0.0-SNAPSHOT + pom + + + + + + + + + + + junit + junit + ${junit.version} + test + + + org.mockito + mockito-core + ${mockito-core.version} + test + + + io.github.resilience4j + resilience4j-retry + ${resilience4j.version} + test + + + org.slf4j + slf4j-api + ${slf4j.version} + test + + + org.slf4j + slf4j-simple + ${slf4j.version} + test + + + + + UTF-8 + 1.8 + 1.8 + 4.12 + 2.27.0 + 1.7.26 + 0.16.0 + + + \ No newline at end of file diff --git a/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java b/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java new file mode 100644 index 0000000000..aef9f7fab7 --- /dev/null +++ b/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java @@ -0,0 +1,81 @@ +package com.baeldung.backoff.jitter; + +import io.github.resilience4j.retry.IntervalFunction; +import io.github.resilience4j.retry.Retry; +import io.github.resilience4j.retry.RetryConfig; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.function.Function; + +import static com.baeldung.backoff.jitter.BackoffWithJitterTest.RetryProperties.*; +import static io.github.resilience4j.retry.IntervalFunction.ofExponentialBackoff; +import static io.github.resilience4j.retry.IntervalFunction.ofExponentialRandomBackoff; +import static java.util.Collections.nCopies; +import static java.util.concurrent.Executors.newFixedThreadPool; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.*; + +public class BackoffWithJitterTest { + + static Logger log = LoggerFactory.getLogger(BackoffWithJitterTest.class); + + interface PingPongService { + + String call(String ping) throws PingPongServiceException; + } + + class PingPongServiceException extends RuntimeException { + + public PingPongServiceException(String reason) { + super(reason); + } + } + + private PingPongService service; + private static final int NUM_TASKS = 8; + + @Before + public void setUp() { + service = mock(PingPongService.class); + } + + @Test + public void whenRetryExponentialBackoff_thenRetriedConfiguredNoOfTimes() { + IntervalFunction intervalFn = ofExponentialBackoff(INITIAL_INTERVAL, MULTIPLIER); + Function pingPongFn = getRetryablePingPongFn(intervalFn); + + when(service.call(anyString())).thenThrow(PingPongServiceException.class); + try { + pingPongFn.apply("Hello"); + } catch (PingPongServiceException e) { + verify(service, times(MAX_TRIES)).call(anyString()); + } + } + + private Function getRetryablePingPongFn(IntervalFunction intervalFn) { + RetryConfig retryConfig = RetryConfig.custom() + .maxAttempts(MAX_TRIES) + .intervalFunction(intervalFn) + .retryExceptions(PingPongServiceException.class) + .build(); + Retry retry = Retry.of("pingpong", retryConfig); + return Retry.decorateFunction(retry, ping -> { + log.info("Invoked at {}", LocalDateTime.now()); + return service.call(ping); + }); + } + + static class RetryProperties { + static final Long INITIAL_INTERVAL = 1000L; + static final Double MULTIPLIER = 2.0D; + static final Double RANDOMIZATION_FACTOR = 0.6D; + static final Integer MAX_TRIES = 4; + } +} diff --git a/patterns/pom.xml b/patterns/pom.xml index 2be9d2519e..7f7368ca07 100644 --- a/patterns/pom.xml +++ b/patterns/pom.xml @@ -19,7 +19,8 @@ design-patterns design-patterns-2 solid - dip + dip + backoff-jitter From 412e8b7634df712ad966d4ddce22f3ecc76d488b Mon Sep 17 00:00:00 2001 From: priyank-sriv Date: Mon, 22 Jul 2019 00:55:25 +0530 Subject: [PATCH 35/84] simple exponential backoff --- .../backoff/jitter/BackoffWithJitterTest.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java b/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java index aef9f7fab7..966207f430 100644 --- a/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java +++ b/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java @@ -59,6 +59,22 @@ public class BackoffWithJitterTest { } } + @Test + public void whenRetryExponentialBackoffWithoutJitter_thenThunderingHerdProblemOccurs() throws InterruptedException { + IntervalFunction intervalFn = ofExponentialBackoff(INITIAL_INTERVAL, MULTIPLIER); + test(intervalFn); + } + + private void test(IntervalFunction intervalFn) throws InterruptedException { + Function pingPongFn = getRetryablePingPongFn(intervalFn); + ExecutorService executors = newFixedThreadPool(NUM_TASKS); + List> tasks = nCopies(NUM_TASKS, () -> pingPongFn.apply("Hello")); + + when(service.call(anyString())).thenThrow(PingPongServiceException.class); + + executors.invokeAll(tasks); + } + private Function getRetryablePingPongFn(IntervalFunction intervalFn) { RetryConfig retryConfig = RetryConfig.custom() .maxAttempts(MAX_TRIES) From ae1807fca2a9170abd547f6caf22017974aa3ac7 Mon Sep 17 00:00:00 2001 From: priyank-sriv Date: Mon, 22 Jul 2019 00:55:41 +0530 Subject: [PATCH 36/84] backoff with jitter --- .../com/baeldung/backoff/jitter/BackoffWithJitterTest.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java b/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java index 966207f430..0f0e652596 100644 --- a/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java +++ b/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java @@ -65,6 +65,12 @@ public class BackoffWithJitterTest { test(intervalFn); } + @Test + public void whenRetryExponentialBackoffWithJitter_thenRetriesAreSpread() throws InterruptedException { + IntervalFunction intervalFn = ofExponentialRandomBackoff(INITIAL_INTERVAL, MULTIPLIER, RANDOMIZATION_FACTOR); + test(intervalFn); + } + private void test(IntervalFunction intervalFn) throws InterruptedException { Function pingPongFn = getRetryablePingPongFn(intervalFn); ExecutorService executors = newFixedThreadPool(NUM_TASKS); From cb686cf9c4f1587d729e66668ec9387631b4a1f9 Mon Sep 17 00:00:00 2001 From: priyank-sriv Date: Tue, 23 Jul 2019 01:52:22 +0530 Subject: [PATCH 37/84] minor modifications --- patterns/backoff-jitter/README.md | 2 ++ patterns/backoff-jitter/pom.xml | 7 ------- .../backoff/jitter/BackoffWithJitterTest.java | 12 ++++++------ 3 files changed, 8 insertions(+), 13 deletions(-) create mode 100644 patterns/backoff-jitter/README.md diff --git a/patterns/backoff-jitter/README.md b/patterns/backoff-jitter/README.md new file mode 100644 index 0000000000..6459e4c8e0 --- /dev/null +++ b/patterns/backoff-jitter/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Better Retries with Exponential Backoff and Jitter](https://baeldung.com/retries-with-exponential-backoff-and-jitter) diff --git a/patterns/backoff-jitter/pom.xml b/patterns/backoff-jitter/pom.xml index 0a48a18abb..6b0d016609 100644 --- a/patterns/backoff-jitter/pom.xml +++ b/patterns/backoff-jitter/pom.xml @@ -8,13 +8,6 @@ 1.0.0-SNAPSHOT pom - - - - - - - junit diff --git a/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java b/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java index 0f0e652596..f6b3ebbe45 100644 --- a/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java +++ b/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java @@ -39,7 +39,7 @@ public class BackoffWithJitterTest { } private PingPongService service; - private static final int NUM_TASKS = 8; + private static final int NUM_CONCURRENT_CLIENTS = 8; @Before public void setUp() { @@ -55,7 +55,7 @@ public class BackoffWithJitterTest { try { pingPongFn.apply("Hello"); } catch (PingPongServiceException e) { - verify(service, times(MAX_TRIES)).call(anyString()); + verify(service, times(MAX_RETRIES)).call(anyString()); } } @@ -73,8 +73,8 @@ public class BackoffWithJitterTest { private void test(IntervalFunction intervalFn) throws InterruptedException { Function pingPongFn = getRetryablePingPongFn(intervalFn); - ExecutorService executors = newFixedThreadPool(NUM_TASKS); - List> tasks = nCopies(NUM_TASKS, () -> pingPongFn.apply("Hello")); + ExecutorService executors = newFixedThreadPool(NUM_CONCURRENT_CLIENTS); + List> tasks = nCopies(NUM_CONCURRENT_CLIENTS, () -> pingPongFn.apply("Hello")); when(service.call(anyString())).thenThrow(PingPongServiceException.class); @@ -83,7 +83,7 @@ public class BackoffWithJitterTest { private Function getRetryablePingPongFn(IntervalFunction intervalFn) { RetryConfig retryConfig = RetryConfig.custom() - .maxAttempts(MAX_TRIES) + .maxAttempts(MAX_RETRIES) .intervalFunction(intervalFn) .retryExceptions(PingPongServiceException.class) .build(); @@ -98,6 +98,6 @@ public class BackoffWithJitterTest { static final Long INITIAL_INTERVAL = 1000L; static final Double MULTIPLIER = 2.0D; static final Double RANDOMIZATION_FACTOR = 0.6D; - static final Integer MAX_TRIES = 4; + static final Integer MAX_RETRIES = 4; } } From b6de1db857aec5368fe74cae9396fa0cb452bb77 Mon Sep 17 00:00:00 2001 From: eelhazati Date: Tue, 23 Jul 2019 09:09:56 +0100 Subject: [PATCH 38/84] add refresh token feature. --- .../server/api/TokenEndpoint.java | 4 +- .../handler/AbstractGrantTypeHandler.java | 87 +++++++++++++++++++ .../AuthorizationCodeGrantTypeHandler.java | 53 +---------- .../handler/RefreshTokenGrantTypeHandler.java | 64 ++++++++++++++ .../oauth2/client/AbstractServlet.java | 23 +++++ .../oauth2/client/CallbackServlet.java | 3 + .../oauth2/client/RefreshTokenServlet.java | 52 +++++++++++ .../oauth2-client/src/main/webapp/index.jsp | 16 +++- 8 files changed, 250 insertions(+), 52 deletions(-) create mode 100644 oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AbstractGrantTypeHandler.java create mode 100644 oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/RefreshTokenGrantTypeHandler.java create mode 100644 oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/AbstractServlet.java create mode 100644 oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java index f39bb2ea2d..df4011ddc1 100644 --- a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java @@ -15,15 +15,15 @@ import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; +import java.util.Arrays; import java.util.Base64; -import java.util.Collections; import java.util.List; import java.util.Objects; @Path("token") public class TokenEndpoint { - List supportedGrantTypes = Collections.singletonList("authorization_code"); + List supportedGrantTypes = Arrays.asList("authorization_code", "refresh_token"); @Inject private AppDataRepository appDataRepository; diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AbstractGrantTypeHandler.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AbstractGrantTypeHandler.java new file mode 100644 index 0000000000..324bacb33f --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AbstractGrantTypeHandler.java @@ -0,0 +1,87 @@ +package com.baeldung.oauth2.authorization.server.handler; + +import com.baeldung.oauth2.authorization.server.PEMKeyUtils; +import com.nimbusds.jose.*; +import com.nimbusds.jose.crypto.RSASSASigner; +import com.nimbusds.jose.crypto.RSASSAVerifier; +import com.nimbusds.jose.jwk.JWK; +import com.nimbusds.jose.jwk.RSAKey; +import com.nimbusds.jwt.JWTClaimsSet; +import com.nimbusds.jwt.SignedJWT; +import org.eclipse.microprofile.config.Config; + +import javax.inject.Inject; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.Arrays; +import java.util.Date; +import java.util.UUID; + +public abstract class AbstractGrantTypeHandler implements AuthorizationGrantTypeHandler { + + //Always RSA 256, but could be parametrized + protected JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).type(JOSEObjectType.JWT).build(); + + @Inject + protected Config config; + + //30 min + protected Long expiresInMin = 30L; + + protected JWSVerifier getJWSVerifier() throws Exception { + String verificationkey = config.getValue("verificationkey", String.class); + String pemEncodedRSAPublicKey = PEMKeyUtils.readKeyAsString(verificationkey); + RSAKey rsaPublicKey = (RSAKey) JWK.parseFromPEMEncodedObjects(pemEncodedRSAPublicKey); + return new RSASSAVerifier(rsaPublicKey); + } + + protected JWSSigner getJwsSigner() throws Exception { + String signingkey = config.getValue("signingkey", String.class); + String pemEncodedRSAPrivateKey = PEMKeyUtils.readKeyAsString(signingkey); + RSAKey rsaKey = (RSAKey) JWK.parseFromPEMEncodedObjects(pemEncodedRSAPrivateKey); + return new RSASSASigner(rsaKey.toRSAPrivateKey()); + } + + protected String getAccessToken(String clientId, String subject, String approvedScope) throws Exception { + //4. Signing + JWSSigner jwsSigner = getJwsSigner(); + + Instant now = Instant.now(); + //Long expiresInMin = 30L; + Date expirationTime = Date.from(now.plus(expiresInMin, ChronoUnit.MINUTES)); + + //3. JWT Payload or claims + JWTClaimsSet jwtClaims = new JWTClaimsSet.Builder() + .issuer("http://localhost:9080") + .subject(subject) + .claim("upn", subject) + .claim("client_id", clientId) + .audience("http://localhost:9280") + .claim("scope", approvedScope) + .claim("groups", Arrays.asList(approvedScope.split(" "))) + .expirationTime(expirationTime) // expires in 30 minutes + .notBeforeTime(Date.from(now)) + .issueTime(Date.from(now)) + .jwtID(UUID.randomUUID().toString()) + .build(); + SignedJWT signedJWT = new SignedJWT(jwsHeader, jwtClaims); + signedJWT.sign(jwsSigner); + return signedJWT.serialize(); + } + + protected String getRefreshToken(String clientId, String subject, String approvedScope) throws Exception { + JWSSigner jwsSigner = getJwsSigner(); + Instant now = Instant.now(); + //6.Build refresh token + JWTClaimsSet refreshTokenClaims = new JWTClaimsSet.Builder() + .subject(subject) + .claim("client_id", clientId) + .claim("scope", approvedScope) + //refresh token for 1 day. + .expirationTime(Date.from(now.plus(1, ChronoUnit.DAYS))) + .build(); + SignedJWT signedRefreshToken = new SignedJWT(jwsHeader, refreshTokenClaims); + signedRefreshToken.sign(jwsSigner); + return signedRefreshToken.serialize(); + } +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationCodeGrantTypeHandler.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationCodeGrantTypeHandler.java index 889c7fcea2..78128aead6 100644 --- a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationCodeGrantTypeHandler.java +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationCodeGrantTypeHandler.java @@ -1,18 +1,7 @@ package com.baeldung.oauth2.authorization.server.handler; -import com.baeldung.oauth2.authorization.server.PEMKeyUtils; import com.baeldung.oauth2.authorization.server.model.AuthorizationCode; -import com.nimbusds.jose.JOSEObjectType; -import com.nimbusds.jose.JWSAlgorithm; -import com.nimbusds.jose.JWSHeader; -import com.nimbusds.jose.crypto.RSASSASigner; -import com.nimbusds.jose.jwk.JWK; -import com.nimbusds.jose.jwk.RSAKey; -import com.nimbusds.jwt.JWTClaimsSet; -import com.nimbusds.jwt.SignedJWT; -import org.eclipse.microprofile.config.Config; -import javax.inject.Inject; import javax.inject.Named; import javax.json.Json; import javax.json.JsonObject; @@ -20,22 +9,14 @@ import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MultivaluedMap; -import java.time.Instant; import java.time.LocalDateTime; -import java.time.temporal.ChronoUnit; -import java.util.Arrays; -import java.util.Date; -import java.util.UUID; @Named("authorization_code") -public class AuthorizationCodeGrantTypeHandler implements AuthorizationGrantTypeHandler { +public class AuthorizationCodeGrantTypeHandler extends AbstractGrantTypeHandler { @PersistenceContext private EntityManager entityManager; - @Inject - private Config config; - @Override public JsonObject createAccessToken(String clientId, MultivaluedMap params) throws Exception { //1. code is required @@ -58,42 +39,16 @@ public class AuthorizationCodeGrantTypeHandler implements AuthorizationGrantType throw new WebApplicationException("invalid_grant"); } - //JWT Header - JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).type(JOSEObjectType.JWT).build(); - - Instant now = Instant.now(); - Long expiresInMin = 30L; - Date expiresIn = Date.from(now.plus(expiresInMin, ChronoUnit.MINUTES)); - //3. JWT Payload or claims - JWTClaimsSet jwtClaims = new JWTClaimsSet.Builder() - .issuer("http://localhost:9080") - .subject(authorizationCode.getUserId()) - .claim("upn", authorizationCode.getUserId()) - .audience("http://localhost:9280") - .claim("scope", authorizationCode.getApprovedScopes()) - .claim("groups", Arrays.asList(authorizationCode.getApprovedScopes().split(" "))) - .expirationTime(expiresIn) // expires in 30 minutes - .notBeforeTime(Date.from(now)) - .issueTime(Date.from(now)) - .jwtID(UUID.randomUUID().toString()) - .build(); - SignedJWT signedJWT = new SignedJWT(jwsHeader, jwtClaims); - - //4. Signing - String signingkey = config.getValue("signingkey", String.class); - String pemEncodedRSAPrivateKey = PEMKeyUtils.readKeyAsString(signingkey); - RSAKey rsaKey = (RSAKey) JWK.parseFromPEMEncodedObjects(pemEncodedRSAPrivateKey); - signedJWT.sign(new RSASSASigner(rsaKey.toRSAPrivateKey())); - - //5. Finally the JWT access token - String accessToken = signedJWT.serialize(); + String accessToken = getAccessToken(clientId, authorizationCode.getUserId(), authorizationCode.getApprovedScopes()); + String refreshToken = getRefreshToken(clientId, authorizationCode.getUserId(), authorizationCode.getApprovedScopes()); return Json.createObjectBuilder() .add("token_type", "Bearer") .add("access_token", accessToken) .add("expires_in", expiresInMin * 60) .add("scope", authorizationCode.getApprovedScopes()) + .add("refresh_token", refreshToken) .build(); } } diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/RefreshTokenGrantTypeHandler.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/RefreshTokenGrantTypeHandler.java new file mode 100644 index 0000000000..27c0ed4427 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/RefreshTokenGrantTypeHandler.java @@ -0,0 +1,64 @@ +package com.baeldung.oauth2.authorization.server.handler; + +import com.nimbusds.jose.JWSVerifier; +import com.nimbusds.jwt.SignedJWT; + +import javax.inject.Named; +import javax.json.Json; +import javax.json.JsonObject; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MultivaluedMap; +import java.util.*; + +@Named("refresh_token") +public class RefreshTokenGrantTypeHandler extends AbstractGrantTypeHandler { + + @Override + public JsonObject createAccessToken(String clientId, MultivaluedMap params) throws Exception { + String refreshToken = params.getFirst("refresh_token"); + if (refreshToken == null || "".equals(refreshToken)) { + throw new WebApplicationException("invalid_grant"); + } + + //Decode refresh token + SignedJWT signedRefreshToken = SignedJWT.parse(refreshToken); + JWSVerifier verifier = getJWSVerifier(); + + if (!signedRefreshToken.verify(verifier)) { + throw new WebApplicationException("Invalid refresh token."); + } + if (!(new Date().before(signedRefreshToken.getJWTClaimsSet().getExpirationTime()))) { + throw new WebApplicationException("Refresh token expired."); + } + String refreshTokenClientId = signedRefreshToken.getJWTClaimsSet().getStringClaim("client_id"); + if (!clientId.equals(refreshTokenClientId)) { + throw new WebApplicationException("Invalid client_id."); + } + + //At this point, the refresh token is valid and not yet expired + //So create a new access token from it. + String subject = signedRefreshToken.getJWTClaimsSet().getSubject(); + String approvedScopes = signedRefreshToken.getJWTClaimsSet().getStringClaim("scope"); + + String finalScope = approvedScopes; + String requestedScopes = params.getFirst("scope"); + if (requestedScopes != null && !requestedScopes.isEmpty()) { + Set allowedScopes = new LinkedHashSet<>(); + Set rScopes = new HashSet(Arrays.asList(requestedScopes.split(" "))); + Set aScopes = new HashSet(Arrays.asList(approvedScopes.split(" "))); + for (String scope : rScopes) { + if (aScopes.contains(scope)) allowedScopes.add(scope); + } + finalScope = String.join(" ", allowedScopes); + } + + String accessToken = getAccessToken(clientId, subject, finalScope); + return Json.createObjectBuilder() + .add("token_type", "Bearer") + .add("access_token", accessToken) + .add("expires_in", expiresInMin * 60) + .add("scope", finalScope) + .add("refresh_token", refreshToken) + .build(); + } +} diff --git a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/AbstractServlet.java b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/AbstractServlet.java new file mode 100644 index 0000000000..7059c4f7e1 --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/AbstractServlet.java @@ -0,0 +1,23 @@ +package com.baeldung.oauth2.client; + +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Base64; + +public abstract class AbstractServlet extends HttpServlet { + + protected void dispatch(String location, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + RequestDispatcher requestDispatcher = request.getRequestDispatcher(location); + requestDispatcher.forward(request, response); + } + + protected String getAuthorizationHeaderValue(String clientId, String clientSecret) { + String token = clientId + ":" + clientSecret; + String encodedString = Base64.getEncoder().encodeToString(token.getBytes()); + return "Basic " + encodedString; + } +} diff --git a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java index 87aa8bc668..a172d20235 100644 --- a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java +++ b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java @@ -29,6 +29,9 @@ public class CallbackServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + String clientId = config.getValue("client.clientId", String.class); + String clientSecret = config.getValue("client.clientSecret", String.class); + //Error: String error = request.getParameter("error"); if (error != null) { diff --git a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java new file mode 100644 index 0000000000..2cfadc700f --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java @@ -0,0 +1,52 @@ +package com.baeldung.oauth2.client; + +import org.eclipse.microprofile.config.Config; + +import javax.inject.Inject; +import javax.json.JsonObject; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Form; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; +import java.io.IOException; + +@WebServlet(urlPatterns = "/refreshtoken") +public class RefreshTokenServlet extends AbstractServlet { + + @Inject + private Config config; + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + String clientId = config.getValue("client.clientId", String.class); + String clientSecret = config.getValue("client.clientSecret", String.class); + + JsonObject actualTokenResponse = (JsonObject) request.getSession().getAttribute("tokenResponse"); + Client client = ClientBuilder.newClient(); + WebTarget target = client.target(config.getValue("provider.tokenUri", String.class)); + + Form form = new Form(); + form.param("grant_type", "refresh_token"); + form.param("refresh_token", actualTokenResponse.getString("refresh_token")); + + String scope = request.getParameter("scope"); + if (scope != null && !scope.isEmpty()) { + form.param("scope", scope); + } + + JsonObject tokenResponse = target.request(MediaType.APPLICATION_JSON_TYPE) + .header(HttpHeaders.AUTHORIZATION, getAuthorizationHeaderValue(clientId, clientSecret)) + .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), JsonObject.class); + + request.getSession().setAttribute("tokenResponse", tokenResponse); + dispatch("/", request, response); + } +} diff --git a/oauth2-framework-impl/oauth2-client/src/main/webapp/index.jsp b/oauth2-framework-impl/oauth2-client/src/main/webapp/index.jsp index 23fec70f33..ccb74df228 100644 --- a/oauth2-framework-impl/oauth2-client/src/main/webapp/index.jsp +++ b/oauth2-framework-impl/oauth2-client/src/main/webapp/index.jsp @@ -10,6 +10,7 @@ body { margin: 0px; } + input[type=text], input[type=password] { width: 75%; padding: 4px 0px; @@ -17,6 +18,7 @@ border: 1px solid #502bcc; box-sizing: border-box; } + .container-error { padding: 16px; border: 1px solid #cc102a; @@ -25,6 +27,7 @@ margin-left: 25px; margin-bottom: 25px; } + .container { padding: 16px; border: 1px solid #130ecc; @@ -81,8 +84,20 @@
  • access_token: ${tokenResponse.getString("access_token")}
  • scope: ${tokenResponse.getString("scope")}
  • Expires in (s): ${tokenResponse.getInt("expires_in")}
  • +
  • refresh_token: ${tokenResponse.getString("refresh_token")}
  • + + +

    OAuth2 Resource Server Call


    @@ -90,7 +105,6 @@
  • Read Protected Resource
  • Write Protected Resource
  • -
    From 7486f1a305855f3c27c3dacae97365a9dc3efc8b Mon Sep 17 00:00:00 2001 From: eelhazati Date: Tue, 23 Jul 2019 09:24:25 +0100 Subject: [PATCH 39/84] scope in refresh token request should be a subset of those authorized by the resource owner. --- .../handler/RefreshTokenGrantTypeHandler.java | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/RefreshTokenGrantTypeHandler.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/RefreshTokenGrantTypeHandler.java index 27c0ed4427..513bcc2cf0 100644 --- a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/RefreshTokenGrantTypeHandler.java +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/RefreshTokenGrantTypeHandler.java @@ -8,7 +8,10 @@ import javax.json.Json; import javax.json.JsonObject; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MultivaluedMap; -import java.util.*; +import java.util.Arrays; +import java.util.Date; +import java.util.HashSet; +import java.util.Set; @Named("refresh_token") public class RefreshTokenGrantTypeHandler extends AbstractGrantTypeHandler { @@ -40,24 +43,23 @@ public class RefreshTokenGrantTypeHandler extends AbstractGrantTypeHandler { String subject = signedRefreshToken.getJWTClaimsSet().getSubject(); String approvedScopes = signedRefreshToken.getJWTClaimsSet().getStringClaim("scope"); - String finalScope = approvedScopes; String requestedScopes = params.getFirst("scope"); if (requestedScopes != null && !requestedScopes.isEmpty()) { - Set allowedScopes = new LinkedHashSet<>(); Set rScopes = new HashSet(Arrays.asList(requestedScopes.split(" "))); Set aScopes = new HashSet(Arrays.asList(approvedScopes.split(" "))); - for (String scope : rScopes) { - if (aScopes.contains(scope)) allowedScopes.add(scope); + if (!aScopes.containsAll(rScopes)) { + throw new WebApplicationException("Requested scopes should be a subset of those authorized by the resource owner."); } - finalScope = String.join(" ", allowedScopes); + } else { + requestedScopes = approvedScopes; } - String accessToken = getAccessToken(clientId, subject, finalScope); + String accessToken = getAccessToken(clientId, subject, requestedScopes); return Json.createObjectBuilder() .add("token_type", "Bearer") .add("access_token", accessToken) .add("expires_in", expiresInMin * 60) - .add("scope", finalScope) + .add("scope", requestedScopes) .add("refresh_token", refreshToken) .build(); } From e314cddbe66eb1c063369f1b460792b19682547d Mon Sep 17 00:00:00 2001 From: eelhazati Date: Tue, 23 Jul 2019 10:03:17 +0100 Subject: [PATCH 40/84] scope in refresh token request should be a subset of those authorized by the resource owner. --- .../oauth2/client/CallbackServlet.java | 32 ++++++------------- .../oauth2/client/RefreshTokenServlet.java | 7 +++- 2 files changed, 16 insertions(+), 23 deletions(-) diff --git a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java index a172d20235..e72877076c 100644 --- a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java +++ b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java @@ -4,10 +4,8 @@ import org.eclipse.microprofile.config.Config; import javax.inject.Inject; import javax.json.JsonObject; -import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.client.Client; @@ -18,10 +16,9 @@ import javax.ws.rs.core.Form; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import java.io.IOException; -import java.util.Base64; @WebServlet(urlPatterns = "/callback") -public class CallbackServlet extends HttpServlet { +public class CallbackServlet extends AbstractServlet { @Inject private Config config; @@ -56,24 +53,15 @@ public class CallbackServlet extends HttpServlet { form.param("code", code); form.param("redirect_uri", config.getValue("client.redirectUri", String.class)); - JsonObject tokenResponse = target.request(MediaType.APPLICATION_JSON_TYPE) - .header(HttpHeaders.AUTHORIZATION, getAuthorizationHeaderValue()) - .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), JsonObject.class); - - request.getSession().setAttribute("tokenResponse", tokenResponse); + try { + JsonObject tokenResponse = target.request(MediaType.APPLICATION_JSON_TYPE) + .header(HttpHeaders.AUTHORIZATION, getAuthorizationHeaderValue(clientId, clientSecret)) + .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), JsonObject.class); + request.getSession().setAttribute("tokenResponse", tokenResponse); + } catch (Exception ex) { + System.out.println(ex.getMessage()); + request.setAttribute("error", ex.getMessage()); + } dispatch("/", request, response); } - - private void dispatch(String location, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - RequestDispatcher requestDispatcher = request.getRequestDispatcher(location); - requestDispatcher.forward(request, response); - } - - private String getAuthorizationHeaderValue() { - String clientId = config.getValue("client.clientId", String.class); - String clientSecret = config.getValue("client.clientSecret", String.class); - String token = clientId + ":" + clientSecret; - String encodedString = Base64.getEncoder().encodeToString(token.getBytes()); - return "Basic " + encodedString; - } } diff --git a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java index 2cfadc700f..b9fd7a4a21 100644 --- a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java +++ b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java @@ -46,7 +46,12 @@ public class RefreshTokenServlet extends AbstractServlet { .header(HttpHeaders.AUTHORIZATION, getAuthorizationHeaderValue(clientId, clientSecret)) .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), JsonObject.class); - request.getSession().setAttribute("tokenResponse", tokenResponse); + String error = tokenResponse.getString("error"); + if (error != null) { + request.setAttribute("error", error); + } else { + request.getSession().setAttribute("tokenResponse", tokenResponse); + } dispatch("/", request, response); } } From b6b90f556af9099e0e0db47a151fa5f0ca4dcb4c Mon Sep 17 00:00:00 2001 From: "EZZEDDINE.ELHAZATI" Date: Tue, 23 Jul 2019 13:26:23 +0100 Subject: [PATCH 41/84] refactoring. --- .../server/api/TokenEndpoint.java | 42 +++++++++++-------- 1 file changed, 24 insertions(+), 18 deletions(-) diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java index df4011ddc1..4716c1bb26 100644 --- a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java @@ -18,7 +18,6 @@ import javax.ws.rs.core.Response; import java.util.Arrays; import java.util.Base64; import java.util.List; -import java.util.Objects; @Path("token") public class TokenEndpoint { @@ -39,28 +38,26 @@ public class TokenEndpoint { //Check grant_type params String grantType = params.getFirst("grant_type"); - Objects.requireNonNull(grantType, "grant_type params is required"); - if (!supportedGrantTypes.contains(grantType)) { - JsonObject error = Json.createObjectBuilder() - .add("error", "unsupported_grant_type") - .add("error_description", "grant type should be one of :" + supportedGrantTypes) - .build(); - return Response.status(Response.Status.BAD_REQUEST) - .entity(error).build(); + if (grantType == null || grantType.isEmpty()) + return responseError("Invalid_request", "grant_type is required", Response.Status.BAD_REQUEST); + if (!supportedGrantTypes.contains(grantType)) { + return responseError("unsupported_grant_type", "grant_type should be one of :" + supportedGrantTypes, Response.Status.BAD_REQUEST); } //Client Authentication String[] clientCredentials = extract(authHeader); + if (clientCredentials.length != 2) { + return responseError("Invalid_request", "Bad Credentials client_id/client_secret", Response.Status.BAD_REQUEST); + } String clientId = clientCredentials[0]; - String clientSecret = clientCredentials[1]; Client client = appDataRepository.getClient(clientId); - if (client == null || clientSecret == null || !clientSecret.equals(client.getClientSecret())) { - JsonObject error = Json.createObjectBuilder() - .add("error", "invalid_client") - .build(); - return Response.status(Response.Status.UNAUTHORIZED) - .entity(error).build(); + if (client == null) { + return responseError("Invalid_request", "Invalid client_id", Response.Status.BAD_REQUEST); + } + String clientSecret = clientCredentials[1]; + if (!clientSecret.equals(client.getClientSecret())) { + return responseError("Invalid_request", "Invalid client_secret", Response.Status.UNAUTHORIZED); } AuthorizationGrantTypeHandler authorizationGrantTypeHandler = authorizationGrantTypeHandlers.select(NamedLiteral.of(grantType)).get(); @@ -68,7 +65,7 @@ public class TokenEndpoint { try { tokenResponse = authorizationGrantTypeHandler.createAccessToken(clientId, params); } catch (Exception e) { - e.printStackTrace(); + return responseError("Invalid_request", "Can't get token", Response.Status.INTERNAL_SERVER_ERROR); } return Response.ok(tokenResponse) @@ -81,6 +78,15 @@ public class TokenEndpoint { if (authHeader != null && authHeader.startsWith("Basic ")) { return new String(Base64.getDecoder().decode(authHeader.substring(6))).split(":"); } - return null; + return new String[]{}; + } + + private Response responseError(String error, String errorDescription, Response.Status status) { + JsonObject errorResponse = Json.createObjectBuilder() + .add("error", error) + .add("error_description", errorDescription) + .build(); + return Response.status(status) + .entity(errorResponse).build(); } } From 4c6182d45f4edabf0b54e7c88e108db6b634ba28 Mon Sep 17 00:00:00 2001 From: "EZZEDDINE.ELHAZATI" Date: Tue, 23 Jul 2019 16:04:35 +0100 Subject: [PATCH 42/84] refactoring. --- .../authorization/server/api/TokenEndpoint.java | 2 ++ .../handler/RefreshTokenGrantTypeHandler.java | 8 +++++++- .../oauth2/client/RefreshTokenServlet.java | 14 ++++++-------- 3 files changed, 15 insertions(+), 9 deletions(-) diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java index 4716c1bb26..0ea12da16e 100644 --- a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java @@ -64,6 +64,8 @@ public class TokenEndpoint { JsonObject tokenResponse = null; try { tokenResponse = authorizationGrantTypeHandler.createAccessToken(clientId, params); + } catch (WebApplicationException e) { + return e.getResponse(); } catch (Exception e) { return responseError("Invalid_request", "Can't get token", Response.Status.INTERNAL_SERVER_ERROR); } diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/RefreshTokenGrantTypeHandler.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/RefreshTokenGrantTypeHandler.java index 513bcc2cf0..63e3552353 100644 --- a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/RefreshTokenGrantTypeHandler.java +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/RefreshTokenGrantTypeHandler.java @@ -8,6 +8,7 @@ import javax.json.Json; import javax.json.JsonObject; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; import java.util.Arrays; import java.util.Date; import java.util.HashSet; @@ -48,7 +49,12 @@ public class RefreshTokenGrantTypeHandler extends AbstractGrantTypeHandler { Set rScopes = new HashSet(Arrays.asList(requestedScopes.split(" "))); Set aScopes = new HashSet(Arrays.asList(approvedScopes.split(" "))); if (!aScopes.containsAll(rScopes)) { - throw new WebApplicationException("Requested scopes should be a subset of those authorized by the resource owner."); + JsonObject error = Json.createObjectBuilder() + .add("error", "Invalid_request") + .add("error_description", "Requested scopes should be a subset of the original scopes.") + .build(); + Response response = Response.status(Response.Status.BAD_REQUEST).entity(error).build(); + throw new WebApplicationException(response); } } else { requestedScopes = approvedScopes; diff --git a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java index b9fd7a4a21..766a4e3f1f 100644 --- a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java +++ b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java @@ -15,6 +15,7 @@ import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Form; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import java.io.IOException; @WebServlet(urlPatterns = "/refreshtoken") @@ -42,16 +43,13 @@ public class RefreshTokenServlet extends AbstractServlet { form.param("scope", scope); } - JsonObject tokenResponse = target.request(MediaType.APPLICATION_JSON_TYPE) + Response jaxrsResponse = target.request(MediaType.APPLICATION_JSON_TYPE) .header(HttpHeaders.AUTHORIZATION, getAuthorizationHeaderValue(clientId, clientSecret)) - .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), JsonObject.class); + .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), Response.class); + JsonObject tokenResponse = jaxrsResponse.readEntity(JsonObject.class); + System.out.println(tokenResponse); - String error = tokenResponse.getString("error"); - if (error != null) { - request.setAttribute("error", error); - } else { - request.getSession().setAttribute("tokenResponse", tokenResponse); - } + request.getSession().setAttribute("tokenResponse", tokenResponse); dispatch("/", request, response); } } From 4998ed9be4dcaaa58ee729f3b1f79b73fd8fda89 Mon Sep 17 00:00:00 2001 From: Justin Albano Date: Tue, 23 Jul 2019 10:59:02 -0400 Subject: [PATCH 43/84] BAEL-3153: Added test cases for String toLowerCase and toUpperCase The toLowerCase and toUpperCase methods are simple enough that no new classes are needed under the main/ directory. The included tests exercise the changing of case for an English string using the default locale, a foreign string using the default locale, and a foreign string using a provided locale. --- java-strings-2/README.MD | 14 ++++----- .../changecase/ToLowerCaseUnitTest.java | 29 +++++++++++++++++++ .../changecase/ToUpperCaseUnitTest.java | 29 +++++++++++++++++++ 3 files changed, 65 insertions(+), 7 deletions(-) create mode 100644 java-strings-2/src/test/java/com/baeldung/string/changecase/ToLowerCaseUnitTest.java create mode 100644 java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java diff --git a/java-strings-2/README.MD b/java-strings-2/README.MD index c6d4f0222a..4db93f64e0 100644 --- a/java-strings-2/README.MD +++ b/java-strings-2/README.MD @@ -1,7 +1,7 @@ -## Relevant Articles - -- [Java Localization – Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting) -- [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring) -- [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords) -- [Blank and Empty Strings in Java](https://www.baeldung.com/java-blank-empty-strings) -- [String Initialization in Java](https://www.baeldung.com/java-string-initialization) +## Relevant Articles + +- [Java Localization – Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting) +- [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring) +- [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords) +- [Blank and Empty Strings in Java](https://www.baeldung.com/java-blank-empty-strings) +- [String Initialization in Java](https://www.baeldung.com/java-string-initialization) diff --git a/java-strings-2/src/test/java/com/baeldung/string/changecase/ToLowerCaseUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/changecase/ToLowerCaseUnitTest.java new file mode 100644 index 0000000000..14102be993 --- /dev/null +++ b/java-strings-2/src/test/java/com/baeldung/string/changecase/ToLowerCaseUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.string.changecase; + +import static org.junit.Assert.assertEquals; + +import java.util.Locale; + +import org.junit.Test; + +public class ToLowerCaseUnitTest { + + private static final Locale TURKISH = new Locale("tr"); + private String name = "John Doe"; + private String foreignUppercase = "\u0049"; + + @Test + public void givenMixedCaseString_WhenToLowerCase_ThenResultIsLowerCase() { + assertEquals("john doe", name.toLowerCase()); + } + + @Test + public void givenForeignString_WhenToLowerCaseWithoutLocale_ThenResultIsLowerCase() { + assertEquals("\u0069", foreignUppercase.toLowerCase()); + } + + @Test + public void givenForeignString_WhenToLowerCaseWithLocale_ThenResultIsLowerCase() { + assertEquals("\u0131", foreignUppercase.toLowerCase(TURKISH)); + } +} diff --git a/java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java new file mode 100644 index 0000000000..90b80714a7 --- /dev/null +++ b/java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.string.changecase; + +import static org.junit.Assert.assertEquals; + +import java.util.Locale; + +import org.junit.Test; + +public class ToUpperCaseUnitTest { + + private static final Locale TURKISH = new Locale("tr"); + private String name = "John Doe"; + private String foreignUppercase = "\u0069"; + + @Test + public void givenMixedCaseString_WhenToUpperCase_ThenResultIsUpperCase() { + assertEquals("JOHN DOE", name.toUpperCase()); + } + + @Test + public void givenForeignString_WhenToUpperCaseWithoutLocale_ThenResultIsUpperCase() { + assertEquals("\u0049", foreignUppercase.toUpperCase()); + } + + @Test + public void givenForeignString_WhenToUpperCaseWithLocale_ThenResultIsUpperCase() { + assertEquals("\u0130", foreignUppercase.toUpperCase(TURKISH)); + } +} From ce9e9561993eaf36255cb516aea372cf363fac6b Mon Sep 17 00:00:00 2001 From: "EZZEDDINE.ELHAZATI" Date: Tue, 23 Jul 2019 16:13:48 +0100 Subject: [PATCH 44/84] refactoring. --- .../com/baeldung/oauth2/client/RefreshTokenServlet.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java index 766a4e3f1f..a519a53070 100644 --- a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java +++ b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java @@ -47,9 +47,11 @@ public class RefreshTokenServlet extends AbstractServlet { .header(HttpHeaders.AUTHORIZATION, getAuthorizationHeaderValue(clientId, clientSecret)) .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), Response.class); JsonObject tokenResponse = jaxrsResponse.readEntity(JsonObject.class); - System.out.println(tokenResponse); - - request.getSession().setAttribute("tokenResponse", tokenResponse); + if (jaxrsResponse.getStatus() == 200) { + request.getSession().setAttribute("tokenResponse", tokenResponse); + } else { + request.setAttribute("error", tokenResponse.getString("error_description", "error!")); + } dispatch("/", request, response); } } From b355af4d01472a32d823685a3ff35f1d3736cc9a Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Tue, 23 Jul 2019 16:22:20 -0300 Subject: [PATCH 45/84] fixed migration to spring boot 2, plus now added properties in articles --- spring-security-mvc-session/pom.xml | 87 +++++-------------- .../baeldung/SpringSessionApplication.java | 2 +- .../monitoring/MetricRegistrySingleton.java | 2 +- ...SimpleUrlAuthenticationSuccessHandler.java | 2 +- .../baeldung/security/SessionFilter.java | 2 +- .../java/com/baeldung/spring/MvcConfig.java | 33 +++++++ .../baeldung/spring/SecSecurityConfig.java | 11 ++- .../web/SessionListenerWithMetrics.java | 5 +- .../java/org/baeldung/spring/MvcConfig.java | 44 ---------- .../src/main/resources/application.properties | 8 ++ .../SpringContextIntegrationTest.java | 15 ++++ .../SpringContextIntegrationTest.java | 19 ---- .../java/org/baeldung/SpringContextTest.java | 19 ---- 13 files changed, 90 insertions(+), 159 deletions(-) rename spring-security-mvc-session/src/main/java/{org => com}/baeldung/SpringSessionApplication.java (93%) rename spring-security-mvc-session/src/main/java/{org => com}/baeldung/monitoring/MetricRegistrySingleton.java (95%) rename spring-security-mvc-session/src/main/java/{org => com}/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java (99%) rename spring-security-mvc-session/src/main/java/{org => com}/baeldung/security/SessionFilter.java (97%) create mode 100644 spring-security-mvc-session/src/main/java/com/baeldung/spring/MvcConfig.java rename spring-security-mvc-session/src/main/java/{org => com}/baeldung/spring/SecSecurityConfig.java (91%) rename spring-security-mvc-session/src/main/java/{org => com}/baeldung/web/SessionListenerWithMetrics.java (92%) delete mode 100644 spring-security-mvc-session/src/main/java/org/baeldung/spring/MvcConfig.java create mode 100644 spring-security-mvc-session/src/main/resources/application.properties create mode 100644 spring-security-mvc-session/src/test/java/com/baeldung/SpringContextIntegrationTest.java delete mode 100644 spring-security-mvc-session/src/test/java/org/baeldung/SpringContextIntegrationTest.java delete mode 100644 spring-security-mvc-session/src/test/java/org/baeldung/SpringContextTest.java diff --git a/spring-security-mvc-session/pom.xml b/spring-security-mvc-session/pom.xml index b55ce70517..5ed7fbecd3 100644 --- a/spring-security-mvc-session/pom.xml +++ b/spring-security-mvc-session/pom.xml @@ -1,18 +1,19 @@ - + 4.0.0 com.baeldung spring-security-mvc-session 0.1-SNAPSHOT spring-security-mvc-session - war + jar - parent-boot-2 com.baeldung + parent-boot-2 0.0.1-SNAPSHOT ../parent-boot-2 - + @@ -35,20 +36,13 @@ org.apache.tomcat.embed tomcat-embed-jasper + provided org.springframework.boot spring-boot-starter-tomcat - - - - javax.servlet - javax.servlet-api - provided - - javax.servlet jstl @@ -56,70 +50,35 @@ - - com.codahale.metrics + io.dropwizard.metrics metrics-core - ${codahale.metrics.version} - + - org.springframework.boot - spring-boot-starter-test - test - - + org.springframework.boot + spring-boot-starter-test + test +
    + + org.springframework.security + spring-security-test + test +
    - spring-security-mvc-session - - - src/main/resources - true - - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} + org.springframework.boot + spring-boot-maven-plugin - true - - jetty8x - embedded - - - - - - - 8082 - - + com.baeldung.SpringSessionApplication + JAR - - - - - 3.0.2 - - - 1.6.1 - - - \ No newline at end of file + diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/SpringSessionApplication.java b/spring-security-mvc-session/src/main/java/com/baeldung/SpringSessionApplication.java similarity index 93% rename from spring-security-mvc-session/src/main/java/org/baeldung/SpringSessionApplication.java rename to spring-security-mvc-session/src/main/java/com/baeldung/SpringSessionApplication.java index 9e52f0430a..c2a4b35df0 100644 --- a/spring-security-mvc-session/src/main/java/org/baeldung/SpringSessionApplication.java +++ b/spring-security-mvc-session/src/main/java/com/baeldung/SpringSessionApplication.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/monitoring/MetricRegistrySingleton.java b/spring-security-mvc-session/src/main/java/com/baeldung/monitoring/MetricRegistrySingleton.java similarity index 95% rename from spring-security-mvc-session/src/main/java/org/baeldung/monitoring/MetricRegistrySingleton.java rename to spring-security-mvc-session/src/main/java/com/baeldung/monitoring/MetricRegistrySingleton.java index ed253305ed..e2224996c2 100644 --- a/spring-security-mvc-session/src/main/java/org/baeldung/monitoring/MetricRegistrySingleton.java +++ b/spring-security-mvc-session/src/main/java/com/baeldung/monitoring/MetricRegistrySingleton.java @@ -1,4 +1,4 @@ -package org.baeldung.monitoring; +package com.baeldung.monitoring; import java.util.concurrent.TimeUnit; diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java b/spring-security-mvc-session/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java similarity index 99% rename from spring-security-mvc-session/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java rename to spring-security-mvc-session/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java index 19f49ea59d..9d4fc19098 100644 --- a/spring-security-mvc-session/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java +++ b/spring-security-mvc-session/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java @@ -1,4 +1,4 @@ -package org.baeldung.security; +package com.baeldung.security; import java.io.IOException; import java.util.Collection; diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/security/SessionFilter.java b/spring-security-mvc-session/src/main/java/com/baeldung/security/SessionFilter.java similarity index 97% rename from spring-security-mvc-session/src/main/java/org/baeldung/security/SessionFilter.java rename to spring-security-mvc-session/src/main/java/com/baeldung/security/SessionFilter.java index d37d46e478..f4f876af9c 100644 --- a/spring-security-mvc-session/src/main/java/org/baeldung/security/SessionFilter.java +++ b/spring-security-mvc-session/src/main/java/com/baeldung/security/SessionFilter.java @@ -1,4 +1,4 @@ -package org.baeldung.security; +package com.baeldung.security; import java.io.IOException; import java.util.Arrays; diff --git a/spring-security-mvc-session/src/main/java/com/baeldung/spring/MvcConfig.java b/spring-security-mvc-session/src/main/java/com/baeldung/spring/MvcConfig.java new file mode 100644 index 0000000000..38a4f3f81b --- /dev/null +++ b/spring-security-mvc-session/src/main/java/com/baeldung/spring/MvcConfig.java @@ -0,0 +1,33 @@ +package com.baeldung.spring; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class MvcConfig implements WebMvcConfigurer { + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + registry.addViewController("/anonymous.html"); + + registry.addViewController("/login.html"); + registry.addViewController("/homepage.html"); + registry.addViewController("/sessionExpired.html"); + registry.addViewController("/invalidSession.html"); + registry.addViewController("/console.html"); + } + + + /* + * Spring Boot supports configuring a ViewResolver with properties + */ +// @Bean +// public ViewResolver viewResolver() { +// final InternalResourceViewResolver bean = new InternalResourceViewResolver(); +// +// bean.setViewClass(JstlView.class); +// bean.setPrefix("/WEB-INF/view/"); +// bean.setSuffix(".jsp"); +// } +} diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-mvc-session/src/main/java/com/baeldung/spring/SecSecurityConfig.java similarity index 91% rename from spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java rename to spring-security-mvc-session/src/main/java/com/baeldung/spring/SecSecurityConfig.java index b7996ebf18..a922ba6f7f 100644 --- a/spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-mvc-session/src/main/java/com/baeldung/spring/SecSecurityConfig.java @@ -1,11 +1,9 @@ -package org.baeldung.spring; +package com.baeldung.spring; -import org.baeldung.security.MySimpleUrlAuthenticationSuccessHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; 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.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @@ -13,9 +11,10 @@ import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.security.web.session.HttpSessionEventPublisher; +import com.baeldung.security.MySimpleUrlAuthenticationSuccessHandler; + @Configuration // @ImportResource({ "classpath:webSecurityConfig.xml" }) -@EnableWebSecurity public class SecSecurityConfig extends WebSecurityConfigurerAdapter { public SecSecurityConfig() { @@ -39,7 +38,7 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { .csrf().disable() .authorizeRequests() .antMatchers("/anonymous*").anonymous() - .antMatchers("/login*").permitAll() + .antMatchers("/login*","/invalidSession*", "/sessionExpired*").permitAll() .anyRequest().authenticated() .and() .formLogin() @@ -70,7 +69,7 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { public HttpSessionEventPublisher httpSessionEventPublisher() { return new HttpSessionEventPublisher(); } - + @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/web/SessionListenerWithMetrics.java b/spring-security-mvc-session/src/main/java/com/baeldung/web/SessionListenerWithMetrics.java similarity index 92% rename from spring-security-mvc-session/src/main/java/org/baeldung/web/SessionListenerWithMetrics.java rename to spring-security-mvc-session/src/main/java/com/baeldung/web/SessionListenerWithMetrics.java index 46bf2708f7..fb1a81744e 100644 --- a/spring-security-mvc-session/src/main/java/org/baeldung/web/SessionListenerWithMetrics.java +++ b/spring-security-mvc-session/src/main/java/com/baeldung/web/SessionListenerWithMetrics.java @@ -1,12 +1,11 @@ -package org.baeldung.web; +package com.baeldung.web; import java.util.concurrent.atomic.AtomicInteger; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; -import org.baeldung.monitoring.MetricRegistrySingleton; - +import com.baeldung.monitoring.MetricRegistrySingleton; import com.codahale.metrics.Counter; public class SessionListenerWithMetrics implements HttpSessionListener { diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/spring/MvcConfig.java b/spring-security-mvc-session/src/main/java/org/baeldung/spring/MvcConfig.java deleted file mode 100644 index b9f50ded73..0000000000 --- a/spring-security-mvc-session/src/main/java/org/baeldung/spring/MvcConfig.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.baeldung.spring; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import org.springframework.web.servlet.view.InternalResourceViewResolver; -import org.springframework.web.servlet.view.JstlView; - -@EnableWebMvc -@Configuration -public class MvcConfig implements WebMvcConfigurer { - - public MvcConfig() { - super(); - } - - // API - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - - registry.addViewController("/anonymous.html"); - - registry.addViewController("/login.html"); - registry.addViewController("/homepage.html"); - registry.addViewController("/sessionExpired.html"); - registry.addViewController("/invalidExpired.html"); - registry.addViewController("/console.html"); - } - - @Bean - public ViewResolver viewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); - - bean.setViewClass(JstlView.class); - bean.setPrefix("/WEB-INF/view/"); - bean.setSuffix(".jsp"); - - return bean; - } -} \ No newline at end of file diff --git a/spring-security-mvc-session/src/main/resources/application.properties b/spring-security-mvc-session/src/main/resources/application.properties new file mode 100644 index 0000000000..39ec0a0b27 --- /dev/null +++ b/spring-security-mvc-session/src/main/resources/application.properties @@ -0,0 +1,8 @@ +server.servlet.session.timeout=60s + +spring.mvc.view.prefix=/WEB-INF/view/ +spring.mvc.view.suffix=.jsp + +## Secure Session Cookie configurations +#server.servlet.session.cookie.http-only=true +#server.servlet.session.cookie.secure=true \ No newline at end of file diff --git a/spring-security-mvc-session/src/test/java/com/baeldung/SpringContextIntegrationTest.java b/spring-security-mvc-session/src/test/java/com/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..8e53a6371a --- /dev/null +++ b/spring-security-mvc-session/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,15 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-session/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-mvc-session/src/test/java/org/baeldung/SpringContextIntegrationTest.java deleted file mode 100644 index 9e74e83a53..0000000000 --- a/spring-security-mvc-session/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.baeldung; - -import org.baeldung.spring.MvcConfig; -import org.baeldung.spring.SecSecurityConfig; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { MvcConfig.class, SecSecurityConfig.class }) -@WebAppConfiguration -public class SpringContextIntegrationTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-security-mvc-session/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-mvc-session/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 5ee80d856a..0000000000 --- a/spring-security-mvc-session/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.baeldung; - -import org.baeldung.spring.MvcConfig; -import org.baeldung.spring.SecSecurityConfig; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { MvcConfig.class, SecSecurityConfig.class }) -@WebAppConfiguration -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} From d3ed9d75fd959cbba33c09d6d4f4d391fb8693cb Mon Sep 17 00:00:00 2001 From: Alessio Stalla Date: Wed, 24 Jul 2019 23:32:58 +0200 Subject: [PATCH 46/84] Tests for BAEL-2991 --- persistence-modules/java-sql2o/README.md | 3 + persistence-modules/java-sql2o/pom.xml | 55 +++ .../jdbi/Sql2oIntegrationTest.java | 343 ++++++++++++++++++ persistence-modules/pom.xml | 1 + 4 files changed, 402 insertions(+) create mode 100644 persistence-modules/java-sql2o/README.md create mode 100644 persistence-modules/java-sql2o/pom.xml create mode 100644 persistence-modules/java-sql2o/src/test/java/com/baeldung/persistence/jdbi/Sql2oIntegrationTest.java diff --git a/persistence-modules/java-sql2o/README.md b/persistence-modules/java-sql2o/README.md new file mode 100644 index 0000000000..4c1ff931ce --- /dev/null +++ b/persistence-modules/java-sql2o/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [A Guide to Jdbi](http://www.baeldung.com/jdbi) diff --git a/persistence-modules/java-sql2o/pom.xml b/persistence-modules/java-sql2o/pom.xml new file mode 100644 index 0000000000..54838c32cb --- /dev/null +++ b/persistence-modules/java-sql2o/pom.xml @@ -0,0 +1,55 @@ + + + 4.0.0 + com.baeldung + java-sql2o + 1.0-SNAPSHOT + + + + org.apache.maven.plugins + maven-compiler-plugin + + 8 + 8 + + + + + java-sql2o + + + + + + org.sql2o + sql2o + ${sql2o.version} + + + org.hsqldb + hsqldb + ${hsqldb.version} + test + + + junit + junit + ${junit.version} + test + + + + + 2.4.0 + 4.12 + 1.6.0 + + + diff --git a/persistence-modules/java-sql2o/src/test/java/com/baeldung/persistence/jdbi/Sql2oIntegrationTest.java b/persistence-modules/java-sql2o/src/test/java/com/baeldung/persistence/jdbi/Sql2oIntegrationTest.java new file mode 100644 index 0000000000..56f2e3a62e --- /dev/null +++ b/persistence-modules/java-sql2o/src/test/java/com/baeldung/persistence/jdbi/Sql2oIntegrationTest.java @@ -0,0 +1,343 @@ +package com.baeldung.persistence.jdbi; + +import org.junit.Test; +import org.sql2o.Connection; +import org.sql2o.Query; +import org.sql2o.ResultSetIterable; +import org.sql2o.Sql2o; +import org.sql2o.data.Row; +import org.sql2o.data.Table; + +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.function.Supplier; +import java.util.stream.Stream; + +import static org.junit.Assert.*; + +public class Sql2oIntegrationTest { + + @Test + public void whenSql2oCreated_thenSuccess() { + Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", ""); + try(Connection connection = sql2o.open()) { + java.sql.Connection jdbcConnection = connection.getJdbcConnection(); + assertFalse(jdbcConnection.isClosed()); + } catch (SQLException e) { + fail(e.getMessage()); + } + } + + @Test + public void whenTableCreated_thenInsertIsPossible() { + Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", ""); + try(Connection connection = sql2o.open()) { + connection.createQuery("create table PROJECT_1 (id integer identity, name varchar(50), url varchar(100))").executeUpdate(); + assertEquals(0, connection.getResult()); + connection.createQuery("INSERT INTO PROJECT_1 VALUES (1, 'tutorials', 'github.com/eugenp/tutorials')").executeUpdate(); + assertEquals(1, connection.getResult()); + connection.createQuery("drop table PROJECT_1").executeUpdate(); + } + } + + @Test + public void whenIdentityColumn_thenInsertReturnsNewId() { + Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", ""); + try(Connection connection = sql2o.open()) { + connection.createQuery("create table PROJECT_2 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate(); + Query query = connection.createQuery( + "INSERT INTO PROJECT_2 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')", + true); + assertEquals(0, query.executeUpdate().getKey()); + query = connection.createQuery("INSERT INTO PROJECT_2 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')", + true); + assertEquals(1, query.executeUpdate().getKeys()[0]); + connection.createQuery("drop table PROJECT_2").executeUpdate(); + } + } + + @Test + public void whenSelect_thenResultsAreObjects() { + Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", ""); + try(Connection connection = sql2o.open()) { + connection.createQuery("create table PROJECT_3 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_3 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_3 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')").executeUpdate(); + Query query = connection.createQuery("select * from PROJECT_3 order by id"); + List list = query.executeAndFetch(Project.class); + + assertEquals("tutorials", list.get(0).getName()); + assertEquals("REST with Spring", list.get(1).getName()); + + connection.createQuery("drop table PROJECT_3").executeUpdate(); + } + } + + @Test + public void whenSelectAlias_thenResultsAreObjects() { + Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", ""); + try(Connection connection = sql2o.open()) { + connection.createQuery("create table PROJECT_4 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100), creation_date date)").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_4 (NAME, URL, creation_date) VALUES ('tutorials', 'github.com/eugenp/tutorials', '2019-01-01')").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_4 (NAME, URL, creation_date) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring', '2019-02-01')").executeUpdate(); + Query query = connection.createQuery("select NAME, URL, creation_date as creationDate from PROJECT_4 order by id"); + List list = query.executeAndFetch(Project.class); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + assertEquals("2019-01-01", sdf.format(list.get(0).getCreationDate())); + assertEquals("2019-02-01", sdf.format(list.get(1).getCreationDate())); + + connection.createQuery("drop table PROJECT_4").executeUpdate(); + } + } + + @Test + public void whenSelectMapping_thenResultsAreObjects() { + Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", ""); + try(Connection connection = sql2o.open()) { + connection.createQuery("create table PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100), creation_date date)").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_5 (NAME, URL, creation_date) VALUES ('tutorials', 'github.com/eugenp/tutorials', '2019-01-01')").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_5 (NAME, URL, creation_date) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring', '2019-02-01')").executeUpdate(); + Query query = connection.createQuery("select * from PROJECT_5 order by id") + .addColumnMapping("CrEaTiOn_date", "creationDate"); + List list = query.executeAndFetch(Project.class); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + assertEquals("2019-01-01", sdf.format(list.get(0).getCreationDate())); + assertEquals("2019-02-01", sdf.format(list.get(1).getCreationDate())); + + connection.createQuery("drop table PROJECT_5").executeUpdate(); + } + } + + @Test + public void whenSelectCount_thenResultIsScalar() { + Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", ""); + try(Connection connection = sql2o.open()) { + connection.createQuery("create table PROJECT_6 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100), creation_date date)").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_6 (NAME, URL, creation_date) VALUES ('tutorials', 'github.com/eugenp/tutorials', '2019-01-01')").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_6 (NAME, URL, creation_date) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring', '2019-02-01')").executeUpdate(); + Query query = connection.createQuery("select count(*) from PROJECT_6"); + assertEquals(2.0, query.executeScalar(Double.TYPE), 0.001); + connection.createQuery("drop table PROJECT_6").executeUpdate(); + } + } + + @Test + public void whenFetchTable_thenResultsAreMaps() { + Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", ""); + try(Connection connection = sql2o.open()) { + connection.createQuery("create table PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100), creation_date date)").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_5 (NAME, URL, creation_date) VALUES ('tutorials', 'github.com/eugenp/tutorials', '2019-01-01')").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_5 (NAME, URL, creation_date) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring', '2019-02-01')").executeUpdate(); + Query query = connection.createQuery("select * from PROJECT_5 order by id"); + Table table = query.executeAndFetchTable(); + List> list = table.asList(); + + assertEquals("tutorials", list.get(0).get("name")); + assertEquals("REST with Spring", list.get(1).get("name")); + + connection.createQuery("drop table PROJECT_5").executeUpdate(); + } + } + + @Test + public void whenFetchTable_thenResultsAreRows() { + Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", ""); + try(Connection connection = sql2o.open()) { + connection.createQuery("create table PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100), creation_date date)").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_5 (NAME, URL, creation_date) VALUES ('tutorials', 'github.com/eugenp/tutorials', '2019-01-01')").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_5 (NAME, URL, creation_date) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring', '2019-02-01')").executeUpdate(); + Query query = connection.createQuery("select * from PROJECT_5 order by id"); + Table table = query.executeAndFetchTable(); + List rows = table.rows(); + + assertEquals("tutorials", rows.get(0).getString("name")); + assertEquals("REST with Spring", rows.get(1).getString("name")); + + connection.createQuery("drop table PROJECT_5").executeUpdate(); + } + } + + @Test + public void whenParameters_thenReplacement() { + Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", ""); + try(Connection connection = sql2o.open()) { + connection.createQuery("create table PROJECT_10 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate(); + Query query = connection.createQuery("INSERT INTO PROJECT_10 (NAME, URL) VALUES (:name, :url)") + .addParameter("name", "REST with Spring") + .addParameter("url", "github.com/eugenp/REST-With-Spring"); + assertEquals(1, query.executeUpdate().getResult()); + + List list = connection.createQuery("SELECT * FROM PROJECT_10 WHERE NAME = 'REST with Spring'").executeAndFetch(Project.class); + assertEquals(1, list.size()); + + connection.createQuery("drop table PROJECT_10").executeUpdate(); + } + } + + @Test + public void whenPOJOParameters_thenReplacement() { + Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", ""); + try(Connection connection = sql2o.open()) { + connection.createQuery("create table PROJECT_11 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate(); + + Project project = new Project(); + project.setName("REST with Spring"); + project.setUrl("github.com/eugenp/REST-With-Spring"); + connection.createQuery("INSERT INTO PROJECT_11 (NAME, URL) VALUES (:name, :url)") + .bind(project).executeUpdate(); + assertEquals(1, connection.getResult()); + + List list = connection.createQuery("SELECT * FROM PROJECT_11 WHERE NAME = 'REST with Spring'").executeAndFetch(Project.class); + assertEquals(1, list.size()); + + connection.createQuery("drop table PROJECT_11").executeUpdate(); + } + } + + @Test + public void whenTransactionRollback_thenNoDataInserted() { + Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", ""); + try(Connection connection = sql2o.beginTransaction()) { + connection.createQuery("create table PROJECT_12 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_12 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_12 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')").executeUpdate(); + connection.rollback(); + List> list = connection.createQuery("SELECT * FROM PROJECT_12").executeAndFetchTable().asList(); + assertEquals(0, list.size()); + } + } + + @Test + public void whenTransactionEnds_thenSubsequentStatementsNotRolledBack() { + Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", ""); + try(Connection connection = sql2o.beginTransaction()) { + connection.createQuery("create table PROJECT_13 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_13 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')").executeUpdate(); + List> list = connection.createQuery("SELECT * FROM PROJECT_13").executeAndFetchTable().asList(); + assertEquals(1, list.size()); + connection.rollback(); + list = connection.createQuery("SELECT * FROM PROJECT_13").executeAndFetchTable().asList(); + assertEquals(0, list.size()); + connection.createQuery("INSERT INTO PROJECT_13 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')").executeUpdate(); + list = connection.createQuery("SELECT * FROM PROJECT_13").executeAndFetchTable().asList(); + assertEquals(1, list.size()); + //No implicit rollback + } + try(Connection connection = sql2o.beginTransaction()) { + List> list = connection.createQuery("SELECT * FROM PROJECT_13").executeAndFetchTable().asList(); + assertEquals(1, list.size()); + } + } + + @Test + public void whenTransactionRollbackThenCommit_thenOnlyLastInserted() { + Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", ""); + try(Connection connection = sql2o.beginTransaction()) { + connection.createQuery("create table PROJECT_14 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_14 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')").executeUpdate(); + List> list = connection.createQuery("SELECT * FROM PROJECT_14").executeAndFetchTable().asList(); + assertEquals(1, list.size()); + connection.rollback(false); + list = connection.createQuery("SELECT * FROM PROJECT_14").executeAndFetchTable().asList(); + assertEquals(0, list.size()); + connection.createQuery("INSERT INTO PROJECT_14 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')").executeUpdate(); + list = connection.createQuery("SELECT * FROM PROJECT_14").executeAndFetchTable().asList(); + assertEquals(1, list.size()); + //Implicit rollback + } + try(Connection connection = sql2o.beginTransaction()) { + List> list = connection.createQuery("SELECT * FROM PROJECT_14").executeAndFetchTable().asList(); + assertEquals(0, list.size()); + connection.createQuery("INSERT INTO PROJECT_14 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_14 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')").executeUpdate(); + connection.commit(); + list = connection.createQuery("SELECT * FROM PROJECT_14").executeAndFetchTable().asList(); + assertEquals(2, list.size()); + } + try(Connection connection = sql2o.beginTransaction()) { + List> list = connection.createQuery("SELECT * FROM PROJECT_14").executeAndFetchTable().asList(); + assertEquals(2, list.size()); + } + } + + @Test + public void whenBatch_thenMultipleInserts() { + Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", ""); + try(Connection connection = sql2o.beginTransaction()) { + connection.createQuery("create table PROJECT_15 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate(); + Query query = connection.createQuery("INSERT INTO PROJECT_15 (NAME, URL) VALUES (:name, :url)"); + for(int i = 0; i < 1000; i++) { + query.addParameter("name", "tutorials" + i); + query.addParameter("url", "https://github.com/eugenp/tutorials" + i); + query.addToBatch(); + } + query.executeBatch(); + connection.commit(); + } + try(Connection connection = sql2o.beginTransaction()) { + assertEquals(1000L, connection.createQuery("SELECT count(*) FROM PROJECT_15").executeScalar()); + } + } + + @Test + public void whenLazyFetch_thenResultsAreObjects() { + Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", ""); + try(Connection connection = sql2o.open()) { + connection.createQuery("create table PROJECT_16 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_16 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_16 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')").executeUpdate(); + Query query = connection.createQuery("select * from PROJECT_16 order by id"); + try(ResultSetIterable projects = query.executeAndFetchLazy(Project.class)) { + for(Project p : projects) { + assertNotNull(p.getName()); + assertNotNull(p.getUrl()); + assertNull(p.getCreationDate()); + } + } + connection.createQuery("drop table PROJECT_16").executeUpdate(); + } + } + + static class Project { + private long id; + private String name; + private String url; + private Date creationDate; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public Date getCreationDate() { + return creationDate; + } + + public void setCreationDate(Date creationDate) { + this.creationDate = creationDate; + } + } + + +} diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index 390bcc9d51..5df91b5a8d 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -30,6 +30,7 @@ java-jdbi java-jpa java-mongodb + java-sql2o jnosql liquibase orientdb From 155d3ea52f328f3bb6cfaa98d18fc4671e5a63e2 Mon Sep 17 00:00:00 2001 From: Alessio Stalla Date: Wed, 24 Jul 2019 23:35:22 +0200 Subject: [PATCH 47/84] Fix readme --- persistence-modules/java-sql2o/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/java-sql2o/README.md b/persistence-modules/java-sql2o/README.md index 4c1ff931ce..a86e45f1c8 100644 --- a/persistence-modules/java-sql2o/README.md +++ b/persistence-modules/java-sql2o/README.md @@ -1,3 +1,3 @@ ### Relevant Articles: -- [A Guide to Jdbi](http://www.baeldung.com/jdbi) +- [A Guide to Sql2o](http://www.baeldung.com/sql2o) From 2b5e275716fb5d032c65dba07a4ef846b76cb20c Mon Sep 17 00:00:00 2001 From: Alessio Stalla Date: Wed, 24 Jul 2019 23:35:54 +0200 Subject: [PATCH 48/84] Fix package name --- .../persistence/{jdbi => sql2o}/Sql2oIntegrationTest.java | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) rename persistence-modules/java-sql2o/src/test/java/com/baeldung/persistence/{jdbi => sql2o}/Sql2oIntegrationTest.java (99%) diff --git a/persistence-modules/java-sql2o/src/test/java/com/baeldung/persistence/jdbi/Sql2oIntegrationTest.java b/persistence-modules/java-sql2o/src/test/java/com/baeldung/persistence/sql2o/Sql2oIntegrationTest.java similarity index 99% rename from persistence-modules/java-sql2o/src/test/java/com/baeldung/persistence/jdbi/Sql2oIntegrationTest.java rename to persistence-modules/java-sql2o/src/test/java/com/baeldung/persistence/sql2o/Sql2oIntegrationTest.java index 56f2e3a62e..4429b1578c 100644 --- a/persistence-modules/java-sql2o/src/test/java/com/baeldung/persistence/jdbi/Sql2oIntegrationTest.java +++ b/persistence-modules/java-sql2o/src/test/java/com/baeldung/persistence/sql2o/Sql2oIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.persistence.jdbi; +package com.baeldung.persistence.sql2o; import org.junit.Test; import org.sql2o.Connection; @@ -8,12 +8,9 @@ import org.sql2o.Sql2o; import org.sql2o.data.Row; import org.sql2o.data.Table; -import java.sql.PreparedStatement; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.*; -import java.util.function.Supplier; -import java.util.stream.Stream; import static org.junit.Assert.*; From ffada1e2a749cf5903d28921e4697760f2b9569f Mon Sep 17 00:00:00 2001 From: Justin Albano Date: Thu, 25 Jul 2019 07:52:18 -0400 Subject: [PATCH 49/84] BAEL-3153: Updated code format to match standard Baeldung format Converted tabs into spaces --- .../changecase/ToLowerCaseUnitTest.java | 36 +++++++++---------- .../changecase/ToUpperCaseUnitTest.java | 34 +++++++++--------- 2 files changed, 35 insertions(+), 35 deletions(-) diff --git a/java-strings-2/src/test/java/com/baeldung/string/changecase/ToLowerCaseUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/changecase/ToLowerCaseUnitTest.java index 14102be993..c395b61068 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/changecase/ToLowerCaseUnitTest.java +++ b/java-strings-2/src/test/java/com/baeldung/string/changecase/ToLowerCaseUnitTest.java @@ -7,23 +7,23 @@ import java.util.Locale; import org.junit.Test; public class ToLowerCaseUnitTest { - - private static final Locale TURKISH = new Locale("tr"); - private String name = "John Doe"; - private String foreignUppercase = "\u0049"; - @Test - public void givenMixedCaseString_WhenToLowerCase_ThenResultIsLowerCase() { - assertEquals("john doe", name.toLowerCase()); - } - - @Test - public void givenForeignString_WhenToLowerCaseWithoutLocale_ThenResultIsLowerCase() { - assertEquals("\u0069", foreignUppercase.toLowerCase()); - } - - @Test - public void givenForeignString_WhenToLowerCaseWithLocale_ThenResultIsLowerCase() { - assertEquals("\u0131", foreignUppercase.toLowerCase(TURKISH)); - } + private static final Locale TURKISH = new Locale("tr"); + private String name = "John Doe"; + private String foreignUppercase = "\u0049"; + + @Test + public void givenMixedCaseString_WhenToLowerCase_ThenResultIsLowerCase() { + assertEquals("john doe", name.toLowerCase()); + } + + @Test + public void givenForeignString_WhenToLowerCaseWithoutLocale_ThenResultIsLowerCase() { + assertEquals("\u0069", foreignUppercase.toLowerCase()); + } + + @Test + public void givenForeignString_WhenToLowerCaseWithLocale_ThenResultIsLowerCase() { + assertEquals("\u0131", foreignUppercase.toLowerCase(TURKISH)); + } } diff --git a/java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java index 90b80714a7..365b5ae52f 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java +++ b/java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java @@ -8,22 +8,22 @@ import org.junit.Test; public class ToUpperCaseUnitTest { - private static final Locale TURKISH = new Locale("tr"); - private String name = "John Doe"; - private String foreignUppercase = "\u0069"; + private static final Locale TURKISH = new Locale("tr"); + private String name = "John Doe"; + private String foreignUppercase = "\u0069"; - @Test - public void givenMixedCaseString_WhenToUpperCase_ThenResultIsUpperCase() { - assertEquals("JOHN DOE", name.toUpperCase()); - } - - @Test - public void givenForeignString_WhenToUpperCaseWithoutLocale_ThenResultIsUpperCase() { - assertEquals("\u0049", foreignUppercase.toUpperCase()); - } - - @Test - public void givenForeignString_WhenToUpperCaseWithLocale_ThenResultIsUpperCase() { - assertEquals("\u0130", foreignUppercase.toUpperCase(TURKISH)); - } + @Test + public void givenMixedCaseString_WhenToUpperCase_ThenResultIsUpperCase() { + assertEquals("JOHN DOE", name.toUpperCase()); + } + + @Test + public void givenForeignString_WhenToUpperCaseWithoutLocale_ThenResultIsUpperCase() { + assertEquals("\u0049", foreignUppercase.toUpperCase()); + } + + @Test + public void givenForeignString_WhenToUpperCaseWithLocale_ThenResultIsUpperCase() { + assertEquals("\u0130", foreignUppercase.toUpperCase(TURKISH)); + } } From b981da41c825aeb1bb821c4268cc78b0f8ec9d47 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Thu, 25 Jul 2019 11:40:21 -0300 Subject: [PATCH 50/84] added live tests for session timeout properties --- .../baeldung/web/SessionRestController.java | 17 ++++ .../src/main/resources/application.properties | 2 +- .../SessionConfigurationIntegrationTest.java | 92 +++++++++++++++++++ 3 files changed, 110 insertions(+), 1 deletion(-) create mode 100644 spring-security-mvc-session/src/main/java/com/baeldung/web/SessionRestController.java create mode 100644 spring-security-mvc-session/src/test/java/com/baeldung/session/SessionConfigurationIntegrationTest.java diff --git a/spring-security-mvc-session/src/main/java/com/baeldung/web/SessionRestController.java b/spring-security-mvc-session/src/main/java/com/baeldung/web/SessionRestController.java new file mode 100644 index 0000000000..1353ee25d0 --- /dev/null +++ b/spring-security-mvc-session/src/main/java/com/baeldung/web/SessionRestController.java @@ -0,0 +1,17 @@ +package com.baeldung.web; + +import javax.servlet.http.HttpSession; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class SessionRestController { + + @GetMapping("/session-max-interval") + @ResponseBody + public String retrieveMaxSessionIncativeInterval(HttpSession session) { + return "Max Inactive Interval before Session expires: " + session.getMaxInactiveInterval(); + } +} diff --git a/spring-security-mvc-session/src/main/resources/application.properties b/spring-security-mvc-session/src/main/resources/application.properties index 39ec0a0b27..56b2b7b123 100644 --- a/spring-security-mvc-session/src/main/resources/application.properties +++ b/spring-security-mvc-session/src/main/resources/application.properties @@ -1,4 +1,4 @@ -server.servlet.session.timeout=60s +server.servlet.session.timeout=65s spring.mvc.view.prefix=/WEB-INF/view/ spring.mvc.view.suffix=.jsp diff --git a/spring-security-mvc-session/src/test/java/com/baeldung/session/SessionConfigurationIntegrationTest.java b/spring-security-mvc-session/src/test/java/com/baeldung/session/SessionConfigurationIntegrationTest.java new file mode 100644 index 0000000000..5a9bf72077 --- /dev/null +++ b/spring-security-mvc-session/src/test/java/com/baeldung/session/SessionConfigurationIntegrationTest.java @@ -0,0 +1,92 @@ +package com.baeldung.session; + +import static io.restassured.RestAssured.given; +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Optional; + +import org.junit.Test; +import org.springframework.http.HttpStatus; + +import io.restassured.filter.session.SessionFilter; +import io.restassured.response.Response; +import io.restassured.specification.RequestSpecification; + +/** + * This Live Test requires the service to be up and running. + */ +public class SessionConfigurationIntegrationTest { + + private static final String USER = "user1"; + private static final String PASSWORD = "user1Pass"; + private static final String SESSION_SVC_URL = "http://localhost:8080/session-max-interval"; + + @Test + public void givenValidUser_whenRequestResourceAfterSessionExpiration_thenRedirectedToInvalidSessionUri() throws Exception { + SessionFilter sessionFilter = new SessionFilter(); + simpleSvcRequestLoggingIn(sessionFilter); + Response resp2 = simpleResponseRequestUsingSessionNotFollowingRedirects(sessionFilter); + assertThat(resp2.getStatusCode()).isEqualTo(HttpStatus.OK.value()); + assertThat(resp2.getBody() + .asString()).isEqualTo("Max Inactive Interval before Session expires: 60"); + + // session will be expired in 60 seconds... + Thread.sleep(62000); + Response resp3 = simpleResponseRequestUsingSessionNotFollowingRedirects(sessionFilter); + + assertThat(resp3.getStatusCode()).isEqualTo(HttpStatus.FOUND.value()); + assertThat(resp3.getHeader("Location")).isEqualTo("http://localhost:8080/invalidSession.html"); + } + + @Test + public void givenValidUser_whenLoginMoreThanMaxValidSession_thenRedirectedToExpiredSessionUri() throws Exception { + SessionFilter sessionFilter = new SessionFilter(); + simpleSvcRequestLoggingIn(sessionFilter); + simpleSvcRequestLoggingIn(); + + // this login will expire the first session + simpleSvcRequestLoggingIn(); + + // now try to access a resource using expired session + Response resp4 = given().filter(sessionFilter) + .and() + .redirects() + .follow(false) + .when() + .get(SESSION_SVC_URL); + + assertThat(resp4.getStatusCode()).isEqualTo(HttpStatus.FOUND.value()); + assertThat(resp4.getHeader("Location")).isEqualTo("http://localhost:8080/sessionExpired.html"); + } + + private static void simpleSvcRequestLoggingIn() { + simpleSvcRequestLoggingIn(null); + } + + private static void simpleSvcRequestLoggingIn(SessionFilter sessionFilter) { + Response response = simpleResponseSvcRequestLoggingIn(Optional.ofNullable(sessionFilter)); + + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK.value()); + assertThat(response.getBody() + .asString()).isEqualTo("Max Inactive Interval before Session expires: 60"); + } + + private static Response simpleResponseSvcRequestLoggingIn(Optional sessionFilter) { + RequestSpecification spec = given().auth() + .form(USER, PASSWORD); + sessionFilter.ifPresent(filter -> spec.and() + .filter(filter)); + return spec.when() + .get(SESSION_SVC_URL); + } + + private static Response simpleResponseRequestUsingSessionNotFollowingRedirects(SessionFilter sessionFilter) { + return given().filter(sessionFilter) + .and() + .redirects() + .follow(false) + .when() + .get(SESSION_SVC_URL); + } + +} From 30f4da3dd5b6d29dd64778fa68ab4e51167025c3 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Thu, 25 Jul 2019 12:08:47 -0300 Subject: [PATCH 51/84] renamed spring-security-mvc-session to simply spring-security-mvc --- pom.xml | 6 +++--- .../.gitignore | 0 .../README.md | 0 .../pom.xml | 4 ++-- .../main/java/com/baeldung/SpringSessionApplication.java | 0 .../com/baeldung/monitoring/MetricRegistrySingleton.java | 0 .../security/MySimpleUrlAuthenticationSuccessHandler.java | 0 .../src/main/java/com/baeldung/security/SessionFilter.java | 0 .../src/main/java/com/baeldung/spring/MvcConfig.java | 0 .../main/java/com/baeldung/spring/SecSecurityConfig.java | 0 .../java/com/baeldung/web/SessionListenerWithMetrics.java | 0 .../main/java/com/baeldung/web/SessionRestController.java | 0 .../src/main/resources/application.properties | 0 .../src/main/resources/logback.xml | 0 .../src/main/resources/webSecurityConfig.xml | 0 .../src/main/webapp/WEB-INF/mvc-servlet.xml | 0 .../src/main/webapp/WEB-INF/view/anonymous.jsp | 0 .../src/main/webapp/WEB-INF/view/console.jsp | 0 .../src/main/webapp/WEB-INF/view/homepage.jsp | 0 .../src/main/webapp/WEB-INF/view/invalidSession.jsp | 0 .../src/main/webapp/WEB-INF/view/login.jsp | 0 .../src/main/webapp/WEB-INF/view/sessionExpired.jsp | 0 .../src/main/webapp/WEB-INF/web.xml | 0 .../java/com/baeldung/SpringContextIntegrationTest.java | 0 .../session/SessionConfigurationIntegrationTest.java | 0 .../src/test/resources/.gitignore | 0 26 files changed, 5 insertions(+), 5 deletions(-) rename {spring-security-mvc-session => spring-security-mvc}/.gitignore (100%) rename {spring-security-mvc-session => spring-security-mvc}/README.md (100%) rename {spring-security-mvc-session => spring-security-mvc}/pom.xml (96%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/java/com/baeldung/SpringSessionApplication.java (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/java/com/baeldung/monitoring/MetricRegistrySingleton.java (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/java/com/baeldung/security/SessionFilter.java (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/java/com/baeldung/spring/MvcConfig.java (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/java/com/baeldung/spring/SecSecurityConfig.java (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/java/com/baeldung/web/SessionListenerWithMetrics.java (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/java/com/baeldung/web/SessionRestController.java (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/resources/application.properties (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/resources/logback.xml (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/resources/webSecurityConfig.xml (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/webapp/WEB-INF/mvc-servlet.xml (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/webapp/WEB-INF/view/anonymous.jsp (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/webapp/WEB-INF/view/console.jsp (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/webapp/WEB-INF/view/homepage.jsp (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/webapp/WEB-INF/view/invalidSession.jsp (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/webapp/WEB-INF/view/login.jsp (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/webapp/WEB-INF/view/sessionExpired.jsp (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/webapp/WEB-INF/web.xml (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/test/java/com/baeldung/SpringContextIntegrationTest.java (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/test/java/com/baeldung/session/SessionConfigurationIntegrationTest.java (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/test/resources/.gitignore (100%) diff --git a/pom.xml b/pom.xml index 21a42f89d6..81baa611d8 100644 --- a/pom.xml +++ b/pom.xml @@ -741,7 +741,7 @@ spring-security-mvc-ldap spring-security-mvc-login spring-security-mvc-persisted-remember-me - spring-security-mvc-session + spring-security-mvc spring-security-mvc-socket spring-security-openid @@ -916,7 +916,7 @@ spring-security-mvc-digest-auth spring-security-mvc-ldap spring-security-mvc-persisted-remember-me - spring-security-mvc-session + spring-security-mvc spring-security-mvc-socket spring-security-rest spring-security-sso @@ -1407,7 +1407,7 @@ spring-security-mvc-ldap spring-security-mvc-login spring-security-mvc-persisted-remember-me - spring-security-mvc-session + spring-security-mvc spring-security-mvc-socket spring-security-openid diff --git a/spring-security-mvc-session/.gitignore b/spring-security-mvc/.gitignore similarity index 100% rename from spring-security-mvc-session/.gitignore rename to spring-security-mvc/.gitignore diff --git a/spring-security-mvc-session/README.md b/spring-security-mvc/README.md similarity index 100% rename from spring-security-mvc-session/README.md rename to spring-security-mvc/README.md diff --git a/spring-security-mvc-session/pom.xml b/spring-security-mvc/pom.xml similarity index 96% rename from spring-security-mvc-session/pom.xml rename to spring-security-mvc/pom.xml index 5ed7fbecd3..98ad3daa46 100644 --- a/spring-security-mvc-session/pom.xml +++ b/spring-security-mvc/pom.xml @@ -3,9 +3,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung - spring-security-mvc-session + spring-security-mvc 0.1-SNAPSHOT - spring-security-mvc-session + spring-security-mvc jar diff --git a/spring-security-mvc-session/src/main/java/com/baeldung/SpringSessionApplication.java b/spring-security-mvc/src/main/java/com/baeldung/SpringSessionApplication.java similarity index 100% rename from spring-security-mvc-session/src/main/java/com/baeldung/SpringSessionApplication.java rename to spring-security-mvc/src/main/java/com/baeldung/SpringSessionApplication.java diff --git a/spring-security-mvc-session/src/main/java/com/baeldung/monitoring/MetricRegistrySingleton.java b/spring-security-mvc/src/main/java/com/baeldung/monitoring/MetricRegistrySingleton.java similarity index 100% rename from spring-security-mvc-session/src/main/java/com/baeldung/monitoring/MetricRegistrySingleton.java rename to spring-security-mvc/src/main/java/com/baeldung/monitoring/MetricRegistrySingleton.java diff --git a/spring-security-mvc-session/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java b/spring-security-mvc/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java similarity index 100% rename from spring-security-mvc-session/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java rename to spring-security-mvc/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java diff --git a/spring-security-mvc-session/src/main/java/com/baeldung/security/SessionFilter.java b/spring-security-mvc/src/main/java/com/baeldung/security/SessionFilter.java similarity index 100% rename from spring-security-mvc-session/src/main/java/com/baeldung/security/SessionFilter.java rename to spring-security-mvc/src/main/java/com/baeldung/security/SessionFilter.java diff --git a/spring-security-mvc-session/src/main/java/com/baeldung/spring/MvcConfig.java b/spring-security-mvc/src/main/java/com/baeldung/spring/MvcConfig.java similarity index 100% rename from spring-security-mvc-session/src/main/java/com/baeldung/spring/MvcConfig.java rename to spring-security-mvc/src/main/java/com/baeldung/spring/MvcConfig.java diff --git a/spring-security-mvc-session/src/main/java/com/baeldung/spring/SecSecurityConfig.java b/spring-security-mvc/src/main/java/com/baeldung/spring/SecSecurityConfig.java similarity index 100% rename from spring-security-mvc-session/src/main/java/com/baeldung/spring/SecSecurityConfig.java rename to spring-security-mvc/src/main/java/com/baeldung/spring/SecSecurityConfig.java diff --git a/spring-security-mvc-session/src/main/java/com/baeldung/web/SessionListenerWithMetrics.java b/spring-security-mvc/src/main/java/com/baeldung/web/SessionListenerWithMetrics.java similarity index 100% rename from spring-security-mvc-session/src/main/java/com/baeldung/web/SessionListenerWithMetrics.java rename to spring-security-mvc/src/main/java/com/baeldung/web/SessionListenerWithMetrics.java diff --git a/spring-security-mvc-session/src/main/java/com/baeldung/web/SessionRestController.java b/spring-security-mvc/src/main/java/com/baeldung/web/SessionRestController.java similarity index 100% rename from spring-security-mvc-session/src/main/java/com/baeldung/web/SessionRestController.java rename to spring-security-mvc/src/main/java/com/baeldung/web/SessionRestController.java diff --git a/spring-security-mvc-session/src/main/resources/application.properties b/spring-security-mvc/src/main/resources/application.properties similarity index 100% rename from spring-security-mvc-session/src/main/resources/application.properties rename to spring-security-mvc/src/main/resources/application.properties diff --git a/spring-security-mvc-session/src/main/resources/logback.xml b/spring-security-mvc/src/main/resources/logback.xml similarity index 100% rename from spring-security-mvc-session/src/main/resources/logback.xml rename to spring-security-mvc/src/main/resources/logback.xml diff --git a/spring-security-mvc-session/src/main/resources/webSecurityConfig.xml b/spring-security-mvc/src/main/resources/webSecurityConfig.xml similarity index 100% rename from spring-security-mvc-session/src/main/resources/webSecurityConfig.xml rename to spring-security-mvc/src/main/resources/webSecurityConfig.xml diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/mvc-servlet.xml b/spring-security-mvc/src/main/webapp/WEB-INF/mvc-servlet.xml similarity index 100% rename from spring-security-mvc-session/src/main/webapp/WEB-INF/mvc-servlet.xml rename to spring-security-mvc/src/main/webapp/WEB-INF/mvc-servlet.xml diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/anonymous.jsp b/spring-security-mvc/src/main/webapp/WEB-INF/view/anonymous.jsp similarity index 100% rename from spring-security-mvc-session/src/main/webapp/WEB-INF/view/anonymous.jsp rename to spring-security-mvc/src/main/webapp/WEB-INF/view/anonymous.jsp diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/console.jsp b/spring-security-mvc/src/main/webapp/WEB-INF/view/console.jsp similarity index 100% rename from spring-security-mvc-session/src/main/webapp/WEB-INF/view/console.jsp rename to spring-security-mvc/src/main/webapp/WEB-INF/view/console.jsp diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/homepage.jsp b/spring-security-mvc/src/main/webapp/WEB-INF/view/homepage.jsp similarity index 100% rename from spring-security-mvc-session/src/main/webapp/WEB-INF/view/homepage.jsp rename to spring-security-mvc/src/main/webapp/WEB-INF/view/homepage.jsp diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/invalidSession.jsp b/spring-security-mvc/src/main/webapp/WEB-INF/view/invalidSession.jsp similarity index 100% rename from spring-security-mvc-session/src/main/webapp/WEB-INF/view/invalidSession.jsp rename to spring-security-mvc/src/main/webapp/WEB-INF/view/invalidSession.jsp diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/login.jsp b/spring-security-mvc/src/main/webapp/WEB-INF/view/login.jsp similarity index 100% rename from spring-security-mvc-session/src/main/webapp/WEB-INF/view/login.jsp rename to spring-security-mvc/src/main/webapp/WEB-INF/view/login.jsp diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/sessionExpired.jsp b/spring-security-mvc/src/main/webapp/WEB-INF/view/sessionExpired.jsp similarity index 100% rename from spring-security-mvc-session/src/main/webapp/WEB-INF/view/sessionExpired.jsp rename to spring-security-mvc/src/main/webapp/WEB-INF/view/sessionExpired.jsp diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/web.xml b/spring-security-mvc/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from spring-security-mvc-session/src/main/webapp/WEB-INF/web.xml rename to spring-security-mvc/src/main/webapp/WEB-INF/web.xml diff --git a/spring-security-mvc-session/src/test/java/com/baeldung/SpringContextIntegrationTest.java b/spring-security-mvc/src/test/java/com/baeldung/SpringContextIntegrationTest.java similarity index 100% rename from spring-security-mvc-session/src/test/java/com/baeldung/SpringContextIntegrationTest.java rename to spring-security-mvc/src/test/java/com/baeldung/SpringContextIntegrationTest.java diff --git a/spring-security-mvc-session/src/test/java/com/baeldung/session/SessionConfigurationIntegrationTest.java b/spring-security-mvc/src/test/java/com/baeldung/session/SessionConfigurationIntegrationTest.java similarity index 100% rename from spring-security-mvc-session/src/test/java/com/baeldung/session/SessionConfigurationIntegrationTest.java rename to spring-security-mvc/src/test/java/com/baeldung/session/SessionConfigurationIntegrationTest.java diff --git a/spring-security-mvc-session/src/test/resources/.gitignore b/spring-security-mvc/src/test/resources/.gitignore similarity index 100% rename from spring-security-mvc-session/src/test/resources/.gitignore rename to spring-security-mvc/src/test/resources/.gitignore From 29e2806ade867f6189db6ba76aa1dbac73bdcf52 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Fri, 26 Jul 2019 00:26:13 +0530 Subject: [PATCH 52/84] [BAEL-10984-1] - Added new URL for MyUIServlet and updated Grid creation logic --- .../java/com/baeldung/introduction/Row.java | 45 +++++++++++++++++++ .../com/baeldung/introduction/VaadinUI.java | 14 +++--- 2 files changed, 54 insertions(+), 5 deletions(-) create mode 100644 vaadin/src/main/java/com/baeldung/introduction/Row.java diff --git a/vaadin/src/main/java/com/baeldung/introduction/Row.java b/vaadin/src/main/java/com/baeldung/introduction/Row.java new file mode 100644 index 0000000000..412a286376 --- /dev/null +++ b/vaadin/src/main/java/com/baeldung/introduction/Row.java @@ -0,0 +1,45 @@ +package com.baeldung.introduction; + +public class Row { + + private String column1; + + private String column2; + + private String column3; + + public Row() { + + } + + public Row(String column1, String column2, String column3) { + super(); + this.column1 = column1; + this.column2 = column2; + this.column3 = column3; + } + + public String getColumn1() { + return column1; + } + + public void setColumn1(String column1) { + this.column1 = column1; + } + + public String getColumn2() { + return column2; + } + + public void setColumn2(String column2) { + this.column2 = column2; + } + + public String getColumn3() { + return column3; + } + + public void setColumn3(String column3) { + this.column3 = column3; + } +} \ No newline at end of file diff --git a/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java b/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java index 68be53b1b3..22ce19f5e0 100644 --- a/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java +++ b/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java @@ -201,10 +201,14 @@ public class VaadinUI extends UI { TwinColSelect twinColSelect = new TwinColSelect("TwinColSelect"); twinColSelect.setItems(numbers); - Grid grid = new Grid("Grid"); - grid.setColumns("Column1", "Column2", "Column3"); - grid.setItems("Item1", "Item2", "Item3"); - grid.setItems("Item4", "Item5", "Item6"); + Grid grid = new Grid(Row.class); + grid.setColumns("column1", "column2", "column3"); + Row row1 = new Row("Item1", "Item2", "Item3"); + Row row2 = new Row("Item4", "Item5", "Item6"); + List rows = new ArrayList(); + rows.add(row1); + rows.add(row2); + grid.setItems(rows); Panel panel = new Panel("Panel"); panel.setContent(grid); @@ -271,7 +275,7 @@ public class VaadinUI extends UI { setContent(verticalLayout); } - @WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true) + @WebServlet(urlPatterns = "/VAADIN/*", name = "MyUIServlet", asyncSupported = true) @VaadinServletConfiguration(ui = VaadinUI.class, productionMode = false) public static class MyUIServlet extends VaadinServlet { } From 5b5733239c06b595649324d744e97c6a2dc97d68 Mon Sep 17 00:00:00 2001 From: DOHA Date: Thu, 25 Jul 2019 23:11:26 +0300 Subject: [PATCH 53/84] depth first search --- .../main/java/com/baeldung/graph/Graph.java | 71 +++++++++++++++++++ .../java/com/baeldung/tree/BinaryTree.java | 63 ++++++++++++++++ .../com/baeldung/graph/GraphUnitTest.java | 31 ++++++++ .../com/baeldung/tree/BinaryTreeUnitTest.java | 6 ++ 4 files changed, 171 insertions(+) create mode 100644 data-structures/src/main/java/com/baeldung/graph/Graph.java create mode 100644 data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java diff --git a/data-structures/src/main/java/com/baeldung/graph/Graph.java b/data-structures/src/main/java/com/baeldung/graph/Graph.java new file mode 100644 index 0000000000..b20301f86f --- /dev/null +++ b/data-structures/src/main/java/com/baeldung/graph/Graph.java @@ -0,0 +1,71 @@ +package com.baeldung.graph; + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +public class Graph { + + private List> neighbours; + private int n; + + public Graph(int n) { + this.n = n; + this.neighbours = new ArrayList>(n); + for (int i = 0; i < n; i++) { + this.neighbours.add(new ArrayList()); + } + } + + public void addEdge(int src, int dest) { + this.neighbours.get(src) + .add(dest); + } + + public void dfsWithoutRecursion(int start) { + Stack stack = new Stack(); + boolean[] isVisited = new boolean[n]; + stack.push(start); + while (!stack.isEmpty()) { + int current = stack.pop(); + isVisited[current] = true; + System.out.print(" " + current); + for (int dest : neighbours.get(current)) { + if (!isVisited[dest]) + stack.push(dest); + } + } + } + + public void dfs(int start) { + boolean[] isVisited = new boolean[n]; + dfsRecursive(start, isVisited); + } + + private void dfsRecursive(int current, boolean[] isVisited) { + isVisited[current] = true; + System.out.print(" " + current); + for (int dest : neighbours.get(current)) { + if (!isVisited[dest]) + dfsRecursive(dest, isVisited); + } + } + + public void topologicalSort(int start) { + Stack result = new Stack(); + boolean[] isVisited = new boolean[n]; + topologicalSortRecursive(start, isVisited, result); + while (!result.isEmpty()) { + System.out.print(" " + result.pop()); + } + } + + private void topologicalSortRecursive(int current, boolean[] isVisited, Stack result) { + isVisited[current] = true; + for (int dest : neighbours.get(current)) { + if (!isVisited[dest]) + topologicalSortRecursive(dest, isVisited, result); + } + result.push(current); + } +} diff --git a/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java b/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java index f435e41afa..ff73ee8e54 100644 --- a/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java +++ b/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java @@ -2,6 +2,7 @@ package com.baeldung.tree; import java.util.LinkedList; import java.util.Queue; +import java.util.Stack; public class BinaryTree { @@ -147,6 +148,68 @@ public class BinaryTree { } } + + public void traverseInOrderWithoutRecursion() { + Stack stack = new Stack(); + Node current = root; + stack.push(root); + while(! stack.isEmpty()) { + while(current.left != null) { + current = current.left; + stack.push(current); + } + current = stack.pop(); + System.out.print(" " + current.value); + if(current.right != null) { + current = current.right; + stack.push(current); + } + } + } + + public void traversePreOrderWithoutRecursion() { + Stack stack = new Stack(); + Node current = root; + stack.push(root); + while(! stack.isEmpty()) { + current = stack.pop(); + System.out.print(" " + current.value); + + if(current.right != null) + stack.push(current.right); + + if(current.left != null) + stack.push(current.left); + } + } + + public void traversePostOrderWithoutRecursion() { + Stack stack = new Stack(); + Node prev = root; + Node current = root; + stack.push(root); + + while (!stack.isEmpty()) { + current = stack.peek(); + boolean hasChild = (current.left != null || current.right != null); + boolean isPrevLastChild = (prev == current.right || (prev == current.left && current.right == null)); + + if (!hasChild || isPrevLastChild) { + current = stack.pop(); + System.out.print(" " + current.value); + prev = current; + } else { + if (current.right != null) { + stack.push(current.right); + } + if (current.left != null) { + stack.push(current.left); + } + } + } + } + + class Node { int value; Node left; diff --git a/data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java b/data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java new file mode 100644 index 0000000000..837f83b494 --- /dev/null +++ b/data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.graph; + +import org.junit.Test; + +public class GraphUnitTest { + + @Test + public void givenDirectedGraph_whenDFS_thenPrintAllValues() { + Graph graph = createDirectedGraph(); + graph.dfs(0); + System.out.println(); + graph.dfsWithoutRecursion(0); + } + + @Test + public void givenDirectedGraph_whenGetTopologicalSort_thenPrintValuesSorted() { + Graph graph = createDirectedGraph(); + graph.topologicalSort(0); + } + + private Graph createDirectedGraph() { + Graph graph = new Graph(6); + graph.addEdge(0, 1); + graph.addEdge(0, 2); + graph.addEdge(1, 3); + graph.addEdge(2, 3); + graph.addEdge(3, 4); + graph.addEdge(4, 5); + return graph; + } +} diff --git a/data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java b/data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java index f81247b74d..f99cb52ed7 100644 --- a/data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java +++ b/data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java @@ -87,6 +87,8 @@ public class BinaryTreeUnitTest { BinaryTree bt = createBinaryTree(); bt.traverseInOrder(bt.root); + System.out.println(); + bt.traverseInOrderWithoutRecursion(); } @Test @@ -95,6 +97,8 @@ public class BinaryTreeUnitTest { BinaryTree bt = createBinaryTree(); bt.traversePreOrder(bt.root); + System.out.println(); + bt.traversePreOrderWithoutRecursion(); } @Test @@ -103,6 +107,8 @@ public class BinaryTreeUnitTest { BinaryTree bt = createBinaryTree(); bt.traversePostOrder(bt.root); + System.out.println(); + bt.traversePostOrderWithoutRecursion(); } @Test From f1d68f74f6298025354adb494feae9f7df5e5d65 Mon Sep 17 00:00:00 2001 From: Krzysztof Majewski Date: Fri, 26 Jul 2019 12:33:04 +0200 Subject: [PATCH 54/84] add new module --- persistence-modules/java-jpa-2/README.md | 1 + persistence-modules/java-jpa-2/pom.xml | 115 ++++++++++++++++++ .../java/com/baeldung/jpa/entity/Article.java | 0 .../java-jpa-2/src/main/resources/logback.xml | 13 ++ persistence-modules/pom.xml | 1 + pom.xml | 2 + 6 files changed, 132 insertions(+) create mode 100644 persistence-modules/java-jpa-2/README.md create mode 100644 persistence-modules/java-jpa-2/pom.xml rename persistence-modules/{java-jpa => java-jpa-2}/src/main/java/com/baeldung/jpa/entity/Article.java (100%) create mode 100644 persistence-modules/java-jpa-2/src/main/resources/logback.xml diff --git a/persistence-modules/java-jpa-2/README.md b/persistence-modules/java-jpa-2/README.md new file mode 100644 index 0000000000..e65ce65a95 --- /dev/null +++ b/persistence-modules/java-jpa-2/README.md @@ -0,0 +1 @@ +# Relevant Articles diff --git a/persistence-modules/java-jpa-2/pom.xml b/persistence-modules/java-jpa-2/pom.xml new file mode 100644 index 0000000000..c8c9a24599 --- /dev/null +++ b/persistence-modules/java-jpa-2/pom.xml @@ -0,0 +1,115 @@ + + + 4.0.0 + java-jpa-2 + java-jpa-2 + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + ../../pom.xml + + + + + org.hibernate + hibernate-core + ${hibernate.version} + + + org.hibernate + hibernate-jpamodelgen + ${hibernate.version} + + + com.h2database + h2 + ${h2.version} + + + + + javax.persistence + javax.persistence-api + ${javax.persistence-api.version} + + + + + org.eclipse.persistence + eclipselink + ${eclipselink.version} + runtime + + + org.postgresql + postgresql + ${postgres.version} + runtime + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + -proc:none + + + + org.bsc.maven + maven-processor-plugin + 3.3.3 + + + process + + process + + generate-sources + + target/metamodel + + org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.0.0 + + + add-source + generate-sources + + add-source + + + + target/metamodel + + + + + + + + + + 5.4.0.Final + 2.7.4-RC1 + 42.2.5 + 2.2 + + + diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Article.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/entity/Article.java similarity index 100% rename from persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Article.java rename to persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/entity/Article.java diff --git a/persistence-modules/java-jpa-2/src/main/resources/logback.xml b/persistence-modules/java-jpa-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/java-jpa-2/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index 390bcc9d51..79879fc2ff 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -29,6 +29,7 @@ java-cockroachdb java-jdbi java-jpa + java-jpa-2 java-mongodb jnosql liquibase diff --git a/pom.xml b/pom.xml index 2e34254bf5..a4e74f8423 100644 --- a/pom.xml +++ b/pom.xml @@ -988,6 +988,7 @@ persistence-modules/hibernate5 persistence-modules/hibernate-mapping persistence-modules/java-jpa + persistence-modules/java-jpa-2 persistence-modules/java-mongodb persistence-modules/jnosql @@ -1500,6 +1501,7 @@ persistence-modules/hibernate5 persistence-modules/java-jpa + persistence-modules/java-jpa-2 persistence-modules/java-mongodb persistence-modules/jnosql From 7486e228856e486261a2459276c9969c39c176e3 Mon Sep 17 00:00:00 2001 From: Justin Albano Date: Fri, 26 Jul 2019 11:42:52 -0400 Subject: [PATCH 55/84] =?UTF-8?q?=C2=96BAEL-3153:=20Reverted=20READ=20file?= =?UTF-8?q?=20to=20original=20contents.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- java-strings-2/README.MD | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/java-strings-2/README.MD b/java-strings-2/README.MD index 4db93f64e0..c6d4f0222a 100644 --- a/java-strings-2/README.MD +++ b/java-strings-2/README.MD @@ -1,7 +1,7 @@ -## Relevant Articles - -- [Java Localization – Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting) -- [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring) -- [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords) -- [Blank and Empty Strings in Java](https://www.baeldung.com/java-blank-empty-strings) -- [String Initialization in Java](https://www.baeldung.com/java-string-initialization) +## Relevant Articles + +- [Java Localization – Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting) +- [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring) +- [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords) +- [Blank and Empty Strings in Java](https://www.baeldung.com/java-blank-empty-strings) +- [String Initialization in Java](https://www.baeldung.com/java-string-initialization) From e67462412e8deb5b0a23ed162ce82c5b8ecaf097 Mon Sep 17 00:00:00 2001 From: Justin Albano Date: Fri, 26 Jul 2019 23:33:34 -0400 Subject: [PATCH 56/84] BAEL-3153: Corrected name of foreign lower case variable in tests --- .../com/baeldung/string/changecase/ToUpperCaseUnitTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java index 365b5ae52f..1807f854b2 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java +++ b/java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java @@ -10,7 +10,7 @@ public class ToUpperCaseUnitTest { private static final Locale TURKISH = new Locale("tr"); private String name = "John Doe"; - private String foreignUppercase = "\u0069"; + private String foreignLowercase = "\u0069"; @Test public void givenMixedCaseString_WhenToUpperCase_ThenResultIsUpperCase() { @@ -19,11 +19,11 @@ public class ToUpperCaseUnitTest { @Test public void givenForeignString_WhenToUpperCaseWithoutLocale_ThenResultIsUpperCase() { - assertEquals("\u0049", foreignUppercase.toUpperCase()); + assertEquals("\u0049", foreignLowercase.toUpperCase()); } @Test public void givenForeignString_WhenToUpperCaseWithLocale_ThenResultIsUpperCase() { - assertEquals("\u0130", foreignUppercase.toUpperCase(TURKISH)); + assertEquals("\u0130", foreignLowercase.toUpperCase(TURKISH)); } } From f1232810e2f3b569a72ce145d2e4d08ba072e0ea Mon Sep 17 00:00:00 2001 From: rpvilao Date: Sat, 27 Jul 2019 09:40:59 +0200 Subject: [PATCH 57/84] Fixes the parent boot (#7409) --- parent-boot-performance/README.md | 1 - parent-boot-performance/pom.xml | 92 ------------------------------- spring-boot-performance/pom.xml | 6 +- 3 files changed, 3 insertions(+), 96 deletions(-) delete mode 100644 parent-boot-performance/README.md delete mode 100644 parent-boot-performance/pom.xml diff --git a/parent-boot-performance/README.md b/parent-boot-performance/README.md deleted file mode 100644 index fce9e101da..0000000000 --- a/parent-boot-performance/README.md +++ /dev/null @@ -1 +0,0 @@ -This is a parent module for projects that want to take advantage of the latest Spring Boot improvements/features. \ No newline at end of file diff --git a/parent-boot-performance/pom.xml b/parent-boot-performance/pom.xml deleted file mode 100644 index b7d12e2ba4..0000000000 --- a/parent-boot-performance/pom.xml +++ /dev/null @@ -1,92 +0,0 @@ - - 4.0.0 - parent-boot-performance - 0.0.1-SNAPSHOT - parent-boot-performance - pom - Parent for all modules that want to take advantage of the latest Spring Boot improvements/features. Current version: 2.2 - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot.version} - pom - import - - - - - - - io.rest-assured - rest-assured - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot.version} - - ${start-class} - - - - - - - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - - - - - thin-jar - - - - org.springframework.boot - spring-boot-maven-plugin - - - - org.springframework.boot.experimental - spring-boot-thin-layout - ${thin.version} - - - - - - - - - - 3.1.0 - - 1.0.21.RELEASE - 2.2.0.M3 - - diff --git a/spring-boot-performance/pom.xml b/spring-boot-performance/pom.xml index f51df8bc0c..a4efa4a8d7 100644 --- a/spring-boot-performance/pom.xml +++ b/spring-boot-performance/pom.xml @@ -8,10 +8,10 @@ This is a simple Spring Boot application taking advantage of the latest Spring Boot improvements/features. Current version: 2.2 - parent-boot-performance + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-performance + ../parent-boot-2 @@ -42,4 +42,4 @@ com.baeldung.lazyinitialization.Application - \ No newline at end of file + From 8d62e17b8e05f07f14b9fdf3f9c0c86063d13046 Mon Sep 17 00:00:00 2001 From: maryarm <45322329+maryarm@users.noreply.github.com> Date: Sat, 27 Jul 2019 16:50:52 +0430 Subject: [PATCH 58/84] #BAEL-2888- Reloading Properties Files in Spring (#7392) Code samples for BAEL-2888 --- spring-boot-properties/.gitignore | 17 ++ spring-boot-properties/README.md | 2 + spring-boot-properties/extra.properties | 1 + spring-boot-properties/extra2.properties | 1 + spring-boot-properties/pom.xml | 104 +++++++++++ .../SpringBootPropertiesApplication.java | 44 +++++ .../configs/PropertiesException.java | 10 ++ .../configs/ReloadableProperties.java | 49 ++++++ .../configs/ReloadablePropertySource.java | 33 ++++ .../ReloadablePropertySourceConfig.java | 29 ++++ .../ReloadablePropertySourceFactory.java | 25 +++ .../src/main/resources/application.properties | 3 + .../PropertiesReloadIntegrationTest.java | 161 ++++++++++++++++++ .../SpringBootPropertiesTestApplication.java | 28 +++ ...figurationPropertiesRefreshConfigBean.java | 20 +++ .../beans/EnvironmentConfigBean.java | 26 +++ .../beans/PropertiesConfigBean.java | 19 +++ .../beans/ValueRefreshConfigBean.java | 13 ++ .../src/test/resources/application.properties | 3 + 19 files changed, 588 insertions(+) create mode 100644 spring-boot-properties/.gitignore create mode 100644 spring-boot-properties/README.md create mode 100644 spring-boot-properties/extra.properties create mode 100644 spring-boot-properties/extra2.properties create mode 100644 spring-boot-properties/pom.xml create mode 100644 spring-boot-properties/src/main/java/com/baeldung/properties/SpringBootPropertiesApplication.java create mode 100644 spring-boot-properties/src/main/java/com/baeldung/properties/configs/PropertiesException.java create mode 100644 spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadableProperties.java create mode 100644 spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySource.java create mode 100644 spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySourceConfig.java create mode 100644 spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySourceFactory.java create mode 100644 spring-boot-properties/src/main/resources/application.properties create mode 100644 spring-boot-properties/src/test/java/com/baeldung/properties/PropertiesReloadIntegrationTest.java create mode 100644 spring-boot-properties/src/test/java/com/baeldung/properties/SpringBootPropertiesTestApplication.java create mode 100644 spring-boot-properties/src/test/java/com/baeldung/properties/beans/ConfigurationPropertiesRefreshConfigBean.java create mode 100644 spring-boot-properties/src/test/java/com/baeldung/properties/beans/EnvironmentConfigBean.java create mode 100644 spring-boot-properties/src/test/java/com/baeldung/properties/beans/PropertiesConfigBean.java create mode 100644 spring-boot-properties/src/test/java/com/baeldung/properties/beans/ValueRefreshConfigBean.java create mode 100644 spring-boot-properties/src/test/resources/application.properties diff --git a/spring-boot-properties/.gitignore b/spring-boot-properties/.gitignore new file mode 100644 index 0000000000..0532ef1888 --- /dev/null +++ b/spring-boot-properties/.gitignore @@ -0,0 +1,17 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear + +*.ipr +*.iml +*.iws diff --git a/spring-boot-properties/README.md b/spring-boot-properties/README.md new file mode 100644 index 0000000000..c43cf4865c --- /dev/null +++ b/spring-boot-properties/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Reloading Properties in Spring](https://www.baeldung.com/reloading-properties-files-in-spring/) \ No newline at end of file diff --git a/spring-boot-properties/extra.properties b/spring-boot-properties/extra.properties new file mode 100644 index 0000000000..8e28a6f889 --- /dev/null +++ b/spring-boot-properties/extra.properties @@ -0,0 +1 @@ +application.theme.color=blue \ No newline at end of file diff --git a/spring-boot-properties/extra2.properties b/spring-boot-properties/extra2.properties new file mode 100644 index 0000000000..2c46edc584 --- /dev/null +++ b/spring-boot-properties/extra2.properties @@ -0,0 +1 @@ +application.theme.background=red \ No newline at end of file diff --git a/spring-boot-properties/pom.xml b/spring-boot-properties/pom.xml new file mode 100644 index 0000000000..27ac48252b --- /dev/null +++ b/spring-boot-properties/pom.xml @@ -0,0 +1,104 @@ + + + 4.0.0 + spring-boot-properties + jar + spring-boot-properties + Spring Boot Properties Module + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + commons-configuration + commons-configuration + ${commons-configuration.version} + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.cloud + spring-cloud-starter + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + spring-boot-properties + + + src/main/resources + true + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + **/*IntegrationTest.java + **/*IntTest.java + + + + + + + json + + + + + + + + + + 1.8 + Greenwich.SR1 + 1.10 + + + diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/SpringBootPropertiesApplication.java b/spring-boot-properties/src/main/java/com/baeldung/properties/SpringBootPropertiesApplication.java new file mode 100644 index 0000000000..67bbddf9f1 --- /dev/null +++ b/spring-boot-properties/src/main/java/com/baeldung/properties/SpringBootPropertiesApplication.java @@ -0,0 +1,44 @@ +package com.baeldung.properties; + +import com.baeldung.properties.configs.ReloadableProperties; +import java.io.File; +import java.util.Properties; +import org.apache.commons.configuration.PropertiesConfiguration; +import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Primary; + +@SpringBootApplication +public class SpringBootPropertiesApplication { + + @Bean + @ConditionalOnProperty(name = "spring.config.location", matchIfMissing = false) + public PropertiesConfiguration propertiesConfiguration( + @Value("${spring.config.location}") String path, + @Value("${spring.properties.refreshDelay}") long refreshDelay) throws Exception { + String filePath = path.substring("file:".length()); + PropertiesConfiguration configuration = new PropertiesConfiguration(new File(filePath).getCanonicalPath()); + FileChangedReloadingStrategy fileChangedReloadingStrategy = new FileChangedReloadingStrategy(); + fileChangedReloadingStrategy.setRefreshDelay(refreshDelay); + configuration.setReloadingStrategy(fileChangedReloadingStrategy); + return configuration; + } + + @Bean + @ConditionalOnBean(PropertiesConfiguration.class) + @Primary + public Properties properties(PropertiesConfiguration propertiesConfiguration) throws Exception { + ReloadableProperties properties = new ReloadableProperties(propertiesConfiguration); + return properties; + } + + public static void main(String[] args) { + SpringApplication.run(SpringBootPropertiesApplication.class, args); + } + +} diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/configs/PropertiesException.java b/spring-boot-properties/src/main/java/com/baeldung/properties/configs/PropertiesException.java new file mode 100644 index 0000000000..5ec3a042f7 --- /dev/null +++ b/spring-boot-properties/src/main/java/com/baeldung/properties/configs/PropertiesException.java @@ -0,0 +1,10 @@ +package com.baeldung.properties.configs; + +public class PropertiesException extends RuntimeException { + public PropertiesException() { + } + + public PropertiesException(Throwable cause) { + super(cause); + } +} diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadableProperties.java b/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadableProperties.java new file mode 100644 index 0000000000..33d503b9bd --- /dev/null +++ b/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadableProperties.java @@ -0,0 +1,49 @@ +package com.baeldung.properties.configs; + +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.util.Properties; +import javax.naming.OperationNotSupportedException; +import org.apache.commons.configuration.PropertiesConfiguration; + +public class ReloadableProperties extends Properties { + private PropertiesConfiguration propertiesConfiguration; + + public ReloadableProperties(PropertiesConfiguration propertiesConfiguration) throws IOException { + super.load(new FileReader(propertiesConfiguration.getFile())); + this.propertiesConfiguration = propertiesConfiguration; + } + + @Override + public synchronized Object setProperty(String key, String value) { + propertiesConfiguration.setProperty(key, value); + return super.setProperty(key, value); + } + + @Override + public String getProperty(String key) { + String val = propertiesConfiguration.getString(key); + super.setProperty(key, val); + return val; + } + + @Override + public String getProperty(String key, String defaultValue) { + String val = propertiesConfiguration.getString(key, defaultValue); + super.setProperty(key, val); + return val; + } + + @Override + public synchronized void load(Reader reader) throws IOException { + throw new PropertiesException(new OperationNotSupportedException()); + } + + @Override + public synchronized void load(InputStream inStream) throws IOException { + throw new PropertiesException(new OperationNotSupportedException()); + } + +} diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySource.java b/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySource.java new file mode 100644 index 0000000000..8a0cef955f --- /dev/null +++ b/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySource.java @@ -0,0 +1,33 @@ +package com.baeldung.properties.configs; + +import org.apache.commons.configuration.PropertiesConfiguration; +import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy; +import org.springframework.core.env.PropertySource; +import org.springframework.util.StringUtils; + +public class ReloadablePropertySource extends PropertySource { + + PropertiesConfiguration propertiesConfiguration; + + public ReloadablePropertySource(String name, PropertiesConfiguration propertiesConfiguration) { + super(name); + this.propertiesConfiguration = propertiesConfiguration; + } + + public ReloadablePropertySource(String name, String path) { + super(StringUtils.isEmpty(name) ? path : name); + try { + this.propertiesConfiguration = new PropertiesConfiguration(path); + FileChangedReloadingStrategy strategy = new FileChangedReloadingStrategy(); + strategy.setRefreshDelay(1000); + this.propertiesConfiguration.setReloadingStrategy(strategy); + } catch (Exception e) { + throw new PropertiesException(e); + } + } + + @Override + public Object getProperty(String s) { + return propertiesConfiguration.getProperty(s); + } +} diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySourceConfig.java b/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySourceConfig.java new file mode 100644 index 0000000000..37e1a04839 --- /dev/null +++ b/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySourceConfig.java @@ -0,0 +1,29 @@ +package com.baeldung.properties.configs; + +import org.apache.commons.configuration.PropertiesConfiguration; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.MutablePropertySources; + +@Configuration +public class ReloadablePropertySourceConfig { + + private ConfigurableEnvironment env; + + public ReloadablePropertySourceConfig(@Autowired ConfigurableEnvironment env) { + this.env = env; + } + + @Bean + @ConditionalOnProperty(name = "spring.config.location", matchIfMissing = false) + public ReloadablePropertySource reloadablePropertySource(PropertiesConfiguration properties) { + ReloadablePropertySource ret = new ReloadablePropertySource("dynamic", properties); + MutablePropertySources sources = env.getPropertySources(); + sources.addFirst(ret); + return ret; + } + +} diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySourceFactory.java b/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySourceFactory.java new file mode 100644 index 0000000000..574362b3bf --- /dev/null +++ b/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySourceFactory.java @@ -0,0 +1,25 @@ +package com.baeldung.properties.configs; + +import java.io.IOException; +import org.springframework.core.env.PropertySource; +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.io.FileUrlResource; +import org.springframework.core.io.Resource; +import org.springframework.core.io.support.DefaultPropertySourceFactory; +import org.springframework.core.io.support.EncodedResource; + +public class ReloadablePropertySourceFactory extends DefaultPropertySourceFactory { + @Override + public PropertySource createPropertySource(String s, EncodedResource encodedResource) throws IOException { + Resource internal = encodedResource.getResource(); + if (internal instanceof FileSystemResource) { + return new ReloadablePropertySource(s, ((FileSystemResource) internal).getPath()); + } + if (internal instanceof FileUrlResource) { + return new ReloadablePropertySource(s, ((FileUrlResource) internal) + .getURL() + .getPath()); + } + return super.createPropertySource(s, encodedResource); + } +} diff --git a/spring-boot-properties/src/main/resources/application.properties b/spring-boot-properties/src/main/resources/application.properties new file mode 100644 index 0000000000..f976004a04 --- /dev/null +++ b/spring-boot-properties/src/main/resources/application.properties @@ -0,0 +1,3 @@ +management.endpoints.web.exposure.include=refresh +spring.properties.refreshDelay=1000 +spring.config.location=file:extra.properties diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/PropertiesReloadIntegrationTest.java b/spring-boot-properties/src/test/java/com/baeldung/properties/PropertiesReloadIntegrationTest.java new file mode 100644 index 0000000000..a73311ded8 --- /dev/null +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/PropertiesReloadIntegrationTest.java @@ -0,0 +1,161 @@ +package com.baeldung.properties; + +import com.baeldung.properties.beans.ConfigurationPropertiesRefreshConfigBean; +import com.baeldung.properties.beans.EnvironmentConfigBean; +import com.baeldung.properties.beans.PropertiesConfigBean; +import com.baeldung.properties.beans.ValueRefreshConfigBean; +import java.io.FileOutputStream; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = SpringBootPropertiesTestApplication.class) +public class PropertiesReloadIntegrationTest { + + protected MockMvc mvc; + + protected long refreshDelay = 3000; + + @Autowired + WebApplicationContext webApplicationContext; + + @Autowired + ValueRefreshConfigBean valueRefreshConfigBean; + + @Autowired + ConfigurationPropertiesRefreshConfigBean configurationPropertiesRefreshConfigBean; + + @Autowired + EnvironmentConfigBean environmentConfigBean; + + @Autowired + PropertiesConfigBean propertiesConfigBean; + + @Autowired + @Qualifier("singletonValueRefreshConfigBean") + ValueRefreshConfigBean singletonValueRefreshConfigBean; + + + @Before + public void setUp() throws Exception { + mvc = MockMvcBuilders + .webAppContextSetup(webApplicationContext) + .build(); + createConfig("extra.properties", "application.theme.color", "blue"); + createConfig("extra2.properties", "application.theme.background", "red"); + Thread.sleep(refreshDelay); + callRefresh(); + } + + @After + public void tearDown() throws Exception { + createConfig("extra.properties", "application.theme.color", "blue"); + createConfig("extra2.properties", "application.theme.background", "red"); + } + + @Test + public void givenEnvironmentReader_whenColorChanged_thenExpectChangeValue() throws Exception { + Assert.assertEquals("blue", environmentConfigBean.getColor()); + + createConfig("extra.properties", "application.theme.color", "red"); + Thread.sleep(refreshDelay); + + Assert.assertEquals("red", environmentConfigBean.getColor()); + } + + @Test + public void givenEnvironmentReader_whenBackgroundChanged_thenExpectChangeValue() throws Exception { + Assert.assertEquals("red", environmentConfigBean.getBackgroundColor()); + + createConfig("extra2.properties", "application.theme.background", "blue"); + Thread.sleep(refreshDelay); + + Assert.assertEquals("blue", environmentConfigBean.getBackgroundColor()); + } + + @Test + public void givenPropertiesReader_whenColorChanged_thenExpectChangeValue() throws Exception { + Assert.assertEquals("blue", propertiesConfigBean.getColor()); + + createConfig("extra.properties", "application.theme.color", "red"); + Thread.sleep(refreshDelay); + + Assert.assertEquals("red", propertiesConfigBean.getColor()); + } + + @Test + public void givenRefreshScopedValueReader_whenColorChangedAndRefreshCalled_thenExpectChangeValue() throws Exception { + Assert.assertEquals("blue", valueRefreshConfigBean.getColor()); + + createConfig("extra.properties", "application.theme.color", "red"); + Thread.sleep(refreshDelay); + + Assert.assertEquals("blue", valueRefreshConfigBean.getColor()); + + callRefresh(); + + Assert.assertEquals("red", valueRefreshConfigBean.getColor()); + } + + @Test + public void givenSingletonRefreshScopedValueReader_whenColorChangedAndRefreshCalled_thenExpectOldValue() throws Exception { + + Assert.assertEquals("blue", singletonValueRefreshConfigBean.getColor()); + + createConfig("extra.properties", "application.theme.color", "red"); + Thread.sleep(refreshDelay); + + Assert.assertEquals("blue", singletonValueRefreshConfigBean.getColor()); + + callRefresh(); + + Assert.assertEquals("blue", singletonValueRefreshConfigBean.getColor()); + } + + @Test + public void givenRefreshScopedConfigurationPropertiesReader_whenColorChangedAndRefreshCalled_thenExpectChangeValue() throws Exception { + + Assert.assertEquals("blue", configurationPropertiesRefreshConfigBean.getColor()); + + createConfig("extra.properties", "application.theme.color", "red"); + Thread.sleep(refreshDelay); + + Assert.assertEquals("blue", configurationPropertiesRefreshConfigBean.getColor()); + + callRefresh(); + + Assert.assertEquals("red", configurationPropertiesRefreshConfigBean.getColor()); + } + + public void callRefresh() throws Exception { + MvcResult mvcResult = mvc + .perform(MockMvcRequestBuilders + .post("/actuator/refresh") + .accept(MediaType.APPLICATION_JSON_VALUE)) + .andReturn(); + MockHttpServletResponse response = mvcResult.getResponse(); + Assert.assertEquals(response.getStatus(), 200); + } + + public void createConfig(String file, String key, String value) throws Exception { + FileOutputStream fo = new FileOutputStream(file); + fo.write(String + .format("%s=%s", key, value) + .getBytes()); + fo.close(); + } +} diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/SpringBootPropertiesTestApplication.java b/spring-boot-properties/src/test/java/com/baeldung/properties/SpringBootPropertiesTestApplication.java new file mode 100644 index 0000000000..c572a6c053 --- /dev/null +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/SpringBootPropertiesTestApplication.java @@ -0,0 +1,28 @@ +package com.baeldung.properties; + +import com.baeldung.properties.beans.ValueRefreshConfigBean; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Scope; +import org.springframework.test.context.web.WebAppConfiguration; + +@SpringBootApplication +@WebAppConfiguration +public class SpringBootPropertiesTestApplication { + + @Bean("singletonValueRefreshConfigBean") + @RefreshScope + @Scope("singleton") + public ValueRefreshConfigBean singletonValueRefreshConfigBean(@Value("${application.theme.color:null}") String val) { + return new ValueRefreshConfigBean(val); + } + + @Bean + @RefreshScope + public ValueRefreshConfigBean valueRefreshConfigBean(@Value("${application.theme.color:null}") String val) { + return new ValueRefreshConfigBean(val); + } + +} diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/beans/ConfigurationPropertiesRefreshConfigBean.java b/spring-boot-properties/src/test/java/com/baeldung/properties/beans/ConfigurationPropertiesRefreshConfigBean.java new file mode 100644 index 0000000000..31f168fdcc --- /dev/null +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/beans/ConfigurationPropertiesRefreshConfigBean.java @@ -0,0 +1,20 @@ +package com.baeldung.properties.beans; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.stereotype.Component; + +@Component +@ConfigurationProperties(prefix = "application.theme") +@RefreshScope +public class ConfigurationPropertiesRefreshConfigBean { + private String color; + + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } +} diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/beans/EnvironmentConfigBean.java b/spring-boot-properties/src/test/java/com/baeldung/properties/beans/EnvironmentConfigBean.java new file mode 100644 index 0000000000..fef12f8656 --- /dev/null +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/beans/EnvironmentConfigBean.java @@ -0,0 +1,26 @@ +package com.baeldung.properties.beans; + +import com.baeldung.properties.configs.ReloadablePropertySourceFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +@Component +@PropertySource(value = "file:extra2.properties", factory = ReloadablePropertySourceFactory.class) +public class EnvironmentConfigBean { + + private Environment environment; + + public EnvironmentConfigBean(@Autowired Environment environment) { + this.environment = environment; + } + + public String getColor() { + return environment.getProperty("application.theme.color"); + } + + public String getBackgroundColor() { + return environment.getProperty("application.theme.background"); + } +} diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/beans/PropertiesConfigBean.java b/spring-boot-properties/src/test/java/com/baeldung/properties/beans/PropertiesConfigBean.java new file mode 100644 index 0000000000..da773b283a --- /dev/null +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/beans/PropertiesConfigBean.java @@ -0,0 +1,19 @@ +package com.baeldung.properties.beans; + +import java.util.Properties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class PropertiesConfigBean { + + private Properties properties; + + public PropertiesConfigBean(@Autowired Properties properties) { + this.properties = properties; + } + + public String getColor() { + return properties.getProperty("application.theme.color"); + } +} diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/beans/ValueRefreshConfigBean.java b/spring-boot-properties/src/test/java/com/baeldung/properties/beans/ValueRefreshConfigBean.java new file mode 100644 index 0000000000..d806938092 --- /dev/null +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/beans/ValueRefreshConfigBean.java @@ -0,0 +1,13 @@ +package com.baeldung.properties.beans; + +public class ValueRefreshConfigBean { + private String color; + + public ValueRefreshConfigBean(String color) { + this.color = color; + } + + public String getColor() { + return color; + } +} diff --git a/spring-boot-properties/src/test/resources/application.properties b/spring-boot-properties/src/test/resources/application.properties new file mode 100644 index 0000000000..6fc241a106 --- /dev/null +++ b/spring-boot-properties/src/test/resources/application.properties @@ -0,0 +1,3 @@ +management.endpoints.web.exposure.include=refresh +spring.properties.refreshDelay=1000 +spring.config.location=file:extra.properties \ No newline at end of file From 1be61beeb38de84a792550fbd4af889f38eeb086 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sat, 27 Jul 2019 17:58:14 +0530 Subject: [PATCH 59/84] [BAEL-16086] - Moved core-java-arrays module, added missing pom.xml, fixed pmd errors --- .../core-java-arrays-2/.gitignore | 25 ++++++++++ .../core-java-arrays-2}/README.MD | 0 core-java-modules/core-java-arrays-2/pom.xml | 50 +++++++++++++++++++ .../conversions/StreamArrayConversion.java | 0 .../array/looping/LoopDiagonally.java | 0 .../StreamArrayConversionUnitTest.java | 0 .../array/looping/LoopDiagonallyUnitTest.java | 2 +- pom.xml | 2 + 8 files changed, 78 insertions(+), 1 deletion(-) create mode 100644 core-java-modules/core-java-arrays-2/.gitignore rename {core-java-arrays => core-java-modules/core-java-arrays-2}/README.MD (100%) create mode 100644 core-java-modules/core-java-arrays-2/pom.xml rename {core-java-arrays => core-java-modules/core-java-arrays-2}/src/main/java/com/baeldung/array/conversions/StreamArrayConversion.java (100%) rename {core-java-arrays => core-java-modules/core-java-arrays-2}/src/main/java/com/baeldung/array/looping/LoopDiagonally.java (100%) rename {core-java-arrays => core-java-modules/core-java-arrays-2}/src/test/java/com/baeldung/array/conversions/StreamArrayConversionUnitTest.java (100%) rename core-java-arrays/src/test/java/com/baeldung/array/looping/LoopDiagonallyTest.java => core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/looping/LoopDiagonallyUnitTest.java (92%) diff --git a/core-java-modules/core-java-arrays-2/.gitignore b/core-java-modules/core-java-arrays-2/.gitignore new file mode 100644 index 0000000000..374c8bf907 --- /dev/null +++ b/core-java-modules/core-java-arrays-2/.gitignore @@ -0,0 +1,25 @@ +*.class + +0.* + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* +.resourceCache + +# Packaged files # +*.jar +*.war +*.ear + +# Files generated by integration tests +backup-pom.xml +/bin/ +/temp + +#IntelliJ specific +.idea/ +*.iml \ No newline at end of file diff --git a/core-java-arrays/README.MD b/core-java-modules/core-java-arrays-2/README.MD similarity index 100% rename from core-java-arrays/README.MD rename to core-java-modules/core-java-arrays-2/README.MD diff --git a/core-java-modules/core-java-arrays-2/pom.xml b/core-java-modules/core-java-arrays-2/pom.xml new file mode 100644 index 0000000000..bfe8a349e1 --- /dev/null +++ b/core-java-modules/core-java-arrays-2/pom.xml @@ -0,0 +1,50 @@ + + 4.0.0 + com.baeldung + core-java-arrays-2 + 0.1.0-SNAPSHOT + core-java-arrays-2 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + + + core-java-arrays-2 + + + src/main/resources + true + + + + + + + + 3.9 + + 3.10.0 + + + diff --git a/core-java-arrays/src/main/java/com/baeldung/array/conversions/StreamArrayConversion.java b/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/conversions/StreamArrayConversion.java similarity index 100% rename from core-java-arrays/src/main/java/com/baeldung/array/conversions/StreamArrayConversion.java rename to core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/conversions/StreamArrayConversion.java diff --git a/core-java-arrays/src/main/java/com/baeldung/array/looping/LoopDiagonally.java b/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/looping/LoopDiagonally.java similarity index 100% rename from core-java-arrays/src/main/java/com/baeldung/array/looping/LoopDiagonally.java rename to core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/looping/LoopDiagonally.java diff --git a/core-java-arrays/src/test/java/com/baeldung/array/conversions/StreamArrayConversionUnitTest.java b/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/conversions/StreamArrayConversionUnitTest.java similarity index 100% rename from core-java-arrays/src/test/java/com/baeldung/array/conversions/StreamArrayConversionUnitTest.java rename to core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/conversions/StreamArrayConversionUnitTest.java diff --git a/core-java-arrays/src/test/java/com/baeldung/array/looping/LoopDiagonallyTest.java b/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/looping/LoopDiagonallyUnitTest.java similarity index 92% rename from core-java-arrays/src/test/java/com/baeldung/array/looping/LoopDiagonallyTest.java rename to core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/looping/LoopDiagonallyUnitTest.java index df6079270b..5f670f4a59 100644 --- a/core-java-arrays/src/test/java/com/baeldung/array/looping/LoopDiagonallyTest.java +++ b/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/looping/LoopDiagonallyUnitTest.java @@ -4,7 +4,7 @@ import org.junit.Test; import static org.junit.Assert.assertEquals; -public class LoopDiagonallyTest { +public class LoopDiagonallyUnitTest { @Test public void twoArrayIsLoopedDiagonallyAsExpected() { diff --git a/pom.xml b/pom.xml index c46a9a5d5a..6cdb35063e 100644 --- a/pom.xml +++ b/pom.xml @@ -392,6 +392,7 @@ core-java-modules/core-java-arrays + core-java-modules/core-java-arrays-2 core-java-modules/core-java-collections core-java-modules/core-java-collections-list core-java-modules/core-java-collections-list-2 @@ -1088,6 +1089,7 @@ core-java-modules/core-java-arrays + core-java-modules/core-java-arrays-2 core-java-modules/core-java-collections core-java-modules/core-java-collections-list core-java-modules/core-java-collections-list-2 From 49cfd94439b2283051ab2587043544e97b0a740e Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sat, 27 Jul 2019 18:06:02 +0530 Subject: [PATCH 60/84] [BAEL-15959] - Removed spring-security dependency --- spring-5-mvc/pom.xml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/spring-5-mvc/pom.xml b/spring-5-mvc/pom.xml index 302080a8b4..1d96df3d03 100644 --- a/spring-5-mvc/pom.xml +++ b/spring-5-mvc/pom.xml @@ -23,10 +23,6 @@ org.springframework.boot spring-boot-starter-data-jpa - - org.springframework.boot - spring-boot-starter-security - org.springframework.boot spring-boot-starter-validation From 24135c03cfea302b60a9cd66fc18735f407d5592 Mon Sep 17 00:00:00 2001 From: DOHA Date: Sun, 28 Jul 2019 00:01:06 +0300 Subject: [PATCH 61/84] modify graph implementation --- .../main/java/com/baeldung/graph/Graph.java | 33 ++++++++++--------- .../com/baeldung/graph/GraphUnitTest.java | 8 ++++- 2 files changed, 24 insertions(+), 17 deletions(-) diff --git a/data-structures/src/main/java/com/baeldung/graph/Graph.java b/data-structures/src/main/java/com/baeldung/graph/Graph.java index b20301f86f..16b7e04297 100644 --- a/data-structures/src/main/java/com/baeldung/graph/Graph.java +++ b/data-structures/src/main/java/com/baeldung/graph/Graph.java @@ -1,36 +1,36 @@ package com.baeldung.graph; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Stack; public class Graph { - private List> neighbours; - private int n; + private Map> adjVertices; - public Graph(int n) { - this.n = n; - this.neighbours = new ArrayList>(n); - for (int i = 0; i < n; i++) { - this.neighbours.add(new ArrayList()); - } + public Graph() { + this.adjVertices = new HashMap>(); + } + + public void addVertex(int vertex) { + adjVertices.putIfAbsent(vertex, new ArrayList<>()); } public void addEdge(int src, int dest) { - this.neighbours.get(src) - .add(dest); + adjVertices.get(src).add(dest); } public void dfsWithoutRecursion(int start) { Stack stack = new Stack(); - boolean[] isVisited = new boolean[n]; + boolean[] isVisited = new boolean[adjVertices.size()]; stack.push(start); while (!stack.isEmpty()) { int current = stack.pop(); isVisited[current] = true; System.out.print(" " + current); - for (int dest : neighbours.get(current)) { + for (int dest : adjVertices.get(current)) { if (!isVisited[dest]) stack.push(dest); } @@ -38,14 +38,14 @@ public class Graph { } public void dfs(int start) { - boolean[] isVisited = new boolean[n]; + boolean[] isVisited = new boolean[adjVertices.size()]; dfsRecursive(start, isVisited); } private void dfsRecursive(int current, boolean[] isVisited) { isVisited[current] = true; System.out.print(" " + current); - for (int dest : neighbours.get(current)) { + for (int dest : adjVertices.get(current)) { if (!isVisited[dest]) dfsRecursive(dest, isVisited); } @@ -53,7 +53,7 @@ public class Graph { public void topologicalSort(int start) { Stack result = new Stack(); - boolean[] isVisited = new boolean[n]; + boolean[] isVisited = new boolean[adjVertices.size()]; topologicalSortRecursive(start, isVisited, result); while (!result.isEmpty()) { System.out.print(" " + result.pop()); @@ -62,10 +62,11 @@ public class Graph { private void topologicalSortRecursive(int current, boolean[] isVisited, Stack result) { isVisited[current] = true; - for (int dest : neighbours.get(current)) { + for (int dest : adjVertices.get(current)) { if (!isVisited[dest]) topologicalSortRecursive(dest, isVisited, result); } result.push(current); } + } diff --git a/data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java b/data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java index 837f83b494..249cb6e093 100644 --- a/data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java +++ b/data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java @@ -19,7 +19,13 @@ public class GraphUnitTest { } private Graph createDirectedGraph() { - Graph graph = new Graph(6); + Graph graph = new Graph(); + graph.addVertex(0); + graph.addVertex(1); + graph.addVertex(2); + graph.addVertex(3); + graph.addVertex(4); + graph.addVertex(5); graph.addEdge(0, 1); graph.addEdge(0, 2); graph.addEdge(1, 3); From c4110e5fe8a297c9688f6530de973b443382808f Mon Sep 17 00:00:00 2001 From: Devender Kumar <47500074+kumar-devender@users.noreply.github.com> Date: Sun, 28 Jul 2019 06:19:16 +0200 Subject: [PATCH 62/84] Added big decimal validation (#7379) * Added cascading type mudule * fix compile error * updated dependency version in pom * Added BigDecimal validation classes * Updated test cases * Remove syso from test cases * Updated test cases --- .../bigdecimal/Invoice.java | 19 ++++++ .../bigdecimal/InvoiceUnitTest.java | 62 +++++++++++++++++++ .../jpa-hibernate-cascade-type/pom.xml | 8 +-- 3 files changed, 85 insertions(+), 4 deletions(-) create mode 100644 javaxval/src/main/java/org/baeldung/javabeanconstraints/bigdecimal/Invoice.java create mode 100644 javaxval/src/test/java/org/baeldung/javabeanconstraints/bigdecimal/InvoiceUnitTest.java diff --git a/javaxval/src/main/java/org/baeldung/javabeanconstraints/bigdecimal/Invoice.java b/javaxval/src/main/java/org/baeldung/javabeanconstraints/bigdecimal/Invoice.java new file mode 100644 index 0000000000..6df1b79a60 --- /dev/null +++ b/javaxval/src/main/java/org/baeldung/javabeanconstraints/bigdecimal/Invoice.java @@ -0,0 +1,19 @@ +package org.baeldung.javabeanconstraints.bigdecimal; + +import java.math.BigDecimal; + +import javax.validation.constraints.DecimalMin; +import javax.validation.constraints.Digits; + +public class Invoice { + + @DecimalMin(value = "0.0", inclusive = false) + @Digits(integer=3, fraction=2) + private BigDecimal price; + private String description; + + public Invoice(BigDecimal price, String description) { + this.price = price; + this.description = description; + } +} diff --git a/javaxval/src/test/java/org/baeldung/javabeanconstraints/bigdecimal/InvoiceUnitTest.java b/javaxval/src/test/java/org/baeldung/javabeanconstraints/bigdecimal/InvoiceUnitTest.java new file mode 100644 index 0000000000..525dd7d1ad --- /dev/null +++ b/javaxval/src/test/java/org/baeldung/javabeanconstraints/bigdecimal/InvoiceUnitTest.java @@ -0,0 +1,62 @@ +package org.baeldung.javabeanconstraints.bigdecimal; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.math.BigDecimal; +import java.util.Set; + +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; + +import org.junit.BeforeClass; +import org.junit.Test; + +public class InvoiceUnitTest { + + private static Validator validator; + + @BeforeClass + public static void setupValidatorInstance() { + validator = Validation.buildDefaultValidatorFactory().getValidator(); + } + + @Test + public void whenPriceIntegerDigitLessThanThreeWithDecimalValue_thenShouldGiveConstraintViolations() { + Invoice invoice = new Invoice(new BigDecimal(10.21), "Book purchased"); + Set> violations = validator.validate(invoice); + assertThat(violations.size()).isEqualTo(1); + violations.forEach(action-> assertThat(action.getMessage()).isEqualTo("numeric value out of bounds (<3 digits>.<2 digits> expected)")); + } + + @Test + public void whenPriceIntegerDigitLessThanThreeWithIntegerValue_thenShouldNotGiveConstraintViolations() { + Invoice invoice = new Invoice(new BigDecimal(10), "Book purchased"); + Set> violations = validator.validate(invoice); + assertThat(violations.size()).isEqualTo(0); + } + + @Test + public void whenPriceIntegerDigitGreaterThanThree_thenShouldGiveConstraintViolations() { + Invoice invoice = new Invoice(new BigDecimal(1021.21), "Book purchased"); + Set> violations = validator.validate(invoice); + assertThat(violations.size()).isEqualTo(1); + violations.forEach(action-> assertThat(action.getMessage()).isEqualTo("numeric value out of bounds (<3 digits>.<2 digits> expected)")); + } + + @Test + public void whenPriceIsZero_thenShouldGiveConstraintViolations() { + Invoice invoice = new Invoice(new BigDecimal(000.00), "Book purchased"); + Set> violations = validator.validate(invoice); + assertThat(violations.size()).isEqualTo(1); + violations.forEach(action-> assertThat(action.getMessage()).isEqualTo("must be greater than 0.0")); + } + + @Test + public void whenPriceIsGreaterThanZero_thenShouldNotGiveConstraintViolations() { + Invoice invoice = new Invoice(new BigDecimal(100.50), "Book purchased"); + Set> violations = validator.validate(invoice); + assertThat(violations.size()).isEqualTo(0); + } + +} diff --git a/persistence-modules/jpa-hibernate-cascade-type/pom.xml b/persistence-modules/jpa-hibernate-cascade-type/pom.xml index a45f297a6b..8cfc2a5fa2 100644 --- a/persistence-modules/jpa-hibernate-cascade-type/pom.xml +++ b/persistence-modules/jpa-hibernate-cascade-type/pom.xml @@ -2,10 +2,6 @@ - jpa-hibernate-cascade-type - 4.0.0 - 1.0.0-SNAPSHOT - com.baeldung parent-modules @@ -13,6 +9,10 @@ ../../ + jpa-hibernate-cascade-type + 4.0.0 + 1.0.0-SNAPSHOT + org.hibernate From 76aa185add844f125c481171236e17a5fcbca07f Mon Sep 17 00:00:00 2001 From: Eugen Date: Sun, 28 Jul 2019 09:32:42 +0300 Subject: [PATCH 63/84] changing case --- {Twitter4J => twitter4J-temp}/README.md | 0 {Twitter4J => twitter4J-temp}/pom.xml | 0 .../src/main/java/com/baeldung/Application.java | 0 {Twitter4J => twitter4J-temp}/src/main/resources/logback.xml | 0 .../src/main/resources/twitter4j.properties | 0 .../src/test/java/com/baeldung/ApplicationIntegrationTest.java | 0 6 files changed, 0 insertions(+), 0 deletions(-) rename {Twitter4J => twitter4J-temp}/README.md (100%) rename {Twitter4J => twitter4J-temp}/pom.xml (100%) rename {Twitter4J => twitter4J-temp}/src/main/java/com/baeldung/Application.java (100%) rename {Twitter4J => twitter4J-temp}/src/main/resources/logback.xml (100%) rename {Twitter4J => twitter4J-temp}/src/main/resources/twitter4j.properties (100%) rename {Twitter4J => twitter4J-temp}/src/test/java/com/baeldung/ApplicationIntegrationTest.java (100%) diff --git a/Twitter4J/README.md b/twitter4J-temp/README.md similarity index 100% rename from Twitter4J/README.md rename to twitter4J-temp/README.md diff --git a/Twitter4J/pom.xml b/twitter4J-temp/pom.xml similarity index 100% rename from Twitter4J/pom.xml rename to twitter4J-temp/pom.xml diff --git a/Twitter4J/src/main/java/com/baeldung/Application.java b/twitter4J-temp/src/main/java/com/baeldung/Application.java similarity index 100% rename from Twitter4J/src/main/java/com/baeldung/Application.java rename to twitter4J-temp/src/main/java/com/baeldung/Application.java diff --git a/Twitter4J/src/main/resources/logback.xml b/twitter4J-temp/src/main/resources/logback.xml similarity index 100% rename from Twitter4J/src/main/resources/logback.xml rename to twitter4J-temp/src/main/resources/logback.xml diff --git a/Twitter4J/src/main/resources/twitter4j.properties b/twitter4J-temp/src/main/resources/twitter4j.properties similarity index 100% rename from Twitter4J/src/main/resources/twitter4j.properties rename to twitter4J-temp/src/main/resources/twitter4j.properties diff --git a/Twitter4J/src/test/java/com/baeldung/ApplicationIntegrationTest.java b/twitter4J-temp/src/test/java/com/baeldung/ApplicationIntegrationTest.java similarity index 100% rename from Twitter4J/src/test/java/com/baeldung/ApplicationIntegrationTest.java rename to twitter4J-temp/src/test/java/com/baeldung/ApplicationIntegrationTest.java From 7502f58b990b8f761d001035e60e8b7751593015 Mon Sep 17 00:00:00 2001 From: Eugen Date: Sun, 28 Jul 2019 09:33:07 +0300 Subject: [PATCH 64/84] changing case --- {twitter4J-temp => twitter4j}/README.md | 0 {twitter4J-temp => twitter4j}/pom.xml | 0 .../src/main/java/com/baeldung/Application.java | 0 {twitter4J-temp => twitter4j}/src/main/resources/logback.xml | 0 .../src/main/resources/twitter4j.properties | 0 .../src/test/java/com/baeldung/ApplicationIntegrationTest.java | 0 6 files changed, 0 insertions(+), 0 deletions(-) rename {twitter4J-temp => twitter4j}/README.md (100%) rename {twitter4J-temp => twitter4j}/pom.xml (100%) rename {twitter4J-temp => twitter4j}/src/main/java/com/baeldung/Application.java (100%) rename {twitter4J-temp => twitter4j}/src/main/resources/logback.xml (100%) rename {twitter4J-temp => twitter4j}/src/main/resources/twitter4j.properties (100%) rename {twitter4J-temp => twitter4j}/src/test/java/com/baeldung/ApplicationIntegrationTest.java (100%) diff --git a/twitter4J-temp/README.md b/twitter4j/README.md similarity index 100% rename from twitter4J-temp/README.md rename to twitter4j/README.md diff --git a/twitter4J-temp/pom.xml b/twitter4j/pom.xml similarity index 100% rename from twitter4J-temp/pom.xml rename to twitter4j/pom.xml diff --git a/twitter4J-temp/src/main/java/com/baeldung/Application.java b/twitter4j/src/main/java/com/baeldung/Application.java similarity index 100% rename from twitter4J-temp/src/main/java/com/baeldung/Application.java rename to twitter4j/src/main/java/com/baeldung/Application.java diff --git a/twitter4J-temp/src/main/resources/logback.xml b/twitter4j/src/main/resources/logback.xml similarity index 100% rename from twitter4J-temp/src/main/resources/logback.xml rename to twitter4j/src/main/resources/logback.xml diff --git a/twitter4J-temp/src/main/resources/twitter4j.properties b/twitter4j/src/main/resources/twitter4j.properties similarity index 100% rename from twitter4J-temp/src/main/resources/twitter4j.properties rename to twitter4j/src/main/resources/twitter4j.properties diff --git a/twitter4J-temp/src/test/java/com/baeldung/ApplicationIntegrationTest.java b/twitter4j/src/test/java/com/baeldung/ApplicationIntegrationTest.java similarity index 100% rename from twitter4J-temp/src/test/java/com/baeldung/ApplicationIntegrationTest.java rename to twitter4j/src/test/java/com/baeldung/ApplicationIntegrationTest.java From b8d65f954b72cb10f2c1ec808195e687c777f086 Mon Sep 17 00:00:00 2001 From: Eugen Date: Sun, 28 Jul 2019 09:34:07 +0300 Subject: [PATCH 65/84] changing case --- {JGit => jgit-temp}/README.md | 0 {JGit => jgit-temp}/pom.xml | 0 .../src/main/java/com/baeldung/jgit/CreateNewRepository.java | 0 .../src/main/java/com/baeldung/jgit/OpenRepository.java | 0 .../src/main/java/com/baeldung/jgit/helper/Helper.java | 0 .../src/main/java/com/baeldung/jgit/porcelain/AddFile.java | 0 .../src/main/java/com/baeldung/jgit/porcelain/CommitAll.java | 0 .../main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java | 0 .../src/main/java/com/baeldung/jgit/porcelain/Log.java | 0 {JGit => jgit-temp}/src/main/resources/logback.xml | 0 .../src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java | 0 .../test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java | 0 12 files changed, 0 insertions(+), 0 deletions(-) rename {JGit => jgit-temp}/README.md (100%) rename {JGit => jgit-temp}/pom.xml (100%) rename {JGit => jgit-temp}/src/main/java/com/baeldung/jgit/CreateNewRepository.java (100%) rename {JGit => jgit-temp}/src/main/java/com/baeldung/jgit/OpenRepository.java (100%) rename {JGit => jgit-temp}/src/main/java/com/baeldung/jgit/helper/Helper.java (100%) rename {JGit => jgit-temp}/src/main/java/com/baeldung/jgit/porcelain/AddFile.java (100%) rename {JGit => jgit-temp}/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java (100%) rename {JGit => jgit-temp}/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java (100%) rename {JGit => jgit-temp}/src/main/java/com/baeldung/jgit/porcelain/Log.java (100%) rename {JGit => jgit-temp}/src/main/resources/logback.xml (100%) rename {JGit => jgit-temp}/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java (100%) rename {JGit => jgit-temp}/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java (100%) diff --git a/JGit/README.md b/jgit-temp/README.md similarity index 100% rename from JGit/README.md rename to jgit-temp/README.md diff --git a/JGit/pom.xml b/jgit-temp/pom.xml similarity index 100% rename from JGit/pom.xml rename to jgit-temp/pom.xml diff --git a/JGit/src/main/java/com/baeldung/jgit/CreateNewRepository.java b/jgit-temp/src/main/java/com/baeldung/jgit/CreateNewRepository.java similarity index 100% rename from JGit/src/main/java/com/baeldung/jgit/CreateNewRepository.java rename to jgit-temp/src/main/java/com/baeldung/jgit/CreateNewRepository.java diff --git a/JGit/src/main/java/com/baeldung/jgit/OpenRepository.java b/jgit-temp/src/main/java/com/baeldung/jgit/OpenRepository.java similarity index 100% rename from JGit/src/main/java/com/baeldung/jgit/OpenRepository.java rename to jgit-temp/src/main/java/com/baeldung/jgit/OpenRepository.java diff --git a/JGit/src/main/java/com/baeldung/jgit/helper/Helper.java b/jgit-temp/src/main/java/com/baeldung/jgit/helper/Helper.java similarity index 100% rename from JGit/src/main/java/com/baeldung/jgit/helper/Helper.java rename to jgit-temp/src/main/java/com/baeldung/jgit/helper/Helper.java diff --git a/JGit/src/main/java/com/baeldung/jgit/porcelain/AddFile.java b/jgit-temp/src/main/java/com/baeldung/jgit/porcelain/AddFile.java similarity index 100% rename from JGit/src/main/java/com/baeldung/jgit/porcelain/AddFile.java rename to jgit-temp/src/main/java/com/baeldung/jgit/porcelain/AddFile.java diff --git a/JGit/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java b/jgit-temp/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java similarity index 100% rename from JGit/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java rename to jgit-temp/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java diff --git a/JGit/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java b/jgit-temp/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java similarity index 100% rename from JGit/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java rename to jgit-temp/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java diff --git a/JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java b/jgit-temp/src/main/java/com/baeldung/jgit/porcelain/Log.java similarity index 100% rename from JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java rename to jgit-temp/src/main/java/com/baeldung/jgit/porcelain/Log.java diff --git a/JGit/src/main/resources/logback.xml b/jgit-temp/src/main/resources/logback.xml similarity index 100% rename from JGit/src/main/resources/logback.xml rename to jgit-temp/src/main/resources/logback.xml diff --git a/JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java b/jgit-temp/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java similarity index 100% rename from JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java rename to jgit-temp/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java diff --git a/JGit/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java b/jgit-temp/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java similarity index 100% rename from JGit/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java rename to jgit-temp/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java From 38b37df87367bbeff2746b634dcaea7576632add Mon Sep 17 00:00:00 2001 From: Eugen Date: Sun, 28 Jul 2019 09:35:40 +0300 Subject: [PATCH 66/84] changing case --- jgit-temp/README.md | 3 - jgit-temp/pom.xml | 53 ------------- .../baeldung/jgit/CreateNewRepository.java | 30 -------- .../com/baeldung/jgit/OpenRepository.java | 65 ---------------- .../java/com/baeldung/jgit/helper/Helper.java | 33 --------- .../com/baeldung/jgit/porcelain/AddFile.java | 36 --------- .../baeldung/jgit/porcelain/CommitAll.java | 51 ------------- .../jgit/porcelain/CreateAndDeleteTag.java | 56 -------------- .../java/com/baeldung/jgit/porcelain/Log.java | 74 ------------------- jgit-temp/src/main/resources/logback.xml | 13 ---- .../baeldung/jgit/JGitBugIntegrationTest.java | 33 --------- .../jgit/porcelain/PorcelainUnitTest.java | 17 ----- 12 files changed, 464 deletions(-) delete mode 100644 jgit-temp/README.md delete mode 100644 jgit-temp/pom.xml delete mode 100644 jgit-temp/src/main/java/com/baeldung/jgit/CreateNewRepository.java delete mode 100644 jgit-temp/src/main/java/com/baeldung/jgit/OpenRepository.java delete mode 100644 jgit-temp/src/main/java/com/baeldung/jgit/helper/Helper.java delete mode 100644 jgit-temp/src/main/java/com/baeldung/jgit/porcelain/AddFile.java delete mode 100644 jgit-temp/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java delete mode 100644 jgit-temp/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java delete mode 100644 jgit-temp/src/main/java/com/baeldung/jgit/porcelain/Log.java delete mode 100644 jgit-temp/src/main/resources/logback.xml delete mode 100644 jgit-temp/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java delete mode 100644 jgit-temp/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java diff --git a/jgit-temp/README.md b/jgit-temp/README.md deleted file mode 100644 index 5c65f1101b..0000000000 --- a/jgit-temp/README.md +++ /dev/null @@ -1,3 +0,0 @@ -## Relevant articles: - -- [A Guide to JGit](http://www.baeldung.com/jgit) diff --git a/jgit-temp/pom.xml b/jgit-temp/pom.xml deleted file mode 100644 index deae1e45e3..0000000000 --- a/jgit-temp/pom.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - 4.0.0 - com.baeldung - JGit - 1.0-SNAPSHOT - JGit - jar - http://maven.apache.org - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - jgit-repository - https://repo.eclipse.org/content/groups/releases/ - - - - - - - org.eclipse.jgit - org.eclipse.jgit - ${org.eclipse.jgit.version} - - - org.eclipse.jgit - org.eclipse.jgit.archive - ${org.eclipse.jgit.version} - - - commons-io - commons-io - ${commons-io.version} - - - org.slf4j - slf4j-simple - ${org.slf4j.version} - - - - - 4.5.0.201609210915-r - - - \ No newline at end of file diff --git a/jgit-temp/src/main/java/com/baeldung/jgit/CreateNewRepository.java b/jgit-temp/src/main/java/com/baeldung/jgit/CreateNewRepository.java deleted file mode 100644 index 1702efc315..0000000000 --- a/jgit-temp/src/main/java/com/baeldung/jgit/CreateNewRepository.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.jgit; - -import java.io.File; -import java.io.IOException; -import org.apache.commons.io.FileUtils; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; - -/** - * Simple snippet which shows how to create a new repository - * - * - */ -public class CreateNewRepository { - - public static void main(String[] args) throws IOException, IllegalStateException, GitAPIException { - // prepare a new folder - File localPath = File.createTempFile("TestGitRepository", ""); - if(!localPath.delete()) { - throw new IOException("Could not delete temporary file " + localPath); - } - - // create the directory - try (Git git = Git.init().setDirectory(localPath).call()) { - System.out.println("Having repository: " + git.getRepository().getDirectory()); - } - - FileUtils.deleteDirectory(localPath); - } -} diff --git a/jgit-temp/src/main/java/com/baeldung/jgit/OpenRepository.java b/jgit-temp/src/main/java/com/baeldung/jgit/OpenRepository.java deleted file mode 100644 index 671df2a844..0000000000 --- a/jgit-temp/src/main/java/com/baeldung/jgit/OpenRepository.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.baeldung.jgit; - -import com.baeldung.jgit.helper.Helper; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.storage.file.FileRepositoryBuilder; -import java.io.File; -import java.io.IOException; - -/** - * Simple snippet which shows how to open an existing repository - * - * - */ -public class OpenRepository { - - public static void main(String[] args) throws IOException, GitAPIException { - // first create a test-repository, the return is including the .get directory here! - File repoDir = createSampleGitRepo(); - - // now open the resulting repository with a FileRepositoryBuilder - FileRepositoryBuilder builder = new FileRepositoryBuilder(); - try (Repository repository = builder.setGitDir(repoDir) - .readEnvironment() // scan environment GIT_* variables - .findGitDir() // scan up the file system tree - .build()) { - System.out.println("Having repository: " + repository.getDirectory()); - - // the Ref holds an ObjectId for any type of object (tree, commit, blob, tree) - Ref head = repository.exactRef("refs/heads/master"); - System.out.println("Ref of refs/heads/master: " + head); - } - } - - private static File createSampleGitRepo() throws IOException, GitAPIException { - try (Repository repository = Helper.createNewRepository()) { - System.out.println("Temporary repository at " + repository.getDirectory()); - - // create the file - File myfile = new File(repository.getDirectory().getParent(), "testfile"); - if(!myfile.createNewFile()) { - throw new IOException("Could not create file " + myfile); - } - - // run the add-call - try (Git git = new Git(repository)) { - git.add() - .addFilepattern("testfile") - .call(); - - - // and then commit the changes - git.commit() - .setMessage("Added testfile") - .call(); - } - - System.out.println("Added file " + myfile + " to repository at " + repository.getDirectory()); - - return repository.getDirectory(); - } - } -} diff --git a/jgit-temp/src/main/java/com/baeldung/jgit/helper/Helper.java b/jgit-temp/src/main/java/com/baeldung/jgit/helper/Helper.java deleted file mode 100644 index 39d7b767d2..0000000000 --- a/jgit-temp/src/main/java/com/baeldung/jgit/helper/Helper.java +++ /dev/null @@ -1,33 +0,0 @@ - -package com.baeldung.jgit.helper; - -import java.io.File; -import java.io.IOException; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.storage.file.FileRepositoryBuilder; - -public class Helper { - - public static Repository openJGitRepository() throws IOException { - FileRepositoryBuilder builder = new FileRepositoryBuilder(); - return builder - .readEnvironment() // scan environment GIT_* variables - .findGitDir() // scan up the file system tree - .build(); - } - - public static Repository createNewRepository() throws IOException { - // prepare a new folder - File localPath = File.createTempFile("TestGitRepository", ""); - if(!localPath.delete()) { - throw new IOException("Could not delete temporary file " + localPath); - } - - // create the directory - Repository repository = FileRepositoryBuilder.create(new File(localPath, ".git")); - repository.create(); - - return repository; - } - -} diff --git a/jgit-temp/src/main/java/com/baeldung/jgit/porcelain/AddFile.java b/jgit-temp/src/main/java/com/baeldung/jgit/porcelain/AddFile.java deleted file mode 100644 index 314366f08c..0000000000 --- a/jgit-temp/src/main/java/com/baeldung/jgit/porcelain/AddFile.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.jgit.porcelain; - -import java.io.File; -import java.io.IOException; -import com.baeldung.jgit.helper.Helper; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Repository; - -/** - * Simple snippet which shows how to add a file to the index - * - * - */ -public class AddFile { - - public static void main(String[] args) throws IOException, GitAPIException { - // prepare a new test-repository - try (Repository repository = Helper.createNewRepository()) { - try (Git git = new Git(repository)) { - // create the file - File myfile = new File(repository.getDirectory().getParent(), "testfile"); - if(!myfile.createNewFile()) { - throw new IOException("Could not create file " + myfile); - } - - // run the add-call - git.add() - .addFilepattern("testfile") - .call(); - - System.out.println("Added file " + myfile + " to repository at " + repository.getDirectory()); - } - } - } -} diff --git a/jgit-temp/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java b/jgit-temp/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java deleted file mode 100644 index 4c0956ebf8..0000000000 --- a/jgit-temp/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.jgit.porcelain; - -import java.io.File; -import java.io.IOException; -import java.io.PrintWriter; -import com.baeldung.jgit.helper.Helper; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Repository; - -/** - * Simple snippet which shows how to commit all files - * - * - */ -public class CommitAll { - - public static void main(String[] args) throws IOException, GitAPIException { - // prepare a new test-repository - try (Repository repository = Helper.createNewRepository()) { - try (Git git = new Git(repository)) { - // create the file - File myfile = new File(repository.getDirectory().getParent(), "testfile"); - if(!myfile.createNewFile()) { - throw new IOException("Could not create file " + myfile); - } - - // Stage all files in the repo including new files - git.add().addFilepattern(".").call(); - - // and then commit the changes. - git.commit() - .setMessage("Commit all changes including additions") - .call(); - - try(PrintWriter writer = new PrintWriter(myfile)) { - writer.append("Hello, world!"); - } - - // Stage all changed files, omitting new files, and commit with one command - git.commit() - .setAll(true) - .setMessage("Commit changes to all files") - .call(); - - - System.out.println("Committed all changes to repository at " + repository.getDirectory()); - } - } - } -} diff --git a/jgit-temp/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java b/jgit-temp/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java deleted file mode 100644 index 0f735daf8c..0000000000 --- a/jgit-temp/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.baeldung.jgit.porcelain; - -import java.io.IOException; -import com.baeldung.jgit.helper.Helper; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.ObjectId; -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; -import org.eclipse.jgit.revwalk.RevWalk; - -/** - * Simple snippet which shows how to create a tag - * - * - */ -public class CreateAndDeleteTag { - - public static void main(String[] args) throws IOException, GitAPIException { - // prepare test-repository - try (Repository repository = Helper.openJGitRepository()) { - try (Git git = new Git(repository)) { - // remove the tag before creating it - git.tagDelete().setTags("tag_for_testing").call(); - - // set it on the current HEAD - Ref tag = git.tag().setName("tag_for_testing").call(); - System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory()); - - // remove the tag again - git.tagDelete().setTags("tag_for_testing").call(); - - // read some other commit and set the tag on it - ObjectId id = repository.resolve("HEAD^"); - try (RevWalk walk = new RevWalk(repository)) { - RevCommit commit = walk.parseCommit(id); - tag = git.tag().setObjectId(commit).setName("tag_for_testing").call(); - System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory()); - - // remove the tag again - git.tagDelete().setTags("tag_for_testing").call(); - - // create an annotated tag - tag = git.tag().setName("tag_for_testing").setAnnotated(true).call(); - System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory()); - - // remove the tag again - git.tagDelete().setTags("tag_for_testing").call(); - - walk.dispose(); - } - } - } - } -} diff --git a/jgit-temp/src/main/java/com/baeldung/jgit/porcelain/Log.java b/jgit-temp/src/main/java/com/baeldung/jgit/porcelain/Log.java deleted file mode 100644 index a50028a9ae..0000000000 --- a/jgit-temp/src/main/java/com/baeldung/jgit/porcelain/Log.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.baeldung.jgit.porcelain; - -import java.io.IOException; -import com.baeldung.jgit.helper.Helper; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; - -/** - * Simple snippet which shows how to get the commit-ids for a file to provide log information. - * - * - */ -public class Log { - - @SuppressWarnings("unused") - public static void main(String[] args) throws IOException, GitAPIException { - try (Repository repository = Helper.openJGitRepository()) { - try (Git git = new Git(repository)) { - Iterable logs = git.log() - .call(); - int count = 0; - for (RevCommit rev : logs) { - //System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); - count++; - } - System.out.println("Had " + count + " commits overall on current branch"); - - logs = git.log() - .add(repository.resolve(git.getRepository().getFullBranch())) - .call(); - count = 0; - for (RevCommit rev : logs) { - System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); - count++; - } - System.out.println("Had " + count + " commits overall on "+git.getRepository().getFullBranch()); - - logs = git.log() - .all() - .call(); - count = 0; - for (RevCommit rev : logs) { - //System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); - count++; - } - System.out.println("Had " + count + " commits overall in repository"); - - logs = git.log() - // for all log.all() - .addPath("README.md") - .call(); - count = 0; - for (RevCommit rev : logs) { - //System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); - count++; - } - System.out.println("Had " + count + " commits on README.md"); - - logs = git.log() - // for all log.all() - .addPath("pom.xml") - .call(); - count = 0; - for (RevCommit rev : logs) { - //System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); - count++; - } - System.out.println("Had " + count + " commits on pom.xml"); - } - } - } -} diff --git a/jgit-temp/src/main/resources/logback.xml b/jgit-temp/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/jgit-temp/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/jgit-temp/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java b/jgit-temp/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java deleted file mode 100644 index ad34890996..0000000000 --- a/jgit-temp/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.jgit; - -import com.baeldung.jgit.helper.Helper; -import org.eclipse.jgit.lib.ObjectLoader; -import org.eclipse.jgit.lib.ObjectReader; -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevWalk; -import org.junit.Test; -import java.io.IOException; -import static org.junit.Assert.assertNotNull; - -/** - * Tests which show issues with JGit that we reported upstream. - */ -public class JGitBugIntegrationTest { - @Test - public void testRevWalkDisposeClosesReader() throws IOException { - try (Repository repo = Helper.openJGitRepository()) { - try (ObjectReader reader = repo.newObjectReader()) { - try (RevWalk walk = new RevWalk(reader)) { - walk.dispose(); - - Ref head = repo.exactRef("refs/heads/master"); - System.out.println("Found head: " + head); - - ObjectLoader loader = reader.open(head.getObjectId()); - assertNotNull(loader); - } - } - } - } -} diff --git a/jgit-temp/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java b/jgit-temp/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java deleted file mode 100644 index d3b3358664..0000000000 --- a/jgit-temp/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.jgit.porcelain; - -import org.junit.Test; - -public class PorcelainUnitTest { - @Test - public void runSamples() throws Exception { - // simply call all the samples to see any severe problems with the samples - AddFile.main(null); - - CommitAll.main(null); - - CreateAndDeleteTag.main(null); - - Log.main(null); - } -} From 1db074d22d61b5ebca3ba3d6116ae03cabc48bf1 Mon Sep 17 00:00:00 2001 From: Eugen Date: Sun, 28 Jul 2019 09:35:46 +0300 Subject: [PATCH 67/84] changing case --- jgit/README.md | 3 + jgit/pom.xml | 53 +++++++++++++ .../baeldung/jgit/CreateNewRepository.java | 30 ++++++++ .../com/baeldung/jgit/OpenRepository.java | 65 ++++++++++++++++ .../java/com/baeldung/jgit/helper/Helper.java | 33 +++++++++ .../com/baeldung/jgit/porcelain/AddFile.java | 36 +++++++++ .../baeldung/jgit/porcelain/CommitAll.java | 51 +++++++++++++ .../jgit/porcelain/CreateAndDeleteTag.java | 56 ++++++++++++++ .../java/com/baeldung/jgit/porcelain/Log.java | 74 +++++++++++++++++++ jgit/src/main/resources/logback.xml | 13 ++++ .../baeldung/jgit/JGitBugIntegrationTest.java | 33 +++++++++ .../jgit/porcelain/PorcelainUnitTest.java | 17 +++++ 12 files changed, 464 insertions(+) create mode 100644 jgit/README.md create mode 100644 jgit/pom.xml create mode 100644 jgit/src/main/java/com/baeldung/jgit/CreateNewRepository.java create mode 100644 jgit/src/main/java/com/baeldung/jgit/OpenRepository.java create mode 100644 jgit/src/main/java/com/baeldung/jgit/helper/Helper.java create mode 100644 jgit/src/main/java/com/baeldung/jgit/porcelain/AddFile.java create mode 100644 jgit/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java create mode 100644 jgit/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java create mode 100644 jgit/src/main/java/com/baeldung/jgit/porcelain/Log.java create mode 100644 jgit/src/main/resources/logback.xml create mode 100644 jgit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java create mode 100644 jgit/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java diff --git a/jgit/README.md b/jgit/README.md new file mode 100644 index 0000000000..5c65f1101b --- /dev/null +++ b/jgit/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [A Guide to JGit](http://www.baeldung.com/jgit) diff --git a/jgit/pom.xml b/jgit/pom.xml new file mode 100644 index 0000000000..deae1e45e3 --- /dev/null +++ b/jgit/pom.xml @@ -0,0 +1,53 @@ + + + 4.0.0 + com.baeldung + JGit + 1.0-SNAPSHOT + JGit + jar + http://maven.apache.org + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + jgit-repository + https://repo.eclipse.org/content/groups/releases/ + + + + + + + org.eclipse.jgit + org.eclipse.jgit + ${org.eclipse.jgit.version} + + + org.eclipse.jgit + org.eclipse.jgit.archive + ${org.eclipse.jgit.version} + + + commons-io + commons-io + ${commons-io.version} + + + org.slf4j + slf4j-simple + ${org.slf4j.version} + + + + + 4.5.0.201609210915-r + + + \ No newline at end of file diff --git a/jgit/src/main/java/com/baeldung/jgit/CreateNewRepository.java b/jgit/src/main/java/com/baeldung/jgit/CreateNewRepository.java new file mode 100644 index 0000000000..1702efc315 --- /dev/null +++ b/jgit/src/main/java/com/baeldung/jgit/CreateNewRepository.java @@ -0,0 +1,30 @@ +package com.baeldung.jgit; + +import java.io.File; +import java.io.IOException; +import org.apache.commons.io.FileUtils; +import org.eclipse.jgit.api.Git; +import org.eclipse.jgit.api.errors.GitAPIException; + +/** + * Simple snippet which shows how to create a new repository + * + * + */ +public class CreateNewRepository { + + public static void main(String[] args) throws IOException, IllegalStateException, GitAPIException { + // prepare a new folder + File localPath = File.createTempFile("TestGitRepository", ""); + if(!localPath.delete()) { + throw new IOException("Could not delete temporary file " + localPath); + } + + // create the directory + try (Git git = Git.init().setDirectory(localPath).call()) { + System.out.println("Having repository: " + git.getRepository().getDirectory()); + } + + FileUtils.deleteDirectory(localPath); + } +} diff --git a/jgit/src/main/java/com/baeldung/jgit/OpenRepository.java b/jgit/src/main/java/com/baeldung/jgit/OpenRepository.java new file mode 100644 index 0000000000..671df2a844 --- /dev/null +++ b/jgit/src/main/java/com/baeldung/jgit/OpenRepository.java @@ -0,0 +1,65 @@ +package com.baeldung.jgit; + +import com.baeldung.jgit.helper.Helper; +import org.eclipse.jgit.api.Git; +import org.eclipse.jgit.api.errors.GitAPIException; +import org.eclipse.jgit.lib.Ref; +import org.eclipse.jgit.lib.Repository; +import org.eclipse.jgit.storage.file.FileRepositoryBuilder; +import java.io.File; +import java.io.IOException; + +/** + * Simple snippet which shows how to open an existing repository + * + * + */ +public class OpenRepository { + + public static void main(String[] args) throws IOException, GitAPIException { + // first create a test-repository, the return is including the .get directory here! + File repoDir = createSampleGitRepo(); + + // now open the resulting repository with a FileRepositoryBuilder + FileRepositoryBuilder builder = new FileRepositoryBuilder(); + try (Repository repository = builder.setGitDir(repoDir) + .readEnvironment() // scan environment GIT_* variables + .findGitDir() // scan up the file system tree + .build()) { + System.out.println("Having repository: " + repository.getDirectory()); + + // the Ref holds an ObjectId for any type of object (tree, commit, blob, tree) + Ref head = repository.exactRef("refs/heads/master"); + System.out.println("Ref of refs/heads/master: " + head); + } + } + + private static File createSampleGitRepo() throws IOException, GitAPIException { + try (Repository repository = Helper.createNewRepository()) { + System.out.println("Temporary repository at " + repository.getDirectory()); + + // create the file + File myfile = new File(repository.getDirectory().getParent(), "testfile"); + if(!myfile.createNewFile()) { + throw new IOException("Could not create file " + myfile); + } + + // run the add-call + try (Git git = new Git(repository)) { + git.add() + .addFilepattern("testfile") + .call(); + + + // and then commit the changes + git.commit() + .setMessage("Added testfile") + .call(); + } + + System.out.println("Added file " + myfile + " to repository at " + repository.getDirectory()); + + return repository.getDirectory(); + } + } +} diff --git a/jgit/src/main/java/com/baeldung/jgit/helper/Helper.java b/jgit/src/main/java/com/baeldung/jgit/helper/Helper.java new file mode 100644 index 0000000000..39d7b767d2 --- /dev/null +++ b/jgit/src/main/java/com/baeldung/jgit/helper/Helper.java @@ -0,0 +1,33 @@ + +package com.baeldung.jgit.helper; + +import java.io.File; +import java.io.IOException; +import org.eclipse.jgit.lib.Repository; +import org.eclipse.jgit.storage.file.FileRepositoryBuilder; + +public class Helper { + + public static Repository openJGitRepository() throws IOException { + FileRepositoryBuilder builder = new FileRepositoryBuilder(); + return builder + .readEnvironment() // scan environment GIT_* variables + .findGitDir() // scan up the file system tree + .build(); + } + + public static Repository createNewRepository() throws IOException { + // prepare a new folder + File localPath = File.createTempFile("TestGitRepository", ""); + if(!localPath.delete()) { + throw new IOException("Could not delete temporary file " + localPath); + } + + // create the directory + Repository repository = FileRepositoryBuilder.create(new File(localPath, ".git")); + repository.create(); + + return repository; + } + +} diff --git a/jgit/src/main/java/com/baeldung/jgit/porcelain/AddFile.java b/jgit/src/main/java/com/baeldung/jgit/porcelain/AddFile.java new file mode 100644 index 0000000000..314366f08c --- /dev/null +++ b/jgit/src/main/java/com/baeldung/jgit/porcelain/AddFile.java @@ -0,0 +1,36 @@ +package com.baeldung.jgit.porcelain; + +import java.io.File; +import java.io.IOException; +import com.baeldung.jgit.helper.Helper; +import org.eclipse.jgit.api.Git; +import org.eclipse.jgit.api.errors.GitAPIException; +import org.eclipse.jgit.lib.Repository; + +/** + * Simple snippet which shows how to add a file to the index + * + * + */ +public class AddFile { + + public static void main(String[] args) throws IOException, GitAPIException { + // prepare a new test-repository + try (Repository repository = Helper.createNewRepository()) { + try (Git git = new Git(repository)) { + // create the file + File myfile = new File(repository.getDirectory().getParent(), "testfile"); + if(!myfile.createNewFile()) { + throw new IOException("Could not create file " + myfile); + } + + // run the add-call + git.add() + .addFilepattern("testfile") + .call(); + + System.out.println("Added file " + myfile + " to repository at " + repository.getDirectory()); + } + } + } +} diff --git a/jgit/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java b/jgit/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java new file mode 100644 index 0000000000..4c0956ebf8 --- /dev/null +++ b/jgit/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java @@ -0,0 +1,51 @@ +package com.baeldung.jgit.porcelain; + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import com.baeldung.jgit.helper.Helper; +import org.eclipse.jgit.api.Git; +import org.eclipse.jgit.api.errors.GitAPIException; +import org.eclipse.jgit.lib.Repository; + +/** + * Simple snippet which shows how to commit all files + * + * + */ +public class CommitAll { + + public static void main(String[] args) throws IOException, GitAPIException { + // prepare a new test-repository + try (Repository repository = Helper.createNewRepository()) { + try (Git git = new Git(repository)) { + // create the file + File myfile = new File(repository.getDirectory().getParent(), "testfile"); + if(!myfile.createNewFile()) { + throw new IOException("Could not create file " + myfile); + } + + // Stage all files in the repo including new files + git.add().addFilepattern(".").call(); + + // and then commit the changes. + git.commit() + .setMessage("Commit all changes including additions") + .call(); + + try(PrintWriter writer = new PrintWriter(myfile)) { + writer.append("Hello, world!"); + } + + // Stage all changed files, omitting new files, and commit with one command + git.commit() + .setAll(true) + .setMessage("Commit changes to all files") + .call(); + + + System.out.println("Committed all changes to repository at " + repository.getDirectory()); + } + } + } +} diff --git a/jgit/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java b/jgit/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java new file mode 100644 index 0000000000..0f735daf8c --- /dev/null +++ b/jgit/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java @@ -0,0 +1,56 @@ +package com.baeldung.jgit.porcelain; + +import java.io.IOException; +import com.baeldung.jgit.helper.Helper; +import org.eclipse.jgit.api.Git; +import org.eclipse.jgit.api.errors.GitAPIException; +import org.eclipse.jgit.lib.ObjectId; +import org.eclipse.jgit.lib.Ref; +import org.eclipse.jgit.lib.Repository; +import org.eclipse.jgit.revwalk.RevCommit; +import org.eclipse.jgit.revwalk.RevWalk; + +/** + * Simple snippet which shows how to create a tag + * + * + */ +public class CreateAndDeleteTag { + + public static void main(String[] args) throws IOException, GitAPIException { + // prepare test-repository + try (Repository repository = Helper.openJGitRepository()) { + try (Git git = new Git(repository)) { + // remove the tag before creating it + git.tagDelete().setTags("tag_for_testing").call(); + + // set it on the current HEAD + Ref tag = git.tag().setName("tag_for_testing").call(); + System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory()); + + // remove the tag again + git.tagDelete().setTags("tag_for_testing").call(); + + // read some other commit and set the tag on it + ObjectId id = repository.resolve("HEAD^"); + try (RevWalk walk = new RevWalk(repository)) { + RevCommit commit = walk.parseCommit(id); + tag = git.tag().setObjectId(commit).setName("tag_for_testing").call(); + System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory()); + + // remove the tag again + git.tagDelete().setTags("tag_for_testing").call(); + + // create an annotated tag + tag = git.tag().setName("tag_for_testing").setAnnotated(true).call(); + System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory()); + + // remove the tag again + git.tagDelete().setTags("tag_for_testing").call(); + + walk.dispose(); + } + } + } + } +} diff --git a/jgit/src/main/java/com/baeldung/jgit/porcelain/Log.java b/jgit/src/main/java/com/baeldung/jgit/porcelain/Log.java new file mode 100644 index 0000000000..a50028a9ae --- /dev/null +++ b/jgit/src/main/java/com/baeldung/jgit/porcelain/Log.java @@ -0,0 +1,74 @@ +package com.baeldung.jgit.porcelain; + +import java.io.IOException; +import com.baeldung.jgit.helper.Helper; +import org.eclipse.jgit.api.Git; +import org.eclipse.jgit.api.errors.GitAPIException; +import org.eclipse.jgit.lib.Repository; +import org.eclipse.jgit.revwalk.RevCommit; + +/** + * Simple snippet which shows how to get the commit-ids for a file to provide log information. + * + * + */ +public class Log { + + @SuppressWarnings("unused") + public static void main(String[] args) throws IOException, GitAPIException { + try (Repository repository = Helper.openJGitRepository()) { + try (Git git = new Git(repository)) { + Iterable logs = git.log() + .call(); + int count = 0; + for (RevCommit rev : logs) { + //System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); + count++; + } + System.out.println("Had " + count + " commits overall on current branch"); + + logs = git.log() + .add(repository.resolve(git.getRepository().getFullBranch())) + .call(); + count = 0; + for (RevCommit rev : logs) { + System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); + count++; + } + System.out.println("Had " + count + " commits overall on "+git.getRepository().getFullBranch()); + + logs = git.log() + .all() + .call(); + count = 0; + for (RevCommit rev : logs) { + //System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); + count++; + } + System.out.println("Had " + count + " commits overall in repository"); + + logs = git.log() + // for all log.all() + .addPath("README.md") + .call(); + count = 0; + for (RevCommit rev : logs) { + //System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); + count++; + } + System.out.println("Had " + count + " commits on README.md"); + + logs = git.log() + // for all log.all() + .addPath("pom.xml") + .call(); + count = 0; + for (RevCommit rev : logs) { + //System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); + count++; + } + System.out.println("Had " + count + " commits on pom.xml"); + } + } + } +} diff --git a/jgit/src/main/resources/logback.xml b/jgit/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/jgit/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/jgit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java b/jgit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java new file mode 100644 index 0000000000..ad34890996 --- /dev/null +++ b/jgit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java @@ -0,0 +1,33 @@ +package com.baeldung.jgit; + +import com.baeldung.jgit.helper.Helper; +import org.eclipse.jgit.lib.ObjectLoader; +import org.eclipse.jgit.lib.ObjectReader; +import org.eclipse.jgit.lib.Ref; +import org.eclipse.jgit.lib.Repository; +import org.eclipse.jgit.revwalk.RevWalk; +import org.junit.Test; +import java.io.IOException; +import static org.junit.Assert.assertNotNull; + +/** + * Tests which show issues with JGit that we reported upstream. + */ +public class JGitBugIntegrationTest { + @Test + public void testRevWalkDisposeClosesReader() throws IOException { + try (Repository repo = Helper.openJGitRepository()) { + try (ObjectReader reader = repo.newObjectReader()) { + try (RevWalk walk = new RevWalk(reader)) { + walk.dispose(); + + Ref head = repo.exactRef("refs/heads/master"); + System.out.println("Found head: " + head); + + ObjectLoader loader = reader.open(head.getObjectId()); + assertNotNull(loader); + } + } + } + } +} diff --git a/jgit/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java b/jgit/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java new file mode 100644 index 0000000000..d3b3358664 --- /dev/null +++ b/jgit/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.jgit.porcelain; + +import org.junit.Test; + +public class PorcelainUnitTest { + @Test + public void runSamples() throws Exception { + // simply call all the samples to see any severe problems with the samples + AddFile.main(null); + + CommitAll.main(null); + + CreateAndDeleteTag.main(null); + + Log.main(null); + } +} From 0094c08a3d86338a402e6401cc04a8d7a349a7dc Mon Sep 17 00:00:00 2001 From: Eugen Date: Sun, 28 Jul 2019 09:39:48 +0300 Subject: [PATCH 68/84] changing case in the pom --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 6cdb35063e..0754b186cf 100644 --- a/pom.xml +++ b/pom.xml @@ -483,7 +483,7 @@ jee-7 --> jee-7-security jersey - JGit + jgit jgroups jhipster-5 jib @@ -781,7 +781,7 @@ testing-modules twilio - Twitter4J + twitter4j undertow From 0a5d51461ce8e581ff1bc98972e99584bfc3b85e Mon Sep 17 00:00:00 2001 From: Eugen Date: Sun, 28 Jul 2019 09:40:25 +0300 Subject: [PATCH 69/84] changing case in the pom --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 0754b186cf..5b5058763d 100644 --- a/pom.xml +++ b/pom.xml @@ -1176,7 +1176,7 @@ jee-7 --> jee-7-security jersey - JGit + jgit jgroups jhipster-5 jib @@ -1451,7 +1451,7 @@ testing-modules twilio - Twitter4J + twitter4j undertow From c0308756da53ba3486bec13915de4d27fbca76e6 Mon Sep 17 00:00:00 2001 From: Eugen Date: Sun, 28 Jul 2019 09:45:13 +0300 Subject: [PATCH 70/84] Update README.md --- README.md | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 7f78cf1515..cc3f48d8ed 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,16 @@ -The "REST with Spring" Classes +The Courses ============================== -Here's the Master Class of REST With Spring (along with the newly announced Boot 2 material):
    -**[>> THE REST WITH SPRING - MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)** -And here's the Master Class of Learn Spring Security:
    -**[>> LEARN SPRING SECURITY - MASTER CLASS](http://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)** +Here's the new "Learn Spring" course:
    +**[>> LEARN SPRING - THE MASTER CLASS](https://www.baeldung.com/learn-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=ls#master-class)** + +Here's the Master Class of "REST With Spring" (along with the new announced Boot 2 material):
    +**[>> THE REST WITH SPRING - MASTER CLASS](https://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)** + +And here's the Master Class of "Learn Spring Security":
    +**[>> LEARN SPRING SECURITY - MASTER CLASS](https://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)** @@ -15,7 +19,7 @@ Java and Spring Tutorials This project is **a collection of small and focused tutorials** - each covering a single and well defined area of development in the Java ecosystem. A strong focus of these is, of course, the Spring Framework - Spring, Spring Boot and Spring Security. -In additional to Spring, the following technologies are in focus: `core Java`, `Jackson`, `HttpClient`, `Guava`. +In additional to Spring, the modules here are covering a number of aspects in Java. Building the project @@ -32,6 +36,7 @@ Running a Spring Boot module ==================== To run a Spring Boot module run the command: `mvn spring-boot:run` in the module directory + ###Running Tests The command `mvn clean install` will run the unit tests in a module. From 8ae248ce42bde06937b5477f8b114bb0ad061408 Mon Sep 17 00:00:00 2001 From: Eugen Date: Sun, 28 Jul 2019 09:47:03 +0300 Subject: [PATCH 71/84] Update README.md --- README.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index cc3f48d8ed..4cad075cc3 100644 --- a/README.md +++ b/README.md @@ -37,8 +37,14 @@ Running a Spring Boot module To run a Spring Boot module run the command: `mvn spring-boot:run` in the module directory -###Running Tests +Working with the IDE +==================== +This repo contains a large number of modules. +When you're working with an individual module, there's no need to import all of them (or build all of them) - you can simply import that particular module in either Eclipse or IntelliJ. + +Running Tests +============= The command `mvn clean install` will run the unit tests in a module. To run the integration tests, use the command `mvn clean install -Pintegration-lite-first` From 9b97533de725e7050db6da71774b8866822ad023 Mon Sep 17 00:00:00 2001 From: fanatixan Date: Mon, 29 Jul 2019 07:46:22 +0200 Subject: [PATCH 72/84] bael-3119 (#7436) --- .../relationships/aggregation/Car.java | 9 ++++++ .../aggregation/CarWithStaticInnerWheel.java | 13 +++++++++ .../relationships/aggregation/Wheel.java | 7 +++++ .../relationships/association/Child.java | 7 +++++ .../relationships/association/Mother.java | 9 ++++++ .../relationships/composition/Building.java | 18 ++++++++++++ .../BuildingWithDefinitionRoomInMethod.java | 28 +++++++++++++++++++ .../relationships/university/Department.java | 9 ++++++ .../relationships/university/Professor.java | 10 +++++++ .../relationships/university/University.java | 9 ++++++ 10 files changed, 119 insertions(+) create mode 100644 core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Car.java create mode 100644 core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/CarWithStaticInnerWheel.java create mode 100644 core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Wheel.java create mode 100644 core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Child.java create mode 100644 core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Mother.java create mode 100644 core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/Building.java create mode 100644 core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/BuildingWithDefinitionRoomInMethod.java create mode 100644 core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Department.java create mode 100644 core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Professor.java create mode 100644 core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/University.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Car.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Car.java new file mode 100644 index 0000000000..6be9a18781 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Car.java @@ -0,0 +1,9 @@ +package com.baeldung.relationships.aggregation; + +import java.util.List; + +public class Car { + + private List wheels; + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/CarWithStaticInnerWheel.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/CarWithStaticInnerWheel.java new file mode 100644 index 0000000000..96c07f13a4 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/CarWithStaticInnerWheel.java @@ -0,0 +1,13 @@ +package com.baeldung.relationships.aggregation; + +import java.util.List; + +public class CarWithStaticInnerWheel { + + private List wheels; + + public static class Wheel { + + } + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Wheel.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Wheel.java new file mode 100644 index 0000000000..1f38ea85ad --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Wheel.java @@ -0,0 +1,7 @@ +package com.baeldung.relationships.aggregation; + +public class Wheel { + + private Car car; + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Child.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Child.java new file mode 100644 index 0000000000..4c748e8084 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Child.java @@ -0,0 +1,7 @@ +package com.baeldung.relationships.association; + +public class Child { + + private Mother mother; + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Mother.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Mother.java new file mode 100644 index 0000000000..0e8edef125 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Mother.java @@ -0,0 +1,9 @@ +package com.baeldung.relationships.association; + +import java.util.List; + +public class Mother { + + private List children; + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/Building.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/Building.java new file mode 100644 index 0000000000..1ab44f73fa --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/Building.java @@ -0,0 +1,18 @@ +package com.baeldung.relationships.composition; + +import java.util.List; + +public class Building { + + private String address; + private List rooms; + + public class Room { + + public String getBuildingAddress() { + return Building.this.address; + } + + } + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/BuildingWithDefinitionRoomInMethod.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/BuildingWithDefinitionRoomInMethod.java new file mode 100644 index 0000000000..4e3411cf30 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/BuildingWithDefinitionRoomInMethod.java @@ -0,0 +1,28 @@ +package com.baeldung.relationships.composition; + +public class BuildingWithDefinitionRoomInMethod { + + public Room createAnonymousRoom() { + return new Room() { + @Override + public void doInRoom() {} + }; + } + + public Room createInlineRoom() { + class InlineRoom implements Room { + @Override + public void doInRoom() {} + } + return new InlineRoom(); + } + + public Room createLambdaRoom() { + return () -> {}; + } + + public interface Room { + void doInRoom(); + } + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Department.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Department.java new file mode 100644 index 0000000000..63cfd1b89e --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Department.java @@ -0,0 +1,9 @@ +package com.baeldung.relationships.university; + +import java.util.List; + +public class Department { + + private List professors; + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Professor.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Professor.java new file mode 100644 index 0000000000..8e1258c3e6 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Professor.java @@ -0,0 +1,10 @@ +package com.baeldung.relationships.university; + +import java.util.List; + +public class Professor { + + private List department; + private List friends; + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/University.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/University.java new file mode 100644 index 0000000000..e5e518e0f1 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/University.java @@ -0,0 +1,9 @@ +package com.baeldung.relationships.university; + +import java.util.List; + +public class University { + + private List department; + +} From 5aecdeb0211c9dc44e3e5138d4a30bf837d19204 Mon Sep 17 00:00:00 2001 From: Ger Roza Date: Mon, 29 Jul 2019 02:56:21 -0300 Subject: [PATCH 73/84] [BAEL-3066] Spring Security: Exploring JDBC Authentication (#7441) * created multi-module project from spring-security-mvc-boot * Added JDBC Authentication application to spring-security-mvc-boot-default * Added JDBC Authentication application to spring-security-mvc-boot-mysql * Added JDBC Authentication application to spring-security-mvc-boot-postgre * adding new modules to parent spring-security-mvc-boot module, reformatting sql scripts, and added form fields to H2 LiveTest --- spring-security-mvc-boot/pom.xml | 32 ++++------- .../spring-security-mvc-boot-default/pom.xml | 42 +++++++++++++++ .../src/main/java/com/baeldung/AppConfig.java | 0 .../com/baeldung/SpringSecurityConfig.java | 0 .../data/repositories/TweetRepository.java | 0 .../data/repositories/UserRepository.java | 0 .../java/com/baeldung/models/AppUser.java | 0 .../main/java/com/baeldung/models/Tweet.java | 0 .../baeldung/security/AppUserPrincipal.java | 0 .../AuthenticationSuccessHandlerImpl.java | 0 .../security/CustomUserDetailsService.java | 0 .../com/baeldung/util/DummyContentUtil.java | 0 .../java/org/baeldung/custom/Application.java | 4 -- .../custom/config/MethodSecurityConfig.java | 0 .../org/baeldung/custom/config/MvcConfig.java | 0 .../custom/config/SecurityConfig.java | 0 .../custom/persistence/SetupData.java | 0 .../dao/OrganizationRepository.java | 0 .../persistence/dao/PrivilegeRepository.java | 0 .../persistence/dao/UserRepository.java | 0 .../custom/persistence/model/Foo.java | 0 .../persistence/model/Organization.java | 0 .../custom/persistence/model/Privilege.java | 0 .../custom/persistence/model/User.java | 0 ...CustomMethodSecurityExpressionHandler.java | 0 .../CustomMethodSecurityExpressionRoot.java | 0 .../security/CustomPermissionEvaluator.java | 0 .../security/MySecurityExpressionRoot.java | 0 .../custom/security/MyUserDetailsService.java | 0 .../custom/security/MyUserPrincipal.java | 0 .../baeldung/custom/web/MainController.java | 0 .../java/org/baeldung/ip/IpApplication.java | 0 .../CustomIpAuthenticationProvider.java | 0 .../baeldung/ip/config/SecurityConfig.java | 0 .../baeldung/ip/config/SecurityXmlConfig.java | 0 .../org/baeldung/ip/web/MainController.java | 0 .../h2/H2JdbcAuthenticationApplication.java | 15 ++++++ .../h2/config/SecurityConfiguration.java | 51 ++++++++++++++++++ .../h2/web/UserController.java | 17 ++++++ .../CustomAuthenticationProvider.java | 0 .../MultipleAuthController.java | 0 .../MultipleAuthProvidersApplication.java | 0 .../MultipleAuthProvidersSecurityConfig.java | 0 .../MultipleEntryPointsApplication.java | 0 .../MultipleEntryPointsSecurityConfig.java | 0 .../multipleentrypoints/PagesController.java | 0 .../MultipleLoginApplication.java | 5 +- .../multiplelogin/MultipleLoginMvcConfig.java | 0 .../MultipleLoginSecurityConfig.java | 0 .../multiplelogin/UsersController.java | 0 .../CustomAuthenticationProvider.java | 0 .../MyLogoutSuccessHandler.java | 0 .../MyUserDetailsService.java | 0 .../RolesAuthoritiesApplication.java | 0 .../rolesauthorities/config/MvcConfig.java | 0 .../config/SecurityConfig.java | 0 .../rolesauthorities/model/Privilege.java | 0 .../baeldung/rolesauthorities/model/Role.java | 0 .../baeldung/rolesauthorities/model/User.java | 0 .../persistence/IUserService.java | 0 .../persistence/PrivilegeRepository.java | 0 .../persistence/RoleRepository.java | 0 .../persistence/SetupDataLoader.java | 0 .../persistence/UserRepository.java | 0 .../persistence/UserService.java | 0 .../baeldung/ssl/HttpsEnabledApplication.java | 0 .../java/org/baeldung/ssl/SecurityConfig.java | 0 .../org/baeldung/ssl/WelcomeController.java | 0 .../org/baeldung/voter/MinuteBasedVoter.java | 0 .../org/baeldung/voter/VoterApplication.java | 0 .../org/baeldung/voter/VoterMvcConfig.java | 0 .../org/baeldung/voter/WebSecurityConfig.java | 0 .../org/baeldung/voter/XmlSecurityConfig.java | 0 .../main/resources/application-ssl.properties | 0 .../src/main/resources/application.properties | 4 +- .../src/main/resources/keystore/baeldung.p12 | Bin .../src/main/resources/logback.xml | 0 .../main/resources/persistence-h2.properties | 0 .../spring-security-custom-voter.xml | 0 .../src/main/resources/spring-security-ip.xml | 0 ...pring-security-multiple-auth-providers.xml | 0 .../spring-security-multiple-entry.xml | 0 .../src/main/resources/templates/403.html | 0 .../main/resources/templates/adminPage.html | 0 .../src/main/resources/templates/index.html | 0 .../src/main/resources/templates/login.html | 0 .../main/resources/templates/loginAdmin.html | 0 .../main/resources/templates/loginUser.html | 0 .../templates/multipleHttpElems/login.html | 0 .../multipleHttpElems/loginWithWarning.html | 0 .../multipleHttpElems/multipleHttpLinks.html | 0 .../multipleHttpElems/myAdminPage.html | 0 .../multipleHttpElems/myGuestPage.html | 0 .../multipleHttpElems/myPrivateUserPage.html | 0 .../multipleHttpElems/myUserPage.html | 0 .../src/main/resources/templates/private.html | 0 .../resources/templates/protectedLinks.html | 0 .../templates/rolesauthorities/home.html | 0 .../templates/rolesauthorities/login.html | 0 .../protectedbyauthority.html | 0 .../rolesauthorities/protectedbynothing.html | 0 .../rolesauthorities/protectedbyrole.html | 0 .../main/resources/templates/ssl/welcome.html | 0 .../main/resources/templates/userPage.html | 0 ...SpringDataWithSecurityIntegrationTest.java | 0 .../SpringContextIntegrationTest.java | 0 .../h2/web/UserControllerLiveTest.java | 35 ++++++++++++ .../org/baeldung/web/ApplicationLiveTest.java | 0 ...stomUserDetailsServiceIntegrationTest.java | 0 .../web/HttpsApplicationIntegrationTest.java | 0 .../java/org/baeldung/web/IpLiveTest.java | 0 ...thProvidersApplicationIntegrationTest.java | 0 .../MultipleEntryPointsIntegrationTest.java | 0 .../spring-security-mvc-boot-mysql/pom.xml | 28 ++++++++++ .../MySqlJdbcAuthenticationApplication.java | 13 +++++ .../mysql/config/SecurityConfiguration.java | 35 ++++++++++++ .../mysql/web/UserController.java | 17 ++++++ .../src/main/resources/application.properties | 8 +++ .../src/main/resources/data.sql | 4 ++ .../src/main/resources/schema.sql | 18 +++++++ .../mysql/SpringContextIntegrationTest.java | 15 ++++++ .../mysql/web/UserControllerLiveTest.java | 35 ++++++++++++ .../spring-security-mvc-boot-postgre/pom.xml | 28 ++++++++++ .../PostgreJdbcAuthenticationApplication.java | 13 +++++ .../postgre/config/SecurityConfiguration.java | 29 ++++++++++ .../postgre/web/UserController.java | 17 ++++++ .../src/main/resources/application.properties | 8 +++ .../src/main/resources/data.sql | 4 ++ .../src/main/resources/schema.sql | 16 ++++++ .../postgre/SpringContextIntegrationTest.java | 17 ++++++ .../postgre/web/UserControllerLiveTest.java | 35 ++++++++++++ 131 files changed, 514 insertions(+), 31 deletions(-) create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-default/pom.xml rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/com/baeldung/AppConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/com/baeldung/SpringSecurityConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/com/baeldung/data/repositories/TweetRepository.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/com/baeldung/data/repositories/UserRepository.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/com/baeldung/models/AppUser.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/com/baeldung/models/Tweet.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/com/baeldung/security/AppUserPrincipal.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/com/baeldung/security/AuthenticationSuccessHandlerImpl.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/com/baeldung/security/CustomUserDetailsService.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/com/baeldung/util/DummyContentUtil.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/Application.java (61%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/config/MethodSecurityConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/config/MvcConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/config/SecurityConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/persistence/SetupData.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/persistence/dao/OrganizationRepository.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/persistence/dao/PrivilegeRepository.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/persistence/dao/UserRepository.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/persistence/model/Foo.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/persistence/model/Organization.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/persistence/model/Privilege.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/persistence/model/User.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionHandler.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionRoot.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/security/CustomPermissionEvaluator.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/security/MySecurityExpressionRoot.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/security/MyUserDetailsService.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/security/MyUserPrincipal.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/web/MainController.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/ip/IpApplication.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/ip/config/SecurityConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/ip/web/MainController.java (100%) create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/web/UserController.java rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/multipleauthproviders/CustomAuthenticationProvider.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthController.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/multipleentrypoints/PagesController.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java (69%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/multiplelogin/MultipleLoginMvcConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/multiplelogin/MultipleLoginSecurityConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/multiplelogin/UsersController.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/rolesauthorities/CustomAuthenticationProvider.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/rolesauthorities/MyLogoutSuccessHandler.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/rolesauthorities/MyUserDetailsService.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/rolesauthorities/config/SecurityConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/rolesauthorities/model/Privilege.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/rolesauthorities/model/Role.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/rolesauthorities/model/User.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/rolesauthorities/persistence/IUserService.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/rolesauthorities/persistence/PrivilegeRepository.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/rolesauthorities/persistence/RoleRepository.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/rolesauthorities/persistence/SetupDataLoader.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/rolesauthorities/persistence/UserRepository.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/rolesauthorities/persistence/UserService.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/ssl/HttpsEnabledApplication.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/ssl/SecurityConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/ssl/WelcomeController.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/voter/MinuteBasedVoter.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/voter/VoterApplication.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/voter/VoterMvcConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/voter/WebSecurityConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/voter/XmlSecurityConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/application-ssl.properties (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/application.properties (74%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/keystore/baeldung.p12 (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/logback.xml (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/persistence-h2.properties (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/spring-security-custom-voter.xml (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/spring-security-ip.xml (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/spring-security-multiple-auth-providers.xml (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/spring-security-multiple-entry.xml (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/403.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/adminPage.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/index.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/login.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/loginAdmin.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/loginUser.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/multipleHttpElems/login.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/multipleHttpElems/loginWithWarning.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/multipleHttpElems/multipleHttpLinks.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/multipleHttpElems/myAdminPage.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/multipleHttpElems/myGuestPage.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/multipleHttpElems/myPrivateUserPage.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/multipleHttpElems/myUserPage.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/private.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/protectedLinks.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/rolesauthorities/home.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/rolesauthorities/login.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/rolesauthorities/protectedbyauthority.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/rolesauthorities/protectedbynothing.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/rolesauthorities/protectedbyrole.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/ssl/welcome.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/userPage.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/test/java/org/baeldung/SpringContextIntegrationTest.java (100%) create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/test/java/org/baeldung/web/ApplicationLiveTest.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/test/java/org/baeldung/web/IpLiveTest.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/test/java/org/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/test/java/org/baeldung/web/MultipleEntryPointsIntegrationTest.java (100%) create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-mysql/pom.xml create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/web/UserController.java create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/application.properties create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/data.sql create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/schema.sql create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/test/java/com/baeldung/jdbcauthentication/mysql/SpringContextIntegrationTest.java create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/test/java/com/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-postgre/pom.xml create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/web/UserController.java create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/application.properties create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/data.sql create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/schema.sql create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/test/java/com/baeldung/jdbcauthentication/postgre/SpringContextIntegrationTest.java create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/test/java/com/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java diff --git a/spring-security-mvc-boot/pom.xml b/spring-security-mvc-boot/pom.xml index 4c25dc01e8..906bebf442 100644 --- a/spring-security-mvc-boot/pom.xml +++ b/spring-security-mvc-boot/pom.xml @@ -1,12 +1,13 @@ - + 4.0.0 com.baeldung spring-security-mvc-boot 0.0.1-SNAPSHOT spring-security-mvc-boot - war + pom Spring Security MVC Boot @@ -45,10 +46,6 @@ org.springframework.security spring-security-data
    - - com.h2database - h2 - org.hamcrest hamcrest-core @@ -198,7 +195,7 @@ **/*LiveTest.java **/*IntegrationTest.java - **/*IntTest.java + **/*IntTest.java **/*EntryPointsTest.java @@ -217,22 +214,13 @@ + + spring-security-mvc-boot-default + spring-security-mvc-boot-mysql + spring-security-mvc-boot-postgre + - org.baeldung.custom.Application - - - - - - - - - 1.1.2 1.6.1 2.6.11 diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/pom.xml b/spring-security-mvc-boot/spring-security-mvc-boot-default/pom.xml new file mode 100644 index 0000000000..8f7f18f093 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-default/pom.xml @@ -0,0 +1,42 @@ + + + 4.0.0 + com.baeldung + spring-security-mvc-boot-default + 0.0.1-SNAPSHOT + spring-security-mvc-boot-default + jar + Spring Security MVC Boot + + + spring-security-mvc-boot + com.baeldung + 0.0.1-SNAPSHOT + ../ + + + + + com.h2database + h2 + + + + + org.baeldung.custom.Application + + + + + + + + + + + diff --git a/spring-security-mvc-boot/src/main/java/com/baeldung/AppConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/AppConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/com/baeldung/AppConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/AppConfig.java diff --git a/spring-security-mvc-boot/src/main/java/com/baeldung/SpringSecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/SpringSecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/com/baeldung/SpringSecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/SpringSecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/java/com/baeldung/data/repositories/TweetRepository.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/data/repositories/TweetRepository.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/com/baeldung/data/repositories/TweetRepository.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/data/repositories/TweetRepository.java diff --git a/spring-security-mvc-boot/src/main/java/com/baeldung/data/repositories/UserRepository.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/data/repositories/UserRepository.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/com/baeldung/data/repositories/UserRepository.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/data/repositories/UserRepository.java diff --git a/spring-security-mvc-boot/src/main/java/com/baeldung/models/AppUser.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/models/AppUser.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/com/baeldung/models/AppUser.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/models/AppUser.java diff --git a/spring-security-mvc-boot/src/main/java/com/baeldung/models/Tweet.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/models/Tweet.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/com/baeldung/models/Tweet.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/models/Tweet.java diff --git a/spring-security-mvc-boot/src/main/java/com/baeldung/security/AppUserPrincipal.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/security/AppUserPrincipal.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/com/baeldung/security/AppUserPrincipal.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/security/AppUserPrincipal.java diff --git a/spring-security-mvc-boot/src/main/java/com/baeldung/security/AuthenticationSuccessHandlerImpl.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/security/AuthenticationSuccessHandlerImpl.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/com/baeldung/security/AuthenticationSuccessHandlerImpl.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/security/AuthenticationSuccessHandlerImpl.java diff --git a/spring-security-mvc-boot/src/main/java/com/baeldung/security/CustomUserDetailsService.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/security/CustomUserDetailsService.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/com/baeldung/security/CustomUserDetailsService.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/security/CustomUserDetailsService.java diff --git a/spring-security-mvc-boot/src/main/java/com/baeldung/util/DummyContentUtil.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/util/DummyContentUtil.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/com/baeldung/util/DummyContentUtil.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/util/DummyContentUtil.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/Application.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/Application.java similarity index 61% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/Application.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/Application.java index f932ac3066..682d429963 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/Application.java +++ b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/Application.java @@ -1,12 +1,8 @@ package org.baeldung.custom; import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @SpringBootApplication public class Application extends SpringBootServletInitializer { diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/MethodSecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/config/MethodSecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/MethodSecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/config/MethodSecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/MvcConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/config/MvcConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/MvcConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/config/MvcConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/SecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/config/SecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/SecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/config/SecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/SetupData.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/SetupData.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/SetupData.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/SetupData.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/OrganizationRepository.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/dao/OrganizationRepository.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/OrganizationRepository.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/dao/OrganizationRepository.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/PrivilegeRepository.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/dao/PrivilegeRepository.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/PrivilegeRepository.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/dao/PrivilegeRepository.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/UserRepository.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/dao/UserRepository.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/UserRepository.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/dao/UserRepository.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Foo.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/model/Foo.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Foo.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/model/Foo.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Organization.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/model/Organization.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Organization.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/model/Organization.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Privilege.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/model/Privilege.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Privilege.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/model/Privilege.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/User.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/model/User.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/User.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/model/User.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionHandler.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionHandler.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionHandler.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionHandler.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionRoot.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionRoot.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionRoot.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionRoot.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomPermissionEvaluator.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/CustomPermissionEvaluator.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomPermissionEvaluator.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/CustomPermissionEvaluator.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MySecurityExpressionRoot.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/MySecurityExpressionRoot.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MySecurityExpressionRoot.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/MySecurityExpressionRoot.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MyUserDetailsService.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/MyUserDetailsService.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MyUserDetailsService.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/MyUserDetailsService.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MyUserPrincipal.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/MyUserPrincipal.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MyUserPrincipal.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/MyUserPrincipal.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/web/MainController.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/web/MainController.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/web/MainController.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/web/MainController.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ip/IpApplication.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/IpApplication.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/ip/IpApplication.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/IpApplication.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/config/SecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/config/SecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ip/web/MainController.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/web/MainController.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/ip/web/MainController.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/web/MainController.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java new file mode 100644 index 0000000000..6bd30414ef --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java @@ -0,0 +1,15 @@ +package org.baeldung.jdbcauthentication.h2; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; + +@SpringBootApplication +@EnableWebSecurity +public class H2JdbcAuthenticationApplication { + + public static void main(String[] args) { + SpringApplication.run(H2JdbcAuthenticationApplication.class, args); + } + +} diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java new file mode 100644 index 0000000000..8b8696f0b2 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java @@ -0,0 +1,51 @@ +package org.baeldung.jdbcauthentication.h2.config; + +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +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.WebSecurityConfigurerAdapter; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +public class SecurityConfiguration extends WebSecurityConfigurerAdapter { + @Override + protected void configure(HttpSecurity httpSecurity) throws Exception { + httpSecurity.authorizeRequests() + .antMatchers("/h2-console/**") + .permitAll() + .anyRequest() + .authenticated() + .and() + .formLogin() + .permitAll(); + httpSecurity.csrf() + .ignoringAntMatchers("/h2-console/**"); + httpSecurity.headers() + .frameOptions() + .sameOrigin(); + } + + @Autowired + private DataSource dataSource; + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth.jdbcAuthentication() + .dataSource(dataSource) + .withDefaultSchema() + .withUser(User.withUsername("user") + .password(passwordEncoder().encode("pass")) + .roles("USER")); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } +} \ No newline at end of file diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/web/UserController.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/web/UserController.java new file mode 100644 index 0000000000..0955061614 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/web/UserController.java @@ -0,0 +1,17 @@ +package org.baeldung.jdbcauthentication.h2.web; + +import java.security.Principal; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/principal") +public class UserController { + + @GetMapping + public Principal retrievePrincipal(Principal principal) { + return principal; + } +} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/CustomAuthenticationProvider.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/CustomAuthenticationProvider.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/CustomAuthenticationProvider.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/CustomAuthenticationProvider.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthController.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthController.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthController.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthController.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/PagesController.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleentrypoints/PagesController.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/PagesController.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleentrypoints/PagesController.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java similarity index 69% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java index e9dc541ad3..d25324eb54 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java +++ b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java @@ -1,11 +1,8 @@ package org.baeldung.multiplelogin; import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @ComponentScan("org.baeldung.multiplelogin") diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginMvcConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/MultipleLoginMvcConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginMvcConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/MultipleLoginMvcConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginSecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/MultipleLoginSecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginSecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/MultipleLoginSecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/UsersController.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/UsersController.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/UsersController.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/UsersController.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/CustomAuthenticationProvider.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/CustomAuthenticationProvider.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/CustomAuthenticationProvider.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/CustomAuthenticationProvider.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/MyLogoutSuccessHandler.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/MyLogoutSuccessHandler.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/MyLogoutSuccessHandler.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/MyLogoutSuccessHandler.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/MyUserDetailsService.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/MyUserDetailsService.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/MyUserDetailsService.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/MyUserDetailsService.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/config/SecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/config/SecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/config/SecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/config/SecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/Privilege.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/model/Privilege.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/Privilege.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/model/Privilege.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/Role.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/model/Role.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/Role.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/model/Role.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/User.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/model/User.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/User.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/model/User.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/IUserService.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/IUserService.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/IUserService.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/IUserService.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/PrivilegeRepository.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/PrivilegeRepository.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/PrivilegeRepository.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/PrivilegeRepository.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/RoleRepository.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/RoleRepository.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/RoleRepository.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/RoleRepository.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/SetupDataLoader.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/SetupDataLoader.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/SetupDataLoader.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/SetupDataLoader.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/UserRepository.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/UserRepository.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/UserRepository.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/UserRepository.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/UserService.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/UserService.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/UserService.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/UserService.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/HttpsEnabledApplication.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ssl/HttpsEnabledApplication.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/ssl/HttpsEnabledApplication.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ssl/HttpsEnabledApplication.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/SecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ssl/SecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/ssl/SecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ssl/SecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/WelcomeController.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ssl/WelcomeController.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/ssl/WelcomeController.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ssl/WelcomeController.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/voter/MinuteBasedVoter.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/MinuteBasedVoter.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/voter/MinuteBasedVoter.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/MinuteBasedVoter.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/voter/VoterApplication.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/VoterApplication.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/voter/VoterApplication.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/VoterApplication.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/voter/VoterMvcConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/VoterMvcConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/voter/VoterMvcConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/VoterMvcConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/voter/WebSecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/WebSecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/voter/WebSecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/WebSecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/voter/XmlSecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/XmlSecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/voter/XmlSecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/XmlSecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/resources/application-ssl.properties b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/application-ssl.properties similarity index 100% rename from spring-security-mvc-boot/src/main/resources/application-ssl.properties rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/application-ssl.properties diff --git a/spring-security-mvc-boot/src/main/resources/application.properties b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/application.properties similarity index 74% rename from spring-security-mvc-boot/src/main/resources/application.properties rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/application.properties index 25eac743d1..365dedab9e 100644 --- a/spring-security-mvc-boot/src/main/resources/application.properties +++ b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/application.properties @@ -8,5 +8,7 @@ spring.jpa.database=H2 spring.jpa.show-sql=false spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect +logging.level.org.springframework.security.web.FilterChainProxy=DEBUG -#logging.level.org.springframework.security.web.FilterChainProxy=DEBUG \ No newline at end of file +spring.h2.console.enabled=true +spring.h2.console.path=/h2-console \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/resources/keystore/baeldung.p12 b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/keystore/baeldung.p12 similarity index 100% rename from spring-security-mvc-boot/src/main/resources/keystore/baeldung.p12 rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/keystore/baeldung.p12 diff --git a/spring-security-mvc-boot/src/main/resources/logback.xml b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/logback.xml similarity index 100% rename from spring-security-mvc-boot/src/main/resources/logback.xml rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/logback.xml diff --git a/spring-security-mvc-boot/src/main/resources/persistence-h2.properties b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/persistence-h2.properties similarity index 100% rename from spring-security-mvc-boot/src/main/resources/persistence-h2.properties rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/persistence-h2.properties diff --git a/spring-security-mvc-boot/src/main/resources/spring-security-custom-voter.xml b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/spring-security-custom-voter.xml similarity index 100% rename from spring-security-mvc-boot/src/main/resources/spring-security-custom-voter.xml rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/spring-security-custom-voter.xml diff --git a/spring-security-mvc-boot/src/main/resources/spring-security-ip.xml b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/spring-security-ip.xml similarity index 100% rename from spring-security-mvc-boot/src/main/resources/spring-security-ip.xml rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/spring-security-ip.xml diff --git a/spring-security-mvc-boot/src/main/resources/spring-security-multiple-auth-providers.xml b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/spring-security-multiple-auth-providers.xml similarity index 100% rename from spring-security-mvc-boot/src/main/resources/spring-security-multiple-auth-providers.xml rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/spring-security-multiple-auth-providers.xml diff --git a/spring-security-mvc-boot/src/main/resources/spring-security-multiple-entry.xml b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/spring-security-multiple-entry.xml similarity index 100% rename from spring-security-mvc-boot/src/main/resources/spring-security-multiple-entry.xml rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/spring-security-multiple-entry.xml diff --git a/spring-security-mvc-boot/src/main/resources/templates/403.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/403.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/403.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/403.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/adminPage.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/adminPage.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/adminPage.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/adminPage.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/index.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/index.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/index.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/index.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/login.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/login.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/login.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/login.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/loginAdmin.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/loginAdmin.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/loginAdmin.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/loginAdmin.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/loginUser.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/loginUser.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/loginUser.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/loginUser.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/login.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/login.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/login.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/login.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/loginWithWarning.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/loginWithWarning.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/loginWithWarning.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/loginWithWarning.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/multipleHttpLinks.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/multipleHttpLinks.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/multipleHttpLinks.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/multipleHttpLinks.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myAdminPage.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/myAdminPage.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myAdminPage.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/myAdminPage.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myGuestPage.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/myGuestPage.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myGuestPage.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/myGuestPage.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myPrivateUserPage.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/myPrivateUserPage.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myPrivateUserPage.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/myPrivateUserPage.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myUserPage.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/myUserPage.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myUserPage.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/myUserPage.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/private.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/private.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/private.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/private.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/protectedLinks.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/protectedLinks.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/protectedLinks.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/protectedLinks.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/home.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/home.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/home.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/home.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/login.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/login.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/login.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/login.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbyauthority.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/protectedbyauthority.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbyauthority.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/protectedbyauthority.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbynothing.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/protectedbynothing.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbynothing.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/protectedbynothing.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbyrole.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/protectedbyrole.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbyrole.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/protectedbyrole.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/ssl/welcome.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/ssl/welcome.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/ssl/welcome.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/ssl/welcome.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/userPage.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/userPage.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/userPage.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/userPage.html diff --git a/spring-security-mvc-boot/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java similarity index 100% rename from spring-security-mvc-boot/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/SpringContextIntegrationTest.java similarity index 100% rename from spring-security-mvc-boot/src/test/java/org/baeldung/SpringContextIntegrationTest.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/SpringContextIntegrationTest.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java new file mode 100644 index 0000000000..638e9d7919 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java @@ -0,0 +1,35 @@ +package org.baeldung.jdbcauthentication.h2.web; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.is; + +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; + +import io.restassured.authentication.FormAuthConfig; +import io.restassured.filter.session.SessionFilter; + +/** + * This Live Test requires the H2JdbcAuthenticationApplication application to be up and running + */ +public class UserControllerLiveTest { + + private static final String PRINCIPAL_SVC_URL = "http://localhost:8082/principal"; + + @Test + public void givenExisting_whenRequestPrincipal_thenRetrieveData() throws Exception { + SessionFilter filter = new SessionFilter(); + given().auth() + .form("user", "pass", new FormAuthConfig("/login", "username", "password").withCsrfFieldName("_csrf")) + .and() + .filter(filter) + .when() + .get(PRINCIPAL_SVC_URL) + .then() + .statusCode(HttpStatus.OK.value()) + .and() + .body("authorities[0].authority", is("ROLE_USER")) + .body("principal.username", is("user")) + .body("name", is("user")); + } +} diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/web/ApplicationLiveTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/ApplicationLiveTest.java similarity index 100% rename from spring-security-mvc-boot/src/test/java/org/baeldung/web/ApplicationLiveTest.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/ApplicationLiveTest.java diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java similarity index 100% rename from spring-security-mvc-boot/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java similarity index 100% rename from spring-security-mvc-boot/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/web/IpLiveTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/IpLiveTest.java similarity index 100% rename from spring-security-mvc-boot/src/test/java/org/baeldung/web/IpLiveTest.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/IpLiveTest.java diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java similarity index 100% rename from spring-security-mvc-boot/src/test/java/org/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/web/MultipleEntryPointsIntegrationTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/MultipleEntryPointsIntegrationTest.java similarity index 100% rename from spring-security-mvc-boot/src/test/java/org/baeldung/web/MultipleEntryPointsIntegrationTest.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/MultipleEntryPointsIntegrationTest.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/pom.xml b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/pom.xml new file mode 100644 index 0000000000..765953c557 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/pom.xml @@ -0,0 +1,28 @@ + + + 4.0.0 + com.baeldung + spring-security-mvc-boot-mysql + 0.0.1-SNAPSHOT + spring-security-mvc-boot-mysql + jar + Spring Security MVC Boot using MySQL + + + spring-security-mvc-boot + com.baeldung + 0.0.1-SNAPSHOT + .. + + + + + mysql + mysql-connector-java + runtime + + + + diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java new file mode 100644 index 0000000000..238a48730c --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.jdbcauthentication.mysql; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class MySqlJdbcAuthenticationApplication { + + public static void main(String[] args) { + SpringApplication.run(MySqlJdbcAuthenticationApplication.class, args); + } + +} diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java new file mode 100644 index 0000000000..a0584818cd --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java @@ -0,0 +1,35 @@ +package com.baeldung.jdbcauthentication.mysql.config; + +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +public class SecurityConfiguration { + + @Autowired + private DataSource dataSource; + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth.jdbcAuthentication() + .dataSource(dataSource) + .usersByUsernameQuery("select email,password,enabled " + + "from bael_users " + + "where email = ?") + .authoritiesByUsernameQuery("select email,authority " + + "from authorities " + + "where email = ?"); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + +} \ No newline at end of file diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/web/UserController.java b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/web/UserController.java new file mode 100644 index 0000000000..ed15f8bfe6 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/web/UserController.java @@ -0,0 +1,17 @@ +package com.baeldung.jdbcauthentication.mysql.web; + +import java.security.Principal; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/principal") +public class UserController { + + @GetMapping + public Principal retrievePrincipal(Principal principal) { + return principal; + } +} \ No newline at end of file diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/application.properties b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/application.properties new file mode 100644 index 0000000000..2962475108 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/application.properties @@ -0,0 +1,8 @@ +server.port=8082 + +spring.datasource.url=jdbc:mysql://localhost:3306/jdbc_authentication +spring.datasource.username=root +spring.datasource.password=pass + +spring.datasource.initialization-mode=always +spring.jpa.hibernate.ddl-auto=none diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/data.sql b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/data.sql new file mode 100644 index 0000000000..8214fd8204 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/data.sql @@ -0,0 +1,4 @@ +-- User user@email.com/pass +INSERT INTO bael_users (name, email, password, enabled) values ('user', 'user@email.com', '$2a$10$8.UnVuG9HHgffUDAlk8qfOuVGkqRzgVymGe07xd00DMxs.AQubh4a', 1); + +INSERT INTO authorities (email, authority) values ('user@email.com', 'ROLE_USER'); \ No newline at end of file diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/schema.sql b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/schema.sql new file mode 100644 index 0000000000..bb38c74366 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/schema.sql @@ -0,0 +1,18 @@ +DROP TABLE IF EXISTS authorities; +DROP TABLE IF EXISTS bael_users; + +CREATE TABLE bael_users ( + name VARCHAR(50) NOT NULL, + email VARCHAR(50) NOT NULL, + password VARCHAR(100) NOT NULL, + enabled TINYINT NOT NULL DEFAULT 1, + PRIMARY KEY (email) +); + +CREATE TABLE authorities ( + email VARCHAR(50) NOT NULL, + authority VARCHAR(50) NOT NULL, + FOREIGN KEY (email) REFERENCES bael_users(email) +); + +CREATE UNIQUE INDEX ix_auth_email on authorities (email,authority); \ No newline at end of file diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/test/java/com/baeldung/jdbcauthentication/mysql/SpringContextIntegrationTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/test/java/com/baeldung/jdbcauthentication/mysql/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..2c19e2c0ca --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/test/java/com/baeldung/jdbcauthentication/mysql/SpringContextIntegrationTest.java @@ -0,0 +1,15 @@ +package com.baeldung.jdbcauthentication.mysql; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = MySqlJdbcAuthenticationApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/test/java/com/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/test/java/com/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java new file mode 100644 index 0000000000..79bc84ea69 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/test/java/com/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java @@ -0,0 +1,35 @@ +package com.baeldung.jdbcauthentication.mysql.web; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.is; + +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; + +/** + * This Live Test requires: + * * a MySql instance running, that allows a 'root' user with password 'pass', and with a database named jdbc_authentication + * (e.g. with the following command `docker run -p 3306:3306 --name bael-mysql -e MYSQL_ROOT_PASSWORD=pass -e MYSQL_DATABASE=jdbc_authentication mysql:latest`) + * * the service up and running + * + */ +public class UserControllerLiveTest { + + private static final String PRINCIPAL_SVC_URL = "http://localhost:8082/principal"; + + @Test + public void givenExisting_whenRequestPrincipal_thenRetrieveData() throws Exception { + given().auth() + .preemptive() + .basic("user@email.com", "pass") + .when() + .get(PRINCIPAL_SVC_URL) + .then() + .statusCode(HttpStatus.OK.value()) + .and() + .body("authorities[0].authority", is("ROLE_USER")) + .body("principal.username", is("user@email.com")) + .body("name", is("user@email.com")); + } + +} diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/pom.xml b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/pom.xml new file mode 100644 index 0000000000..e68e47b596 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/pom.xml @@ -0,0 +1,28 @@ + + + 4.0.0 + com.baeldung + spring-security-mvc-boot-postgre + 0.0.1-SNAPSHOT + spring-security-mvc-boot-postgre + jar + Spring Security MVC Boot using PostgreSQL + + + spring-security-mvc-boot + com.baeldung + 0.0.1-SNAPSHOT + .. + + + + + org.postgresql + postgresql + runtime + + + + diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java new file mode 100644 index 0000000000..d4b555e8c6 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.jdbcauthentication.postgre; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class PostgreJdbcAuthenticationApplication { + + public static void main(String[] args) { + SpringApplication.run(PostgreJdbcAuthenticationApplication.class, args); + } + +} diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java new file mode 100644 index 0000000000..85dc9d364c --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java @@ -0,0 +1,29 @@ +package com.baeldung.jdbcauthentication.postgre.config; + +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +public class SecurityConfiguration { + + @Autowired + private DataSource dataSource; + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth.jdbcAuthentication() + .dataSource(dataSource); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + +} \ No newline at end of file diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/web/UserController.java b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/web/UserController.java new file mode 100644 index 0000000000..da85a46562 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/web/UserController.java @@ -0,0 +1,17 @@ +package com.baeldung.jdbcauthentication.postgre.web; + +import java.security.Principal; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/principal") +public class UserController { + + @GetMapping + public Principal retrievePrincipal(Principal principal) { + return principal; + } +} \ No newline at end of file diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/application.properties b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/application.properties new file mode 100644 index 0000000000..2940c5121e --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/application.properties @@ -0,0 +1,8 @@ +server.port=8082 + +spring.datasource.url=jdbc:postgresql://localhost:5432/jdbc_authentication +spring.datasource.username=postgres +spring.datasource.password=pass + +spring.datasource.initialization-mode=always +spring.jpa.hibernate.ddl-auto=none diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/data.sql b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/data.sql new file mode 100644 index 0000000000..fcc6b54949 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/data.sql @@ -0,0 +1,4 @@ +-- User user/pass +INSERT INTO users (username, password, enabled) values ('user', '$2a$10$8.UnVuG9HHgffUDAlk8qfOuVGkqRzgVymGe07xd00DMxs.AQubh4a', true); + +INSERT INTO authorities (username, authority) values ('user', 'ROLE_USER'); \ No newline at end of file diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/schema.sql b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/schema.sql new file mode 100644 index 0000000000..d78edfb528 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/schema.sql @@ -0,0 +1,16 @@ +DROP TABLE IF EXISTS authorities; +DROP TABLE IF EXISTS users; + +CREATE TABLE users ( + username varchar(50) NOT NULL PRIMARY KEY, + password varchar(100) NOT NULL, + enabled boolean not null DEFAULT true +); + +CREATE TABLE authorities ( + username varchar(50) NOT NULL, + authority varchar(50) NOT NULL, + CONSTRAINT foreign_authorities_users_1 foreign key(username) references users(username) +); + +CREATE UNIQUE INDEX ix_auth_username on authorities (username,authority); \ No newline at end of file diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/test/java/com/baeldung/jdbcauthentication/postgre/SpringContextIntegrationTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/test/java/com/baeldung/jdbcauthentication/postgre/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..f133ef73be --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/test/java/com/baeldung/jdbcauthentication/postgre/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package com.baeldung.jdbcauthentication.postgre; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.jdbcauthentication.postgre.PostgreJdbcAuthenticationApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = PostgreJdbcAuthenticationApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/test/java/com/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/test/java/com/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java new file mode 100644 index 0000000000..b5f4379c0a --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/test/java/com/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java @@ -0,0 +1,35 @@ +package com.baeldung.jdbcauthentication.postgre.web; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.is; + +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; + +/** + * This Live Test requires: + * * a PostgreSQL instance running, that allows a 'root' user with password 'pass', and with a database named jdbc_authentication + * (e.g. with the following command `docker run -p 5432:5432 --name bael-postgre -e POSTGRES_PASSWORD=pass -e POSTGRES_DB=jdbc_authentication postgres:latest`) + * * the service up and running + * + */ +public class UserControllerLiveTest { + + private static final String PRINCIPAL_SVC_URL = "http://localhost:8082/principal"; + + @Test + public void givenExisting_whenRequestPrincipal_thenRetrieveData() throws Exception { + given().auth() + .preemptive() + .basic("user", "pass") + .when() + .get(PRINCIPAL_SVC_URL) + .then() + .statusCode(HttpStatus.OK.value()) + .and() + .body("authorities[0].authority", is("ROLE_USER")) + .body("principal.username", is("user")) + .body("name", is("user")); + } + +} From f174fa0ae93e46820456607a141fa3fcfb52e53e Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Mon, 29 Jul 2019 09:55:54 -0300 Subject: [PATCH 74/84] Fix test naming, now renamed as LiveTest --- ...onIntegrationTest.java => SessionConfigurationLiveTest.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename spring-security-mvc/src/test/java/com/baeldung/session/{SessionConfigurationIntegrationTest.java => SessionConfigurationLiveTest.java} (98%) diff --git a/spring-security-mvc/src/test/java/com/baeldung/session/SessionConfigurationIntegrationTest.java b/spring-security-mvc/src/test/java/com/baeldung/session/SessionConfigurationLiveTest.java similarity index 98% rename from spring-security-mvc/src/test/java/com/baeldung/session/SessionConfigurationIntegrationTest.java rename to spring-security-mvc/src/test/java/com/baeldung/session/SessionConfigurationLiveTest.java index 5a9bf72077..7d9a03d5f6 100644 --- a/spring-security-mvc/src/test/java/com/baeldung/session/SessionConfigurationIntegrationTest.java +++ b/spring-security-mvc/src/test/java/com/baeldung/session/SessionConfigurationLiveTest.java @@ -15,7 +15,7 @@ import io.restassured.specification.RequestSpecification; /** * This Live Test requires the service to be up and running. */ -public class SessionConfigurationIntegrationTest { +public class SessionConfigurationLiveTest { private static final String USER = "user1"; private static final String PASSWORD = "user1Pass"; From 8f5bb3c6a94e64660abac317e0a52bd54908996a Mon Sep 17 00:00:00 2001 From: Paul Latzelsperger <43503240+beardyinc@users.noreply.github.com> Date: Mon, 29 Jul 2019 22:38:42 +0200 Subject: [PATCH 75/84] Bael 3082 (#7446) * added example code for BAEL-3082 * added another test case, refactored method names * moved to basics module --- .../failure_vs_error/SimpleCalculator.java | 15 +++++++ .../SimpleCalculatorUnitTest.java | 39 +++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 testing-modules/junit-5-basics/src/main/java/com/baeldung/failure_vs_error/SimpleCalculator.java create mode 100644 testing-modules/junit-5-basics/src/test/java/com/baeldung/failure_vs_error/SimpleCalculatorUnitTest.java diff --git a/testing-modules/junit-5-basics/src/main/java/com/baeldung/failure_vs_error/SimpleCalculator.java b/testing-modules/junit-5-basics/src/main/java/com/baeldung/failure_vs_error/SimpleCalculator.java new file mode 100644 index 0000000000..d018aa939f --- /dev/null +++ b/testing-modules/junit-5-basics/src/main/java/com/baeldung/failure_vs_error/SimpleCalculator.java @@ -0,0 +1,15 @@ +package com.baeldung.failure_vs_error; + +/** + * @author paullatzelsperger + * @since 2019-07-17 + */ +public class SimpleCalculator { + + public static double divideNumbers(double dividend, double divisor) { + if (divisor == 0) { + throw new ArithmeticException("Division by zero!"); + } + return dividend / divisor; + } +} diff --git a/testing-modules/junit-5-basics/src/test/java/com/baeldung/failure_vs_error/SimpleCalculatorUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/failure_vs_error/SimpleCalculatorUnitTest.java new file mode 100644 index 0000000000..6833834959 --- /dev/null +++ b/testing-modules/junit-5-basics/src/test/java/com/baeldung/failure_vs_error/SimpleCalculatorUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.failure_vs_error; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * @author paullatzelsperger + * @since 2019-07-17 + */ +class SimpleCalculatorUnitTest { + + @Test + void whenDivideByValidNumber_thenAssertCorrectResult() { + double result = SimpleCalculator.divideNumbers(6, 3); + assertEquals(2, result); + } + + @Test + @Disabled("test is expected to fail, disabled so that CI build still goes through") + void whenDivideNumbers_thenExpectWrongResult() { + double result = SimpleCalculator.divideNumbers(6, 3); + assertEquals(15, result); + } + + @Test + @Disabled("test is expected to raise an error, disabled so that CI build still goes through") + void whenDivideByZero_thenThrowsException() { + SimpleCalculator.divideNumbers(10, 0); + } + + @Test + void whenDivideByZero_thenAssertException(){ + assertThrows(ArithmeticException.class, () -> SimpleCalculator.divideNumbers(10, 0)); + } + +} From d9a20d17641f8a769cefe474684b955187de2b51 Mon Sep 17 00:00:00 2001 From: josephine-barboza Date: Tue, 30 Jul 2019 03:14:52 +0530 Subject: [PATCH 76/84] BAEL-2906 Functional Controllers in Spring MVC (#6972) * BAEL-2906 Functional Controllers in Spring MVC * BAEL-2906 Functional Controllers in Spring MVC * BAEL-2906 Functional Controllers in Spring MVC * BAEL-2906 Removed unnecessary files * BAEL-2906 Removed project * BAEL-2906 Removed comments --- spring-boot-mvc-2/.gitignore | 25 +++++++ spring-boot-mvc-2/README.md | 3 + spring-boot-mvc-2/pom.xml | 68 +++++++++++++++++ .../SpringBootMvcFnApplication.java | 74 +++++++++++++++++++ .../springbootmvc/ctrl/ProductController.java | 59 +++++++++++++++ .../baeldung/springbootmvc/model/Product.java | 72 ++++++++++++++++++ .../springbootmvc/svc/ProductService.java | 63 ++++++++++++++++ .../src/main/resources/application.properties | 1 + .../src/main/resources/logback.xml | 13 ++++ 9 files changed, 378 insertions(+) create mode 100644 spring-boot-mvc-2/.gitignore create mode 100644 spring-boot-mvc-2/README.md create mode 100644 spring-boot-mvc-2/pom.xml create mode 100644 spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/SpringBootMvcFnApplication.java create mode 100644 spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/ctrl/ProductController.java create mode 100644 spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/model/Product.java create mode 100644 spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/svc/ProductService.java create mode 100644 spring-boot-mvc-2/src/main/resources/application.properties create mode 100644 spring-boot-mvc-2/src/main/resources/logback.xml diff --git a/spring-boot-mvc-2/.gitignore b/spring-boot-mvc-2/.gitignore new file mode 100644 index 0000000000..82eca336e3 --- /dev/null +++ b/spring-boot-mvc-2/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/spring-boot-mvc-2/README.md b/spring-boot-mvc-2/README.md new file mode 100644 index 0000000000..a405298cbe --- /dev/null +++ b/spring-boot-mvc-2/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Functional Controllers in Spring MVC]() \ No newline at end of file diff --git a/spring-boot-mvc-2/pom.xml b/spring-boot-mvc-2/pom.xml new file mode 100644 index 0000000000..18121325a5 --- /dev/null +++ b/spring-boot-mvc-2/pom.xml @@ -0,0 +1,68 @@ + + + 4.0.0 + spring-boot-mvc-2 + spring-boot-mvc-2 + jar + Module For Spring Boot MVC Web Fn + + + org.springframework.boot + spring-boot-starter-parent + 2.2.0.BUILD-SNAPSHOT + + + + + + org.springframework.boot + spring-boot-starter-web + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.springbootmvc.SpringBootMvcFnApplication + JAR + + + + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + \ No newline at end of file diff --git a/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/SpringBootMvcFnApplication.java b/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/SpringBootMvcFnApplication.java new file mode 100644 index 0000000000..2a85550bd7 --- /dev/null +++ b/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/SpringBootMvcFnApplication.java @@ -0,0 +1,74 @@ +package com.baeldung.springbootmvc; + +import static org.springframework.web.servlet.function.RouterFunctions.route; +import static org.springframework.web.servlet.function.ServerResponse.notFound; +import static org.springframework.web.servlet.function.ServerResponse.status; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.http.HttpStatus; +import org.springframework.web.servlet.function.RequestPredicates; +import org.springframework.web.servlet.function.RouterFunction; +import org.springframework.web.servlet.function.ServerResponse; + +import com.baeldung.springbootmvc.ctrl.ProductController; +import com.baeldung.springbootmvc.svc.ProductService; + +@SpringBootApplication +public class SpringBootMvcFnApplication { + + private static final Logger LOG = LoggerFactory.getLogger(SpringBootMvcFnApplication.class); + + public static void main(String[] args) { + SpringApplication.run(SpringBootMvcFnApplication.class, args); + } + + @Bean + RouterFunction productListing(ProductController pc, ProductService ps) { + return pc.productListing(ps); + } + + @Bean + RouterFunction allApplicationRoutes(ProductController pc, ProductService ps) { + return route().add(pc.remainingProductRoutes(ps)) + .before(req -> { + LOG.info("Found a route which matches " + req.uri() + .getPath()); + return req; + }) + .after((req, res) -> { + if (res.statusCode() == HttpStatus.OK) { + LOG.info("Finished processing request " + req.uri() + .getPath()); + } else { + LOG.info("There was an error while processing request" + req.uri()); + } + return res; + }) + .onError(Throwable.class, (e, res) -> { + LOG.error("Fatal exception has occurred", e); + return status(HttpStatus.INTERNAL_SERVER_ERROR).build(); + }) + .build() + .and(route(RequestPredicates.all(), req -> notFound().build())); + } + + public static class Error { + private String errorMessage; + + public Error(String message) { + this.errorMessage = message; + } + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + } +} diff --git a/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/ctrl/ProductController.java b/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/ctrl/ProductController.java new file mode 100644 index 0000000000..6a77e72cea --- /dev/null +++ b/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/ctrl/ProductController.java @@ -0,0 +1,59 @@ +package com.baeldung.springbootmvc.ctrl; + +import static org.springframework.web.servlet.function.RouterFunctions.route; +import static org.springframework.web.servlet.function.ServerResponse.ok; +import static org.springframework.web.servlet.function.ServerResponse.status; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.function.EntityResponse; +import org.springframework.web.servlet.function.RequestPredicates; +import org.springframework.web.servlet.function.RouterFunction; +import org.springframework.web.servlet.function.ServerRequest; +import org.springframework.web.servlet.function.ServerResponse; + +import com.baeldung.springbootmvc.SpringBootMvcFnApplication.Error; +import com.baeldung.springbootmvc.model.Product; +import com.baeldung.springbootmvc.svc.ProductService; + +@Component +public class ProductController { + + public RouterFunction productListing(ProductService ps) { + return route().GET("/product", req -> ok().body(ps.findAll())) + .build(); + } + + public RouterFunction productSearch(ProductService ps) { + return route().nest(RequestPredicates.path("/product"), builder -> { + builder.GET("/name/{name}", req -> ok().body(ps.findByName(req.pathVariable("name")))) + .GET("/id/{id}", req -> ok().body(ps.findById(Integer.parseInt(req.pathVariable("id"))))); + }) + .onError(ProductService.ItemNotFoundException.class, (e, req) -> EntityResponse.fromObject(new Error(e.getMessage())) + .status(HttpStatus.NOT_FOUND) + .build()) + .build(); + } + + public RouterFunction adminFunctions(ProductService ps) { + return route().POST("/product", req -> ok().body(ps.save(req.body(Product.class)))) + .filter((req, next) -> authenticate(req) ? next.handle(req) : status(HttpStatus.UNAUTHORIZED).build()) + .onError(IllegalArgumentException.class, (e, req) -> EntityResponse.fromObject(new Error(e.getMessage())) + .status(HttpStatus.BAD_REQUEST) + .build()) + .build(); + } + + public RouterFunction remainingProductRoutes(ProductService ps) { + return route().add(productSearch(ps)) + .add(adminFunctions(ps)) + .build(); + } + + private boolean authenticate(ServerRequest req) { + return Boolean.TRUE; + } + +} diff --git a/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/model/Product.java b/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/model/Product.java new file mode 100644 index 0000000000..1213b3c11e --- /dev/null +++ b/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/model/Product.java @@ -0,0 +1,72 @@ +package com.baeldung.springbootmvc.model; + +public class Product { + private String name; + private double price; + private int id; + + public Product(String name, double price, int id) { + super(); + this.name = name; + this.price = price; + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public double getPrice() { + return price; + } + + public void setPrice(double price) { + this.price = price; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + id; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + long temp; + temp = Double.doubleToLongBits(price); + result = prime * result + (int) (temp ^ (temp >>> 32)); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Product other = (Product) obj; + if (id != other.id) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (Double.doubleToLongBits(price) != Double.doubleToLongBits(other.price)) + return false; + return true; + } + +} diff --git a/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/svc/ProductService.java b/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/svc/ProductService.java new file mode 100644 index 0000000000..e2d281d54f --- /dev/null +++ b/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/svc/ProductService.java @@ -0,0 +1,63 @@ +package com.baeldung.springbootmvc.svc; + +import java.util.HashSet; +import java.util.Set; + +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import com.baeldung.springbootmvc.model.Product; + +@Service +public class ProductService { + + private final Set products = new HashSet<>(); + + { + products.add(new Product("Book", 23.90, 1)); + products.add(new Product("Pen", 44.34, 2)); + } + + public Product findById(int id) { + return products.stream() + .filter(obj -> obj.getId() == id) + .findFirst() + .orElseThrow(() -> new ItemNotFoundException("Product not found")); + } + + public Product findByName(String name) { + return products.stream() + .filter(obj -> obj.getName() + .equalsIgnoreCase(name)) + .findFirst() + .orElseThrow(() -> new ItemNotFoundException("Product not found")); + } + + public Set findAll() { + return products; + } + + public Product save(Product product) { + if (StringUtils.isEmpty(product.getName()) || product.getPrice() == 0.0) { + throw new IllegalArgumentException(); + } + int newId = products.stream() + .mapToInt(Product::getId) + .max() + .getAsInt() + 1; + product.setId(newId); + products.add(product); + return product; + } + + public static class ItemNotFoundException extends RuntimeException { + /** + * + */ + private static final long serialVersionUID = 1L; + + public ItemNotFoundException(String msg) { + super(msg); + } + } +} diff --git a/spring-boot-mvc-2/src/main/resources/application.properties b/spring-boot-mvc-2/src/main/resources/application.properties new file mode 100644 index 0000000000..709574239b --- /dev/null +++ b/spring-boot-mvc-2/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.main.allow-bean-definition-overriding=true \ No newline at end of file diff --git a/spring-boot-mvc-2/src/main/resources/logback.xml b/spring-boot-mvc-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-boot-mvc-2/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file From 627fb4f1d114c81ceae4bbbbc04860ef026af182 Mon Sep 17 00:00:00 2001 From: maryarm <45322329+maryarm@users.noreply.github.com> Date: Tue, 30 Jul 2019 09:49:08 +0430 Subject: [PATCH 77/84] #BAEL-2888: Reloading Properties Files in Spring (#7427) -change package name to "com.baeldung.properties.reloading" -remove module 's ".gitignore" --- spring-boot-properties/.gitignore | 17 ----------------- .../SpringBootPropertiesApplication.java | 4 ++-- .../configs/PropertiesException.java | 2 +- .../configs/ReloadableProperties.java | 2 +- .../configs/ReloadablePropertySource.java | 2 +- .../configs/ReloadablePropertySourceConfig.java | 2 +- .../ReloadablePropertySourceFactory.java | 2 +- .../PropertiesReloadIntegrationTest.java | 10 +++++----- .../SpringBootPropertiesTestApplication.java | 4 ++-- ...onfigurationPropertiesRefreshConfigBean.java | 2 +- .../beans/EnvironmentConfigBean.java | 4 ++-- .../beans/PropertiesConfigBean.java | 2 +- .../beans/ValueRefreshConfigBean.java | 2 +- 13 files changed, 19 insertions(+), 36 deletions(-) delete mode 100644 spring-boot-properties/.gitignore rename spring-boot-properties/src/main/java/com/baeldung/properties/{ => reloading}/SpringBootPropertiesApplication.java (94%) rename spring-boot-properties/src/main/java/com/baeldung/properties/{ => reloading}/configs/PropertiesException.java (78%) rename spring-boot-properties/src/main/java/com/baeldung/properties/{ => reloading}/configs/ReloadableProperties.java (96%) rename spring-boot-properties/src/main/java/com/baeldung/properties/{ => reloading}/configs/ReloadablePropertySource.java (95%) rename spring-boot-properties/src/main/java/com/baeldung/properties/{ => reloading}/configs/ReloadablePropertySourceConfig.java (95%) rename spring-boot-properties/src/main/java/com/baeldung/properties/{ => reloading}/configs/ReloadablePropertySourceFactory.java (95%) rename spring-boot-properties/src/test/java/com/baeldung/properties/{ => reloading}/PropertiesReloadIntegrationTest.java (94%) rename spring-boot-properties/src/test/java/com/baeldung/properties/{ => reloading}/SpringBootPropertiesTestApplication.java (89%) rename spring-boot-properties/src/test/java/com/baeldung/properties/{ => reloading}/beans/ConfigurationPropertiesRefreshConfigBean.java (91%) rename spring-boot-properties/src/test/java/com/baeldung/properties/{ => reloading}/beans/EnvironmentConfigBean.java (85%) rename spring-boot-properties/src/test/java/com/baeldung/properties/{ => reloading}/beans/PropertiesConfigBean.java (90%) rename spring-boot-properties/src/test/java/com/baeldung/properties/{ => reloading}/beans/ValueRefreshConfigBean.java (81%) diff --git a/spring-boot-properties/.gitignore b/spring-boot-properties/.gitignore deleted file mode 100644 index 0532ef1888..0000000000 --- a/spring-boot-properties/.gitignore +++ /dev/null @@ -1,17 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear - -*.ipr -*.iml -*.iws diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/SpringBootPropertiesApplication.java b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/SpringBootPropertiesApplication.java similarity index 94% rename from spring-boot-properties/src/main/java/com/baeldung/properties/SpringBootPropertiesApplication.java rename to spring-boot-properties/src/main/java/com/baeldung/properties/reloading/SpringBootPropertiesApplication.java index 67bbddf9f1..6f76379a99 100644 --- a/spring-boot-properties/src/main/java/com/baeldung/properties/SpringBootPropertiesApplication.java +++ b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/SpringBootPropertiesApplication.java @@ -1,6 +1,6 @@ -package com.baeldung.properties; +package com.baeldung.properties.reloading; -import com.baeldung.properties.configs.ReloadableProperties; +import com.baeldung.properties.reloading.configs.ReloadableProperties; import java.io.File; import java.util.Properties; import org.apache.commons.configuration.PropertiesConfiguration; diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/configs/PropertiesException.java b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/PropertiesException.java similarity index 78% rename from spring-boot-properties/src/main/java/com/baeldung/properties/configs/PropertiesException.java rename to spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/PropertiesException.java index 5ec3a042f7..09c18aef33 100644 --- a/spring-boot-properties/src/main/java/com/baeldung/properties/configs/PropertiesException.java +++ b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/PropertiesException.java @@ -1,4 +1,4 @@ -package com.baeldung.properties.configs; +package com.baeldung.properties.reloading.configs; public class PropertiesException extends RuntimeException { public PropertiesException() { diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadableProperties.java b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadableProperties.java similarity index 96% rename from spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadableProperties.java rename to spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadableProperties.java index 33d503b9bd..e90e68d09a 100644 --- a/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadableProperties.java +++ b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadableProperties.java @@ -1,4 +1,4 @@ -package com.baeldung.properties.configs; +package com.baeldung.properties.reloading.configs; import java.io.FileReader; import java.io.IOException; diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySource.java b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySource.java similarity index 95% rename from spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySource.java rename to spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySource.java index 8a0cef955f..6d76a2e1e2 100644 --- a/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySource.java +++ b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySource.java @@ -1,4 +1,4 @@ -package com.baeldung.properties.configs; +package com.baeldung.properties.reloading.configs; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy; diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySourceConfig.java b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySourceConfig.java similarity index 95% rename from spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySourceConfig.java rename to spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySourceConfig.java index 37e1a04839..dd70e3842e 100644 --- a/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySourceConfig.java +++ b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySourceConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.properties.configs; +package com.baeldung.properties.reloading.configs; import org.apache.commons.configuration.PropertiesConfiguration; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySourceFactory.java b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySourceFactory.java similarity index 95% rename from spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySourceFactory.java rename to spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySourceFactory.java index 574362b3bf..2a620b0b2d 100644 --- a/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySourceFactory.java +++ b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySourceFactory.java @@ -1,4 +1,4 @@ -package com.baeldung.properties.configs; +package com.baeldung.properties.reloading.configs; import java.io.IOException; import org.springframework.core.env.PropertySource; diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/PropertiesReloadIntegrationTest.java b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/PropertiesReloadIntegrationTest.java similarity index 94% rename from spring-boot-properties/src/test/java/com/baeldung/properties/PropertiesReloadIntegrationTest.java rename to spring-boot-properties/src/test/java/com/baeldung/properties/reloading/PropertiesReloadIntegrationTest.java index a73311ded8..0c28cb085b 100644 --- a/spring-boot-properties/src/test/java/com/baeldung/properties/PropertiesReloadIntegrationTest.java +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/PropertiesReloadIntegrationTest.java @@ -1,9 +1,9 @@ -package com.baeldung.properties; +package com.baeldung.properties.reloading; -import com.baeldung.properties.beans.ConfigurationPropertiesRefreshConfigBean; -import com.baeldung.properties.beans.EnvironmentConfigBean; -import com.baeldung.properties.beans.PropertiesConfigBean; -import com.baeldung.properties.beans.ValueRefreshConfigBean; +import com.baeldung.properties.reloading.beans.ConfigurationPropertiesRefreshConfigBean; +import com.baeldung.properties.reloading.beans.EnvironmentConfigBean; +import com.baeldung.properties.reloading.beans.PropertiesConfigBean; +import com.baeldung.properties.reloading.beans.ValueRefreshConfigBean; import java.io.FileOutputStream; import org.junit.After; import org.junit.Assert; diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/SpringBootPropertiesTestApplication.java b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/SpringBootPropertiesTestApplication.java similarity index 89% rename from spring-boot-properties/src/test/java/com/baeldung/properties/SpringBootPropertiesTestApplication.java rename to spring-boot-properties/src/test/java/com/baeldung/properties/reloading/SpringBootPropertiesTestApplication.java index c572a6c053..50e8ef5b62 100644 --- a/spring-boot-properties/src/test/java/com/baeldung/properties/SpringBootPropertiesTestApplication.java +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/SpringBootPropertiesTestApplication.java @@ -1,6 +1,6 @@ -package com.baeldung.properties; +package com.baeldung.properties.reloading; -import com.baeldung.properties.beans.ValueRefreshConfigBean; +import com.baeldung.properties.reloading.beans.ValueRefreshConfigBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.context.config.annotation.RefreshScope; diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/beans/ConfigurationPropertiesRefreshConfigBean.java b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/ConfigurationPropertiesRefreshConfigBean.java similarity index 91% rename from spring-boot-properties/src/test/java/com/baeldung/properties/beans/ConfigurationPropertiesRefreshConfigBean.java rename to spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/ConfigurationPropertiesRefreshConfigBean.java index 31f168fdcc..16892b904b 100644 --- a/spring-boot-properties/src/test/java/com/baeldung/properties/beans/ConfigurationPropertiesRefreshConfigBean.java +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/ConfigurationPropertiesRefreshConfigBean.java @@ -1,4 +1,4 @@ -package com.baeldung.properties.beans; +package com.baeldung.properties.reloading.beans; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.context.config.annotation.RefreshScope; diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/beans/EnvironmentConfigBean.java b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/EnvironmentConfigBean.java similarity index 85% rename from spring-boot-properties/src/test/java/com/baeldung/properties/beans/EnvironmentConfigBean.java rename to spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/EnvironmentConfigBean.java index fef12f8656..325e8c658e 100644 --- a/spring-boot-properties/src/test/java/com/baeldung/properties/beans/EnvironmentConfigBean.java +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/EnvironmentConfigBean.java @@ -1,6 +1,6 @@ -package com.baeldung.properties.beans; +package com.baeldung.properties.reloading.beans; -import com.baeldung.properties.configs.ReloadablePropertySourceFactory; +import com.baeldung.properties.reloading.configs.ReloadablePropertySourceFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/beans/PropertiesConfigBean.java b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/PropertiesConfigBean.java similarity index 90% rename from spring-boot-properties/src/test/java/com/baeldung/properties/beans/PropertiesConfigBean.java rename to spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/PropertiesConfigBean.java index da773b283a..8118f6156e 100644 --- a/spring-boot-properties/src/test/java/com/baeldung/properties/beans/PropertiesConfigBean.java +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/PropertiesConfigBean.java @@ -1,4 +1,4 @@ -package com.baeldung.properties.beans; +package com.baeldung.properties.reloading.beans; import java.util.Properties; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/beans/ValueRefreshConfigBean.java b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/ValueRefreshConfigBean.java similarity index 81% rename from spring-boot-properties/src/test/java/com/baeldung/properties/beans/ValueRefreshConfigBean.java rename to spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/ValueRefreshConfigBean.java index d806938092..1018d7c9f5 100644 --- a/spring-boot-properties/src/test/java/com/baeldung/properties/beans/ValueRefreshConfigBean.java +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/ValueRefreshConfigBean.java @@ -1,4 +1,4 @@ -package com.baeldung.properties.beans; +package com.baeldung.properties.reloading.beans; public class ValueRefreshConfigBean { private String color; From 36ad6f15ef1b1f5db8aeb1e6d0257d12a1adccb2 Mon Sep 17 00:00:00 2001 From: Kumar Chandrakant Date: Tue, 30 Jul 2019 11:39:34 +0530 Subject: [PATCH 78/84] Adding code for the tutorial tracked under BAEL-3073. (#7442) --- .../baeldung/sasl/ClientCallbackHandler.java | 29 +++++++ .../baeldung/sasl/ServerCallbackHandler.java | 34 +++++++++ .../java/com/baeldung/sasl/SaslUnitTest.java | 76 +++++++++++++++++++ 3 files changed, 139 insertions(+) create mode 100644 core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ClientCallbackHandler.java create mode 100644 core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ServerCallbackHandler.java create mode 100644 core-java-modules/core-java-security/src/test/java/com/baeldung/sasl/SaslUnitTest.java diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ClientCallbackHandler.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ClientCallbackHandler.java new file mode 100644 index 0000000000..d73f2a2708 --- /dev/null +++ b/core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ClientCallbackHandler.java @@ -0,0 +1,29 @@ +package com.baeldung.sasl; + +import java.io.IOException; + +import javax.security.auth.callback.Callback; +import javax.security.auth.callback.CallbackHandler; +import javax.security.auth.callback.NameCallback; +import javax.security.auth.callback.PasswordCallback; +import javax.security.auth.callback.UnsupportedCallbackException; +import javax.security.sasl.RealmCallback; + +public class ClientCallbackHandler implements CallbackHandler { + + @Override + public void handle(Callback[] cbs) throws IOException, UnsupportedCallbackException { + for (Callback cb : cbs) { + if (cb instanceof NameCallback) { + NameCallback nc = (NameCallback) cb; + nc.setName("username"); + } else if (cb instanceof PasswordCallback) { + PasswordCallback pc = (PasswordCallback) cb; + pc.setPassword("password".toCharArray()); + } else if (cb instanceof RealmCallback) { + RealmCallback rc = (RealmCallback) cb; + rc.setText("myServer"); + } + } + } +} diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ServerCallbackHandler.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ServerCallbackHandler.java new file mode 100644 index 0000000000..3e071d68cc --- /dev/null +++ b/core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ServerCallbackHandler.java @@ -0,0 +1,34 @@ +package com.baeldung.sasl; + +import java.io.IOException; + +import javax.security.auth.callback.Callback; +import javax.security.auth.callback.CallbackHandler; +import javax.security.auth.callback.NameCallback; +import javax.security.auth.callback.PasswordCallback; +import javax.security.auth.callback.UnsupportedCallbackException; +import javax.security.sasl.AuthorizeCallback; +import javax.security.sasl.RealmCallback; + +public class ServerCallbackHandler implements CallbackHandler { + + @Override + public void handle(Callback[] cbs) throws IOException, UnsupportedCallbackException { + for (Callback cb : cbs) { + if (cb instanceof AuthorizeCallback) { + AuthorizeCallback ac = (AuthorizeCallback) cb; + ac.setAuthorized(true); + } else if (cb instanceof NameCallback) { + NameCallback nc = (NameCallback) cb; + nc.setName("username"); + + } else if (cb instanceof PasswordCallback) { + PasswordCallback pc = (PasswordCallback) cb; + pc.setPassword("password".toCharArray()); + } else if (cb instanceof RealmCallback) { + RealmCallback rc = (RealmCallback) cb; + rc.setText("myServer"); + } + } + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-security/src/test/java/com/baeldung/sasl/SaslUnitTest.java b/core-java-modules/core-java-security/src/test/java/com/baeldung/sasl/SaslUnitTest.java new file mode 100644 index 0000000000..6601654781 --- /dev/null +++ b/core-java-modules/core-java-security/src/test/java/com/baeldung/sasl/SaslUnitTest.java @@ -0,0 +1,76 @@ +package com.baeldung.sasl; + +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; + +import javax.security.sasl.Sasl; +import javax.security.sasl.SaslClient; +import javax.security.sasl.SaslException; +import javax.security.sasl.SaslServer; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class SaslUnitTest { + + private static final String MECHANISM = "DIGEST-MD5"; + private static final String SERVER_NAME = "myServer"; + private static final String PROTOCOL = "myProtocol"; + private static final String AUTHORIZATION_ID = null; + private static final String QOP_LEVEL = "auth-conf"; + + private SaslServer saslServer; + private SaslClient saslClient; + + @Before + public void setUp() throws SaslException { + + ServerCallbackHandler serverHandler = new ServerCallbackHandler(); + ClientCallbackHandler clientHandler = new ClientCallbackHandler(); + + Map props = new HashMap<>(); + props.put(Sasl.QOP, QOP_LEVEL); + + saslServer = Sasl.createSaslServer(MECHANISM, PROTOCOL, SERVER_NAME, props, serverHandler); + saslClient = Sasl.createSaslClient(new String[] { MECHANISM }, AUTHORIZATION_ID, PROTOCOL, SERVER_NAME, props, clientHandler); + + } + + @Test + public void givenHandlers_whenStarted_thenAutenticationWorks() throws SaslException { + + byte[] challenge; + byte[] response; + + challenge = saslServer.evaluateResponse(new byte[0]); + response = saslClient.evaluateChallenge(challenge); + + challenge = saslServer.evaluateResponse(response); + response = saslClient.evaluateChallenge(challenge); + + assertTrue(saslServer.isComplete()); + assertTrue(saslClient.isComplete()); + + String qop = (String) saslClient.getNegotiatedProperty(Sasl.QOP); + assertEquals("auth-conf", qop); + + byte[] outgoing = "Baeldung".getBytes(); + byte[] secureOutgoing = saslClient.wrap(outgoing, 0, outgoing.length); + + byte[] secureIncoming = secureOutgoing; + byte[] incoming = saslServer.unwrap(secureIncoming, 0, secureIncoming.length); + assertEquals("Baeldung", new String(incoming, StandardCharsets.UTF_8)); + } + + @After + public void tearDown() throws SaslException { + saslClient.dispose(); + saslServer.dispose(); + } + +} From 8e3f2ae495116db8bfaf35f035351fe2c4d73218 Mon Sep 17 00:00:00 2001 From: Krzysztof Majewski Date: Tue, 30 Jul 2019 08:35:24 +0200 Subject: [PATCH 79/84] update --- persistence-modules/java-jpa-2/pom.xml | 96 +++++++++---------- .../java-jpa-2/src/main/resources/logback.xml | 13 --- 2 files changed, 48 insertions(+), 61 deletions(-) delete mode 100644 persistence-modules/java-jpa-2/src/main/resources/logback.xml diff --git a/persistence-modules/java-jpa-2/pom.xml b/persistence-modules/java-jpa-2/pom.xml index c8c9a24599..12586db1b7 100644 --- a/persistence-modules/java-jpa-2/pom.xml +++ b/persistence-modules/java-jpa-2/pom.xml @@ -19,11 +19,11 @@ hibernate-core ${hibernate.version} - - org.hibernate - hibernate-jpamodelgen - ${hibernate.version} - + + org.hibernate + hibernate-jpamodelgen + ${hibernate.version} + com.h2database h2 @@ -52,8 +52,8 @@
    - - + + org.apache.maven.plugins maven-compiler-plugin @@ -62,48 +62,48 @@ -proc:none - - org.bsc.maven - maven-processor-plugin - 3.3.3 - - - process - - process - - generate-sources - - target/metamodel - - org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor - - - - - + + org.bsc.maven + maven-processor-plugin + 3.3.3 + + + process + + process + + generate-sources + + target/metamodel + + org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor + + + + + - - org.codehaus.mojo - build-helper-maven-plugin - 3.0.0 - - - add-source - generate-sources - - add-source - - - - target/metamodel - - - - - - - + + org.codehaus.mojo + build-helper-maven-plugin + 3.0.0 + + + add-source + generate-sources + + add-source + + + + target/metamodel + + + + + + + 5.4.0.Final diff --git a/persistence-modules/java-jpa-2/src/main/resources/logback.xml b/persistence-modules/java-jpa-2/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/persistence-modules/java-jpa-2/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file From 2aa2f078ddb720ebf555f84cdd98bc237a363012 Mon Sep 17 00:00:00 2001 From: "sreekanth.nair" Date: Tue, 30 Jul 2019 12:55:29 +0530 Subject: [PATCH 80/84] [BAEL-3121] Added source for finding number of lines in a file --- .../main/java/com/baeldung/files/Main.java | 24 ++++ .../baeldung/files/NumberOfLineFinder.java | 112 ++++++++++++++++++ .../file/NumberOfLineFinderUnitTest.java | 60 ++++++++++ 3 files changed, 196 insertions(+) create mode 100644 core-java-modules/core-java-io/src/main/java/com/baeldung/files/Main.java create mode 100644 core-java-modules/core-java-io/src/main/java/com/baeldung/files/NumberOfLineFinder.java create mode 100644 core-java-modules/core-java-io/src/test/java/com/baeldung/file/NumberOfLineFinderUnitTest.java diff --git a/core-java-modules/core-java-io/src/main/java/com/baeldung/files/Main.java b/core-java-modules/core-java-io/src/main/java/com/baeldung/files/Main.java new file mode 100644 index 0000000000..c3bcd048a4 --- /dev/null +++ b/core-java-modules/core-java-io/src/main/java/com/baeldung/files/Main.java @@ -0,0 +1,24 @@ +package com.baeldung.files; + +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingApacheCommonsIO; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingBufferedReader; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingGoogleGuava; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingLineNumberReader; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFileChannel; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFiles; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingScanner; + +public class Main { + + private static final String INPUT_FILE_NAME = "src/main/resources/input.txt"; + + public static void main(String... args) throws Exception { + System.out.printf("Total Number of Lines Using BufferedReader: %s%n", getTotalNumberOfLinesUsingBufferedReader(INPUT_FILE_NAME)); + System.out.printf("Total Number of Lines Using LineNumberReader: %s%n", getTotalNumberOfLinesUsingLineNumberReader(INPUT_FILE_NAME)); + System.out.printf("Total Number of Lines Using Scanner: %s%n", getTotalNumberOfLinesUsingScanner(INPUT_FILE_NAME)); + System.out.printf("Total Number of Lines Using NIO Files: %s%n", getTotalNumberOfLinesUsingNIOFiles(INPUT_FILE_NAME)); + System.out.printf("Total Number of Lines Using NIO FileChannel: %s%n", getTotalNumberOfLinesUsingNIOFileChannel(INPUT_FILE_NAME)); + System.out.printf("Total Number of Lines Using Apache Commons IO: %s%n", getTotalNumberOfLinesUsingApacheCommonsIO(INPUT_FILE_NAME)); + System.out.printf("Total Number of Lines Using NIO Google Guava: %s%n", getTotalNumberOfLinesUsingGoogleGuava(INPUT_FILE_NAME)); + } +} diff --git a/core-java-modules/core-java-io/src/main/java/com/baeldung/files/NumberOfLineFinder.java b/core-java-modules/core-java-io/src/main/java/com/baeldung/files/NumberOfLineFinder.java new file mode 100644 index 0000000000..076825d76c --- /dev/null +++ b/core-java-modules/core-java-io/src/main/java/com/baeldung/files/NumberOfLineFinder.java @@ -0,0 +1,112 @@ +package com.baeldung.files; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.LineNumberReader; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.channels.FileChannel.MapMode; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.List; +import java.util.Scanner; +import java.util.stream.Stream; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.LineIterator; + +public class NumberOfLineFinder { + + public static int getTotalNumberOfLinesUsingBufferedReader(String fileName) { + int lines = 0; + try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) { + while (reader.readLine() != null) { + lines++; + } + } catch (IOException ioe) { + ioe.printStackTrace(); + } + return lines; + } + + public static int getTotalNumberOfLinesUsingLineNumberReader(String fileName) { + int lines = 0; + try (LineNumberReader reader = new LineNumberReader(new FileReader(fileName))) { + reader.skip(Integer.MAX_VALUE); + lines = reader.getLineNumber() + 1; + } catch (IOException ioe) { + ioe.printStackTrace(); + } + return lines; + } + + public static int getTotalNumberOfLinesUsingScanner(String fileName) { + int lines = 0; + try (Scanner scanner = new Scanner(new FileReader(fileName))) { + while (scanner.hasNextLine()) { + scanner.nextLine(); + lines++; + } + } catch (IOException ioe) { + ioe.printStackTrace(); + } + return lines; + } + + public static int getTotalNumberOfLinesUsingNIOFiles(String fileName) { + int lines = 0; + try (Stream fileStream = Files.lines(Paths.get(fileName))) { + lines = (int) fileStream.count(); + } catch (IOException ioe) { + ioe.printStackTrace(); + } + return lines; + } + + public static int getTotalNumberOfLinesUsingNIOFileChannel(String fileName) { + int lines = 1; + try (FileChannel channel = FileChannel.open(Paths.get(fileName), StandardOpenOption.READ)) { + ByteBuffer byteBuffer = channel.map(MapMode.READ_ONLY, 0, channel.size()); + while (byteBuffer.hasRemaining()) { + byte currentChar = byteBuffer.get(); + if (currentChar == '\n') { + lines++; + } + } + } catch (IOException ioe) { + ioe.printStackTrace(); + } + return lines; + } + + public static int getTotalNumberOfLinesUsingApacheCommonsIO(String fileName) { + int lines = 0; + try { + LineIterator lineIterator = FileUtils.lineIterator(new File(fileName)); + while (lineIterator.hasNext()) { + lineIterator.nextLine(); + lines++; + } + } catch (IOException ioe) { + ioe.printStackTrace(); + } + return lines; + } + + public static int getTotalNumberOfLinesUsingGoogleGuava(String fileName) { + int lines = 0; + try { + List lineItems = com.google.common.io.Files.readLines(Paths.get(fileName) + .toFile(), Charset.defaultCharset()); + lines = lineItems.size(); + } catch (IOException ioe) { + ioe.printStackTrace(); + } + return lines; + } + +} diff --git a/core-java-modules/core-java-io/src/test/java/com/baeldung/file/NumberOfLineFinderUnitTest.java b/core-java-modules/core-java-io/src/test/java/com/baeldung/file/NumberOfLineFinderUnitTest.java new file mode 100644 index 0000000000..6f0427ebd2 --- /dev/null +++ b/core-java-modules/core-java-io/src/test/java/com/baeldung/file/NumberOfLineFinderUnitTest.java @@ -0,0 +1,60 @@ +package com.baeldung.file; + +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingApacheCommonsIO; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingBufferedReader; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingGoogleGuava; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingLineNumberReader; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFileChannel; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFiles; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingScanner; +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class NumberOfLineFinderUnitTest { + private static final String INPUT_FILE_NAME = "src/main/resources/input.txt"; + private static final int ACTUAL_LINE_COUNT = 45; + + @Test + public void whenUsingBufferedReader_thenReturnTotalNumberOfLines() { + int lines = getTotalNumberOfLinesUsingBufferedReader(INPUT_FILE_NAME); + assertEquals(ACTUAL_LINE_COUNT, lines); + } + + @Test + public void whenUsingLineNumberReader_thenReturnTotalNumberOfLines() { + int lines = getTotalNumberOfLinesUsingLineNumberReader(INPUT_FILE_NAME); + assertEquals(ACTUAL_LINE_COUNT, lines); + } + + @Test + public void whenUsingScanner_thenReturnTotalNumberOfLines() { + int lines = getTotalNumberOfLinesUsingScanner(INPUT_FILE_NAME); + assertEquals(ACTUAL_LINE_COUNT, lines); + } + + @Test + public void whenUsingNIOFiles_thenReturnTotalNumberOfLines() { + int lines = getTotalNumberOfLinesUsingNIOFiles(INPUT_FILE_NAME); + assertEquals(ACTUAL_LINE_COUNT, lines); + } + + @Test + public void whenUsingNIOFileChannel_thenReturnTotalNumberOfLines() { + int lines = getTotalNumberOfLinesUsingNIOFileChannel(INPUT_FILE_NAME); + assertEquals(ACTUAL_LINE_COUNT, lines); + } + + @Test + public void whenUsingApacheCommonsIO_thenReturnTotalNumberOfLines() { + int lines = getTotalNumberOfLinesUsingApacheCommonsIO(INPUT_FILE_NAME); + assertEquals(ACTUAL_LINE_COUNT, lines); + } + + @Test + public void whenUsingGoogleGuava_thenReturnTotalNumberOfLines() { + int lines = getTotalNumberOfLinesUsingGoogleGuava(INPUT_FILE_NAME); + assertEquals(ACTUAL_LINE_COUNT, lines); + } + +} From 19d73e961173a82aa8822589986d113f75355b68 Mon Sep 17 00:00:00 2001 From: Alessio Stalla Date: Tue, 30 Jul 2019 14:36:32 +0200 Subject: [PATCH 81/84] Fix parent POM --- persistence-modules/java-sql2o/pom.xml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/persistence-modules/java-sql2o/pom.xml b/persistence-modules/java-sql2o/pom.xml index 54838c32cb..fe5a0e5dc8 100644 --- a/persistence-modules/java-sql2o/pom.xml +++ b/persistence-modules/java-sql2o/pom.xml @@ -2,7 +2,6 @@ 4.0.0 - com.baeldung java-sql2o 1.0-SNAPSHOT @@ -19,12 +18,12 @@ java-sql2o - + From db90a53e38b269698646678c4a6c20ad2d69cbc7 Mon Sep 17 00:00:00 2001 From: Justin Albano Date: Tue, 30 Jul 2019 15:54:17 -0400 Subject: [PATCH 82/84] BAEL-3141: Added test cases for String to Double conversion. (#7448) These tests exercise the conversion of Strings that can be converted to Doubles, as well as the exceptions that are thrown for invalid Strings. --- .../StringToDoubleConversionUnitTest.java | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 java-strings-2/src/test/java/com/baeldung/string/todouble/StringToDoubleConversionUnitTest.java diff --git a/java-strings-2/src/test/java/com/baeldung/string/todouble/StringToDoubleConversionUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/todouble/StringToDoubleConversionUnitTest.java new file mode 100644 index 0000000000..9abb7ac453 --- /dev/null +++ b/java-strings-2/src/test/java/com/baeldung/string/todouble/StringToDoubleConversionUnitTest.java @@ -0,0 +1,56 @@ +package com.baeldung.string.todouble; + +import static org.junit.Assert.assertEquals; + +import java.text.DecimalFormat; +import java.text.ParseException; + +import org.junit.Test; + +public class StringToDoubleConversionUnitTest { + + @Test + public void givenValidString_WhenParseDouble_ThenResultIsPrimitiveDouble() { + assertEquals(1.23, Double.parseDouble("1.23"), 0.000001); + } + + @Test(expected = NullPointerException.class) + public void givenNullString_WhenParseDouble_ThenNullPointerExceptionIsThrown() { + Double.parseDouble(null); + } + + @Test(expected = NumberFormatException.class) + public void givenInalidString_WhenParseDouble_ThenNumberFormatExceptionIsThrown() { + Double.parseDouble("&"); + } + + @Test + public void givenValidString_WhenValueOf_ThenResultIsPrimitiveDouble() { + assertEquals(1.23, Double.valueOf("1.23"), 0.000001); + } + + @Test(expected = NullPointerException.class) + public void givenNullString_WhenValueOf_ThenNullPointerExceptionIsThrown() { + Double.valueOf(null); + } + + @Test(expected = NumberFormatException.class) + public void givenInalidString_WhenValueOf_ThenNumberFormatExceptionIsThrown() { + Double.valueOf("&"); + } + + @Test + public void givenValidString_WhenDecimalFormat_ThenResultIsValidDouble() throws ParseException { + assertEquals(1.23, new DecimalFormat("#").parse("1.23").doubleValue(), 0.000001); + } + + @Test(expected = NullPointerException.class) + public void givenNullString_WhenDecimalFormat_ThenNullPointerExceptionIsThrown() throws ParseException { + new DecimalFormat("#").parse(null); + } + + @Test(expected = ParseException.class) + public void givenInvalidString_WhenDecimalFormat_ThenParseExceptionIsThrown() throws ParseException { + new DecimalFormat("#").parse("&"); + } +} From ecf8bd76cc7232e6d1a23cc16a651fea7abeb435 Mon Sep 17 00:00:00 2001 From: Sumeet Gajbhar Date: Wed, 31 Jul 2019 01:42:25 +0530 Subject: [PATCH 83/84] BAEL-3027 binary number arithmetic operations (#7437) * BAEL-3027 binary number arithmetic operations * BAEL-3127 updated the unit test case names * added unit test cases for built-in java functions * updated function name * BAEL-3127 updated unit test case names * BAEL-3127 removed comments from code --- .../baeldung/binarynumbers/BinaryNumbers.java | 148 ++++++++++++++++++ .../binarynumbers/BinaryNumbersUnitTest.java | 73 +++++++++ 2 files changed, 221 insertions(+) create mode 100644 java-numbers-2/src/main/java/com/baeldung/binarynumbers/BinaryNumbers.java create mode 100644 java-numbers-2/src/test/java/com/baeldung/binarynumbers/BinaryNumbersUnitTest.java diff --git a/java-numbers-2/src/main/java/com/baeldung/binarynumbers/BinaryNumbers.java b/java-numbers-2/src/main/java/com/baeldung/binarynumbers/BinaryNumbers.java new file mode 100644 index 0000000000..effdee07ad --- /dev/null +++ b/java-numbers-2/src/main/java/com/baeldung/binarynumbers/BinaryNumbers.java @@ -0,0 +1,148 @@ +package com.baeldung.binarynumbers; + +public class BinaryNumbers { + + /** + * This method takes a decimal number and convert it into a binary number. + * example:- input:10, output:1010 + * + * @param decimalNumber + * @return binary number + */ + public Integer convertDecimalToBinary(Integer decimalNumber) { + + if (decimalNumber == 0) { + return decimalNumber; + } + + StringBuilder binaryNumber = new StringBuilder(); + + while (decimalNumber > 0) { + + int remainder = decimalNumber % 2; + int result = decimalNumber / 2; + + binaryNumber.append(remainder); + decimalNumber = result; + } + + binaryNumber = binaryNumber.reverse(); + + return Integer.valueOf(binaryNumber.toString()); + } + + /** + * This method takes a binary number and convert it into a decimal number. + * example:- input:101, output:5 + * + * @param binary number + * @return decimal Number + */ + public Integer convertBinaryToDecimal(Integer binaryNumber) { + + Integer result = 0; + Integer base = 1; + + while (binaryNumber > 0) { + + int lastDigit = binaryNumber % 10; + binaryNumber = binaryNumber / 10; + + result += lastDigit * base; + + base = base * 2; + } + return result; + } + + /** + * This method accepts two binary numbers and returns sum of input numbers. + * Example:- firstNum: 101, secondNum: 100, output: 1001 + * + * @param firstNum + * @param secondNum + * @return addition of input numbers + */ + public Integer addBinaryNumber(Integer firstNum, Integer secondNum) { + + StringBuilder output = new StringBuilder(); + + int carry = 0; + int temp; + + while (firstNum != 0 || secondNum != 0) { + + temp = (firstNum % 10 + secondNum % 10 + carry) % 2; + output.append(temp); + + carry = (firstNum % 10 + secondNum % 10 + carry) / 2; + + firstNum = firstNum / 10; + secondNum = secondNum / 10; + } + + if (carry != 0) { + output.append(carry); + } + + return Integer.valueOf(output.reverse() + .toString()); + } + + /** + * This method takes two binary number as input and subtract second number from the first number. + * example:- firstNum: 1000, secondNum: 11, output: 101 + * @param firstNum + * @param secondNum + * @return Result of subtraction of secondNum from first + */ + public Integer substractBinaryNumber(Integer firstNum, Integer secondNum) { + + int onesComplement = Integer.valueOf(getOnesComplement(secondNum)); + + StringBuilder output = new StringBuilder(); + + int carry = 0; + int temp; + + while (firstNum != 0 || onesComplement != 0) { + + temp = (firstNum % 10 + onesComplement % 10 + carry) % 2; + output.append(temp); + + carry = (firstNum % 10 + onesComplement % 10 + carry) / 2; + + firstNum = firstNum / 10; + onesComplement = onesComplement / 10; + } + + String additionOfFirstNumAndOnesComplement = output.reverse() + .toString(); + + if (carry == 1) { + return addBinaryNumber(Integer.valueOf(additionOfFirstNumAndOnesComplement), carry); + } else { + return getOnesComplement(Integer.valueOf(additionOfFirstNumAndOnesComplement)); + } + + } + + public Integer getOnesComplement(Integer num) { + + StringBuilder onesComplement = new StringBuilder(); + + while (num > 0) { + int lastDigit = num % 10; + if (lastDigit == 0) { + onesComplement.append(1); + } else { + onesComplement.append(0); + } + num = num / 10; + } + + return Integer.valueOf(onesComplement.reverse() + .toString()); + } + +} diff --git a/java-numbers-2/src/test/java/com/baeldung/binarynumbers/BinaryNumbersUnitTest.java b/java-numbers-2/src/test/java/com/baeldung/binarynumbers/BinaryNumbersUnitTest.java new file mode 100644 index 0000000000..ca6022261d --- /dev/null +++ b/java-numbers-2/src/test/java/com/baeldung/binarynumbers/BinaryNumbersUnitTest.java @@ -0,0 +1,73 @@ +package com.baeldung.binarynumbers; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class BinaryNumbersUnitTest { + + private BinaryNumbers binaryNumbers = new BinaryNumbers(); + + @Test + public void given_decimalNumber_then_returnBinaryNumber() { + assertEquals(Integer.valueOf(1000), binaryNumbers.convertDecimalToBinary(8)); + assertEquals(Integer.valueOf(10100), binaryNumbers.convertDecimalToBinary(20)); + } + + @Test + public void given_decimalNumber_then_convertToBinaryNumber() { + assertEquals("1000", Integer.toBinaryString(8)); + assertEquals("10100", Integer.toBinaryString(20)); + } + + @Test + public void given_binaryNumber_then_ConvertToDecimalNumber() { + assertEquals(8, Integer.parseInt("1000", 2)); + assertEquals(20, Integer.parseInt("10100", 2)); + } + + @Test + public void given_binaryNumber_then_returnDecimalNumber() { + assertEquals(Integer.valueOf(8), binaryNumbers.convertBinaryToDecimal(1000)); + assertEquals(Integer.valueOf(20), binaryNumbers.convertBinaryToDecimal(10100)); + } + + @Test + public void given_twoBinaryNumber_then_returnAddition() { + // adding 4 and 10 + assertEquals(Integer.valueOf(1110), binaryNumbers.addBinaryNumber(100, 1010)); + + // adding 26 and 14 + assertEquals(Integer.valueOf(101000), binaryNumbers.addBinaryNumber(11010, 1110)); + } + + @Test + public void given_twoBinaryNumber_then_returnSubtraction() { + // subtracting 16 from 25 + assertEquals(Integer.valueOf(1001), binaryNumbers.substractBinaryNumber(11001, 10000)); + + // subtracting 29 from 16, the output here is negative + assertEquals(Integer.valueOf(1101), binaryNumbers.substractBinaryNumber(10000, 11101)); + } + + @Test + public void given_binaryLiteral_thenReturnDecimalValue() { + + byte five = 0b101; + assertEquals((byte) 5, five); + + short three = 0b11; + assertEquals((short) 3, three); + + int nine = 0B1001; + assertEquals(9, nine); + + long twentyNine = 0B11101; + assertEquals(29, twentyNine); + + int minusThirtySeven = -0B100101; + assertEquals(-37, minusThirtySeven); + + } + +} From 970889ad14d80da42f3b7eff5c23f48fb17f3141 Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Wed, 31 Jul 2019 12:04:14 +0300 Subject: [PATCH 84/84] minor cleanup work --- pom.xml | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/pom.xml b/pom.xml index 5b5058763d..f66250a8fd 100644 --- a/pom.xml +++ b/pom.xml @@ -10,10 +10,6 @@ parent-modules pom - - quarkus - - @@ -1589,4 +1585,5 @@ 1.16.12 1.4.197 +