From 6a2fcd54c33f583e28b6bd379948066a18171a05 Mon Sep 17 00:00:00 2001 From: Vishal Date: Wed, 12 Aug 2020 09:57:39 +0530 Subject: [PATCH 01/58] Add unit test to assert two list equality without considering order of elements in it. --- testing-modules/testing-assertions/pom.xml | 12 +++++ .../OrderAgnosticListComparison.java | 46 +++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 testing-modules/testing-assertions/src/test/java/com/baeldung/listassert/OrderAgnosticListComparison.java diff --git a/testing-modules/testing-assertions/pom.xml b/testing-modules/testing-assertions/pom.xml index 0a7c4b0860..fe8c86d058 100644 --- a/testing-modules/testing-assertions/pom.xml +++ b/testing-modules/testing-assertions/pom.xml @@ -24,5 +24,17 @@ 3.15.0 test + + org.hamcrest + hamcrest-all + 1.3 + test + + + org.apache.commons + commons-collections4 + 4.4 + test + diff --git a/testing-modules/testing-assertions/src/test/java/com/baeldung/listassert/OrderAgnosticListComparison.java b/testing-modules/testing-assertions/src/test/java/com/baeldung/listassert/OrderAgnosticListComparison.java new file mode 100644 index 0000000000..b03723e5bd --- /dev/null +++ b/testing-modules/testing-assertions/src/test/java/com/baeldung/listassert/OrderAgnosticListComparison.java @@ -0,0 +1,46 @@ +package com.baeldung.listassert; + +import org.hamcrest.Matchers; +import org.apache.commons.collections4.CollectionUtils; +import org.junit.Test; + + +import java.util.Arrays; +import java.util.List; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class OrderAgnosticListComparison { + + private final List first = Arrays.asList(1, 3, 4, 6, 8); + private final List second = Arrays.asList(8, 1, 6, 3, 4); + private final List third = Arrays.asList(1, 3, 3, 6, 6); + + //In this test using simple JUnit assertion + @Test + public void whenTestingForOrderAgnosticEqualityShouldBeTrue() { + assertTrue(first.size() == second.size() && + first.containsAll(second) && second.containsAll(first)); + } + + @Test + public void whenTestingForOrderAgnosticEqualityShouldBeFalse() { + assertFalse(first.size() == third.size() && + first.containsAll(third) && third.containsAll(first)); + } + + //In this test using Hamcrest lib apis for assertion + @Test + public void whenTestingForOrderAgnosticEqualityShouldBeEqual() { + assertThat(first, Matchers.containsInAnyOrder(second.toArray())); + } + + //In this test asserting lists using Apache Commons apis + @Test + public void whenTestingForOrderAgnosticEqualityShouldBeTrueIfEqualOtherwiseFalse() { + assertTrue(CollectionUtils.isEqualCollection(first, second)); + assertFalse(CollectionUtils.isEqualCollection(first, third)); + } +} From 04fe3387070c98e508d7091625cfd332130d92e7 Mon Sep 17 00:00:00 2001 From: Sorin Zamfir Date: Sat, 15 Aug 2020 14:42:21 +0300 Subject: [PATCH 02/58] BAEL-4516: First structure --- gradle-5/settings.gradle | 3 +- gradle-5/source-sets/build.gradle | 35 +++++++++++++++++++ .../com/baeldung/itest/SourceSetsItest.java | 19 ++++++++++ .../com/baeldung/main/SourceSetsMain.java | 9 +++++ .../com/baeldung/test/SourceSetsTest.java | 19 ++++++++++ 5 files changed, 84 insertions(+), 1 deletion(-) create mode 100644 gradle-5/source-sets/build.gradle create mode 100644 gradle-5/source-sets/src/itest/java/com/baeldung/itest/SourceSetsItest.java create mode 100644 gradle-5/source-sets/src/main/java/com/baeldung/main/SourceSetsMain.java create mode 100644 gradle-5/source-sets/src/test/java/com/baeldung/test/SourceSetsTest.java diff --git a/gradle-5/settings.gradle b/gradle-5/settings.gradle index 1997e12ca5..5384d071e7 100644 --- a/gradle-5/settings.gradle +++ b/gradle-5/settings.gradle @@ -1,3 +1,4 @@ rootProject.name='gradle-5-articles' include 'java-exec' -include 'unused-dependencies' \ No newline at end of file +include 'unused-dependencies' +include 'source-sets' \ No newline at end of file diff --git a/gradle-5/source-sets/build.gradle b/gradle-5/source-sets/build.gradle new file mode 100644 index 0000000000..909b125aed --- /dev/null +++ b/gradle-5/source-sets/build.gradle @@ -0,0 +1,35 @@ + +apply plugin: "eclipse" + +description = "Source Sets example" + +task printConfigurations(){ + doLast{ + configurations.each { + println it.name + } + } +} + +sourceSets{ + itest { + java { + } + } +} + +dependencies { + implementation('org.apache.httpcomponents:httpclient:4.5.12') + testImplementation('junit:junit:4.12') + itestImplementation('com.google.guava:guava:29.0-jre') +} + +configurations { + itestImplementation.extendsFrom(testImplementation) +} + +eclipse { + classpath { + plusConfigurations+=[configurations.itestCompileClasspath] + } +} \ No newline at end of file diff --git a/gradle-5/source-sets/src/itest/java/com/baeldung/itest/SourceSetsItest.java b/gradle-5/source-sets/src/itest/java/com/baeldung/itest/SourceSetsItest.java new file mode 100644 index 0000000000..7f5d0699a2 --- /dev/null +++ b/gradle-5/source-sets/src/itest/java/com/baeldung/itest/SourceSetsItest.java @@ -0,0 +1,19 @@ +package com.baeldung.itest; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.List; + +import org.junit.Test; + +import com.google.common.collect.ImmutableList; + +public class SourceSetsItest { + + @Test + public void whenRunThenFail() { + List someStrings = ImmutableList.of("Baeldung", "is", "cool"); + assertThat(false, is(true)); + } +} diff --git a/gradle-5/source-sets/src/main/java/com/baeldung/main/SourceSetsMain.java b/gradle-5/source-sets/src/main/java/com/baeldung/main/SourceSetsMain.java new file mode 100644 index 0000000000..319894d336 --- /dev/null +++ b/gradle-5/source-sets/src/main/java/com/baeldung/main/SourceSetsMain.java @@ -0,0 +1,9 @@ +package com.baeldung.main; + +public class SourceSetsMain { + + public static void main(String[] args) { + System.out.println("Hell..oh...world!"); + } + +} diff --git a/gradle-5/source-sets/src/test/java/com/baeldung/test/SourceSetsTest.java b/gradle-5/source-sets/src/test/java/com/baeldung/test/SourceSetsTest.java new file mode 100644 index 0000000000..829b6ee36b --- /dev/null +++ b/gradle-5/source-sets/src/test/java/com/baeldung/test/SourceSetsTest.java @@ -0,0 +1,19 @@ +package com.baeldung.test; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.List; + +import org.junit.Test; + +import com.google.common.collect.ImmutableList; + +public class SourceSetsTest { + + @Test + public void whenRunThenSuccess() { + List someStrings = ImmutableList.of("Baeldung", "is", "cool"); + assertThat(true, is(true)); + } +} From 6b75e0cbed0eb62f96df5f60228b1ec1170dd4dd Mon Sep 17 00:00:00 2001 From: Sorin Zamfir Date: Sun, 16 Aug 2020 22:39:00 +0300 Subject: [PATCH 03/58] BAEL-4516: Task for config and srcset info --- gradle-5/source-sets/build.gradle | 47 +++++++++++++++++++++---------- 1 file changed, 32 insertions(+), 15 deletions(-) diff --git a/gradle-5/source-sets/build.gradle b/gradle-5/source-sets/build.gradle index 909b125aed..47f64aca04 100644 --- a/gradle-5/source-sets/build.gradle +++ b/gradle-5/source-sets/build.gradle @@ -1,35 +1,52 @@ apply plugin: "eclipse" +apply plugin: "java" description = "Source Sets example" -task printConfigurations(){ +task printSourceSetInformation(){ doLast{ - configurations.each { - println it.name + sourceSets.each { srcSet -> + println "["+srcSet.name+"]" + print "-->Source directories: "+srcSet.allJava.srcDirs+"\n" + print "-->Output directories: "+srcSet.output.classesDirs.files+"\n" + print "-->Compile classpath:\n" + srcSet.compileClasspath.files.each { + print " "+it.path+"\n" + } + println "" } } } -sourceSets{ - itest { - java { +task printConfigurationInformation(){ + doLast{ + configurations.each { config -> + println "["+config.name+"]" } } } +// sourceSets{ + +// itest { +// java { +// } +// } +// } + dependencies { implementation('org.apache.httpcomponents:httpclient:4.5.12') testImplementation('junit:junit:4.12') - itestImplementation('com.google.guava:guava:29.0-jre') + // itestImplementation('com.google.guava:guava:29.0-jre') } -configurations { - itestImplementation.extendsFrom(testImplementation) -} +// configurations { +// itestImplementation.extendsFrom(testImplementation) +// } -eclipse { - classpath { - plusConfigurations+=[configurations.itestCompileClasspath] - } -} \ No newline at end of file +// eclipse { +// classpath { +// plusConfigurations+=[configurations.itestCompileClasspath] +// } +// } \ No newline at end of file From 3cbfd383edd32b2848286c643fbc53b5f7609718 Mon Sep 17 00:00:00 2001 From: Vishal Date: Mon, 17 Aug 2020 18:06:20 +0530 Subject: [PATCH 04/58] Refactor | Add common formatting, remove comments, update test class name,follow test method naming convention and use Junit5 --- testing-modules/testing-assertions/pom.xml | 22 +++++++++ .../OrderAgnosticListComparison.java | 46 ------------------- .../OrderAgnosticListComparisonUnitTest.java | 40 ++++++++++++++++ 3 files changed, 62 insertions(+), 46 deletions(-) delete mode 100644 testing-modules/testing-assertions/src/test/java/com/baeldung/listassert/OrderAgnosticListComparison.java create mode 100644 testing-modules/testing-assertions/src/test/java/com/baeldung/listassert/OrderAgnosticListComparisonUnitTest.java diff --git a/testing-modules/testing-assertions/pom.xml b/testing-modules/testing-assertions/pom.xml index fe8c86d058..5bb6f5faaa 100644 --- a/testing-modules/testing-assertions/pom.xml +++ b/testing-modules/testing-assertions/pom.xml @@ -18,6 +18,18 @@ logback-classic 1.2.3 + + org.junit.jupiter + junit-jupiter-engine + 5.6.2 + test + + + org.junit.jupiter + junit-jupiter-api + 5.6.2 + test + org.assertj assertj-core @@ -37,4 +49,14 @@ test + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.1 + + + diff --git a/testing-modules/testing-assertions/src/test/java/com/baeldung/listassert/OrderAgnosticListComparison.java b/testing-modules/testing-assertions/src/test/java/com/baeldung/listassert/OrderAgnosticListComparison.java deleted file mode 100644 index b03723e5bd..0000000000 --- a/testing-modules/testing-assertions/src/test/java/com/baeldung/listassert/OrderAgnosticListComparison.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.listassert; - -import org.hamcrest.Matchers; -import org.apache.commons.collections4.CollectionUtils; -import org.junit.Test; - - -import java.util.Arrays; -import java.util.List; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -public class OrderAgnosticListComparison { - - private final List first = Arrays.asList(1, 3, 4, 6, 8); - private final List second = Arrays.asList(8, 1, 6, 3, 4); - private final List third = Arrays.asList(1, 3, 3, 6, 6); - - //In this test using simple JUnit assertion - @Test - public void whenTestingForOrderAgnosticEqualityShouldBeTrue() { - assertTrue(first.size() == second.size() && - first.containsAll(second) && second.containsAll(first)); - } - - @Test - public void whenTestingForOrderAgnosticEqualityShouldBeFalse() { - assertFalse(first.size() == third.size() && - first.containsAll(third) && third.containsAll(first)); - } - - //In this test using Hamcrest lib apis for assertion - @Test - public void whenTestingForOrderAgnosticEqualityShouldBeEqual() { - assertThat(first, Matchers.containsInAnyOrder(second.toArray())); - } - - //In this test asserting lists using Apache Commons apis - @Test - public void whenTestingForOrderAgnosticEqualityShouldBeTrueIfEqualOtherwiseFalse() { - assertTrue(CollectionUtils.isEqualCollection(first, second)); - assertFalse(CollectionUtils.isEqualCollection(first, third)); - } -} diff --git a/testing-modules/testing-assertions/src/test/java/com/baeldung/listassert/OrderAgnosticListComparisonUnitTest.java b/testing-modules/testing-assertions/src/test/java/com/baeldung/listassert/OrderAgnosticListComparisonUnitTest.java new file mode 100644 index 0000000000..9ef6f203af --- /dev/null +++ b/testing-modules/testing-assertions/src/test/java/com/baeldung/listassert/OrderAgnosticListComparisonUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.listassert; + +import org.apache.commons.collections4.CollectionUtils; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class OrderAgnosticListComparisonUnitTest { + + private final List first = Arrays.asList(1, 3, 4, 6, 8); + private final List second = Arrays.asList(8, 1, 6, 3, 4); + private final List third = Arrays.asList(1, 3, 3, 6, 6); + + @Test + public void whenTestingForOrderAgnosticEquality_ShouldBeTrue() { + assertTrue(first.size() == second.size() && first.containsAll(second) && second.containsAll(first)); + } + + @Test + public void whenTestingForOrderAgnosticEquality_ShouldBeFalse() { + assertFalse(first.size() == third.size() && first.containsAll(third) && third.containsAll(first)); + } + + @Test + public void whenTestingForOrderAgnosticEquality_ShouldBeEqual() { + assertThat(first, Matchers.containsInAnyOrder(second.toArray())); + } + + @Test + public void whenTestingForOrderAgnosticEquality_ShouldBeTrueIfEqualOtherwiseFalse() { + assertTrue(CollectionUtils.isEqualCollection(first, second)); + assertFalse(CollectionUtils.isEqualCollection(first, third)); + } +} From eac28eb90f89acc2be018013ac31348ec64705b9 Mon Sep 17 00:00:00 2001 From: azhwani <> Date: Mon, 17 Aug 2020 15:12:50 +0100 Subject: [PATCH 05/58] first commit --- .../NotificationApplication.java | 12 +++++++++ .../config/NotificationConfig.java | 26 ++++++++++++++++++ .../service/EmailNotification.java | 10 +++++++ .../service/NotificationSender.java | 5 ++++ .../service/SmsNotification.java | 10 +++++++ .../src/main/resources/application.properties | 2 ++ .../NotificationUnitTest.java | 27 +++++++++++++++++++ 7 files changed, 92 insertions(+) create mode 100644 spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/NotificationApplication.java create mode 100644 spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/config/NotificationConfig.java create mode 100644 spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/service/EmailNotification.java create mode 100644 spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/service/NotificationSender.java create mode 100644 spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/service/SmsNotification.java create mode 100644 spring-boot-modules/spring-boot-autoconfiguration/src/test/java/com/baeldung/conditionalonproperty/NotificationUnitTest.java diff --git a/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/NotificationApplication.java b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/NotificationApplication.java new file mode 100644 index 0000000000..977de5534d --- /dev/null +++ b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/NotificationApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.conditionalonproperty; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class NotificationApplication { + + public static void main(String[] args) { + SpringApplication.run(NotificationApplication.class, args); + } +} diff --git a/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/config/NotificationConfig.java b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/config/NotificationConfig.java new file mode 100644 index 0000000000..ffd942cd02 --- /dev/null +++ b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/config/NotificationConfig.java @@ -0,0 +1,26 @@ +package com.baeldung.conditionalonproperty.config; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.conditionalonproperty.service.EmailNotification; +import com.baeldung.conditionalonproperty.service.NotificationSender; +import com.baeldung.conditionalonproperty.service.SmsNotification; + +@Configuration +public class NotificationConfig { + + @Bean(name = "emailNotification") + @ConditionalOnProperty(prefix = "notification", name = "service", havingValue = "email") + public NotificationSender notificationSender() { + return new EmailNotification(); + } + + @Bean(name = "smsNotification") + @ConditionalOnProperty(prefix = "notification", name = "service", havingValue = "sms") + public NotificationSender notificationSender2() { + return new SmsNotification(); + } + +} diff --git a/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/service/EmailNotification.java b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/service/EmailNotification.java new file mode 100644 index 0000000000..c66800f817 --- /dev/null +++ b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/service/EmailNotification.java @@ -0,0 +1,10 @@ +package com.baeldung.conditionalonproperty.service; + +public class EmailNotification implements NotificationSender { + + @Override + public String send(String message) { + return "Email Notification: " + message; + } + +} diff --git a/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/service/NotificationSender.java b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/service/NotificationSender.java new file mode 100644 index 0000000000..945306e7c4 --- /dev/null +++ b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/service/NotificationSender.java @@ -0,0 +1,5 @@ +package com.baeldung.conditionalonproperty.service; + +public interface NotificationSender { + String send(String message); +} diff --git a/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/service/SmsNotification.java b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/service/SmsNotification.java new file mode 100644 index 0000000000..dcf611da19 --- /dev/null +++ b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/service/SmsNotification.java @@ -0,0 +1,10 @@ +package com.baeldung.conditionalonproperty.service; + +public class SmsNotification implements NotificationSender { + + @Override + public String send(String message) { + return "SMS notification: " + message; + } + +} diff --git a/spring-boot-modules/spring-boot-autoconfiguration/src/main/resources/application.properties b/spring-boot-modules/spring-boot-autoconfiguration/src/main/resources/application.properties index 4456c78e5d..03f753abf9 100644 --- a/spring-boot-modules/spring-boot-autoconfiguration/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-autoconfiguration/src/main/resources/application.properties @@ -1,2 +1,4 @@ spring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto = update + +notification.service=email diff --git a/spring-boot-modules/spring-boot-autoconfiguration/src/test/java/com/baeldung/conditionalonproperty/NotificationUnitTest.java b/spring-boot-modules/spring-boot-autoconfiguration/src/test/java/com/baeldung/conditionalonproperty/NotificationUnitTest.java new file mode 100644 index 0000000000..fb9b177e5f --- /dev/null +++ b/spring-boot-modules/spring-boot-autoconfiguration/src/test/java/com/baeldung/conditionalonproperty/NotificationUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.conditionalonproperty; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +import com.baeldung.conditionalonproperty.config.NotificationConfig; +import com.baeldung.conditionalonproperty.service.EmailNotification; +import com.baeldung.conditionalonproperty.service.NotificationSender; + +public class NotificationUnitTest { + + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner(); + + @Test + public void whenValueSetToEmail_thenCreateEmailNotification() { + this.contextRunner.withPropertyValues("notification.service=email") + .withUserConfiguration(NotificationConfig.class) + .run(context -> { + assertThat(context).hasBean("emailNotification"); + NotificationSender notificationSender = context.getBean(EmailNotification.class); + assertThat(notificationSender.send("Hello From Baeldung!")).isEqualTo("Email Notification: Hello From Baeldung!"); + assertThat(context).doesNotHaveBean("smsNotification"); + }); + } +} From 0df340f847429bac5e557da74078ac72a999179d Mon Sep 17 00:00:00 2001 From: Sorin Zamfir Date: Mon, 17 Aug 2020 23:55:43 +0300 Subject: [PATCH 06/58] BAEL-4516: Refine examples --- gradle-5/source-sets/.gitignore | 1 + gradle-5/source-sets/build.gradle | 37 ++++++++++++++----- .../com/baeldung/itest/SourceSetsItest.java | 22 ++++++++--- .../com/baeldung/main/SourceSetsObject.java | 21 +++++++++++ gradle-5/source-sets/src/random/Random.java | 0 .../com/baeldung/test/SourceSetsTest.java | 11 +++--- 6 files changed, 71 insertions(+), 21 deletions(-) create mode 100644 gradle-5/source-sets/.gitignore create mode 100644 gradle-5/source-sets/src/main/java/com/baeldung/main/SourceSetsObject.java create mode 100644 gradle-5/source-sets/src/random/Random.java diff --git a/gradle-5/source-sets/.gitignore b/gradle-5/source-sets/.gitignore new file mode 100644 index 0000000000..84c048a73c --- /dev/null +++ b/gradle-5/source-sets/.gitignore @@ -0,0 +1 @@ +/build/ diff --git a/gradle-5/source-sets/build.gradle b/gradle-5/source-sets/build.gradle index 47f64aca04..435c54c7a9 100644 --- a/gradle-5/source-sets/build.gradle +++ b/gradle-5/source-sets/build.gradle @@ -27,23 +27,40 @@ task printConfigurationInformation(){ } } -// sourceSets{ +sourceSets{ + itest { + compileClasspath += sourceSets.main.output + runtimeClasspath += sourceSets.main.output + java { + } + } +} -// itest { -// java { -// } -// } -// } +test { + testLogging { + events "passed","skipped", "failed" + } +} + // main { + // java { + // srcDir('src/random') + // } + // } dependencies { implementation('org.apache.httpcomponents:httpclient:4.5.12') testImplementation('junit:junit:4.12') - // itestImplementation('com.google.guava:guava:29.0-jre') + itestImplementation('com.google.guava:guava:29.0-jre') } -// configurations { -// itestImplementation.extendsFrom(testImplementation) -// } +configurations { + itestImplementation.extendsFrom(testImplementation) + itestRuntimeOnly.extendsFrom(t) +} + +task itest(Type: test) { + +} // eclipse { // classpath { diff --git a/gradle-5/source-sets/src/itest/java/com/baeldung/itest/SourceSetsItest.java b/gradle-5/source-sets/src/itest/java/com/baeldung/itest/SourceSetsItest.java index 7f5d0699a2..6a528a9b9b 100644 --- a/gradle-5/source-sets/src/itest/java/com/baeldung/itest/SourceSetsItest.java +++ b/gradle-5/source-sets/src/itest/java/com/baeldung/itest/SourceSetsItest.java @@ -3,17 +3,27 @@ package com.baeldung.itest; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; -import java.util.List; +//import java.util.List; import org.junit.Test; -import com.google.common.collect.ImmutableList; +import com.baeldung.main.SourceSetsObject; +//import com.google.common.collect.ImmutableList; public class SourceSetsItest { - + @Test - public void whenRunThenFail() { - List someStrings = ImmutableList.of("Baeldung", "is", "cool"); - assertThat(false, is(true)); + public void whenRunThenSuccess() { + + SourceSetsObject underTest = new SourceSetsObject("lorem","ipsum"); + + assertThat(underTest.getUser(), is("lorem")); + assertThat(underTest.getPassword(), is("ipsum")); } + +// @Test +// public void whenRunThenFail() { +// List someStrings = ImmutableList.of("Baeldung", "is", "cool"); +// assertThat(false, is(true)); +// } } diff --git a/gradle-5/source-sets/src/main/java/com/baeldung/main/SourceSetsObject.java b/gradle-5/source-sets/src/main/java/com/baeldung/main/SourceSetsObject.java new file mode 100644 index 0000000000..130121789c --- /dev/null +++ b/gradle-5/source-sets/src/main/java/com/baeldung/main/SourceSetsObject.java @@ -0,0 +1,21 @@ +package com.baeldung.main; + +public class SourceSetsObject { + + private final String user; + private final String password; + + public SourceSetsObject(String user, String password) { + this.user = user; + this.password = password; + } + + public String getPassword() { + return password; + } + + public String getUser() { + return user; + } + +} diff --git a/gradle-5/source-sets/src/random/Random.java b/gradle-5/source-sets/src/random/Random.java new file mode 100644 index 0000000000..e69de29bb2 diff --git a/gradle-5/source-sets/src/test/java/com/baeldung/test/SourceSetsTest.java b/gradle-5/source-sets/src/test/java/com/baeldung/test/SourceSetsTest.java index 829b6ee36b..4891ffd694 100644 --- a/gradle-5/source-sets/src/test/java/com/baeldung/test/SourceSetsTest.java +++ b/gradle-5/source-sets/src/test/java/com/baeldung/test/SourceSetsTest.java @@ -3,17 +3,18 @@ package com.baeldung.test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; -import java.util.List; - import org.junit.Test; -import com.google.common.collect.ImmutableList; +import com.baeldung.main.SourceSetsObject; public class SourceSetsTest { @Test public void whenRunThenSuccess() { - List someStrings = ImmutableList.of("Baeldung", "is", "cool"); - assertThat(true, is(true)); + + SourceSetsObject underTest = new SourceSetsObject("lorem","ipsum"); + + assertThat(underTest.getUser(), is("lorem")); + assertThat(underTest.getPassword(), is("ipsum")); } } From 92d27d387612f29fbe6df99bbc9f6c55411c6f0d Mon Sep 17 00:00:00 2001 From: Sorin Zamfir Date: Tue, 18 Aug 2020 21:52:30 +0300 Subject: [PATCH 07/58] BAEL-4516: Cleanup sources --- gradle-5/build.gradle | 10 ++--- .../gradle/wrapper/gradle-wrapper.properties | 2 +- gradle-5/source-sets/build.gradle | 37 +++++++++---------- .../com/baeldung/itest/SourceSetsItest.java | 22 ++++++----- gradle-5/source-sets/src/random/Random.java | 0 5 files changed, 36 insertions(+), 35 deletions(-) delete mode 100644 gradle-5/source-sets/src/random/Random.java diff --git a/gradle-5/build.gradle b/gradle-5/build.gradle index 84cf05bad6..a40afb7024 100644 --- a/gradle-5/build.gradle +++ b/gradle-5/build.gradle @@ -5,11 +5,11 @@ plugins{ description = "Gradle 5 root project" allprojects { apply plugin :"java" - apply plugin :"nebula.lint" - gradleLint { - rules=['unused-dependency'] - reportFormat = 'text' - } + // apply plugin :"nebula.lint" + // gradleLint { + // rules=['unused-dependency'] + // reportFormat = 'text' + // } group = "com.baeldung" version = "0.0.1" sourceCompatibility = "1.8" diff --git a/gradle-5/gradle/wrapper/gradle-wrapper.properties b/gradle-5/gradle/wrapper/gradle-wrapper.properties index 4c46317507..0b7ed8da04 100644 --- a/gradle-5/gradle/wrapper/gradle-wrapper.properties +++ b/gradle-5/gradle/wrapper/gradle-wrapper.properties @@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-bin.zip diff --git a/gradle-5/source-sets/build.gradle b/gradle-5/source-sets/build.gradle index 435c54c7a9..d7d3f18df3 100644 --- a/gradle-5/source-sets/build.gradle +++ b/gradle-5/source-sets/build.gradle @@ -1,10 +1,12 @@ -apply plugin: "eclipse" +// apply plugin: "eclipse" apply plugin: "java" description = "Source Sets example" task printSourceSetInformation(){ + description = "Print source set information" + doLast{ sourceSets.each { srcSet -> println "["+srcSet.name+"]" @@ -19,14 +21,6 @@ task printSourceSetInformation(){ } } -task printConfigurationInformation(){ - doLast{ - configurations.each { config -> - println "["+config.name+"]" - } - } -} - sourceSets{ itest { compileClasspath += sourceSets.main.output @@ -42,26 +36,31 @@ test { } } - // main { - // java { - // srcDir('src/random') - // } - // } dependencies { implementation('org.apache.httpcomponents:httpclient:4.5.12') testImplementation('junit:junit:4.12') itestImplementation('com.google.guava:guava:29.0-jre') } -configurations { - itestImplementation.extendsFrom(testImplementation) - itestRuntimeOnly.extendsFrom(t) +task itest(type: Test) { + description = "Run integration tests" + group = "verification" + testClassesDirs = sourceSets.itest.output.classesDirs + classpath = sourceSets.itest.runtimeClasspath } -task itest(Type: test) { - +itest { + testLogging { + events "passed","skipped", "failed" + } } +configurations { + itestImplementation.extendsFrom(testImplementation) + itestRuntimeOnly.extendsFrom(testRuntimeOnly) +} + + // eclipse { // classpath { // plusConfigurations+=[configurations.itestCompileClasspath] diff --git a/gradle-5/source-sets/src/itest/java/com/baeldung/itest/SourceSetsItest.java b/gradle-5/source-sets/src/itest/java/com/baeldung/itest/SourceSetsItest.java index 6a528a9b9b..fea54574d6 100644 --- a/gradle-5/source-sets/src/itest/java/com/baeldung/itest/SourceSetsItest.java +++ b/gradle-5/source-sets/src/itest/java/com/baeldung/itest/SourceSetsItest.java @@ -3,27 +3,29 @@ package com.baeldung.itest; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; -//import java.util.List; +import java.util.List; import org.junit.Test; import com.baeldung.main.SourceSetsObject; -//import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableList; public class SourceSetsItest { - + @Test public void whenRunThenSuccess() { - SourceSetsObject underTest = new SourceSetsObject("lorem","ipsum"); + SourceSetsObject underTest = new SourceSetsObject("lorem", "ipsum"); assertThat(underTest.getUser(), is("lorem")); assertThat(underTest.getPassword(), is("ipsum")); } - -// @Test -// public void whenRunThenFail() { -// List someStrings = ImmutableList.of("Baeldung", "is", "cool"); -// assertThat(false, is(true)); -// } + + @Test + public void givenImmutableListwhenRunThenSuccess() { + + List someStrings = ImmutableList.of("Baeldung", "is", "cool"); + + assertThat(someStrings.size(), is(3)); + } } diff --git a/gradle-5/source-sets/src/random/Random.java b/gradle-5/source-sets/src/random/Random.java deleted file mode 100644 index e69de29bb2..0000000000 From 10c8ff7a834749365b8fd084b61de97c9fe20d44 Mon Sep 17 00:00:00 2001 From: Sorin Zamfir Date: Wed, 19 Aug 2020 21:11:19 +0300 Subject: [PATCH 08/58] BAEL-4516: Fixed formatting for sources --- gradle-5/build.gradle | 10 +++++----- gradle-5/gradle/wrapper/gradle-wrapper.properties | 2 +- gradle-5/source-sets/build.gradle | 13 ++++++------- .../java/com/baeldung/itest/SourceSetsItest.java | 12 ++++++------ .../test/java/com/baeldung/test/SourceSetsTest.java | 8 ++++---- 5 files changed, 22 insertions(+), 23 deletions(-) diff --git a/gradle-5/build.gradle b/gradle-5/build.gradle index a40afb7024..84cf05bad6 100644 --- a/gradle-5/build.gradle +++ b/gradle-5/build.gradle @@ -5,11 +5,11 @@ plugins{ description = "Gradle 5 root project" allprojects { apply plugin :"java" - // apply plugin :"nebula.lint" - // gradleLint { - // rules=['unused-dependency'] - // reportFormat = 'text' - // } + apply plugin :"nebula.lint" + gradleLint { + rules=['unused-dependency'] + reportFormat = 'text' + } group = "com.baeldung" version = "0.0.1" sourceCompatibility = "1.8" diff --git a/gradle-5/gradle/wrapper/gradle-wrapper.properties b/gradle-5/gradle/wrapper/gradle-wrapper.properties index 0b7ed8da04..4c46317507 100644 --- a/gradle-5/gradle/wrapper/gradle-wrapper.properties +++ b/gradle-5/gradle/wrapper/gradle-wrapper.properties @@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-bin.zip diff --git a/gradle-5/source-sets/build.gradle b/gradle-5/source-sets/build.gradle index d7d3f18df3..8325450cfd 100644 --- a/gradle-5/source-sets/build.gradle +++ b/gradle-5/source-sets/build.gradle @@ -1,5 +1,5 @@ -// apply plugin: "eclipse" +apply plugin: "eclipse" apply plugin: "java" description = "Source Sets example" @@ -60,9 +60,8 @@ configurations { itestRuntimeOnly.extendsFrom(testRuntimeOnly) } - -// eclipse { -// classpath { -// plusConfigurations+=[configurations.itestCompileClasspath] -// } -// } \ No newline at end of file +eclipse { + classpath { + plusConfigurations+=[configurations.itestCompileClasspath] + } +} \ No newline at end of file diff --git a/gradle-5/source-sets/src/itest/java/com/baeldung/itest/SourceSetsItest.java b/gradle-5/source-sets/src/itest/java/com/baeldung/itest/SourceSetsItest.java index fea54574d6..59529f94ae 100644 --- a/gradle-5/source-sets/src/itest/java/com/baeldung/itest/SourceSetsItest.java +++ b/gradle-5/source-sets/src/itest/java/com/baeldung/itest/SourceSetsItest.java @@ -13,19 +13,19 @@ import com.google.common.collect.ImmutableList; public class SourceSetsItest { @Test - public void whenRunThenSuccess() { - + public void whenRun_ThenSuccess() { + SourceSetsObject underTest = new SourceSetsObject("lorem", "ipsum"); - + assertThat(underTest.getUser(), is("lorem")); assertThat(underTest.getPassword(), is("ipsum")); } @Test - public void givenImmutableListwhenRunThenSuccess() { - + public void givenImmutableList_whenRun_ThenSuccess() { + List someStrings = ImmutableList.of("Baeldung", "is", "cool"); - + assertThat(someStrings.size(), is(3)); } } diff --git a/gradle-5/source-sets/src/test/java/com/baeldung/test/SourceSetsTest.java b/gradle-5/source-sets/src/test/java/com/baeldung/test/SourceSetsTest.java index 4891ffd694..b033eb8e52 100644 --- a/gradle-5/source-sets/src/test/java/com/baeldung/test/SourceSetsTest.java +++ b/gradle-5/source-sets/src/test/java/com/baeldung/test/SourceSetsTest.java @@ -10,10 +10,10 @@ import com.baeldung.main.SourceSetsObject; public class SourceSetsTest { @Test - public void whenRunThenSuccess() { - - SourceSetsObject underTest = new SourceSetsObject("lorem","ipsum"); - + public void whenRun_ThenSuccess() { + + SourceSetsObject underTest = new SourceSetsObject("lorem", "ipsum"); + assertThat(underTest.getUser(), is("lorem")); assertThat(underTest.getPassword(), is("ipsum")); } From f44cc311bd672013c4b230960004fcab7e20dd60 Mon Sep 17 00:00:00 2001 From: Anirban Chatterjee Date: Sat, 22 Aug 2020 12:30:44 +0200 Subject: [PATCH 09/58] Added aggregate operations --- .../kotlin/collections/AggregateOperations.kt | 131 ++++++++++++++++++ .../AggregateOperationsUnitTest.kt | 104 ++++++++++++++ 2 files changed, 235 insertions(+) create mode 100644 core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/kotlin/collections/AggregateOperations.kt create mode 100644 core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/kotlin/collections/AggregateOperationsUnitTest.kt diff --git a/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/kotlin/collections/AggregateOperations.kt b/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/kotlin/collections/AggregateOperations.kt new file mode 100644 index 0000000000..854190382c --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/kotlin/collections/AggregateOperations.kt @@ -0,0 +1,131 @@ +package com.baeldung.kotlin.collections + +class AggregateOperations { + private val numbers = listOf(1, 15, 3, 8) + + fun countList(): Int { + return numbers.count() + } + + fun sumList(): Int { + return numbers.sum() + } + + fun averageList(): Double { + return numbers.average() + } + + fun maximumInList(): Int? { + return numbers.max() + } + + fun minimumInList(): Int? { + return numbers.min() + } + + fun maximumByList(): Int? { + return numbers.maxBy { it % 5 } + } + + fun minimumByList(): Int? { + return numbers.minBy { it % 5 } + } + + fun maximumWithList(): String? { + val strings = listOf("Berlin", "Kolkata", "Prague", "Barcelona") + return strings.maxWith(compareBy { it.length % 4 }) + } + + fun minimumWithList(): String? { + val strings = listOf("Berlin", "Kolkata", "Prague", "Barcelona") + return strings.minWith(compareBy { it.length % 4 }) + } + + fun sumByList(): Int { + return numbers.sumBy { it * 5 } + } + + fun sumByDoubleList(): Double { + return numbers.sumByDouble { it.toDouble() / 8 } + } + + fun foldList(): Int { + println("fold operation") + val result = numbers.fold(100) { total, it -> + println("total = $total, it = $it") + total - it + } + println(result) // ((((100 - 1)-15)-3)-8) = 73 + return result + } + + fun foldRightList(): Int { + println("foldRight operation") + val result = numbers.foldRight(100) { it, total -> + println("total = $total, it = $it") + total - it + } + println(result) // ((((100-8)-3)-15)-1) = 73 + return result + } + + fun foldIndexedList(): Int { + println("foldIndexed operation") + val result = numbers.foldIndexed(100) { index, total, it -> + println("total = $total, it = $it, index = $index") + if (index.minus(2) >= 0) total - it else total + } + println(result) // ((100 - 3)-8) = 89 + return result + } + + fun foldRightIndexedList(): Int { + println("foldRightIndexed operation") + val result = numbers.foldRightIndexed(100) { index, it, total -> + println("total = $total, it = $it, index = $index") + if (index.minus(2) >= 0) total - it else total + } + println(result) // ((100 - 8)-3) = 89 + return result + } + + fun reduceList(): Int { + println("reduce operation") + val result = numbers.reduce { total, it -> + println("total = $total, it = $it") + total - it + } + println(result) // (((1 - 15)-3)-8) = -25 + return result + } + + fun reduceRightList(): Int { + println("reduceRight operation") + val result = numbers.reduceRight() { it, total -> + println("total = $total, it = $it") + total - it + } + println(result) // ((8-3)-15)-1) = -11 + return result + } + + fun reduceIndexedList(): Int { + println("reduceIndexed operation") + val result = numbers.reduceIndexed { index, total, it -> + println("total = $total, it = $it, index = $index") + if (index.minus(2) >= 0) total - it else total + } + println(result) // ((1-3)-8) = -10 + return result + } + + fun reduceRightIndexedList(): Int { + println("reduceRightIndexed operation") + val result = numbers.reduceRightIndexed { index, it, total -> + println("total = $total, it = $it, index = $index") + if (index.minus(2) >= 0) total - it else total + } + println(result) // ((8-3) = 5 + return result + } +} diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/kotlin/collections/AggregateOperationsUnitTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/kotlin/collections/AggregateOperationsUnitTest.kt new file mode 100644 index 0000000000..1fb26760fc --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/kotlin/collections/AggregateOperationsUnitTest.kt @@ -0,0 +1,104 @@ +package com.baeldung.kotlin.collections + +import org.junit.jupiter.api.Test +import kotlin.test.assertEquals + +class AggregateOperationsUnitTest { + + private val classUnderTest: AggregateOperations = AggregateOperations() + + @Test + fun whenCountOfList_thenReturnsValue() { + assertEquals(4, classUnderTest.countList()) + } + + @Test + fun whenSumOfList_thenReturnsTotalValue() { + assertEquals(27, classUnderTest.sumList()) + } + + @Test + fun whenAverageOfList_thenReturnsValue() { + assertEquals(6.75, classUnderTest.averageList()) + } + + @Test + fun whenMaximumOfList_thenReturnsMaximumValue() { + assertEquals(15, classUnderTest.maximumInList()) + } + + @Test + fun whenMinimumOfList_thenReturnsMinimumValue() { + assertEquals(1, classUnderTest.minimumInList()) + } + + @Test + fun whenMaxByList_thenReturnsLargestValue() { + assertEquals(3, classUnderTest.maximumByList()) + } + + @Test + fun whenMinByList_thenReturnsSmallestValue() { + assertEquals(15, classUnderTest.minimumByList()) + } + + @Test + fun whenMaxWithList_thenReturnsLargestValue(){ + assertEquals("Kolkata", classUnderTest.maximumWithList()) + } + + @Test + fun whenMinWithList_thenReturnsSmallestValue(){ + assertEquals("Barcelona", classUnderTest.minimumWithList()) + } + + @Test + fun whenSumByList_thenReturnsIntegerValue(){ + assertEquals(135, classUnderTest.sumByList()) + } + + @Test + fun whenSumByDoubleList_thenReturnsDoubleValue(){ + assertEquals(3.375, classUnderTest.sumByDoubleList()) + } + + @Test + fun whenFoldList_thenReturnsValue(){ + assertEquals(73, classUnderTest.foldList()) + } + + @Test + fun whenFoldRightList_thenReturnsValue(){ + assertEquals(73, classUnderTest.foldRightList()) + } + + @Test + fun whenFoldIndexedList_thenReturnsValue(){ + assertEquals(89, classUnderTest.foldIndexedList()) + } + + @Test + fun whenFoldRightIndexedList_thenReturnsValue(){ + assertEquals(89, classUnderTest.foldRightIndexedList()) + } + + @Test + fun whenReduceList_thenReturnsValue(){ + assertEquals(-25, classUnderTest.reduceList()) + } + + @Test + fun whenReduceRightList_thenReturnsValue(){ + assertEquals(-11, classUnderTest.reduceRightList()) + } + + @Test + fun whenReduceIndexedList_thenReturnsValue(){ + assertEquals(-10, classUnderTest.reduceIndexedList()) + } + + @Test + fun whenReduceRightIndexedList_thenReturnsValue(){ + assertEquals(5, classUnderTest.reduceRightIndexedList()) + } +} \ No newline at end of file From e7bef17346661b9d7e07a1b202e3730e066e71d1 Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Sat, 22 Aug 2020 16:17:16 +0530 Subject: [PATCH 10/58] BAEL-4285 BAEL-4285 A Guide to ArrayStoreException --- .../array/ArrayStoreExceptionExample.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/ArrayStoreExceptionExample.java diff --git a/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/ArrayStoreExceptionExample.java b/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/ArrayStoreExceptionExample.java new file mode 100644 index 0000000000..f82efec97b --- /dev/null +++ b/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/ArrayStoreExceptionExample.java @@ -0,0 +1,17 @@ +package com.baeldung.array; + +public class ArrayStoreExceptionExample { + + public static void main(String[] args) { + + try { + Object array[] = new String[5]; + array[0] = 2; + System.out.println(array[0]); + } catch (ArrayStoreException e) { + e.printStackTrace(); + } + + } + +} From 456c3322e71657bd262120fa999ea415f7adb142 Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Sat, 22 Aug 2020 16:20:07 +0530 Subject: [PATCH 11/58] Update README.md BAEL-4285 --- core-java-modules/core-java-arrays-guides/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-arrays-guides/README.md b/core-java-modules/core-java-arrays-guides/README.md index 621443e4a9..85dfc37b3e 100644 --- a/core-java-modules/core-java-arrays-guides/README.md +++ b/core-java-modules/core-java-arrays-guides/README.md @@ -6,3 +6,4 @@ This module contains complete guides about arrays in Java - [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide) - [Guide to the java.util.Arrays Class](https://www.baeldung.com/java-util-arrays) - [What is \[Ljava.lang.Object;?](https://www.baeldung.com/java-tostring-array) +- A Guide to ArrayStoreException From 122127321655fdd6f925591c6533a4d8df3c14de Mon Sep 17 00:00:00 2001 From: Sorin Zamfir Date: Sun, 23 Aug 2020 00:03:45 +0300 Subject: [PATCH 12/58] BAEL-4516: Fix itest sample --- .../itest/java/com/baeldung/itest/SourceSetsItest.java | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/gradle-5/source-sets/src/itest/java/com/baeldung/itest/SourceSetsItest.java b/gradle-5/source-sets/src/itest/java/com/baeldung/itest/SourceSetsItest.java index 59529f94ae..3312c5b6e5 100644 --- a/gradle-5/source-sets/src/itest/java/com/baeldung/itest/SourceSetsItest.java +++ b/gradle-5/source-sets/src/itest/java/com/baeldung/itest/SourceSetsItest.java @@ -13,19 +13,13 @@ import com.google.common.collect.ImmutableList; public class SourceSetsItest { @Test - public void whenRun_ThenSuccess() { + public void givenImmutableList_whenRun_ThenSuccess() { SourceSetsObject underTest = new SourceSetsObject("lorem", "ipsum"); + List someStrings = ImmutableList.of("Baeldung", "is", "cool"); assertThat(underTest.getUser(), is("lorem")); assertThat(underTest.getPassword(), is("ipsum")); - } - - @Test - public void givenImmutableList_whenRun_ThenSuccess() { - - List someStrings = ImmutableList.of("Baeldung", "is", "cool"); - assertThat(someStrings.size(), is(3)); } } From aa223e69eada94f4771d69cfecce0771a6742b52 Mon Sep 17 00:00:00 2001 From: Vishal Date: Sun, 23 Aug 2020 10:35:43 +0530 Subject: [PATCH 13/58] Add tests for AssertJ example and update assertj-core dependency version. --- testing-modules/testing-assertions/pom.xml | 2 +- .../OrderAgnosticListComparisonUnitTest.java | 18 ++++++++++++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/testing-modules/testing-assertions/pom.xml b/testing-modules/testing-assertions/pom.xml index 5bb6f5faaa..fa0f666c7f 100644 --- a/testing-modules/testing-assertions/pom.xml +++ b/testing-modules/testing-assertions/pom.xml @@ -33,7 +33,7 @@ org.assertj assertj-core - 3.15.0 + 3.16.1 test diff --git a/testing-modules/testing-assertions/src/test/java/com/baeldung/listassert/OrderAgnosticListComparisonUnitTest.java b/testing-modules/testing-assertions/src/test/java/com/baeldung/listassert/OrderAgnosticListComparisonUnitTest.java index 9ef6f203af..bf278cea90 100644 --- a/testing-modules/testing-assertions/src/test/java/com/baeldung/listassert/OrderAgnosticListComparisonUnitTest.java +++ b/testing-modules/testing-assertions/src/test/java/com/baeldung/listassert/OrderAgnosticListComparisonUnitTest.java @@ -1,13 +1,14 @@ package com.baeldung.listassert; import org.apache.commons.collections4.CollectionUtils; +import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -29,7 +30,7 @@ public class OrderAgnosticListComparisonUnitTest { @Test public void whenTestingForOrderAgnosticEquality_ShouldBeEqual() { - assertThat(first, Matchers.containsInAnyOrder(second.toArray())); + MatcherAssert.assertThat(first, Matchers.containsInAnyOrder(second.toArray())); } @Test @@ -37,4 +38,17 @@ public class OrderAgnosticListComparisonUnitTest { assertTrue(CollectionUtils.isEqualCollection(first, second)); assertFalse(CollectionUtils.isEqualCollection(first, third)); } + + @Test + void whenTestingForOrderAgnosticEqualityBothList_ShouldBeEqual() { + assertThat(first).hasSameElementsAs(second); + } + + @Test + void whenTestingForOrderAgnosticEqualityBothList_ShouldNotBeEqual() { + List a = Arrays.asList("a", "a", "b", "c"); + List b = Arrays.asList("a", "b", "c"); + + assertThat(a).hasSameElementsAs(b); + } } From 97252050f4f3235715c9b8dc4032a44854c99775 Mon Sep 17 00:00:00 2001 From: Umang Budhwar Date: Sun, 23 Aug 2020 17:36:23 +0530 Subject: [PATCH 14/58] Added code for BAEL-4095 --- spring-boot-modules/pom.xml | 1 + .../spring-boot-swagger/pom.xml | 41 +++++++++++++ .../SpringBootSwaggerApplication.java | 13 ++++ .../configuration/SwaggerConfiguration.java | 61 +++++++++++++++++++ .../controller/RegularRestController.java | 35 +++++++++++ .../src/main/resources/application.properties | 0 6 files changed, 151 insertions(+) create mode 100644 spring-boot-modules/spring-boot-swagger/pom.xml create mode 100644 spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/SpringBootSwaggerApplication.java create mode 100644 spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/configuration/SwaggerConfiguration.java create mode 100644 spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/controller/RegularRestController.java create mode 100644 spring-boot-modules/spring-boot-swagger/src/main/resources/application.properties diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index b4cabaaedf..109be01db3 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -61,6 +61,7 @@ spring-boot-runtime spring-boot-security spring-boot-springdoc + spring-boot-swagger spring-boot-testing spring-boot-vue spring-boot-xml diff --git a/spring-boot-modules/spring-boot-swagger/pom.xml b/spring-boot-modules/spring-boot-swagger/pom.xml new file mode 100644 index 0000000000..4e0180460d --- /dev/null +++ b/spring-boot-modules/spring-boot-swagger/pom.xml @@ -0,0 +1,41 @@ + + + 4.0.0 + + + com.baeldung.spring-boot-modules + spring-boot-modules + 1.0.0-SNAPSHOT + ../ + + + spring-boot-swagger + 0.1.0-SNAPSHOT + spring-boot-swagger + jar + + Module For Spring Boot Swagger + + + org.springframework.boot + spring-boot-starter-web + + + io.springfox + springfox-boot-starter + 3.0.0 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/SpringBootSwaggerApplication.java b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/SpringBootSwaggerApplication.java new file mode 100644 index 0000000000..911c29a4f6 --- /dev/null +++ b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/SpringBootSwaggerApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.swagger2boot; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootSwaggerApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootSwaggerApplication.class, args); + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/configuration/SwaggerConfiguration.java b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/configuration/SwaggerConfiguration.java new file mode 100644 index 0000000000..73dfe85387 --- /dev/null +++ b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/configuration/SwaggerConfiguration.java @@ -0,0 +1,61 @@ +package com.baeldung.swagger2boot.configuration; + +import java.util.Collections; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.Contact; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger.web.DocExpansion; +import springfox.documentation.swagger.web.ModelRendering; +import springfox.documentation.swagger.web.OperationsSorter; +import springfox.documentation.swagger.web.TagsSorter; +import springfox.documentation.swagger.web.UiConfiguration; +import springfox.documentation.swagger.web.UiConfigurationBuilder; + +@Configuration +public class SwaggerConfiguration { + + private ApiInfo apiInfo() { + return new ApiInfo("My REST API", "Some custom description of API.", "API TOS", "Terms of service", new Contact("Umang Budhwar", "www.baeldung.com", "umangbudhwar@gmail.com"), "License of API", "API license URL", Collections.emptyList()); + } + + @Bean + public Docket api() { + return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()) + .select() + .apis(RequestHandlerSelectors.any()) + .paths(PathSelectors.any()) + .build(); + } + + /** + * SwaggerUI information + */ + + @Bean + UiConfiguration uiConfig() { + return UiConfigurationBuilder.builder() + .deepLinking(true) + .displayOperationId(false) + .defaultModelsExpandDepth(1) + .defaultModelExpandDepth(1) + .defaultModelRendering(ModelRendering.EXAMPLE) + .displayRequestDuration(false) + .docExpansion(DocExpansion.NONE) + .filter(false) + .maxDisplayedTags(null) + .operationsSorter(OperationsSorter.ALPHA) + .showExtensions(false) + .tagsSorter(TagsSorter.ALPHA) + .supportedSubmitMethods(UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS) + .validatorUrl(null) + .build(); + } + +} diff --git a/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/controller/RegularRestController.java b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/controller/RegularRestController.java new file mode 100644 index 0000000000..5218092c21 --- /dev/null +++ b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/controller/RegularRestController.java @@ -0,0 +1,35 @@ +package com.baeldung.swagger2boot.controller; + +import java.time.LocalDate; +import java.time.LocalTime; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import io.swagger.annotations.ApiOperation; +import springfox.documentation.annotations.ApiIgnore; + +@ApiIgnore +@RestController +public class RegularRestController { + + @ApiIgnore + @ApiOperation(value = "This method is used to get the author name.") + @GetMapping("/getAuthor") + public String getAuthor() { + return "Umang Budhwar"; + } + + @ApiOperation(value = "This method is used to get the current date.", hidden = true) + @GetMapping("/getDate") + public LocalDate getDate() { + return LocalDate.now(); + } + + @ApiOperation(value = "This method is used to get the current time.") + @GetMapping("/getTime") + public LocalTime getTime() { + return LocalTime.now(); + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-swagger/src/main/resources/application.properties b/spring-boot-modules/spring-boot-swagger/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 From cec243af0deadbdfd512dc4e4dbe9380f1ef066d Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Mon, 24 Aug 2020 11:01:12 +0530 Subject: [PATCH 15/58] Update README.md --- core-java-modules/core-java-arrays-guides/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/core-java-modules/core-java-arrays-guides/README.md b/core-java-modules/core-java-arrays-guides/README.md index 85dfc37b3e..621443e4a9 100644 --- a/core-java-modules/core-java-arrays-guides/README.md +++ b/core-java-modules/core-java-arrays-guides/README.md @@ -6,4 +6,3 @@ This module contains complete guides about arrays in Java - [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide) - [Guide to the java.util.Arrays Class](https://www.baeldung.com/java-util-arrays) - [What is \[Ljava.lang.Object;?](https://www.baeldung.com/java-tostring-array) -- A Guide to ArrayStoreException From da1d54699f2a42dd08594dea74b6eeb9faa9193c Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Mon, 24 Aug 2020 11:07:38 +0530 Subject: [PATCH 16/58] changing package changing package --- .../ArrayStoreExceptionExample.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/arraystoreexception/ArrayStoreExceptionExample.java diff --git a/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/arraystoreexception/ArrayStoreExceptionExample.java b/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/arraystoreexception/ArrayStoreExceptionExample.java new file mode 100644 index 0000000000..ab485ca867 --- /dev/null +++ b/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/arraystoreexception/ArrayStoreExceptionExample.java @@ -0,0 +1,17 @@ +package com.baeldung.array.arraystoreexception; + +public class ArrayStoreExceptionExample { + + public static void main(String[] args) { + + try { + Object array[] = new String[5]; + array[0] = 2; + System.out.println(array[0]); + } catch (ArrayStoreException e) { + e.printStackTrace(); + } + + } + +} From 935b4c1278e5e6f0daef5d135f7f94176fdf7ded Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Mon, 24 Aug 2020 11:09:01 +0530 Subject: [PATCH 17/58] Delete ArrayStoreExceptionExample.java --- .../array/ArrayStoreExceptionExample.java | 17 ----------------- 1 file changed, 17 deletions(-) delete mode 100644 core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/ArrayStoreExceptionExample.java diff --git a/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/ArrayStoreExceptionExample.java b/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/ArrayStoreExceptionExample.java deleted file mode 100644 index f82efec97b..0000000000 --- a/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/ArrayStoreExceptionExample.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.array; - -public class ArrayStoreExceptionExample { - - public static void main(String[] args) { - - try { - Object array[] = new String[5]; - array[0] = 2; - System.out.println(array[0]); - } catch (ArrayStoreException e) { - e.printStackTrace(); - } - - } - -} From 765629be47187a94ee36b2ac1df487cb869677a4 Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Mon, 24 Aug 2020 12:02:02 +0530 Subject: [PATCH 18/58] Adding File --- .../arraystoreexception/ArrayStoreExampleCE.java | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/arraystoreexception/ArrayStoreExampleCE.java diff --git a/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/arraystoreexception/ArrayStoreExampleCE.java b/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/arraystoreexception/ArrayStoreExampleCE.java new file mode 100644 index 0000000000..7c81142949 --- /dev/null +++ b/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/arraystoreexception/ArrayStoreExampleCE.java @@ -0,0 +1,11 @@ +package com.baeldung.array.arraystoreexception; + +public class ArrayStoreExampleCE { + + public static void main(String[] args) { + + //String array[] = new String[5]; //This will lead to compile-time error at line-8 when uncommented + //array[0] = 2; + } + +} From 82203b222e89543accda497ec9450db0adbb6e73 Mon Sep 17 00:00:00 2001 From: Anirban Chatterjee Date: Mon, 24 Aug 2020 09:59:39 +0200 Subject: [PATCH 19/58] Removed print statements --- .../kotlin/collections/AggregateOperations.kt | 56 ++++++------------- 1 file changed, 16 insertions(+), 40 deletions(-) diff --git a/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/kotlin/collections/AggregateOperations.kt b/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/kotlin/collections/AggregateOperations.kt index 854190382c..3a348aafaa 100644 --- a/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/kotlin/collections/AggregateOperations.kt +++ b/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/kotlin/collections/AggregateOperations.kt @@ -50,82 +50,58 @@ class AggregateOperations { } fun foldList(): Int { - println("fold operation") - val result = numbers.fold(100) { total, it -> + return numbers.fold(100) { total, it -> println("total = $total, it = $it") total - it - } - println(result) // ((((100 - 1)-15)-3)-8) = 73 - return result + } // ((((100 - 1)-15)-3)-8) = 73 } fun foldRightList(): Int { - println("foldRight operation") - val result = numbers.foldRight(100) { it, total -> + return numbers.foldRight(100) { it, total -> println("total = $total, it = $it") total - it - } - println(result) // ((((100-8)-3)-15)-1) = 73 - return result + } // ((((100-8)-3)-15)-1) = 73 } fun foldIndexedList(): Int { - println("foldIndexed operation") - val result = numbers.foldIndexed(100) { index, total, it -> + return numbers.foldIndexed(100) { index, total, it -> println("total = $total, it = $it, index = $index") if (index.minus(2) >= 0) total - it else total - } - println(result) // ((100 - 3)-8) = 89 - return result + } // ((100 - 3)-8) = 89 } fun foldRightIndexedList(): Int { - println("foldRightIndexed operation") - val result = numbers.foldRightIndexed(100) { index, it, total -> + return numbers.foldRightIndexed(100) { index, it, total -> println("total = $total, it = $it, index = $index") if (index.minus(2) >= 0) total - it else total - } - println(result) // ((100 - 8)-3) = 89 - return result + } // ((100 - 8)-3) = 89 } fun reduceList(): Int { - println("reduce operation") - val result = numbers.reduce { total, it -> + return numbers.reduce { total, it -> println("total = $total, it = $it") total - it - } - println(result) // (((1 - 15)-3)-8) = -25 - return result + } // (((1 - 15)-3)-8) = -25 } fun reduceRightList(): Int { - println("reduceRight operation") - val result = numbers.reduceRight() { it, total -> + return numbers.reduceRight() { it, total -> println("total = $total, it = $it") total - it - } - println(result) // ((8-3)-15)-1) = -11 - return result + } // ((8-3)-15)-1) = -11 } fun reduceIndexedList(): Int { - println("reduceIndexed operation") - val result = numbers.reduceIndexed { index, total, it -> + return numbers.reduceIndexed { index, total, it -> println("total = $total, it = $it, index = $index") if (index.minus(2) >= 0) total - it else total - } - println(result) // ((1-3)-8) = -10 - return result + } // ((1-3)-8) = -10 } fun reduceRightIndexedList(): Int { - println("reduceRightIndexed operation") - val result = numbers.reduceRightIndexed { index, it, total -> + return numbers.reduceRightIndexed { index, it, total -> println("total = $total, it = $it, index = $index") if (index.minus(2) >= 0) total - it else total - } - println(result) // ((8-3) = 5 - return result + } // ((8-3) = 5 } } From c02caaac8924943a3621baf0f7f465c228b557b2 Mon Sep 17 00:00:00 2001 From: Michael Pratt Date: Mon, 24 Aug 2020 09:56:00 -0600 Subject: [PATCH 20/58] BAEL-4224: Hidden inputs with thymeleaf --- .../thymeleaf/blog/BlogController.java | 24 +++++++ .../com/baeldung/thymeleaf/blog/BlogDTO.java | 66 +++++++++++++++++++ .../resources/templates/blog/blog-new.html | 36 ++++++++++ 3 files changed, 126 insertions(+) create mode 100644 spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/blog/BlogController.java create mode 100644 spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/blog/BlogDTO.java create mode 100644 spring-thymeleaf-3/src/main/resources/templates/blog/blog-new.html diff --git a/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/blog/BlogController.java b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/blog/BlogController.java new file mode 100644 index 0000000000..eee2d26409 --- /dev/null +++ b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/blog/BlogController.java @@ -0,0 +1,24 @@ +package com.baeldung.thymeleaf.blog; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; + +import java.util.Random; + +@Controller +public class BlogController { + + @GetMapping("/blog/new") + public String newBlogPost(Model model) + { + // Set a random ID so we can see it in the HTML form + BlogDTO blog = new BlogDTO(); + blog.setBlogId(Math.abs(new Random().nextLong() % 1000000)); + + model.addAttribute("blog", blog); + + return "blog/blog-new"; + } + +} diff --git a/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/blog/BlogDTO.java b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/blog/BlogDTO.java new file mode 100644 index 0000000000..44c77be5ce --- /dev/null +++ b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/blog/BlogDTO.java @@ -0,0 +1,66 @@ +package com.baeldung.thymeleaf.blog; + +import java.util.Date; + +public class BlogDTO { + + private long blogId; + + private String title; + + private String body; + + private String author; + + private String category; + + private Date publishedDate; + + public long getBlogId() { + return blogId; + } + + public void setBlogId(long blogId) { + this.blogId = blogId; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public Date getPublishedDate() { + return publishedDate; + } + + public void setPublishedDate(Date publishedDate) { + this.publishedDate = publishedDate; + } +} diff --git a/spring-thymeleaf-3/src/main/resources/templates/blog/blog-new.html b/spring-thymeleaf-3/src/main/resources/templates/blog/blog-new.html new file mode 100644 index 0000000000..10747b4b07 --- /dev/null +++ b/spring-thymeleaf-3/src/main/resources/templates/blog/blog-new.html @@ -0,0 +1,36 @@ + + + + + Hidden Input Examples + + + +

Hidden Input Example 1

+
+ + + + + +
+ +

Hidden Input Example 2

+
+ + + + + +
+ +

Hidden Input Example 3

+
+ + + + + +
+ + \ No newline at end of file From 77cfa756635a23c23334ea49ce810772d18bb17c Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Wed, 26 Aug 2020 00:50:32 +0800 Subject: [PATCH 21/58] Delete README.md --- docker/docker-spring-boot/README.md | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 docker/docker-spring-boot/README.md diff --git a/docker/docker-spring-boot/README.md b/docker/docker-spring-boot/README.md deleted file mode 100644 index 78f13a3652..0000000000 --- a/docker/docker-spring-boot/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Article: - -- [Creating Docker Images with Spring Boot](https://www.baeldung.com/spring-boot-docker-images) From 00f82c34b6feb341fd17b9969ccefcab46890923 Mon Sep 17 00:00:00 2001 From: Krzysztof Woyke Date: Wed, 26 Aug 2020 12:27:50 +0200 Subject: [PATCH 22/58] JAVA-2398: Fix Spring Boot 2 integration with Swagger 3.0.0 --- spring-boot-modules/spring-boot-mvc/pom.xml | 23 ++++--------------- .../configuration/SpringFoxConfig.java | 19 ++++++++------- 2 files changed, 14 insertions(+), 28 deletions(-) diff --git a/spring-boot-modules/spring-boot-mvc/pom.xml b/spring-boot-modules/spring-boot-mvc/pom.xml index 9ae6d8341a..39046ee6d9 100644 --- a/spring-boot-modules/spring-boot-mvc/pom.xml +++ b/spring-boot-modules/spring-boot-mvc/pom.xml @@ -49,6 +49,10 @@ org.springframework.boot spring-boot-starter-data-jpa
+ + org.springframework.boot + spring-boot-starter-data-rest + mysql @@ -99,24 +103,7 @@ io.springfox - springfox-swagger2 - ${spring.fox.version} - - - io.springfox - springfox-swagger-ui - ${spring.fox.version} - - - - io.springfox - springfox-data-rest - ${spring.fox.version} - - - - io.springfox - springfox-bean-validators + springfox-boot-starter ${spring.fox.version} diff --git a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/configuration/SpringFoxConfig.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/configuration/SpringFoxConfig.java index 434a8d77cb..b404b0c2f8 100644 --- a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/configuration/SpringFoxConfig.java +++ b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/configuration/SpringFoxConfig.java @@ -1,13 +1,9 @@ package com.baeldung.swagger2boot.configuration; -import org.springframework.boot.autoconfigure.domain.EntityScan; +import com.baeldung.swagger2boot.plugin.EmailAnnotationPlugin; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; - -import com.baeldung.swagger2boot.plugin.EmailAnnotationPlugin; - import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; @@ -16,13 +12,16 @@ import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.data.rest.configuration.SpringDataRestConfiguration; import springfox.documentation.spring.web.plugins.Docket; -import springfox.documentation.swagger.web.*; -import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc; +import springfox.documentation.swagger.web.DocExpansion; +import springfox.documentation.swagger.web.ModelRendering; +import springfox.documentation.swagger.web.OperationsSorter; +import springfox.documentation.swagger.web.TagsSorter; +import springfox.documentation.swagger.web.UiConfiguration; +import springfox.documentation.swagger.web.UiConfigurationBuilder; import java.util.Collections; @Configuration -@EnableSwagger2WebMvc @Import({SpringDataRestConfiguration.class, BeanValidatorPluginsConfiguration.class}) public class SpringFoxConfig { @@ -43,8 +42,8 @@ public class SpringFoxConfig { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() - .apis(RequestHandlerSelectors.any()) - .paths(PathSelectors.any()) + .apis(RequestHandlerSelectors.any()) + .paths(PathSelectors.any()) .build(); } From 7d3e128323cb22c4fba4c88195d4037903bd4e26 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Wed, 26 Aug 2020 17:02:39 +0530 Subject: [PATCH 23/58] JAVA-33: Added comments in pom.xml with reason to not upgrade to boot-2 --- jhipster/pom.xml | 2 ++ spring-4/pom.xml | 1 + spring-activiti/pom.xml | 1 + spring-boot-modules/spring-boot-1/pom.xml | 1 + spring-remoting/remoting-hessian-burlap/pom.xml | 1 + 5 files changed, 6 insertions(+) diff --git a/jhipster/pom.xml b/jhipster/pom.xml index dd16205706..1703e82e0e 100644 --- a/jhipster/pom.xml +++ b/jhipster/pom.xml @@ -9,6 +9,8 @@ pom + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT diff --git a/spring-4/pom.xml b/spring-4/pom.xml index b6b8deb273..cd6b232317 100644 --- a/spring-4/pom.xml +++ b/spring-4/pom.xml @@ -8,6 +8,7 @@ jar + com.baeldung parent-boot-1 0.0.1-SNAPSHOT diff --git a/spring-activiti/pom.xml b/spring-activiti/pom.xml index 4803827b45..a8557b4f56 100644 --- a/spring-activiti/pom.xml +++ b/spring-activiti/pom.xml @@ -8,6 +8,7 @@ Demo project for Spring Boot + com.baeldung parent-boot-1 0.0.1-SNAPSHOT diff --git a/spring-boot-modules/spring-boot-1/pom.xml b/spring-boot-modules/spring-boot-1/pom.xml index 145bb221e0..d44120b21e 100644 --- a/spring-boot-modules/spring-boot-1/pom.xml +++ b/spring-boot-modules/spring-boot-1/pom.xml @@ -7,6 +7,7 @@ Module for Spring Boot version 1.x + com.baeldung parent-boot-1 0.0.1-SNAPSHOT diff --git a/spring-remoting/remoting-hessian-burlap/pom.xml b/spring-remoting/remoting-hessian-burlap/pom.xml index fac6e1cb2e..67e3e3eab4 100644 --- a/spring-remoting/remoting-hessian-burlap/pom.xml +++ b/spring-remoting/remoting-hessian-burlap/pom.xml @@ -9,6 +9,7 @@ pom + com.baeldung parent-boot-1 0.0.1-SNAPSHOT From 7b40f75cc9d0b157a9256793e5f60d2b30b9a98b Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Wed, 26 Aug 2020 17:04:08 +0530 Subject: [PATCH 24/58] JAVA-33: Moved spring-boot-camel to parent-boot-2 --- spring-boot-modules/spring-boot-camel/pom.xml | 10 +--- .../java/com/baeldung/camel/Application.java | 56 ++++++++++--------- .../src/main/resources/application.properties | 4 +- .../baeldung/SpringContextTest.java | 0 4 files changed, 35 insertions(+), 35 deletions(-) rename spring-boot-modules/spring-boot-camel/src/test/java/{org => com}/baeldung/SpringContextTest.java (100%) diff --git a/spring-boot-modules/spring-boot-camel/pom.xml b/spring-boot-modules/spring-boot-camel/pom.xml index 881b021b96..46a90b4722 100644 --- a/spring-boot-modules/spring-boot-camel/pom.xml +++ b/spring-boot-modules/spring-boot-camel/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 @@ -38,12 +38,10 @@ org.springframework.boot spring-boot-starter-web - ${spring-boot-starter.version} org.springframework.boot spring-boot-starter-test - ${spring-boot-starter.version} test @@ -55,7 +53,6 @@ org.springframework.boot spring-boot-maven-plugin - ${spring-boot-starter.version} @@ -68,8 +65,7 @@ - 2.19.1 - 1.5.4.RELEASE + 3.0.0-M4 diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/Application.java b/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/Application.java index aadd37a3b4..48294e9c56 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/Application.java +++ b/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/Application.java @@ -12,33 +12,36 @@ import org.apache.camel.model.rest.RestBindingMode; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.aop.AopAutoConfiguration; +import org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration; +import org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration; +import org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.stereotype.Component; -@SpringBootApplication -@ComponentScan(basePackages="com.baeldung.camel") -public class Application{ +@SpringBootApplication(exclude = { WebSocketServletAutoConfiguration.class, AopAutoConfiguration.class, OAuth2ResourceServerAutoConfiguration.class, EmbeddedWebServerFactoryCustomizerAutoConfiguration.class }) +@ComponentScan(basePackages = "com.baeldung.camel") +public class Application { @Value("${server.port}") String serverPort; - + @Value("${baeldung.api.path}") String contextPath; - + public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean ServletRegistrationBean servletRegistrationBean() { - ServletRegistrationBean servlet = new ServletRegistrationBean(new CamelHttpTransportServlet(), contextPath+"/*"); + ServletRegistrationBean servlet = new ServletRegistrationBean(new CamelHttpTransportServlet(), contextPath + "/*"); servlet.setName("CamelServlet"); return servlet; } - @Component class RestApi extends RouteBuilder { @@ -47,7 +50,6 @@ public class Application{ CamelContext context = new DefaultCamelContext(); - // http://localhost:8080/camel/api-doc restConfiguration().contextPath(contextPath) // .port(serverPort) @@ -60,43 +62,43 @@ public class Application{ .component("servlet") .bindingMode(RestBindingMode.json) .dataFormatProperty("prettyPrint", "true"); -/** -The Rest DSL supports automatic binding json/xml contents to/from -POJOs using Camels Data Format. -By default the binding mode is off, meaning there is no automatic -binding happening for incoming and outgoing messages. -You may want to use binding if you develop POJOs that maps to -your REST services request and response types. -*/ - + /** + The Rest DSL supports automatic binding json/xml contents to/from + POJOs using Camels Data Format. + By default the binding mode is off, meaning there is no automatic + binding happening for incoming and outgoing messages. + You may want to use binding if you develop POJOs that maps to + your REST services request and response types. + */ + rest("/api/").description("Teste REST Service") .id("api-route") .post("/bean") .produces(MediaType.APPLICATION_JSON) .consumes(MediaType.APPLICATION_JSON) -// .get("/hello/{place}") + // .get("/hello/{place}") .bindingMode(RestBindingMode.auto) .type(MyBean.class) .enableCORS(true) -// .outType(OutBean.class) + // .outType(OutBean.class) .to("direct:remoteService"); - - - from("direct:remoteService") - .routeId("direct-route") + + from("direct:remoteService").routeId("direct-route") .tracing() .log(">>> ${body.id}") .log(">>> ${body.name}") -// .transform().simple("blue ${in.body.name}") + // .transform().simple("blue ${in.body.name}") .process(new Processor() { @Override public void process(Exchange exchange) throws Exception { - MyBean bodyIn = (MyBean) exchange.getIn().getBody(); - + MyBean bodyIn = (MyBean) exchange.getIn() + .getBody(); + ExampleServices.example(bodyIn); - exchange.getIn().setBody(bodyIn); + exchange.getIn() + .setBody(bodyIn); } }) .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(201)); diff --git a/spring-boot-modules/spring-boot-camel/src/main/resources/application.properties b/spring-boot-modules/spring-boot-camel/src/main/resources/application.properties index bce95f8eaf..29fee8cff6 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-camel/src/main/resources/application.properties @@ -12,4 +12,6 @@ management.port=8081 # disable all management enpoints except health endpoints.enabled = true -endpoints.health.enabled = true \ No newline at end of file +endpoints.health.enabled = true + +spring.main.allow-bean-definition-overriding=true \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-camel/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/SpringContextTest.java similarity index 100% rename from spring-boot-modules/spring-boot-camel/src/test/java/org/baeldung/SpringContextTest.java rename to spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/SpringContextTest.java From 4fac6a711c4edcdf375e36998ad155de76a9c389 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Wed, 26 Aug 2020 21:38:26 +0200 Subject: [PATCH 25/58] JAVA-2431: Migrate log-mdc to parent-spring-5 --- logging-modules/log-mdc/Dockerfile | 0 logging-modules/log-mdc/pom.xml | 4 ++-- 2 files changed, 2 insertions(+), 2 deletions(-) create mode 100644 logging-modules/log-mdc/Dockerfile diff --git a/logging-modules/log-mdc/Dockerfile b/logging-modules/log-mdc/Dockerfile new file mode 100644 index 0000000000..e69de29bb2 diff --git a/logging-modules/log-mdc/pom.xml b/logging-modules/log-mdc/pom.xml index e367a63de6..bc4800ea37 100644 --- a/logging-modules/log-mdc/pom.xml +++ b/logging-modules/log-mdc/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-spring-4 + parent-spring-5 0.0.1-SNAPSHOT - ../../parent-spring-4 + ../../parent-spring-5 From d849f88351bb840a6c355800a3650bcb56fd1522 Mon Sep 17 00:00:00 2001 From: kwoyke Date: Thu, 27 Aug 2020 06:54:29 +0200 Subject: [PATCH 26/58] BAEL-4575: Use copyDependencies feature from the latest liberty-maven-plugin (#9920) --- open-liberty/pom.xml | 35 ++++++++++++----------------------- 1 file changed, 12 insertions(+), 23 deletions(-) diff --git a/open-liberty/pom.xml b/open-liberty/pom.xml index d6588ce49a..0e8b159043 100644 --- a/open-liberty/pom.xml +++ b/open-liberty/pom.xml @@ -27,6 +27,7 @@ org.apache.derby derby ${version.derby} + provided @@ -70,27 +71,16 @@ io.openliberty.tools liberty-maven-plugin ${version.liberty-maven-plugin} - - - org.apache.maven.plugins - maven-dependency-plugin - ${version.maven-dependency-plugin} - - - copy-derby-dependency - package - - copy-dependencies - - - derby - ${project.build.directory}/liberty/wlp/usr/shared/resources/ - - ${testServerHttpPort} - - - - + + + ${project.build.directory}/liberty/wlp/usr/shared/resources/ + + org.apache.derby + derby + ${version.derby} + + + org.apache.maven.plugins @@ -112,8 +102,7 @@ 8.0.0 3.2 10.14.2.0 - 3.1 - 2.10 + 3.3-M3 3.2.3 4.12 1.0.5 From 6f2e3a9e6b728a5bd6fb9edaecc18f51e436c9fd Mon Sep 17 00:00:00 2001 From: kwoyke Date: Thu, 27 Aug 2020 14:12:53 +0200 Subject: [PATCH 27/58] BAEL-4578: Fix failing unit test (#9929) --- .../java/com/baeldung/java10/list/CopyListServiceUnitTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-10/src/test/java/com/baeldung/java10/list/CopyListServiceUnitTest.java b/core-java-modules/core-java-10/src/test/java/com/baeldung/java10/list/CopyListServiceUnitTest.java index f529e219a6..0b70516146 100644 --- a/core-java-modules/core-java-10/src/test/java/com/baeldung/java10/list/CopyListServiceUnitTest.java +++ b/core-java-modules/core-java-10/src/test/java/com/baeldung/java10/list/CopyListServiceUnitTest.java @@ -10,5 +10,6 @@ public class CopyListServiceUnitTest { @Test(expected = UnsupportedOperationException.class) public void whenModifyCopyOfList_thenThrowsException() { List copyList = List.copyOf(Arrays.asList(1, 2, 3, 4)); + copyList.add(4); } } From 93c0a00a48ac42534dc2ee66a65964522a92cb0d Mon Sep 17 00:00:00 2001 From: KarthikBalaraman Date: Thu, 27 Aug 2020 23:02:43 +0530 Subject: [PATCH 28/58] BAEL-4523 - Added code example for article to find the largest power of 2 that is less than the given number (#9840) --- .../largestpowerof2/LargestPowerOf2.java | 60 +++++++++++++++++ .../LargestPowerOf2UnitTest.java | 67 +++++++++++++++++++ 2 files changed, 127 insertions(+) create mode 100644 core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/largestpowerof2/LargestPowerOf2.java create mode 100644 core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/largestpowerof2/LargestPowerOf2UnitTest.java diff --git a/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/largestpowerof2/LargestPowerOf2.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/largestpowerof2/LargestPowerOf2.java new file mode 100644 index 0000000000..ca6b25b3e7 --- /dev/null +++ b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/largestpowerof2/LargestPowerOf2.java @@ -0,0 +1,60 @@ +package com.baeldung.algorithms.largestpowerof2; + +import org.nd4j.linalg.io.Assert; + +public class LargestPowerOf2 { + public long findLargestPowerOf2LessThanTheGivenNumber(long input) { + Assert.isTrue(input > 1, "Invalid input"); + + long firstPowerOf2 = 1; + long nextPowerOf2 = 2; + + while (nextPowerOf2 < input) { + firstPowerOf2 = nextPowerOf2; + nextPowerOf2 = nextPowerOf2 * 2; + } + return firstPowerOf2; + } + + public long findLargestPowerOf2LessThanTheGivenNumberUsingLogBase2(long input) { + Assert.isTrue(input > 1, "Invalid input"); + + long temp = input; + if (input % 2 == 0) { + temp = input - 1; + } + + // Find log base 2 of a given number + long power = (long) (Math.log(temp) / Math.log(2)); + long result = (long) Math.pow(2, power); + + return result; + } + + public long findLargestPowerOf2LessThanTheGivenNumberUsingBitwiseAnd(long input) { + Assert.isTrue(input > 1, "Invalid input"); + long result = 1; + for (long i = input - 1; i > 1; i--) { + if ((i & (i - 1)) == 0) { + result = i; + break; + } + } + return result; + } + + public long findLargestPowerOf2LessThanTheGivenNumberUsingBitShiftApproach(long input) { + Assert.isTrue(input > 1, "Invalid input"); + long result = 1; + long powerOf2; + + for (long i = 0; i < Long.BYTES * 8; i++) { + powerOf2 = 1 << i; + if (powerOf2 >= input) { + break; + } + result = powerOf2; + } + return result; + } +} diff --git a/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/largestpowerof2/LargestPowerOf2UnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/largestpowerof2/LargestPowerOf2UnitTest.java new file mode 100644 index 0000000000..63f7b03cf7 --- /dev/null +++ b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/largestpowerof2/LargestPowerOf2UnitTest.java @@ -0,0 +1,67 @@ +package com.baeldung.algorithms.largestpowerof2; + +import java.util.Arrays; +import java.util.Collection; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class LargestPowerOf2UnitTest { + private long input; + private long expectedResult; + + public LargestPowerOf2UnitTest(long input, long expectedResult) { + this.input = input; + this.expectedResult = expectedResult; + } + + @Parameterized.Parameters(name = "{index}: verifyLargestPowerOf2LessThanTheGivenNumber({0}) = {1}") + public static Collection data() { + return Arrays.asList(new Object[][] { { 2, 1 }, { 4, 2 }, { 500, 256 }, { 512, 256 }, { 1050, 1024 } }); + } + + @Test + public void givenValidInput_verifyLargestPowerOf2LessThanTheGivenNumber() { + LargestPowerOf2 largestPowerOf2 = new LargestPowerOf2(); + + long result = largestPowerOf2.findLargestPowerOf2LessThanTheGivenNumber(input); + + Assert.assertEquals(expectedResult, result); + } + + @Test + public void givenValidInput_verifyLargestPowerOf2LessThanTheGivenNumberUsingLogBase2() { + LargestPowerOf2 largestPowerOf2 = new LargestPowerOf2(); + + long result = largestPowerOf2.findLargestPowerOf2LessThanTheGivenNumberUsingLogBase2(input); + + Assert.assertEquals(expectedResult, result); + } + + @Test + public void givenValidInput_verifyLargestPowerOf2LessThanTheGivenNumberBitwiseAnd() { + LargestPowerOf2 largestPowerOf2 = new LargestPowerOf2(); + + long result = largestPowerOf2.findLargestPowerOf2LessThanTheGivenNumberUsingBitwiseAnd(input); + + Assert.assertEquals(expectedResult, result); + } + + @Test + public void givenValidInput_verifyLargestPowerOf2LessThanTheGivenNumberBitShiftApproach() { + LargestPowerOf2 largestPowerOf2 = new LargestPowerOf2(); + + long result = largestPowerOf2.findLargestPowerOf2LessThanTheGivenNumberUsingBitShiftApproach(input); + + Assert.assertEquals(expectedResult, result); + } + + @Test(expected = IllegalArgumentException.class) + public void givenInvalidInput_ShouldThrowException() { + LargestPowerOf2 largestPowerOf2 = new LargestPowerOf2(); + largestPowerOf2.findLargestPowerOf2LessThanTheGivenNumber(1); + } +} \ No newline at end of file From 9c09e01c0327dcb0c75569a065482670ea162286 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Thu, 27 Aug 2020 22:16:56 +0200 Subject: [PATCH 29/58] JAVA-2431: Fix README.md files --- drools/README.MD | 1 + logging-modules/log-mdc/README.md | 2 -- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/drools/README.MD b/drools/README.MD index 414ad2dea3..6011c8293c 100644 --- a/drools/README.MD +++ b/drools/README.MD @@ -6,3 +6,4 @@ This module contains articles about Drools - [Introduction to Drools](https://www.baeldung.com/drools) - [An Example of Backward Chaining in Drools](https://www.baeldung.com/drools-backward-chaining) +- [Drools Using Rules from Excel Files](https://www.baeldung.com/drools-excel) diff --git a/logging-modules/log-mdc/README.md b/logging-modules/log-mdc/README.md index 0d516619ef..f35bc7fccc 100644 --- a/logging-modules/log-mdc/README.md +++ b/logging-modules/log-mdc/README.md @@ -1,8 +1,6 @@ ### Relevant Articles: -- TBD - [Improved Java Logging with Mapped Diagnostic Context (MDC)](https://www.baeldung.com/mdc-in-log4j-2-logback) - [Java Logging with Nested Diagnostic Context (NDC)](https://www.baeldung.com/java-logging-ndc-log4j) -- [Drools Using Rules from Excel Files](https://www.baeldung.com/drools-excel) ### References From 482357866eb215d3e1becabd7d06961e0d1a24f1 Mon Sep 17 00:00:00 2001 From: kwoyke Date: Fri, 28 Aug 2020 08:01:12 +0200 Subject: [PATCH 30/58] BAEL-4577: Fix @MapsIs usage and add integration test (#9930) --- .../com/baeldung/manytomany/model/Course.java | 39 +++++++++++++----- .../manytomany/model/CourseRating.java | 40 +++++++++++-------- .../manytomany/model/CourseRatingKey.java | 16 +++++++- .../manytomany/model/CourseRegistration.java | 20 +++++----- .../baeldung/manytomany/model/Student.java | 37 +++++++++++------ .../manytomany/ManyToManyIntegrationTest.java | 37 +++++++++++++++-- .../ManyToManyTestConfiguration.java | 22 ++++++---- 7 files changed, 149 insertions(+), 62 deletions(-) diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/Course.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/Course.java index bdfb8e890f..d824505629 100644 --- a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/Course.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/Course.java @@ -1,14 +1,9 @@ package com.baeldung.manytomany.model; +import javax.persistence.*; +import java.util.HashSet; import java.util.Set; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.ManyToMany; -import javax.persistence.OneToMany; -import javax.persistence.Table; - @Entity @Table(name = "course") public class Course { @@ -18,31 +13,55 @@ public class Course { private Long id; @ManyToMany(mappedBy = "likedCourses") - private Set likes; + private Set likes = new HashSet<>(); @OneToMany(mappedBy = "course") - private Set ratings; + private Set ratings = new HashSet<>(); @OneToMany(mappedBy = "course") - private Set registrations; + private Set registrations = new HashSet<>(); // additional properties public Course() { } + public Course(Long id) { + this.id = id; + } + public Long getId() { return id; } + public void setId(Long id) { + this.id = id; + } + + public Set getLikes() { + return likes; + } + + public void setLikes(Set likes) { + this.likes = likes; + } + public Set getRatings() { return ratings; } + public void setRatings(Set ratings) { + this.ratings = ratings; + } + public Set getRegistrations() { return registrations; } + public void setRegistrations(Set registrations) { + this.registrations = registrations; + } + @Override public int hashCode() { final int prime = 31; diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRating.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRating.java index 4951f766bc..b89cc1dae9 100644 --- a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRating.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRating.java @@ -1,12 +1,6 @@ package com.baeldung.manytomany.model; -import javax.persistence.Column; -import javax.persistence.EmbeddedId; -import javax.persistence.Entity; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.MapsId; -import javax.persistence.Table; +import javax.persistence.*; @Entity @Table(name = "course_rating") @@ -16,12 +10,12 @@ public class CourseRating { private CourseRatingKey id; @ManyToOne - @MapsId("student_id") + @MapsId("studentId") @JoinColumn(name = "student_id") private Student student; @ManyToOne - @MapsId("course_id") + @MapsId("courseId") @JoinColumn(name = "course_id") private Course course; @@ -31,26 +25,38 @@ public class CourseRating { public CourseRating() { } - public int getRating() { - return rating; - } - - public void setRating(int rating) { - this.rating = rating; - } - public CourseRatingKey getId() { return id; } + public void setId(CourseRatingKey id) { + this.id = id; + } + public Student getStudent() { return student; } + public void setStudent(Student student) { + this.student = student; + } + public Course getCourse() { return course; } + public void setCourse(Course course) { + this.course = course; + } + + public int getRating() { + return rating; + } + + public void setRating(int rating) { + this.rating = rating; + } + @Override public int hashCode() { final int prime = 31; diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRatingKey.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRatingKey.java index 4e7430ed92..a4b2df9b07 100644 --- a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRatingKey.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRatingKey.java @@ -1,9 +1,8 @@ package com.baeldung.manytomany.model; -import java.io.Serializable; - import javax.persistence.Column; import javax.persistence.Embeddable; +import java.io.Serializable; @Embeddable public class CourseRatingKey implements Serializable { @@ -17,14 +16,27 @@ public class CourseRatingKey implements Serializable { public CourseRatingKey() { } + public CourseRatingKey(Long studentId, Long courseId) { + this.studentId = studentId; + this.courseId = courseId; + } + public Long getStudentId() { return studentId; } + public void setStudentId(Long studentId) { + this.studentId = studentId; + } + public Long getCourseId() { return courseId; } + public void setCourseId(Long courseId) { + this.courseId = courseId; + } + @Override public int hashCode() { final int prime = 31; diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRegistration.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRegistration.java index e1f30af883..ba914b564d 100644 --- a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRegistration.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRegistration.java @@ -1,14 +1,8 @@ package com.baeldung.manytomany.model; +import javax.persistence.*; import java.time.LocalDateTime; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; - @Entity @Table(name = "course_registration") public class CourseRegistration { @@ -36,6 +30,14 @@ public class CourseRegistration { public CourseRegistration() { } + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + public Student getStudent() { return student; } @@ -68,10 +70,6 @@ public class CourseRegistration { this.grade = grade; } - public Long getId() { - return id; - } - @Override public int hashCode() { final int prime = 31; diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/Student.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/Student.java index 00561593a6..53c5d88a57 100644 --- a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/Student.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/Student.java @@ -1,16 +1,9 @@ package com.baeldung.manytomany.model; +import javax.persistence.*; +import java.util.HashSet; import java.util.Set; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; -import javax.persistence.OneToMany; -import javax.persistence.Table; - @Entity @Table(name = "student") public class Student { @@ -21,35 +14,55 @@ public class Student { @ManyToMany @JoinTable(name = "course_like", joinColumns = @JoinColumn(name = "student_id"), inverseJoinColumns = @JoinColumn(name = "course_id")) - private Set likedCourses; + private Set likedCourses = new HashSet<>(); @OneToMany(mappedBy = "student") - private Set ratings; + private Set ratings = new HashSet<>(); @OneToMany(mappedBy = "student") - private Set registrations; + private Set registrations = new HashSet<>(); // additional properties public Student() { } + public Student(Long id) { + this.id = id; + } + public Long getId() { return id; } + public void setId(Long id) { + this.id = id; + } + public Set getLikedCourses() { return likedCourses; } + public void setLikedCourses(Set likedCourses) { + this.likedCourses = likedCourses; + } + public Set getRatings() { return ratings; } + public void setRatings(Set ratings) { + this.ratings = ratings; + } + public Set getRegistrations() { return registrations; } + public void setRegistrations(Set registrations) { + this.registrations = registrations; + } + @Override public int hashCode() { final int prime = 31; diff --git a/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomany/ManyToManyIntegrationTest.java b/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomany/ManyToManyIntegrationTest.java index 5e4334f5d4..f5b02ec2c1 100644 --- a/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomany/ManyToManyIntegrationTest.java +++ b/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomany/ManyToManyIntegrationTest.java @@ -1,17 +1,27 @@ package com.baeldung.manytomany; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; - +import com.baeldung.manytomany.model.Course; +import com.baeldung.manytomany.model.CourseRating; +import com.baeldung.manytomany.model.CourseRatingKey; +import com.baeldung.manytomany.model.Student; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.transaction.annotation.Transactional; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.junit.Assert.assertThat; @RunWith(SpringRunner.class) @ContextConfiguration(classes = ManyToManyTestConfiguration.class) @DirtiesContext +@Transactional public class ManyToManyIntegrationTest { @PersistenceContext @@ -21,4 +31,25 @@ public class ManyToManyIntegrationTest { public void contextStarted() { } + @Test + public void whenCourseRatingPersisted_thenCorrect() { + Student student = new Student(101L); + entityManager.persist(student); + + Course course = new Course(201L); + entityManager.persist(course); + + CourseRating courseRating = new CourseRating(); + courseRating.setId(new CourseRatingKey()); + courseRating.setStudent(student); + courseRating.setCourse(course); + courseRating.setRating(100); + entityManager.persist(courseRating); + + CourseRating persistedCourseRating = entityManager.find(CourseRating.class, new CourseRatingKey(101L, 201L)); + + assertThat(persistedCourseRating, notNullValue()); + assertThat(persistedCourseRating.getStudent().getId(), is(101L)); + assertThat(persistedCourseRating.getCourse().getId(), is(201L)); + } } diff --git a/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomany/ManyToManyTestConfiguration.java b/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomany/ManyToManyTestConfiguration.java index 1cc3621f0d..fa12828074 100644 --- a/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomany/ManyToManyTestConfiguration.java +++ b/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomany/ManyToManyTestConfiguration.java @@ -1,20 +1,21 @@ package com.baeldung.manytomany; -import java.util.HashMap; -import java.util.Map; - -import javax.sql.DataSource; - import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; +import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; +import java.util.HashMap; +import java.util.Map; + @Configuration @PropertySource("manytomany/test.properties") public class ManyToManyTestConfiguration { @@ -23,8 +24,8 @@ public class ManyToManyTestConfiguration { public DataSource dataSource() { EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder(); return dbBuilder.setType(EmbeddedDatabaseType.H2) - .addScript("classpath:/manytomany/db.sql") - .build(); + .addScript("classpath:/manytomany/db.sql") + .build(); } @Bean @@ -44,6 +45,13 @@ public class ManyToManyTestConfiguration { return result; } + @Bean + JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) { + JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(entityManagerFactory); + return transactionManager; + } + public JpaVendorAdapter jpaVendorAdapter() { return new HibernateJpaVendorAdapter(); } From 0c8f7f6716023441203d561ae21fc8b0ef2bf4f5 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Fri, 28 Aug 2020 15:39:15 +0530 Subject: [PATCH 31/58] Fix for String equals check --- .../main/java/com/baeldung/jpa/equality/EqualByBusinessKey.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/java-jpa-3/src/main/java/com/baeldung/jpa/equality/EqualByBusinessKey.java b/persistence-modules/java-jpa-3/src/main/java/com/baeldung/jpa/equality/EqualByBusinessKey.java index 3fe858936a..8cfee8f5d6 100644 --- a/persistence-modules/java-jpa-3/src/main/java/com/baeldung/jpa/equality/EqualByBusinessKey.java +++ b/persistence-modules/java-jpa-3/src/main/java/com/baeldung/jpa/equality/EqualByBusinessKey.java @@ -44,7 +44,7 @@ public class EqualByBusinessKey { return false; } if (obj instanceof EqualByBusinessKey) { - if (((EqualByBusinessKey) obj).getEmail() == getEmail()) { + if (((EqualByBusinessKey) obj).getEmail().equals(getEmail())) { return true; } } From 544c3667538a284797dde4dda7f11f446949a5a2 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Fri, 28 Aug 2020 17:54:52 +0530 Subject: [PATCH 32/58] JAVA-84: Moved 1 article to spring-boot-di --- spring-boot-modules/spring-boot-di/{README.MD => README.md} | 1 + spring-boot-modules/spring-boot-di/pom.xml | 6 ++++++ .../main/java/com/baeldung/displayallbeans/Application.java | 0 .../baeldung/displayallbeans/controller/FooController.java | 0 .../com/baeldung/displayallbeans/service/FooService.java | 0 .../displayallbeans/DisplayBeanIntegrationTest.java | 0 6 files changed, 7 insertions(+) rename spring-boot-modules/spring-boot-di/{README.MD => README.md} (81%) rename spring-boot-modules/{spring-boot => spring-boot-di}/src/main/java/com/baeldung/displayallbeans/Application.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-di}/src/main/java/com/baeldung/displayallbeans/controller/FooController.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-di}/src/main/java/com/baeldung/displayallbeans/service/FooService.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-di}/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java (100%) diff --git a/spring-boot-modules/spring-boot-di/README.MD b/spring-boot-modules/spring-boot-di/README.md similarity index 81% rename from spring-boot-modules/spring-boot-di/README.MD rename to spring-boot-modules/spring-boot-di/README.md index cbd42c5609..2759c73926 100644 --- a/spring-boot-modules/spring-boot-di/README.MD +++ b/spring-boot-modules/spring-boot-di/README.md @@ -9,3 +9,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Component Scanning](https://www.baeldung.com/spring-component-scanning) - [Spring @ComponentScan – Filter Types](https://www.baeldung.com/spring-componentscan-filter-type) +- [How to Get All Spring-Managed Beans?](https://www.baeldung.com/spring-show-all-beans) diff --git a/spring-boot-modules/spring-boot-di/pom.xml b/spring-boot-modules/spring-boot-di/pom.xml index 87a0ad2937..58b427a4a8 100644 --- a/spring-boot-modules/spring-boot-di/pom.xml +++ b/spring-boot-modules/spring-boot-di/pom.xml @@ -27,6 +27,12 @@ org.springframework.boot spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-actuator + + org.springframework.boot spring-boot-starter-tomcat diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/displayallbeans/Application.java b/spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/displayallbeans/Application.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/displayallbeans/Application.java rename to spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/displayallbeans/Application.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java b/spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/displayallbeans/controller/FooController.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java rename to spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/displayallbeans/controller/FooController.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/displayallbeans/service/FooService.java b/spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/displayallbeans/service/FooService.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/displayallbeans/service/FooService.java rename to spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/displayallbeans/service/FooService.java diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java b/spring-boot-modules/spring-boot-di/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java similarity index 100% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java rename to spring-boot-modules/spring-boot-di/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java From 52721a78d6b5c52525c1e8c9af2e00b4b9cf0eab Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Fri, 28 Aug 2020 17:56:09 +0530 Subject: [PATCH 33/58] JAVA-84: Moved 3 articles to spring-boot-libraries --- .../spring-boot-libraries/README.md | 3 + .../spring-boot-libraries/pom.xml | 31 +++- .../com/baeldung/demo/DemoApplication.java | 18 ++ .../java/com/baeldung/graphql/Author.java | 0 .../java/com/baeldung/graphql/AuthorDao.java | 0 .../com/baeldung/graphql/AuthorResolver.java | 0 .../graphql/GraphqlConfiguration.java | 0 .../java/com/baeldung/graphql/Mutation.java | 0 .../main/java/com/baeldung/graphql/Post.java | 0 .../java/com/baeldung/graphql/PostDao.java | 0 .../com/baeldung/graphql/PostResolver.java | 0 .../main/java/com/baeldung/graphql/Query.java | 0 .../com/baeldung/kong/QueryController.java | 0 .../main/java/com/baeldung/kong/StockApp.java | 0 .../java/com/baeldung/toggle/Employee.java | 37 ++++ .../baeldung/toggle/EmployeeRepository.java | 0 .../baeldung/toggle/FeatureAssociation.java | 0 .../com/baeldung/toggle/FeaturesAspect.java | 0 .../java/com/baeldung/toggle/MyFeatures.java | 0 .../com/baeldung/toggle/SalaryController.java | 0 .../com/baeldung/toggle/SalaryService.java | 0 .../baeldung/toggle/ToggleApplication.java | 0 .../baeldung/toggle/ToggleConfiguration.java | 0 .../baeldung/kong/KongAdminAPILiveTest.java | 170 ++++++++++++++++++ .../kong/KongLoadBalanceLiveTest.java | 75 ++++++++ .../com/baeldung/kong/domain/APIObject.java | 54 ++++++ .../baeldung/kong/domain/ConsumerObject.java | 35 ++++ .../baeldung/kong/domain/KeyAuthObject.java | 21 +++ .../baeldung/kong/domain/PluginObject.java | 30 ++++ .../baeldung/kong/domain/TargetObject.java | 31 ++++ .../baeldung/kong/domain/UpstreamObject.java | 21 +++ .../toggle/ToggleIntegrationTest.java | 62 +++++++ spring-boot-modules/spring-boot/pom.xml | 32 ---- 33 files changed, 587 insertions(+), 33 deletions(-) create mode 100644 spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/demo/DemoApplication.java rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/graphql/Author.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/graphql/AuthorDao.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/graphql/AuthorResolver.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/graphql/Mutation.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/graphql/Post.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/graphql/PostDao.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/graphql/PostResolver.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/graphql/Query.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/kong/QueryController.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/kong/StockApp.java (100%) create mode 100644 spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/Employee.java rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/toggle/EmployeeRepository.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/toggle/FeatureAssociation.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/toggle/FeaturesAspect.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/toggle/MyFeatures.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/toggle/SalaryController.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/toggle/SalaryService.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/toggle/ToggleApplication.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/toggle/ToggleConfiguration.java (100%) create mode 100644 spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java create mode 100644 spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java create mode 100644 spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/APIObject.java create mode 100644 spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/ConsumerObject.java create mode 100644 spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/KeyAuthObject.java create mode 100644 spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/PluginObject.java create mode 100644 spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/TargetObject.java create mode 100644 spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/UpstreamObject.java create mode 100644 spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-libraries/README.md b/spring-boot-modules/spring-boot-libraries/README.md index 8cd3db9c93..10c56ca576 100644 --- a/spring-boot-modules/spring-boot-libraries/README.md +++ b/spring-boot-modules/spring-boot-libraries/README.md @@ -12,3 +12,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Generating Barcodes and QR Codes in Java](https://www.baeldung.com/java-generating-barcodes-qr-codes) - [Rate Limiting a Spring API Using Bucket4j](https://www.baeldung.com/spring-bucket4j) - [Spring Boot and Caffeine Cache](https://www.baeldung.com/spring-boot-caffeine-cache) +- [Spring Boot and Togglz Aspect](https://www.baeldung.com/spring-togglz) +- [Getting Started with GraphQL and Spring Boot](https://www.baeldung.com/spring-graphql) +- [An Introduction to Kong](https://www.baeldung.com/kong) diff --git a/spring-boot-modules/spring-boot-libraries/pom.xml b/spring-boot-modules/spring-boot-libraries/pom.xml index 05ab59aab7..3913babaa8 100644 --- a/spring-boot-modules/spring-boot-libraries/pom.xml +++ b/spring-boot-modules/spring-boot-libraries/pom.xml @@ -37,6 +37,36 @@ spring-boot-starter-test test + + + + org.togglz + togglz-spring-boot-starter + ${togglz.version} + + + + org.togglz + togglz-spring-security + ${togglz.version} + + + + + com.graphql-java + graphql-spring-boot-starter + ${graphql-spring-boot-starter.version} + + + com.graphql-java + graphql-java-tools + ${graphql-java-tools.version} + + + com.graphql-java + graphiql-spring-boot-starter + ${graphql-spring-boot-starter.version} + @@ -216,7 +246,6 @@ 1.9.0 2.0.0 5.0.2 - 5.0.2 5.2.4 18.0 2.2.4 diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/demo/DemoApplication.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/demo/DemoApplication.java new file mode 100644 index 0000000000..eb091b4695 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/demo/DemoApplication.java @@ -0,0 +1,18 @@ +package com.baeldung.demo; + +import com.baeldung.graphql.GraphqlConfiguration; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +import org.springframework.context.annotation.Import; + +@SpringBootApplication +@Import(GraphqlConfiguration.class) +public class DemoApplication { + + public static void main(String[] args) { + System.setProperty("spring.config.name", "demo"); + SpringApplication.run(DemoApplication.class, args); + } + +} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/Author.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/Author.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/Author.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/Author.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/AuthorDao.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/AuthorDao.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/AuthorDao.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/AuthorDao.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/AuthorResolver.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/AuthorResolver.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/AuthorResolver.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/AuthorResolver.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/Mutation.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/Mutation.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/Mutation.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/Mutation.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/Post.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/Post.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/Post.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/Post.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/PostDao.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/PostDao.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/PostDao.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/PostDao.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/PostResolver.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/PostResolver.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/PostResolver.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/PostResolver.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/Query.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/Query.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/Query.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/Query.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/kong/QueryController.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/kong/QueryController.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/kong/QueryController.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/kong/QueryController.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/kong/StockApp.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/kong/StockApp.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/kong/StockApp.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/kong/StockApp.java diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/Employee.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/Employee.java new file mode 100644 index 0000000000..64a8b3ce5b --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/Employee.java @@ -0,0 +1,37 @@ +package com.baeldung.toggle; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Employee { + + @Id + private long id; + private double salary; + + public Employee() { + } + + public Employee(long id, double salary) { + this.id = id; + this.salary = salary; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public double getSalary() { + return salary; + } + + public void setSalary(double salary) { + this.salary = salary; + } + +} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/EmployeeRepository.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/EmployeeRepository.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/EmployeeRepository.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/EmployeeRepository.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/FeatureAssociation.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/FeatureAssociation.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/FeatureAssociation.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/FeatureAssociation.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/FeaturesAspect.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/FeaturesAspect.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/FeaturesAspect.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/FeaturesAspect.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/MyFeatures.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/MyFeatures.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/SalaryController.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/SalaryController.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/SalaryController.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/SalaryController.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/SalaryService.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/SalaryService.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/SalaryService.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/SalaryService.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/ToggleApplication.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/ToggleApplication.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/ToggleApplication.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/ToggleApplication.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/ToggleConfiguration.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/ToggleConfiguration.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/ToggleConfiguration.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/ToggleConfiguration.java diff --git a/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java new file mode 100644 index 0000000000..92d2286518 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java @@ -0,0 +1,170 @@ +package com.baeldung.kong; + +import com.baeldung.kong.domain.APIObject; +import com.baeldung.kong.domain.ConsumerObject; +import com.baeldung.kong.domain.KeyAuthObject; +import com.baeldung.kong.domain.PluginObject; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.*; +import org.springframework.test.context.junit4.SpringRunner; + +import java.net.URI; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT; + +/** + * @author aiet + */ +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = DEFINED_PORT, classes = StockApp.class) +public class KongAdminAPILiveTest { + + private String getStockPrice(String code) { + try { + return restTemplate.getForObject(new URI("http://localhost:8080/stock/" + code), String.class); + } catch (Exception ignored) { + } + return null; + } + + @Before + public void init() { + System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); + } + + @Autowired + TestRestTemplate restTemplate; + + @Test + public void givenEndpoint_whenQueryStockPrice_thenPriceCorrect() { + String response = getStockPrice("btc"); + assertEquals("10000", response); + + response = getStockPrice("eth"); + assertEquals("N/A", response); + } + + @Test + public void givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong() throws Exception { + restTemplate.delete("http://localhost:8001/apis/stock-api"); + + APIObject stockAPI = new APIObject("stock-api", "stock.api", "http://localhost:9090", "/"); + HttpEntity apiEntity = new HttpEntity<>(stockAPI); + ResponseEntity addAPIResp = restTemplate.postForEntity("http://localhost:8001/apis", apiEntity, String.class); + + assertEquals(HttpStatus.CREATED, addAPIResp.getStatusCode()); + + addAPIResp = restTemplate.postForEntity("http://localhost:8001/apis", apiEntity, String.class); + assertEquals(HttpStatus.CONFLICT, addAPIResp.getStatusCode()); + String apiListResp = restTemplate.getForObject("http://localhost:8001/apis/", String.class); + + assertTrue(apiListResp.contains("stock-api")); + + HttpHeaders headers = new HttpHeaders(); + headers.set("Host", "stock.api"); + RequestEntity requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/springbootapp/stock/btc")); + ResponseEntity stockPriceResp = restTemplate.exchange(requestEntity, String.class); + + assertEquals("10000", stockPriceResp.getBody()); + } + + @Test + public void givenKongAdminAPI_whenAddAPIConsumer_thenAdded() { + restTemplate.delete("http://localhost:8001/consumers/eugenp"); + + ConsumerObject consumer = new ConsumerObject("eugenp"); + HttpEntity addConsumerEntity = new HttpEntity<>(consumer); + ResponseEntity addConsumerResp = restTemplate.postForEntity("http://localhost:8001/consumers/", addConsumerEntity, String.class); + + assertEquals(HttpStatus.CREATED, addConsumerResp.getStatusCode()); + + addConsumerResp = restTemplate.postForEntity("http://localhost:8001/consumers", addConsumerEntity, String.class); + assertEquals(HttpStatus.CONFLICT, addConsumerResp.getStatusCode()); + + String consumerListResp = restTemplate.getForObject("http://localhost:8001/consumers/", String.class); + assertTrue(consumerListResp.contains("eugenp")); + } + + @Test + public void givenAPI_whenEnableAuth_thenAnonymousDenied() throws Exception { + String apiListResp = restTemplate.getForObject("http://localhost:8001/apis/", String.class); + if (!apiListResp.contains("stock-api")) { + givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong(); + } + + PluginObject authPlugin = new PluginObject("key-auth"); + ResponseEntity enableAuthResp = restTemplate.postForEntity("http://localhost:8001/apis/stock-api/plugins", new HttpEntity<>(authPlugin), String.class); + + assertTrue(HttpStatus.CREATED == enableAuthResp.getStatusCode() || HttpStatus.CONFLICT == enableAuthResp.getStatusCode()); + + String pluginsResp = restTemplate.getForObject("http://localhost:8001/apis/stock-api/plugins", String.class); + assertTrue(pluginsResp.contains("key-auth")); + + HttpHeaders headers = new HttpHeaders(); + headers.set("Host", "stock.api"); + RequestEntity requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/stock/btc")); + ResponseEntity stockPriceResp = restTemplate.exchange(requestEntity, String.class); + assertEquals(HttpStatus.UNAUTHORIZED, stockPriceResp.getStatusCode()); + } + + @Test + public void givenAPIAuthEnabled_whenAddKey_thenAccessAllowed() throws Exception { + String apiListResp = restTemplate.getForObject("http://localhost:8001/apis/", String.class); + if (!apiListResp.contains("stock-api")) { + givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong(); + } + + String consumerListResp = restTemplate.getForObject("http://localhost:8001/consumers/", String.class); + if (!consumerListResp.contains("eugenp")) { + givenKongAdminAPI_whenAddAPIConsumer_thenAdded(); + } + + PluginObject authPlugin = new PluginObject("key-auth"); + ResponseEntity enableAuthResp = restTemplate.postForEntity("http://localhost:8001/apis/stock-api/plugins", new HttpEntity<>(authPlugin), String.class); + assertTrue(HttpStatus.CREATED == enableAuthResp.getStatusCode() || HttpStatus.CONFLICT == enableAuthResp.getStatusCode()); + + final String consumerKey = "eugenp.pass"; + KeyAuthObject keyAuth = new KeyAuthObject(consumerKey); + ResponseEntity keyAuthResp = restTemplate.postForEntity("http://localhost:8001/consumers/eugenp/key-auth", new HttpEntity<>(keyAuth), String.class); + + assertTrue(HttpStatus.CREATED == keyAuthResp.getStatusCode() || HttpStatus.CONFLICT == keyAuthResp.getStatusCode()); + + HttpHeaders headers = new HttpHeaders(); + headers.set("Host", "stock.api"); + headers.set("apikey", consumerKey); + RequestEntity requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/springbootapp/stock/btc")); + ResponseEntity stockPriceResp = restTemplate.exchange(requestEntity, String.class); + + assertEquals("10000", stockPriceResp.getBody()); + + headers.set("apikey", "wrongpass"); + requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/springbootapp/stock/btc")); + stockPriceResp = restTemplate.exchange(requestEntity, String.class); + assertEquals(HttpStatus.FORBIDDEN, stockPriceResp.getStatusCode()); + } + + @Test + public void givenAdminAPIProxy_whenAddAPIViaProxy_thenAPIAdded() throws Exception { + APIObject adminAPI = new APIObject("admin-api", "admin.api", "http://localhost:8001", "/admin-api"); + HttpEntity apiEntity = new HttpEntity<>(adminAPI); + ResponseEntity addAPIResp = restTemplate.postForEntity("http://localhost:8001/apis", apiEntity, String.class); + + assertTrue(HttpStatus.CREATED == addAPIResp.getStatusCode() || HttpStatus.CONFLICT == addAPIResp.getStatusCode()); + + HttpHeaders headers = new HttpHeaders(); + headers.set("Host", "admin.api"); + APIObject baeldungAPI = new APIObject("baeldung-api", "baeldung.com", "http://ww.baeldung.com", "/"); + RequestEntity requestEntity = new RequestEntity<>(baeldungAPI, headers, HttpMethod.POST, new URI("http://localhost:8000/admin-api/apis")); + addAPIResp = restTemplate.exchange(requestEntity, String.class); + + assertTrue(HttpStatus.CREATED == addAPIResp.getStatusCode() || HttpStatus.CONFLICT == addAPIResp.getStatusCode()); + } + +} diff --git a/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java new file mode 100644 index 0000000000..7cf67453a6 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java @@ -0,0 +1,75 @@ +package com.baeldung.kong; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT; + +import java.net.URI; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.RequestEntity; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.kong.domain.APIObject; +import com.baeldung.kong.domain.TargetObject; +import com.baeldung.kong.domain.UpstreamObject; + +/** + * @author aiet + */ +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = DEFINED_PORT, classes = StockApp.class, properties = "server.servlet.contextPath=/springbootapp") +public class KongLoadBalanceLiveTest { + + @Before + public void init() { + System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); + } + + @Autowired + TestRestTemplate restTemplate; + + @Test + public void givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong() throws Exception { + UpstreamObject upstream = new UpstreamObject("stock.api.service"); + ResponseEntity addUpstreamResp = restTemplate.postForEntity("http://localhost:8001/upstreams", new HttpEntity<>(upstream), String.class); + assertTrue(HttpStatus.CREATED == addUpstreamResp.getStatusCode() || HttpStatus.CONFLICT == addUpstreamResp.getStatusCode()); + + TargetObject testTarget = new TargetObject("localhost:8080", 10); + ResponseEntity addTargetResp = restTemplate.postForEntity("http://localhost:8001/upstreams/stock.api.service/targets", new HttpEntity<>(testTarget), String.class); + assertTrue(HttpStatus.CREATED == addTargetResp.getStatusCode() || HttpStatus.CONFLICT == addTargetResp.getStatusCode()); + + TargetObject releaseTarget = new TargetObject("localhost:9090", 40); + addTargetResp = restTemplate.postForEntity("http://localhost:8001/upstreams/stock.api.service/targets", new HttpEntity<>(releaseTarget), String.class); + assertTrue(HttpStatus.CREATED == addTargetResp.getStatusCode() || HttpStatus.CONFLICT == addTargetResp.getStatusCode()); + + APIObject stockAPI = new APIObject("balanced-stock-api", "balanced.stock.api", "http://stock.api.service", "/"); + HttpEntity apiEntity = new HttpEntity<>(stockAPI); + ResponseEntity addAPIResp = restTemplate.postForEntity("http://localhost:8001/apis", apiEntity, String.class); + assertTrue(HttpStatus.CREATED == addAPIResp.getStatusCode() || HttpStatus.CONFLICT == addAPIResp.getStatusCode()); + + HttpHeaders headers = new HttpHeaders(); + headers.set("Host", "balanced.stock.api"); + for (int i = 0; i < 1000; i++) { + RequestEntity requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/springbootapp/stock/btc")); + ResponseEntity stockPriceResp = restTemplate.exchange(requestEntity, String.class); + assertEquals("10000", stockPriceResp.getBody()); + } + + int releaseCount = restTemplate.getForObject("http://localhost:9090/springbootapp/stock/reqcount", Integer.class); + int testCount = restTemplate.getForObject("http://localhost:8080/springbootapp/stock/reqcount", Integer.class); + + assertTrue(Math.round(releaseCount * 1.0 / testCount) == 4); + } + +} diff --git a/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/APIObject.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/APIObject.java new file mode 100644 index 0000000000..f386712444 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/APIObject.java @@ -0,0 +1,54 @@ +package com.baeldung.kong.domain; + +/** + * @author aiet + */ +public class APIObject { + + public APIObject() { + } + + public APIObject(String name, String hosts, String upstream_url, String uris) { + this.name = name; + this.hosts = hosts; + this.upstream_url = upstream_url; + this.uris = uris; + } + + private String name; + private String hosts; + private String upstream_url; + private String uris; + + public String getUris() { + return uris; + } + + public void setUris(String uris) { + this.uris = uris; + } + + public String getUpstream_url() { + return upstream_url; + } + + public void setUpstream_url(String upstream_url) { + this.upstream_url = upstream_url; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getHosts() { + return hosts; + } + + public void setHosts(String hosts) { + this.hosts = hosts; + } +} diff --git a/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/ConsumerObject.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/ConsumerObject.java new file mode 100644 index 0000000000..74bef8f2d1 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/ConsumerObject.java @@ -0,0 +1,35 @@ +package com.baeldung.kong.domain; + +/** + * @author aiet + */ +public class ConsumerObject { + + private String username; + private String custom_id; + + public ConsumerObject(String username) { + this.username = username; + } + + public ConsumerObject(String username, String custom_id) { + this.username = username; + this.custom_id = custom_id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getCustom_id() { + return custom_id; + } + + public void setCustom_id(String custom_id) { + this.custom_id = custom_id; + } +} diff --git a/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/KeyAuthObject.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/KeyAuthObject.java new file mode 100644 index 0000000000..80de6bfcd9 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/KeyAuthObject.java @@ -0,0 +1,21 @@ +package com.baeldung.kong.domain; + +/** + * @author aiet + */ +public class KeyAuthObject { + + public KeyAuthObject(String key) { + this.key = key; + } + + private String key; + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } +} diff --git a/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/PluginObject.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/PluginObject.java new file mode 100644 index 0000000000..c161fc9b54 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/PluginObject.java @@ -0,0 +1,30 @@ +package com.baeldung.kong.domain; + +/** + * @author aiet + */ +public class PluginObject { + + private String name; + private String consumer_id; + + public PluginObject(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getConsumer_id() { + return consumer_id; + } + + public void setConsumer_id(String consumer_id) { + this.consumer_id = consumer_id; + } +} diff --git a/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/TargetObject.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/TargetObject.java new file mode 100644 index 0000000000..79653e2846 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/TargetObject.java @@ -0,0 +1,31 @@ +package com.baeldung.kong.domain; + +/** + * @author aiet + */ +public class TargetObject { + + public TargetObject(String target, int weight) { + this.target = target; + this.weight = weight; + } + + private String target; + private int weight; + + public String getTarget() { + return target; + } + + public void setTarget(String target) { + this.target = target; + } + + public int getWeight() { + return weight; + } + + public void setWeight(int weight) { + this.weight = weight; + } +} diff --git a/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/UpstreamObject.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/UpstreamObject.java new file mode 100644 index 0000000000..6461381ac5 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/UpstreamObject.java @@ -0,0 +1,21 @@ +package com.baeldung.kong.domain; + +/** + * @author aiet + */ +public class UpstreamObject { + + public UpstreamObject(String name) { + this.name = name; + } + + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java new file mode 100644 index 0000000000..3213a10df9 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java @@ -0,0 +1,62 @@ +package com.baeldung.toggle; + +import static org.junit.Assert.assertEquals; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = ToggleApplication.class) +@AutoConfigureMockMvc +public class ToggleIntegrationTest { + + @Autowired + private EmployeeRepository employeeRepository; + + @Autowired + private MockMvc mockMvc; + + @Autowired + private WebApplicationContext wac; + + @Before + public void setup() { + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); + } + + @Test + public void givenFeaturePropertyFalse_whenIncreaseSalary_thenNoIncrease() throws Exception { + Employee emp = new Employee(1, 2000); + employeeRepository.save(emp); + + System.setProperty("employee.feature", "false"); + + mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")).andExpect(status().is(200)); + + emp = employeeRepository.findById(1L).orElse(null); + assertEquals("salary incorrect", 2000, emp.getSalary(), 0.5); + } + + @Test + public void givenFeaturePropertyTrue_whenIncreaseSalary_thenIncrease() throws Exception { + Employee emp = new Employee(1, 2000); + employeeRepository.save(emp); + + System.setProperty("employee.feature", "true"); + + mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")).andExpect(status().is(200)); + + emp = employeeRepository.findById(1L).orElse(null); + assertEquals("salary incorrect", 2200, emp.getSalary(), 0.5); + } +} diff --git a/spring-boot-modules/spring-boot/pom.xml b/spring-boot-modules/spring-boot/pom.xml index e1299a6a16..5efcffdf03 100644 --- a/spring-boot-modules/spring-boot/pom.xml +++ b/spring-boot-modules/spring-boot/pom.xml @@ -44,22 +44,6 @@ spring-boot-starter-actuator - - com.graphql-java - graphql-spring-boot-starter - ${graphql-spring-boot-starter.version} - - - com.graphql-java - graphql-java-tools - ${graphql-java-tools.version} - - - com.graphql-java - graphiql-spring-boot-starter - ${graphiql-spring-boot-starter.version} - - org.springframework.boot spring-boot-starter-tomcat @@ -104,18 +88,6 @@ provided - - org.togglz - togglz-spring-boot-starter - ${togglz.version} - - - - org.togglz - togglz-spring-security - ${togglz.version} - - org.apache.activemq artemis-server @@ -204,11 +176,7 @@ com.baeldung.intro.App 8.5.11 - 2.4.1.Final 1.9.0 - 5.0.2 - 5.0.2 - 5.2.4 18.0 @ From 5749d7ad23468ed7f2e071372be556f4b3925df0 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Fri, 28 Aug 2020 17:57:38 +0530 Subject: [PATCH 34/58] JAVA-84: Moved 1 article to spring-boot-testing --- .../spring-boot-testing/README.md | 1 + .../spring-boot-testing/pom.xml | 8 + .../com/baeldung/boot/testing}/Employee.java | 2 +- .../boot/testing}/EmployeeRepository.java | 2 +- .../boot/testing}/EmployeeRestController.java | 2 +- .../boot/testing}/EmployeeService.java | 2 +- .../boot/testing}/EmployeeServiceImpl.java | 2 +- .../src/main/resources/application.properties | 4 +- .../persistence-generic-entity.properties | 8 + .../EmployeeControllerIntegrationTest.java | 39 ++-- .../EmployeeRepositoryIntegrationTest.java | 7 +- ...EmployeeRestControllerIntegrationTest.java | 12 +- .../EmployeeServiceImplIntegrationTest.java | 11 +- .../com/baeldung/boot/testing}/JsonUtil.java | 2 +- .../application-integrationtest.properties | 0 .../src/test/resources/application.properties | 4 +- .../spring-boot/{README.MD => README.md} | 5 - .../com/baeldung/demo/DemoApplication.java | 4 - .../baeldung/kong/KongAdminAPILiveTest.java | 170 ------------------ .../kong/KongLoadBalanceLiveTest.java | 75 -------- .../com/baeldung/kong/domain/APIObject.java | 54 ------ .../baeldung/kong/domain/ConsumerObject.java | 35 ---- .../baeldung/kong/domain/KeyAuthObject.java | 21 --- .../baeldung/kong/domain/PluginObject.java | 30 ---- .../baeldung/kong/domain/TargetObject.java | 31 ---- .../baeldung/kong/domain/UpstreamObject.java | 21 --- .../toggle/ToggleIntegrationTest.java | 62 ------- 27 files changed, 70 insertions(+), 544 deletions(-) rename spring-boot-modules/{spring-boot/src/main/java/com/baeldung/demo/boottest => spring-boot-testing/src/main/java/com/baeldung/boot/testing}/Employee.java (95%) rename spring-boot-modules/{spring-boot/src/main/java/com/baeldung/demo/boottest => spring-boot-testing/src/main/java/com/baeldung/boot/testing}/EmployeeRepository.java (91%) rename spring-boot-modules/{spring-boot/src/main/java/com/baeldung/demo/boottest => spring-boot-testing/src/main/java/com/baeldung/boot/testing}/EmployeeRestController.java (96%) rename spring-boot-modules/{spring-boot/src/main/java/com/baeldung/demo/boottest => spring-boot-testing/src/main/java/com/baeldung/boot/testing}/EmployeeService.java (89%) rename spring-boot-modules/{spring-boot/src/main/java/com/baeldung/demo/boottest => spring-boot-testing/src/main/java/com/baeldung/boot/testing}/EmployeeServiceImpl.java (96%) create mode 100644 spring-boot-modules/spring-boot-testing/src/main/resources/persistence-generic-entity.properties rename spring-boot-modules/{spring-boot/src/test/java/com/baeldung/demo/boottest => spring-boot-testing/src/test/java/com/baeldung/boot/testing}/EmployeeControllerIntegrationTest.java (87%) rename spring-boot-modules/{spring-boot/src/test/java/com/baeldung/demo/boottest => spring-boot-testing/src/test/java/com/baeldung/boot/testing}/EmployeeRepositoryIntegrationTest.java (94%) rename spring-boot-modules/{spring-boot/src/test/java/com/baeldung/demo/boottest => spring-boot-testing/src/test/java/com/baeldung/boot/testing}/EmployeeRestControllerIntegrationTest.java (87%) rename spring-boot-modules/{spring-boot/src/test/java/com/baeldung/demo/boottest => spring-boot-testing/src/test/java/com/baeldung/boot/testing}/EmployeeServiceImplIntegrationTest.java (94%) rename spring-boot-modules/{spring-boot/src/test/java/com/baeldung/demo/boottest => spring-boot-testing/src/test/java/com/baeldung/boot/testing}/JsonUtil.java (91%) rename spring-boot-modules/{spring-boot => spring-boot-testing}/src/test/resources/application-integrationtest.properties (100%) rename spring-boot-modules/spring-boot/{README.MD => README.md} (79%) delete mode 100644 spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java delete mode 100644 spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java delete mode 100644 spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/APIObject.java delete mode 100644 spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/ConsumerObject.java delete mode 100644 spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/KeyAuthObject.java delete mode 100644 spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/PluginObject.java delete mode 100644 spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/TargetObject.java delete mode 100644 spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/UpstreamObject.java delete mode 100644 spring-boot-modules/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-testing/README.md b/spring-boot-modules/spring-boot-testing/README.md index 192f5cee99..1b7ad661c6 100644 --- a/spring-boot-modules/spring-boot-testing/README.md +++ b/spring-boot-modules/spring-boot-testing/README.md @@ -14,3 +14,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Embedded Redis Server with Spring Boot Test](https://www.baeldung.com/spring-embedded-redis) - [Testing Spring Boot @ConfigurationProperties](https://www.baeldung.com/spring-boot-testing-configurationproperties) - [Prevent ApplicationRunner or CommandLineRunner Beans From Executing During Junit Testing](https://www.baeldung.com/spring-junit-prevent-runner-beans-testing-execution) +- [Testing in Spring Boot](https://www.baeldung.com/spring-boot-testing) diff --git a/spring-boot-modules/spring-boot-testing/pom.xml b/spring-boot-modules/spring-boot-testing/pom.xml index a3b176af88..bd5ef901dd 100644 --- a/spring-boot-modules/spring-boot-testing/pom.xml +++ b/spring-boot-modules/spring-boot-testing/pom.xml @@ -34,6 +34,14 @@ org.springframework.boot spring-boot-starter-security + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + org.springframework.boot spring-boot-starter-test diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/Employee.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/Employee.java similarity index 95% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/Employee.java rename to spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/Employee.java index fa3c1dc809..2921ecc609 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/Employee.java +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/Employee.java @@ -1,4 +1,4 @@ -package com.baeldung.demo.boottest; +package com.baeldung.boot.testing; import javax.persistence.Entity; import javax.persistence.GeneratedValue; diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRepository.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeRepository.java similarity index 91% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRepository.java rename to spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeRepository.java index b6850d587e..bcef5231e0 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRepository.java +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeRepository.java @@ -1,4 +1,4 @@ -package com.baeldung.demo.boottest; +package com.baeldung.boot.testing; import java.util.List; diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRestController.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeRestController.java similarity index 96% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRestController.java rename to spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeRestController.java index 7d2e06d4a0..b52d38e028 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRestController.java +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeRestController.java @@ -1,4 +1,4 @@ -package com.baeldung.demo.boottest; +package com.baeldung.boot.testing; import java.util.List; diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeService.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeService.java similarity index 89% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeService.java rename to spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeService.java index ff1976cad1..6fc48a3c3d 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeService.java +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeService.java @@ -1,4 +1,4 @@ -package com.baeldung.demo.boottest; +package com.baeldung.boot.testing; import java.util.List; diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeServiceImpl.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeServiceImpl.java similarity index 96% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeServiceImpl.java rename to spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeServiceImpl.java index 156fc571f3..7d5ec4a05d 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeServiceImpl.java +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeServiceImpl.java @@ -1,4 +1,4 @@ -package com.baeldung.demo.boottest; +package com.baeldung.boot.testing; import java.util.List; diff --git a/spring-boot-modules/spring-boot-testing/src/main/resources/application.properties b/spring-boot-modules/spring-boot-testing/src/main/resources/application.properties index 8dc7f6e3c3..daab3e8d2c 100644 --- a/spring-boot-modules/spring-boot-testing/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-testing/src/main/resources/application.properties @@ -4,4 +4,6 @@ spring.redis.port= 6379 # security spring.security.user.name=john -spring.security.user.password=123 \ No newline at end of file +spring.security.user.password=123 + +spring.main.allow-bean-definition-overriding=true \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/main/resources/persistence-generic-entity.properties b/spring-boot-modules/spring-boot-testing/src/main/resources/persistence-generic-entity.properties new file mode 100644 index 0000000000..b19304cb1f --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/main/resources/persistence-generic-entity.properties @@ -0,0 +1,8 @@ +jdbc.driverClassName=org.h2.Driver +jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 +jdbc.user=sa +jdbc.pass=sa + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeControllerIntegrationTest.java similarity index 87% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java rename to spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeControllerIntegrationTest.java index 962abf0fa3..c51113a023 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeControllerIntegrationTest.java @@ -1,19 +1,4 @@ -package com.baeldung.demo.boottest; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.mockito.internal.verification.VerificationModeFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.http.MediaType; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; - -import java.util.Arrays; -import java.util.List; +package com.baeldung.boot.testing; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.Matchers.hasSize; @@ -25,8 +10,28 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import java.util.Arrays; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.internal.verification.VerificationModeFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import com.baeldung.boot.testing.Employee; +import com.baeldung.boot.testing.EmployeeRestController; +import com.baeldung.boot.testing.EmployeeService; + @RunWith(SpringRunner.class) -@WebMvcTest(EmployeeRestController.class) +@WebMvcTest(value = EmployeeRestController.class, excludeAutoConfiguration = SecurityAutoConfiguration.class) public class EmployeeControllerIntegrationTest { @Autowired diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeRepositoryIntegrationTest.java similarity index 94% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java rename to spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeRepositoryIntegrationTest.java index 164887886b..b3a7316764 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeRepositoryIntegrationTest.java @@ -1,7 +1,5 @@ -package com.baeldung.demo.boottest; +package com.baeldung.boot.testing; -import com.baeldung.demo.boottest.Employee; -import com.baeldung.demo.boottest.EmployeeRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -9,6 +7,9 @@ import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.context.junit4.SpringRunner; +import com.baeldung.boot.testing.Employee; +import com.baeldung.boot.testing.EmployeeRepository; + import java.util.List; import static org.assertj.core.api.Assertions.assertThat; diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeRestControllerIntegrationTest.java similarity index 87% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java rename to spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeRestControllerIntegrationTest.java index 327e9f9d56..d13fcd79aa 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeRestControllerIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.demo.boottest; +package com.baeldung.boot.testing; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.is; @@ -14,11 +14,12 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import java.io.IOException; import java.util.List; -import com.baeldung.demo.DemoApplication; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; @@ -27,9 +28,14 @@ import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; +import com.baeldung.boot.Application; +import com.baeldung.boot.testing.Employee; +import com.baeldung.boot.testing.EmployeeRepository; + @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = DemoApplication.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = Application.class) @AutoConfigureMockMvc +@EnableAutoConfiguration(exclude=SecurityAutoConfiguration.class) // @TestPropertySource(locations = "classpath:application-integrationtest.properties") @AutoConfigureTestDatabase public class EmployeeRestControllerIntegrationTest { diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeServiceImplIntegrationTest.java similarity index 94% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java rename to spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeServiceImplIntegrationTest.java index 88f2830a2b..3176a7c75a 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeServiceImplIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.demo.boottest; +package com.baeldung.boot.testing; import static org.assertj.core.api.Assertions.assertThat; @@ -6,10 +6,6 @@ import java.util.Arrays; import java.util.List; import java.util.Optional; -import com.baeldung.demo.boottest.Employee; -import com.baeldung.demo.boottest.EmployeeRepository; -import com.baeldung.demo.boottest.EmployeeService; -import com.baeldung.demo.boottest.EmployeeServiceImpl; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -21,6 +17,11 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Bean; import org.springframework.test.context.junit4.SpringRunner; +import com.baeldung.boot.testing.Employee; +import com.baeldung.boot.testing.EmployeeRepository; +import com.baeldung.boot.testing.EmployeeService; +import com.baeldung.boot.testing.EmployeeServiceImpl; + @RunWith(SpringRunner.class) public class EmployeeServiceImplIntegrationTest { diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/JsonUtil.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/JsonUtil.java similarity index 91% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/JsonUtil.java rename to spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/JsonUtil.java index 3fcd709f7c..49d018dde8 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/JsonUtil.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/JsonUtil.java @@ -1,4 +1,4 @@ -package com.baeldung.demo.boottest; +package com.baeldung.boot.testing; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/spring-boot-modules/spring-boot/src/test/resources/application-integrationtest.properties b/spring-boot-modules/spring-boot-testing/src/test/resources/application-integrationtest.properties similarity index 100% rename from spring-boot-modules/spring-boot/src/test/resources/application-integrationtest.properties rename to spring-boot-modules/spring-boot-testing/src/test/resources/application-integrationtest.properties diff --git a/spring-boot-modules/spring-boot-testing/src/test/resources/application.properties b/spring-boot-modules/spring-boot-testing/src/test/resources/application.properties index 0c5b0e13e6..1810c7b1eb 100644 --- a/spring-boot-modules/spring-boot-testing/src/test/resources/application.properties +++ b/spring-boot-modules/spring-boot-testing/src/test/resources/application.properties @@ -3,4 +3,6 @@ spring.redis.host= localhost spring.redis.port= 6370 # security spring.security.user.name=john -spring.security.user.password=123 \ No newline at end of file +spring.security.user.password=123 + +spring.main.allow-bean-definition-overriding=true \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/README.MD b/spring-boot-modules/spring-boot/README.md similarity index 79% rename from spring-boot-modules/spring-boot/README.MD rename to spring-boot-modules/spring-boot/README.md index c95fe51842..510864e339 100644 --- a/spring-boot-modules/spring-boot/README.MD +++ b/spring-boot-modules/spring-boot/README.md @@ -14,12 +14,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Guide to Internationalization in Spring Boot](https://www.baeldung.com/spring-boot-internationalization) - [Dynamic DTO Validation Config Retrieved from the Database](https://www.baeldung.com/spring-dynamic-dto-validation) - [Custom Information in Spring Boot Info Endpoint](https://www.baeldung.com/spring-boot-info-actuator-custom) -- [Testing in Spring Boot](https://www.baeldung.com/spring-boot-testing) -- [How to Get All Spring-Managed Beans?](https://www.baeldung.com/spring-show-all-beans) -- [Spring Boot and Togglz Aspect](https://www.baeldung.com/spring-togglz) -- [Getting Started with GraphQL and Spring Boot](https://www.baeldung.com/spring-graphql) - [Guide to Spring Type Conversions](https://www.baeldung.com/spring-type-conversions) -- [An Introduction to Kong](https://www.baeldung.com/kong) - [Spring Boot: Configuring a Main Class](https://www.baeldung.com/spring-boot-main-class) - [A Quick Intro to the SpringBootServletInitializer](https://www.baeldung.com/spring-boot-servlet-initializer) - [Spring Shutdown Callbacks](https://www.baeldung.com/spring-shutdown-callbacks) diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/DemoApplication.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/DemoApplication.java index eb091b4695..d2bb217c2f 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/DemoApplication.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/DemoApplication.java @@ -1,13 +1,9 @@ package com.baeldung.demo; -import com.baeldung.graphql.GraphqlConfiguration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Import; - @SpringBootApplication -@Import(GraphqlConfiguration.class) public class DemoApplication { public static void main(String[] args) { diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java deleted file mode 100644 index 92d2286518..0000000000 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java +++ /dev/null @@ -1,170 +0,0 @@ -package com.baeldung.kong; - -import com.baeldung.kong.domain.APIObject; -import com.baeldung.kong.domain.ConsumerObject; -import com.baeldung.kong.domain.KeyAuthObject; -import com.baeldung.kong.domain.PluginObject; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.http.*; -import org.springframework.test.context.junit4.SpringRunner; - -import java.net.URI; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT; - -/** - * @author aiet - */ -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = DEFINED_PORT, classes = StockApp.class) -public class KongAdminAPILiveTest { - - private String getStockPrice(String code) { - try { - return restTemplate.getForObject(new URI("http://localhost:8080/stock/" + code), String.class); - } catch (Exception ignored) { - } - return null; - } - - @Before - public void init() { - System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); - } - - @Autowired - TestRestTemplate restTemplate; - - @Test - public void givenEndpoint_whenQueryStockPrice_thenPriceCorrect() { - String response = getStockPrice("btc"); - assertEquals("10000", response); - - response = getStockPrice("eth"); - assertEquals("N/A", response); - } - - @Test - public void givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong() throws Exception { - restTemplate.delete("http://localhost:8001/apis/stock-api"); - - APIObject stockAPI = new APIObject("stock-api", "stock.api", "http://localhost:9090", "/"); - HttpEntity apiEntity = new HttpEntity<>(stockAPI); - ResponseEntity addAPIResp = restTemplate.postForEntity("http://localhost:8001/apis", apiEntity, String.class); - - assertEquals(HttpStatus.CREATED, addAPIResp.getStatusCode()); - - addAPIResp = restTemplate.postForEntity("http://localhost:8001/apis", apiEntity, String.class); - assertEquals(HttpStatus.CONFLICT, addAPIResp.getStatusCode()); - String apiListResp = restTemplate.getForObject("http://localhost:8001/apis/", String.class); - - assertTrue(apiListResp.contains("stock-api")); - - HttpHeaders headers = new HttpHeaders(); - headers.set("Host", "stock.api"); - RequestEntity requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/springbootapp/stock/btc")); - ResponseEntity stockPriceResp = restTemplate.exchange(requestEntity, String.class); - - assertEquals("10000", stockPriceResp.getBody()); - } - - @Test - public void givenKongAdminAPI_whenAddAPIConsumer_thenAdded() { - restTemplate.delete("http://localhost:8001/consumers/eugenp"); - - ConsumerObject consumer = new ConsumerObject("eugenp"); - HttpEntity addConsumerEntity = new HttpEntity<>(consumer); - ResponseEntity addConsumerResp = restTemplate.postForEntity("http://localhost:8001/consumers/", addConsumerEntity, String.class); - - assertEquals(HttpStatus.CREATED, addConsumerResp.getStatusCode()); - - addConsumerResp = restTemplate.postForEntity("http://localhost:8001/consumers", addConsumerEntity, String.class); - assertEquals(HttpStatus.CONFLICT, addConsumerResp.getStatusCode()); - - String consumerListResp = restTemplate.getForObject("http://localhost:8001/consumers/", String.class); - assertTrue(consumerListResp.contains("eugenp")); - } - - @Test - public void givenAPI_whenEnableAuth_thenAnonymousDenied() throws Exception { - String apiListResp = restTemplate.getForObject("http://localhost:8001/apis/", String.class); - if (!apiListResp.contains("stock-api")) { - givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong(); - } - - PluginObject authPlugin = new PluginObject("key-auth"); - ResponseEntity enableAuthResp = restTemplate.postForEntity("http://localhost:8001/apis/stock-api/plugins", new HttpEntity<>(authPlugin), String.class); - - assertTrue(HttpStatus.CREATED == enableAuthResp.getStatusCode() || HttpStatus.CONFLICT == enableAuthResp.getStatusCode()); - - String pluginsResp = restTemplate.getForObject("http://localhost:8001/apis/stock-api/plugins", String.class); - assertTrue(pluginsResp.contains("key-auth")); - - HttpHeaders headers = new HttpHeaders(); - headers.set("Host", "stock.api"); - RequestEntity requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/stock/btc")); - ResponseEntity stockPriceResp = restTemplate.exchange(requestEntity, String.class); - assertEquals(HttpStatus.UNAUTHORIZED, stockPriceResp.getStatusCode()); - } - - @Test - public void givenAPIAuthEnabled_whenAddKey_thenAccessAllowed() throws Exception { - String apiListResp = restTemplate.getForObject("http://localhost:8001/apis/", String.class); - if (!apiListResp.contains("stock-api")) { - givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong(); - } - - String consumerListResp = restTemplate.getForObject("http://localhost:8001/consumers/", String.class); - if (!consumerListResp.contains("eugenp")) { - givenKongAdminAPI_whenAddAPIConsumer_thenAdded(); - } - - PluginObject authPlugin = new PluginObject("key-auth"); - ResponseEntity enableAuthResp = restTemplate.postForEntity("http://localhost:8001/apis/stock-api/plugins", new HttpEntity<>(authPlugin), String.class); - assertTrue(HttpStatus.CREATED == enableAuthResp.getStatusCode() || HttpStatus.CONFLICT == enableAuthResp.getStatusCode()); - - final String consumerKey = "eugenp.pass"; - KeyAuthObject keyAuth = new KeyAuthObject(consumerKey); - ResponseEntity keyAuthResp = restTemplate.postForEntity("http://localhost:8001/consumers/eugenp/key-auth", new HttpEntity<>(keyAuth), String.class); - - assertTrue(HttpStatus.CREATED == keyAuthResp.getStatusCode() || HttpStatus.CONFLICT == keyAuthResp.getStatusCode()); - - HttpHeaders headers = new HttpHeaders(); - headers.set("Host", "stock.api"); - headers.set("apikey", consumerKey); - RequestEntity requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/springbootapp/stock/btc")); - ResponseEntity stockPriceResp = restTemplate.exchange(requestEntity, String.class); - - assertEquals("10000", stockPriceResp.getBody()); - - headers.set("apikey", "wrongpass"); - requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/springbootapp/stock/btc")); - stockPriceResp = restTemplate.exchange(requestEntity, String.class); - assertEquals(HttpStatus.FORBIDDEN, stockPriceResp.getStatusCode()); - } - - @Test - public void givenAdminAPIProxy_whenAddAPIViaProxy_thenAPIAdded() throws Exception { - APIObject adminAPI = new APIObject("admin-api", "admin.api", "http://localhost:8001", "/admin-api"); - HttpEntity apiEntity = new HttpEntity<>(adminAPI); - ResponseEntity addAPIResp = restTemplate.postForEntity("http://localhost:8001/apis", apiEntity, String.class); - - assertTrue(HttpStatus.CREATED == addAPIResp.getStatusCode() || HttpStatus.CONFLICT == addAPIResp.getStatusCode()); - - HttpHeaders headers = new HttpHeaders(); - headers.set("Host", "admin.api"); - APIObject baeldungAPI = new APIObject("baeldung-api", "baeldung.com", "http://ww.baeldung.com", "/"); - RequestEntity requestEntity = new RequestEntity<>(baeldungAPI, headers, HttpMethod.POST, new URI("http://localhost:8000/admin-api/apis")); - addAPIResp = restTemplate.exchange(requestEntity, String.class); - - assertTrue(HttpStatus.CREATED == addAPIResp.getStatusCode() || HttpStatus.CONFLICT == addAPIResp.getStatusCode()); - } - -} diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java deleted file mode 100644 index 7cf67453a6..0000000000 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.baeldung.kong; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT; - -import java.net.URI; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.RequestEntity; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.kong.domain.APIObject; -import com.baeldung.kong.domain.TargetObject; -import com.baeldung.kong.domain.UpstreamObject; - -/** - * @author aiet - */ -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = DEFINED_PORT, classes = StockApp.class, properties = "server.servlet.contextPath=/springbootapp") -public class KongLoadBalanceLiveTest { - - @Before - public void init() { - System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); - } - - @Autowired - TestRestTemplate restTemplate; - - @Test - public void givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong() throws Exception { - UpstreamObject upstream = new UpstreamObject("stock.api.service"); - ResponseEntity addUpstreamResp = restTemplate.postForEntity("http://localhost:8001/upstreams", new HttpEntity<>(upstream), String.class); - assertTrue(HttpStatus.CREATED == addUpstreamResp.getStatusCode() || HttpStatus.CONFLICT == addUpstreamResp.getStatusCode()); - - TargetObject testTarget = new TargetObject("localhost:8080", 10); - ResponseEntity addTargetResp = restTemplate.postForEntity("http://localhost:8001/upstreams/stock.api.service/targets", new HttpEntity<>(testTarget), String.class); - assertTrue(HttpStatus.CREATED == addTargetResp.getStatusCode() || HttpStatus.CONFLICT == addTargetResp.getStatusCode()); - - TargetObject releaseTarget = new TargetObject("localhost:9090", 40); - addTargetResp = restTemplate.postForEntity("http://localhost:8001/upstreams/stock.api.service/targets", new HttpEntity<>(releaseTarget), String.class); - assertTrue(HttpStatus.CREATED == addTargetResp.getStatusCode() || HttpStatus.CONFLICT == addTargetResp.getStatusCode()); - - APIObject stockAPI = new APIObject("balanced-stock-api", "balanced.stock.api", "http://stock.api.service", "/"); - HttpEntity apiEntity = new HttpEntity<>(stockAPI); - ResponseEntity addAPIResp = restTemplate.postForEntity("http://localhost:8001/apis", apiEntity, String.class); - assertTrue(HttpStatus.CREATED == addAPIResp.getStatusCode() || HttpStatus.CONFLICT == addAPIResp.getStatusCode()); - - HttpHeaders headers = new HttpHeaders(); - headers.set("Host", "balanced.stock.api"); - for (int i = 0; i < 1000; i++) { - RequestEntity requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/springbootapp/stock/btc")); - ResponseEntity stockPriceResp = restTemplate.exchange(requestEntity, String.class); - assertEquals("10000", stockPriceResp.getBody()); - } - - int releaseCount = restTemplate.getForObject("http://localhost:9090/springbootapp/stock/reqcount", Integer.class); - int testCount = restTemplate.getForObject("http://localhost:8080/springbootapp/stock/reqcount", Integer.class); - - assertTrue(Math.round(releaseCount * 1.0 / testCount) == 4); - } - -} diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/APIObject.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/APIObject.java deleted file mode 100644 index f386712444..0000000000 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/APIObject.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.baeldung.kong.domain; - -/** - * @author aiet - */ -public class APIObject { - - public APIObject() { - } - - public APIObject(String name, String hosts, String upstream_url, String uris) { - this.name = name; - this.hosts = hosts; - this.upstream_url = upstream_url; - this.uris = uris; - } - - private String name; - private String hosts; - private String upstream_url; - private String uris; - - public String getUris() { - return uris; - } - - public void setUris(String uris) { - this.uris = uris; - } - - public String getUpstream_url() { - return upstream_url; - } - - public void setUpstream_url(String upstream_url) { - this.upstream_url = upstream_url; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getHosts() { - return hosts; - } - - public void setHosts(String hosts) { - this.hosts = hosts; - } -} diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/ConsumerObject.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/ConsumerObject.java deleted file mode 100644 index 74bef8f2d1..0000000000 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/ConsumerObject.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.kong.domain; - -/** - * @author aiet - */ -public class ConsumerObject { - - private String username; - private String custom_id; - - public ConsumerObject(String username) { - this.username = username; - } - - public ConsumerObject(String username, String custom_id) { - this.username = username; - this.custom_id = custom_id; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getCustom_id() { - return custom_id; - } - - public void setCustom_id(String custom_id) { - this.custom_id = custom_id; - } -} diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/KeyAuthObject.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/KeyAuthObject.java deleted file mode 100644 index 80de6bfcd9..0000000000 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/KeyAuthObject.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.kong.domain; - -/** - * @author aiet - */ -public class KeyAuthObject { - - public KeyAuthObject(String key) { - this.key = key; - } - - private String key; - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } -} diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/PluginObject.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/PluginObject.java deleted file mode 100644 index c161fc9b54..0000000000 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/PluginObject.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.kong.domain; - -/** - * @author aiet - */ -public class PluginObject { - - private String name; - private String consumer_id; - - public PluginObject(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getConsumer_id() { - return consumer_id; - } - - public void setConsumer_id(String consumer_id) { - this.consumer_id = consumer_id; - } -} diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/TargetObject.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/TargetObject.java deleted file mode 100644 index 79653e2846..0000000000 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/TargetObject.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.kong.domain; - -/** - * @author aiet - */ -public class TargetObject { - - public TargetObject(String target, int weight) { - this.target = target; - this.weight = weight; - } - - private String target; - private int weight; - - public String getTarget() { - return target; - } - - public void setTarget(String target) { - this.target = target; - } - - public int getWeight() { - return weight; - } - - public void setWeight(int weight) { - this.weight = weight; - } -} diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/UpstreamObject.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/UpstreamObject.java deleted file mode 100644 index 6461381ac5..0000000000 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/UpstreamObject.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.kong.domain; - -/** - * @author aiet - */ -public class UpstreamObject { - - public UpstreamObject(String name) { - this.name = name; - } - - private String name; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } -} diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java deleted file mode 100644 index 3213a10df9..0000000000 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.baeldung.toggle; - -import static org.junit.Assert.assertEquals; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = ToggleApplication.class) -@AutoConfigureMockMvc -public class ToggleIntegrationTest { - - @Autowired - private EmployeeRepository employeeRepository; - - @Autowired - private MockMvc mockMvc; - - @Autowired - private WebApplicationContext wac; - - @Before - public void setup() { - this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); - } - - @Test - public void givenFeaturePropertyFalse_whenIncreaseSalary_thenNoIncrease() throws Exception { - Employee emp = new Employee(1, 2000); - employeeRepository.save(emp); - - System.setProperty("employee.feature", "false"); - - mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")).andExpect(status().is(200)); - - emp = employeeRepository.findById(1L).orElse(null); - assertEquals("salary incorrect", 2000, emp.getSalary(), 0.5); - } - - @Test - public void givenFeaturePropertyTrue_whenIncreaseSalary_thenIncrease() throws Exception { - Employee emp = new Employee(1, 2000); - employeeRepository.save(emp); - - System.setProperty("employee.feature", "true"); - - mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")).andExpect(status().is(200)); - - emp = employeeRepository.findById(1L).orElse(null); - assertEquals("salary incorrect", 2200, emp.getSalary(), 0.5); - } -} From e878b28d98896b0b0d35a1b63a104746eb73cb35 Mon Sep 17 00:00:00 2001 From: Umang Budhwar Date: Sat, 29 Aug 2020 13:05:31 +0530 Subject: [PATCH 35/58] Splitted apiInfo to multiple lines. --- .../swagger2boot/configuration/SwaggerConfiguration.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/configuration/SwaggerConfiguration.java b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/configuration/SwaggerConfiguration.java index 73dfe85387..7bacdde4c8 100644 --- a/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/configuration/SwaggerConfiguration.java +++ b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/configuration/SwaggerConfiguration.java @@ -22,7 +22,9 @@ import springfox.documentation.swagger.web.UiConfigurationBuilder; public class SwaggerConfiguration { private ApiInfo apiInfo() { - return new ApiInfo("My REST API", "Some custom description of API.", "API TOS", "Terms of service", new Contact("Umang Budhwar", "www.baeldung.com", "umangbudhwar@gmail.com"), "License of API", "API license URL", Collections.emptyList()); + return new ApiInfo("My REST API", "Some custom description of API.", "API TOS", "Terms of service", + new Contact("Umang Budhwar", "www.baeldung.com", "umangbudhwar@gmail.com"), + "License of API", "API license URL", Collections.emptyList()); } @Bean From 44d66d9a0fe04ebc8e39b5f9e1651c1a5243537e Mon Sep 17 00:00:00 2001 From: kwoyke Date: Sat, 29 Aug 2020 10:49:40 +0200 Subject: [PATCH 36/58] BAEL-3715: Sync code and article (#9932) --- .../springevents/synchronous/CustomSpringEventPublisher.java | 2 +- .../AsynchronousCustomSpringEventsIntegrationTest.java | 2 +- .../SynchronousCustomSpringEventsIntegrationTest.java | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/CustomSpringEventPublisher.java b/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/CustomSpringEventPublisher.java index e4d7fcdc99..0ed06afd00 100644 --- a/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/CustomSpringEventPublisher.java +++ b/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/CustomSpringEventPublisher.java @@ -10,7 +10,7 @@ public class CustomSpringEventPublisher { @Autowired private ApplicationEventPublisher applicationEventPublisher; - public void publishEvent(final String message) { + public void publishCustomEvent(final String message) { System.out.println("Publishing custom event. "); final CustomSpringEvent customSpringEvent = new CustomSpringEvent(this, message); applicationEventPublisher.publishEvent(customSpringEvent); diff --git a/spring-core-2/src/test/java/com/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsIntegrationTest.java b/spring-core-2/src/test/java/com/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsIntegrationTest.java index 4f8035bcbe..d41f0114ca 100644 --- a/spring-core-2/src/test/java/com/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsIntegrationTest.java +++ b/spring-core-2/src/test/java/com/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsIntegrationTest.java @@ -17,7 +17,7 @@ public class AsynchronousCustomSpringEventsIntegrationTest { @Test public void testCustomSpringEvents() throws InterruptedException { - publisher.publishEvent("Hello world!!"); + publisher.publishCustomEvent("Hello world!!"); System.out.println("Done publishing asynchronous custom event. "); } } diff --git a/spring-core-2/src/test/java/com/baeldung/springevents/synchronous/SynchronousCustomSpringEventsIntegrationTest.java b/spring-core-2/src/test/java/com/baeldung/springevents/synchronous/SynchronousCustomSpringEventsIntegrationTest.java index 1d624d2289..d4d718f980 100644 --- a/spring-core-2/src/test/java/com/baeldung/springevents/synchronous/SynchronousCustomSpringEventsIntegrationTest.java +++ b/spring-core-2/src/test/java/com/baeldung/springevents/synchronous/SynchronousCustomSpringEventsIntegrationTest.java @@ -22,7 +22,7 @@ public class SynchronousCustomSpringEventsIntegrationTest { @Test public void testCustomSpringEvents() { isTrue(!listener.isHitCustomEventHandler(), "The value should be false"); - publisher.publishEvent("Hello world!!"); + publisher.publishCustomEvent("Hello world!!"); System.out.println("Done publishing synchronous custom event. "); isTrue(listener.isHitCustomEventHandler(), "Now the value should be changed to true"); } From 556d5d8eaa2d9c23d0657495f2721d4b2775c025 Mon Sep 17 00:00:00 2001 From: Adrian Maghear Date: Sat, 29 Aug 2020 17:35:01 +0200 Subject: [PATCH 37/58] [BAEL-4471] Quarkus Testing (#9894) * [BAEL-4471] initial commit [BAEL-4471] commit [BAEL-4471] commit [BAEL-4471] commit [BAEL-4471] commit * [BAEL-4471] cosmetic fixes * [BAEL-4471] remove testcontainers * [BAEL-4471] PR comments fixes * [BAEL-4471] PR comments fixes * [BAEL-4471] assign different port per profile while testing * [BAEL-4471] rename unit to integration test --- quarkus/pom.xml | 42 ++++++++++++++++++- .../com/baeldung/quarkus/LibraryResource.java | 25 +++++++++++ .../java/com/baeldung/quarkus/model/Book.java | 17 ++++++++ .../quarkus/repository/BookRepository.java | 18 ++++++++ .../quarkus/service/LibraryService.java | 28 +++++++++++++ .../src/main/resources/application.properties | 11 ++++- .../CustomLibraryResourceManualTest.java | 27 ++++++++++++ .../LibraryHttpEndpointIntegrationTest.java | 21 ++++++++++ ...ryResourceHttpResourceIntegrationTest.java | 40 ++++++++++++++++++ ...braryResourceInjectSpyIntegrationTest.java | 27 ++++++++++++ .../LibraryResourceIntegrationTest.java | 24 +++++++++++ .../quarkus/NativeHelloResourceIT.java | 7 +++- .../quarkus/NativeLibraryResourceIT.java | 10 +++++ .../BookRepositoryIntegrationTest.java | 20 +++++++++ .../LibraryServiceInjectMockUnitTest.java | 38 +++++++++++++++++ .../LibraryServiceIntegrationTest.java | 21 ++++++++++ .../LibraryServiceQuarkusMockUnitTest.java | 38 +++++++++++++++++ .../quarkus/utils/CustomTestProfile.java | 26 ++++++++++++ .../utils/QuarkusTransactionalTest.java | 18 ++++++++ .../quarkus/utils/TestBookRepository.java | 22 ++++++++++ 20 files changed, 476 insertions(+), 4 deletions(-) create mode 100644 quarkus/src/main/java/com/baeldung/quarkus/LibraryResource.java create mode 100644 quarkus/src/main/java/com/baeldung/quarkus/model/Book.java create mode 100644 quarkus/src/main/java/com/baeldung/quarkus/repository/BookRepository.java create mode 100644 quarkus/src/main/java/com/baeldung/quarkus/service/LibraryService.java create mode 100644 quarkus/src/test/java/com/baeldung/quarkus/CustomLibraryResourceManualTest.java create mode 100644 quarkus/src/test/java/com/baeldung/quarkus/LibraryHttpEndpointIntegrationTest.java create mode 100644 quarkus/src/test/java/com/baeldung/quarkus/LibraryResourceHttpResourceIntegrationTest.java create mode 100644 quarkus/src/test/java/com/baeldung/quarkus/LibraryResourceInjectSpyIntegrationTest.java create mode 100644 quarkus/src/test/java/com/baeldung/quarkus/LibraryResourceIntegrationTest.java create mode 100644 quarkus/src/test/java/com/baeldung/quarkus/NativeLibraryResourceIT.java create mode 100644 quarkus/src/test/java/com/baeldung/quarkus/repository/BookRepositoryIntegrationTest.java create mode 100644 quarkus/src/test/java/com/baeldung/quarkus/service/LibraryServiceInjectMockUnitTest.java create mode 100644 quarkus/src/test/java/com/baeldung/quarkus/service/LibraryServiceIntegrationTest.java create mode 100644 quarkus/src/test/java/com/baeldung/quarkus/service/LibraryServiceQuarkusMockUnitTest.java create mode 100644 quarkus/src/test/java/com/baeldung/quarkus/utils/CustomTestProfile.java create mode 100644 quarkus/src/test/java/com/baeldung/quarkus/utils/QuarkusTransactionalTest.java create mode 100644 quarkus/src/test/java/com/baeldung/quarkus/utils/TestBookRepository.java diff --git a/quarkus/pom.xml b/quarkus/pom.xml index 09eb90d110..67356abdef 100644 --- a/quarkus/pom.xml +++ b/quarkus/pom.xml @@ -30,9 +30,48 @@ io.quarkus quarkus-resteasy + + io.quarkus + quarkus-resteasy-jackson + ${quarkus.version} + + + io.quarkus + quarkus-hibernate-orm-panache + ${quarkus.version} + + + io.quarkus + quarkus-jdbc-h2 + ${quarkus.version} + + + org.apache.commons + commons-lang3 + 3.9 + + + org.projectlombok + lombok + 1.18.6 + provided + io.quarkus quarkus-junit5 + ${quarkus.version} + test + + + io.quarkus + quarkus-junit5-mockito + ${quarkus.version} + test + + + io.quarkus + quarkus-test-h2 + ${quarkus.version} test @@ -117,7 +156,8 @@ 2.22.0 - 0.15.0 + 1.7.0.Final + 5.6.0 diff --git a/quarkus/src/main/java/com/baeldung/quarkus/LibraryResource.java b/quarkus/src/main/java/com/baeldung/quarkus/LibraryResource.java new file mode 100644 index 0000000000..88c3f0ed6e --- /dev/null +++ b/quarkus/src/main/java/com/baeldung/quarkus/LibraryResource.java @@ -0,0 +1,25 @@ +package com.baeldung.quarkus; + +import com.baeldung.quarkus.model.Book; +import com.baeldung.quarkus.service.LibraryService; + +import javax.inject.Inject; +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import java.util.Set; + +@Path("/library") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class LibraryResource { + + @Inject + LibraryService libraryService; + + @GET + @Path("/book") + public Set findBooks(@QueryParam("query") String query) { + return libraryService.find(query); + } + +} diff --git a/quarkus/src/main/java/com/baeldung/quarkus/model/Book.java b/quarkus/src/main/java/com/baeldung/quarkus/model/Book.java new file mode 100644 index 0000000000..7d258c1934 --- /dev/null +++ b/quarkus/src/main/java/com/baeldung/quarkus/model/Book.java @@ -0,0 +1,17 @@ +package com.baeldung.quarkus.model; + +import io.quarkus.hibernate.orm.panache.PanacheEntity; +import lombok.*; + +import javax.persistence.Entity; + +@Data +@Entity +@AllArgsConstructor +@EqualsAndHashCode(callSuper = true) +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class Book extends PanacheEntity { + private String title; + private String author; +} + diff --git a/quarkus/src/main/java/com/baeldung/quarkus/repository/BookRepository.java b/quarkus/src/main/java/com/baeldung/quarkus/repository/BookRepository.java new file mode 100644 index 0000000000..b142fa569b --- /dev/null +++ b/quarkus/src/main/java/com/baeldung/quarkus/repository/BookRepository.java @@ -0,0 +1,18 @@ +package com.baeldung.quarkus.repository; + +import com.baeldung.quarkus.model.Book; +import io.quarkus.hibernate.orm.panache.PanacheRepository; + +import javax.enterprise.context.ApplicationScoped; +import java.util.stream.Stream; + +import static io.quarkus.panache.common.Parameters.with; + +@ApplicationScoped +public class BookRepository implements PanacheRepository { + + public Stream findBy(String query) { + return find("author like :query or title like :query", with("query", "%"+query+"%")).stream(); + } + +} diff --git a/quarkus/src/main/java/com/baeldung/quarkus/service/LibraryService.java b/quarkus/src/main/java/com/baeldung/quarkus/service/LibraryService.java new file mode 100644 index 0000000000..be687589bf --- /dev/null +++ b/quarkus/src/main/java/com/baeldung/quarkus/service/LibraryService.java @@ -0,0 +1,28 @@ +package com.baeldung.quarkus.service; + +import com.baeldung.quarkus.model.Book; +import com.baeldung.quarkus.repository.BookRepository; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; +import javax.transaction.Transactional; +import java.util.Set; + +import static java.util.stream.Collectors.toSet; + +@Transactional +@ApplicationScoped +public class LibraryService { + + @Inject + BookRepository bookRepository; + + public Set find(String query) { + if (query == null) { + return bookRepository.findAll().stream().collect(toSet()); + } + + return bookRepository.findBy(query).collect(toSet()); + } + +} diff --git a/quarkus/src/main/resources/application.properties b/quarkus/src/main/resources/application.properties index 3f05d2198f..283cf763b9 100644 --- a/quarkus/src/main/resources/application.properties +++ b/quarkus/src/main/resources/application.properties @@ -1,3 +1,12 @@ # Configuration file # key = value -greeting=Good morning \ No newline at end of file +greeting=Good morning + +quarkus.datasource.db-kind = h2 +quarkus.datasource.jdbc.url = jdbc:h2:tcp://localhost/mem:test + +quarkus.hibernate-orm.database.generation = drop-and-create + +%custom-profile.quarkus.datasource.jdbc.url = jdbc:h2:file:./testdb + +quarkus.http.test-port=0 diff --git a/quarkus/src/test/java/com/baeldung/quarkus/CustomLibraryResourceManualTest.java b/quarkus/src/test/java/com/baeldung/quarkus/CustomLibraryResourceManualTest.java new file mode 100644 index 0000000000..b9175ae457 --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/CustomLibraryResourceManualTest.java @@ -0,0 +1,27 @@ +package com.baeldung.quarkus; + +import com.baeldung.quarkus.utils.CustomTestProfile; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.hasItems; + +@QuarkusTest +@TestProfile(CustomTestProfile.class) +class CustomLibraryResourceManualTest { + + public static final String BOOKSTORE_ENDPOINT = "/custom/library/book"; + + @Test + void whenGetBooksGivenNoQuery_thenAllBooksShouldBeReturned() { + given().contentType(ContentType.JSON) + .when().get(BOOKSTORE_ENDPOINT) + .then().statusCode(200) + .body("size()", is(2)) + .body("title", hasItems("Foundation", "Dune")); + } +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/LibraryHttpEndpointIntegrationTest.java b/quarkus/src/test/java/com/baeldung/quarkus/LibraryHttpEndpointIntegrationTest.java new file mode 100644 index 0000000000..f3a30a2383 --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/LibraryHttpEndpointIntegrationTest.java @@ -0,0 +1,21 @@ +package com.baeldung.quarkus; + +import io.quarkus.test.common.http.TestHTTPEndpoint; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; + +@QuarkusTest +@TestHTTPEndpoint(LibraryResource.class) +class LibraryHttpEndpointIntegrationTest { + + @Test + void whenGetBooks_thenShouldReturnSuccessfully() { + given().contentType(ContentType.JSON) + .when().get("book") + .then().statusCode(200); + } + +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/LibraryResourceHttpResourceIntegrationTest.java b/quarkus/src/test/java/com/baeldung/quarkus/LibraryResourceHttpResourceIntegrationTest.java new file mode 100644 index 0000000000..1931460aaa --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/LibraryResourceHttpResourceIntegrationTest.java @@ -0,0 +1,40 @@ +package com.baeldung.quarkus; + +import io.quarkus.test.common.http.TestHTTPEndpoint; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import org.apache.commons.io.IOUtils; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.net.URL; + +import static io.restassured.RestAssured.given; +import static java.nio.charset.Charset.defaultCharset; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.hasItem; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class LibraryResourceHttpResourceIntegrationTest { + + @TestHTTPEndpoint(LibraryResource.class) + @TestHTTPResource("book") + URL libraryEndpoint; + + @Test + void whenGetBooksByTitle_thenBookShouldBeFound() { + given().contentType(ContentType.JSON).param("query", "Dune") + .when().get(libraryEndpoint) + .then().statusCode(200) + .body("size()", is(1)) + .body("title", hasItem("Dune")) + .body("author", hasItem("Frank Herbert")); + } + + @Test + void whenGetBooks_thenBooksShouldBeFound() throws IOException { + assertTrue(IOUtils.toString(libraryEndpoint.openStream(), defaultCharset()).contains("Asimov")); + } +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/LibraryResourceInjectSpyIntegrationTest.java b/quarkus/src/test/java/com/baeldung/quarkus/LibraryResourceInjectSpyIntegrationTest.java new file mode 100644 index 0000000000..48ec1786fa --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/LibraryResourceInjectSpyIntegrationTest.java @@ -0,0 +1,27 @@ +package com.baeldung.quarkus; + +import com.baeldung.quarkus.service.LibraryService; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.mockito.InjectSpy; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.mockito.Mockito.verify; + +@QuarkusTest +class LibraryResourceInjectSpyIntegrationTest { + + @InjectSpy + LibraryService libraryService; + + @Test + void whenGetBooksByAuthor_thenBookShouldBeFound() { + given().contentType(ContentType.JSON).param("query", "Asimov") + .when().get("/library/book") + .then().statusCode(200); + + verify(libraryService).find("Asimov"); + } + +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/LibraryResourceIntegrationTest.java b/quarkus/src/test/java/com/baeldung/quarkus/LibraryResourceIntegrationTest.java new file mode 100644 index 0000000000..28eba8da44 --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/LibraryResourceIntegrationTest.java @@ -0,0 +1,24 @@ +package com.baeldung.quarkus; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.hasItem; + +@QuarkusTest +class LibraryResourceIntegrationTest { + + @Test + void whenGetBooksByTitle_thenBookShouldBeFound() { + given().contentType(ContentType.JSON).param("query", "Dune") + .when().get("/library/book") + .then().statusCode(200) + .body("size()", is(1)) + .body("title", hasItem("Dune")) + .body("author", hasItem("Frank Herbert")); + } + +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/NativeHelloResourceIT.java b/quarkus/src/test/java/com/baeldung/quarkus/NativeHelloResourceIT.java index 9ada64b6a5..e6c8a3b8fb 100644 --- a/quarkus/src/test/java/com/baeldung/quarkus/NativeHelloResourceIT.java +++ b/quarkus/src/test/java/com/baeldung/quarkus/NativeHelloResourceIT.java @@ -1,8 +1,11 @@ package com.baeldung.quarkus; -import io.quarkus.test.junit.SubstrateTest; +import io.quarkus.test.common.QuarkusTestResource; +import io.quarkus.test.h2.H2DatabaseTestResource; +import io.quarkus.test.junit.NativeImageTest; -@SubstrateTest +@NativeImageTest +@QuarkusTestResource(H2DatabaseTestResource.class) public class NativeHelloResourceIT extends HelloResourceUnitTest { // Execute the same tests but in native mode. diff --git a/quarkus/src/test/java/com/baeldung/quarkus/NativeLibraryResourceIT.java b/quarkus/src/test/java/com/baeldung/quarkus/NativeLibraryResourceIT.java new file mode 100644 index 0000000000..0c11fa6fb4 --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/NativeLibraryResourceIT.java @@ -0,0 +1,10 @@ +package com.baeldung.quarkus; + +import io.quarkus.test.common.QuarkusTestResource; +import io.quarkus.test.h2.H2DatabaseTestResource; +import io.quarkus.test.junit.NativeImageTest; + +@NativeImageTest +@QuarkusTestResource(H2DatabaseTestResource.class) +class NativeLibraryResourceIT extends LibraryHttpEndpointIntegrationTest { +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/repository/BookRepositoryIntegrationTest.java b/quarkus/src/test/java/com/baeldung/quarkus/repository/BookRepositoryIntegrationTest.java new file mode 100644 index 0000000000..7d811b2268 --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/repository/BookRepositoryIntegrationTest.java @@ -0,0 +1,20 @@ +package com.baeldung.quarkus.repository; + +import com.baeldung.quarkus.utils.QuarkusTransactionalTest; +import org.junit.jupiter.api.Test; + +import javax.inject.Inject; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTransactionalTest +class BookRepositoryIntegrationTest { + + @Inject + BookRepository bookRepository; + + @Test + void givenBookInRepository_whenFindByAuthor_thenShouldReturnBookFromRepository() { + assertTrue(bookRepository.findBy("Herbert").findAny().isPresent()); + } +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/service/LibraryServiceInjectMockUnitTest.java b/quarkus/src/test/java/com/baeldung/quarkus/service/LibraryServiceInjectMockUnitTest.java new file mode 100644 index 0000000000..f0b7260c7d --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/service/LibraryServiceInjectMockUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.quarkus.service; + +import com.baeldung.quarkus.model.Book; +import com.baeldung.quarkus.repository.BookRepository; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.mockito.InjectMock; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import javax.inject.Inject; +import java.util.Arrays; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.when; + +@QuarkusTest +class LibraryServiceInjectMockUnitTest { + + @Inject + LibraryService libraryService; + + @InjectMock + BookRepository bookRepository; + + @BeforeEach + void setUp() { + when(bookRepository.findBy("Frank Herbert")) + .thenReturn(Arrays.stream(new Book[] { + new Book("Dune", "Frank Herbert"), + new Book("Children of Dune", "Frank Herbert")})); + } + + @Test + void whenFindByAuthor_thenBooksShouldBeFound() { + assertEquals(2, libraryService.find("Frank Herbert").size()); + } + +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/service/LibraryServiceIntegrationTest.java b/quarkus/src/test/java/com/baeldung/quarkus/service/LibraryServiceIntegrationTest.java new file mode 100644 index 0000000000..16cce4d726 --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/service/LibraryServiceIntegrationTest.java @@ -0,0 +1,21 @@ +package com.baeldung.quarkus.service; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import javax.inject.Inject; + +import static org.junit.jupiter.api.Assertions.assertFalse; + +@QuarkusTest +class LibraryServiceIntegrationTest { + + @Inject + LibraryService libraryService; + + @Test + void whenFindByAuthor_thenBookShouldBeFound() { + assertFalse(libraryService.find("Frank Herbert").isEmpty()); + } + +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/service/LibraryServiceQuarkusMockUnitTest.java b/quarkus/src/test/java/com/baeldung/quarkus/service/LibraryServiceQuarkusMockUnitTest.java new file mode 100644 index 0000000000..e2d40a0a0b --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/service/LibraryServiceQuarkusMockUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.quarkus.service; + +import com.baeldung.quarkus.model.Book; +import com.baeldung.quarkus.repository.BookRepository; +import com.baeldung.quarkus.utils.TestBookRepository; +import io.quarkus.test.junit.QuarkusMock; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import javax.inject.Inject; +import java.util.Arrays; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@QuarkusTest +class LibraryServiceQuarkusMockUnitTest { + + @Inject + LibraryService libraryService; + + @BeforeEach + void setUp() { + BookRepository mock = Mockito.mock(TestBookRepository.class); + Mockito.when(mock.findBy("Asimov")) + .thenReturn(Arrays.stream(new Book[] { + new Book("Foundation", "Isaac Asimov"), + new Book("I Robot", "Isaac Asimov")})); + QuarkusMock.installMockForType(mock, BookRepository.class); + } + + @Test + void whenFindByAuthor_thenBooksShouldBeFound() { + assertEquals(2, libraryService.find("Asimov").size()); + } + +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/utils/CustomTestProfile.java b/quarkus/src/test/java/com/baeldung/quarkus/utils/CustomTestProfile.java new file mode 100644 index 0000000000..75fb736acc --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/utils/CustomTestProfile.java @@ -0,0 +1,26 @@ +package com.baeldung.quarkus.utils; + +import io.quarkus.test.junit.QuarkusTestProfile; + +import java.util.Collections; +import java.util.Map; +import java.util.Set; + +public class CustomTestProfile implements QuarkusTestProfile { + + @Override + public Map getConfigOverrides() { + return Collections.singletonMap("quarkus.resteasy.path", "/custom"); + } + + @Override + public Set> getEnabledAlternatives() { + return Collections.singleton(TestBookRepository.class); + } + + @Override + public String getConfigProfile() { + return "custom-profile"; + } + +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/utils/QuarkusTransactionalTest.java b/quarkus/src/test/java/com/baeldung/quarkus/utils/QuarkusTransactionalTest.java new file mode 100644 index 0000000000..d02cff2662 --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/utils/QuarkusTransactionalTest.java @@ -0,0 +1,18 @@ +package com.baeldung.quarkus.utils; + +import io.quarkus.test.junit.QuarkusTest; + +import javax.enterprise.inject.Stereotype; +import javax.transaction.Transactional; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@QuarkusTest +@Stereotype +@Transactional +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface QuarkusTransactionalTest { +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/utils/TestBookRepository.java b/quarkus/src/test/java/com/baeldung/quarkus/utils/TestBookRepository.java new file mode 100644 index 0000000000..baaa9fd005 --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/utils/TestBookRepository.java @@ -0,0 +1,22 @@ +package com.baeldung.quarkus.utils; + +import com.baeldung.quarkus.model.Book; +import com.baeldung.quarkus.repository.BookRepository; + +import javax.annotation.PostConstruct; +import javax.annotation.Priority; +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.inject.Alternative; + +@Priority(1) +@Alternative +@ApplicationScoped +public class TestBookRepository extends BookRepository { + + @PostConstruct + public void init() { + persist(new Book("Dune", "Frank Herbert"), + new Book("Foundation", "Isaac Asimov")); + } + +} From 597e537bd46a8324184c9c1d203a9c5eef9bbe6e Mon Sep 17 00:00:00 2001 From: mikr Date: Sat, 29 Aug 2020 23:04:29 +0200 Subject: [PATCH 38/58] Java-1458 Reduce logging - jhipster5 --- jhipster-5/bookstore-monolith/pom.xml | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/jhipster-5/bookstore-monolith/pom.xml b/jhipster-5/bookstore-monolith/pom.xml index c965fd962d..dbc46bbb97 100644 --- a/jhipster-5/bookstore-monolith/pom.xml +++ b/jhipster-5/bookstore-monolith/pom.xml @@ -237,6 +237,26 @@ spring-boot:run + + org.codehaus.mojo + properties-maven-plugin + 1.0.0 + + + + set-system-properties + + + + + org.slf4j.simpleLogger.log.com.github.eirslett + error + + + + + + org.apache.maven.plugins maven-compiler-plugin From dee331897721ee8fb4921128f39e9afaf235dc24 Mon Sep 17 00:00:00 2001 From: mikr Date: Sun, 30 Aug 2020 00:05:49 +0200 Subject: [PATCH 39/58] Java-1456 Reduce logging modules apache-spark, spring-boot-crud maven-assembly-plugin --- apache-spark/pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/apache-spark/pom.xml b/apache-spark/pom.xml index 27768d60fc..e0855155bc 100644 --- a/apache-spark/pom.xml +++ b/apache-spark/pom.xml @@ -74,6 +74,7 @@ maven-assembly-plugin + 3.3.0 package From 71b9fd959aeb0b66e513c8965993db69d70ba58c Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Sun, 30 Aug 2020 14:19:34 +0530 Subject: [PATCH 40/58] Update ArrayStoreExceptionExample.java --- .../array/arraystoreexception/ArrayStoreExceptionExample.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/arraystoreexception/ArrayStoreExceptionExample.java b/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/arraystoreexception/ArrayStoreExceptionExample.java index ab485ca867..ce63fd6605 100644 --- a/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/arraystoreexception/ArrayStoreExceptionExample.java +++ b/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/arraystoreexception/ArrayStoreExceptionExample.java @@ -7,9 +7,8 @@ public class ArrayStoreExceptionExample { try { Object array[] = new String[5]; array[0] = 2; - System.out.println(array[0]); } catch (ArrayStoreException e) { - e.printStackTrace(); + // handle the exception } } From 3e89177d9b8d30c44623221050e5770af31b4f2a Mon Sep 17 00:00:00 2001 From: Ali Dehghani Date: Sun, 30 Aug 2020 15:46:52 +0430 Subject: [PATCH 41/58] Fix the integrations tests in ribbon-client-service --- .../src/main/resources/application.yml | 1 - .../RibbonRetryFailureIntegrationTest.java | 7 +++++-- .../RibbonRetrySuccessIntegrationTest.java | 7 +++++-- .../spring/cloud/ribbon/retry/TestUtils.java | 18 ++++++++++++++++++ 4 files changed, 28 insertions(+), 5 deletions(-) create mode 100644 spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/TestUtils.java diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/resources/application.yml b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/resources/application.yml index 29d2360793..a6f67772f2 100644 --- a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/resources/application.yml +++ b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/resources/application.yml @@ -9,7 +9,6 @@ weather-service: ribbon: eureka: enabled: false - listOfServers: http://localhost:8021, http://localhost:8022 ServerListRefreshInterval: 5000 MaxAutoRetries: 3 MaxAutoRetriesNextServer: 1 diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetryFailureIntegrationTest.java b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetryFailureIntegrationTest.java index 0f0a1c4255..6a4fe4bd00 100644 --- a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetryFailureIntegrationTest.java +++ b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetryFailureIntegrationTest.java @@ -10,6 +10,7 @@ import org.springframework.boot.web.server.LocalServerPort; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.http.ResponseEntity; +import static com.baeldung.spring.cloud.ribbon.retry.TestUtils.setUpServices; import static org.junit.jupiter.api.Assertions.assertTrue; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = RibbonClientApp.class) @@ -24,8 +25,10 @@ public class RibbonRetryFailureIntegrationTest { @BeforeAll public static void setup() { - weatherServiceInstance1 = startApp(8021); - weatherServiceInstance2 = startApp(8022); + weatherServiceInstance1 = startApp(0); + weatherServiceInstance2 = startApp(0); + + setUpServices(weatherServiceInstance1, weatherServiceInstance2); } @AfterAll diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetrySuccessIntegrationTest.java b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetrySuccessIntegrationTest.java index 6fdad0f2a9..281f69d0bc 100644 --- a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetrySuccessIntegrationTest.java +++ b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetrySuccessIntegrationTest.java @@ -10,6 +10,7 @@ import org.springframework.boot.web.server.LocalServerPort; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.http.ResponseEntity; +import static com.baeldung.spring.cloud.ribbon.retry.TestUtils.setUpServices; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -25,8 +26,10 @@ public class RibbonRetrySuccessIntegrationTest { @BeforeAll public static void setup() { - weatherServiceInstance1 = startApp(8021); - weatherServiceInstance2 = startApp(8022); + weatherServiceInstance1 = startApp(0); + weatherServiceInstance2 = startApp(0); + + setUpServices(weatherServiceInstance1, weatherServiceInstance2); } private static ConfigurableApplicationContext startApp(int port) { diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/TestUtils.java b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/TestUtils.java new file mode 100644 index 0000000000..67c7847cda --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/TestUtils.java @@ -0,0 +1,18 @@ +package com.baeldung.spring.cloud.ribbon.retry; + +import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext; +import org.springframework.context.ConfigurableApplicationContext; + +class TestUtils { + + static int getWebAppPort(ConfigurableApplicationContext ctx) { + return ((AnnotationConfigServletWebServerApplicationContext) ctx).getWebServer().getPort(); + } + + static void setUpServices(ConfigurableApplicationContext service1, ConfigurableApplicationContext service2) { + int port1 = getWebAppPort(service1); + int port2 = getWebAppPort(service2); + String serversList = String.format("http://localhost:%d, http://localhost:%d", port1, port2); + System.setProperty("weather-service.ribbon.listOfServers", serversList); + } +} From fb36c068cd20d9b5d532e5d894d80ea0243d2823 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sun, 30 Aug 2020 16:51:48 +0530 Subject: [PATCH 42/58] JAVA-33: Moved spring-katharsis to boot-2 --- spring-katharsis/pom.xml | 4 ++-- .../src/main/java/com/baeldung/Application.java | 2 +- .../persistence/katharsis/RoleResourceRepository.java | 10 +++++++--- .../persistence/katharsis/UserResourceRepository.java | 9 ++++++--- .../katharsis/UserToRoleRelationshipRepository.java | 10 ++++++---- .../src/main/resources/application.properties | 2 +- 6 files changed, 23 insertions(+), 14 deletions(-) diff --git a/spring-katharsis/pom.xml b/spring-katharsis/pom.xml index 3aeaa973af..674d9a2a14 100644 --- a/spring-katharsis/pom.xml +++ b/spring-katharsis/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 diff --git a/spring-katharsis/src/main/java/com/baeldung/Application.java b/spring-katharsis/src/main/java/com/baeldung/Application.java index 6c4f047b26..738afa039e 100644 --- a/spring-katharsis/src/main/java/com/baeldung/Application.java +++ b/spring-katharsis/src/main/java/com/baeldung/Application.java @@ -4,7 +4,7 @@ import io.katharsis.spring.boot.v3.KatharsisConfigV3; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.context.annotation.Import; @SpringBootApplication diff --git a/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/RoleResourceRepository.java b/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/RoleResourceRepository.java index c5e6326075..a249def128 100644 --- a/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/RoleResourceRepository.java +++ b/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/RoleResourceRepository.java @@ -7,6 +7,9 @@ import io.katharsis.repository.ResourceRepositoryV2; import io.katharsis.resource.list.ResourceList; import com.baeldung.persistence.model.Role; + +import java.util.Optional; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -17,7 +20,8 @@ public class RoleResourceRepository implements ResourceRepositoryV2 @Override public Role findOne(Long id, QuerySpec querySpec) { - return roleRepository.findOne(id); + Optional role = roleRepository.findById(id); + return role.isPresent()? role.get() : null; } @Override @@ -27,7 +31,7 @@ public class RoleResourceRepository implements ResourceRepositoryV2 @Override public ResourceList findAll(Iterable ids, QuerySpec querySpec) { - return querySpec.apply(roleRepository.findAll(ids)); + return querySpec.apply(roleRepository.findAllById(ids)); } @Override @@ -37,7 +41,7 @@ public class RoleResourceRepository implements ResourceRepositoryV2 @Override public void delete(Long id) { - roleRepository.delete(id); + roleRepository.deleteById(id); } @Override diff --git a/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/UserResourceRepository.java b/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/UserResourceRepository.java index 616431f3f0..af71da4727 100644 --- a/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/UserResourceRepository.java +++ b/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/UserResourceRepository.java @@ -6,6 +6,8 @@ import io.katharsis.queryspec.QuerySpec; import io.katharsis.repository.ResourceRepositoryV2; import io.katharsis.resource.list.ResourceList; +import java.util.Optional; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -17,7 +19,8 @@ public class UserResourceRepository implements ResourceRepositoryV2 @Override public User findOne(Long id, QuerySpec querySpec) { - return userRepository.findOne(id); + Optional user = userRepository.findById(id); + return user.isPresent()? user.get() : null; } @Override @@ -27,7 +30,7 @@ public class UserResourceRepository implements ResourceRepositoryV2 @Override public ResourceList findAll(Iterable ids, QuerySpec querySpec) { - return querySpec.apply(userRepository.findAll(ids)); + return querySpec.apply(userRepository.findAllById(ids)); } @Override @@ -37,7 +40,7 @@ public class UserResourceRepository implements ResourceRepositoryV2 @Override public void delete(Long id) { - userRepository.delete(id); + userRepository.deleteById(id); } @Override diff --git a/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java b/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java index 066292c00f..d0b4a464c9 100644 --- a/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java +++ b/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java @@ -8,6 +8,7 @@ import io.katharsis.repository.RelationshipRepositoryV2; import io.katharsis.resource.list.ResourceList; import java.util.HashSet; +import java.util.Optional; import java.util.Set; import com.baeldung.persistence.model.Role; @@ -31,7 +32,7 @@ public class UserToRoleRelationshipRepository implements RelationshipRepositoryV @Override public void setRelations(User user, Iterable roleIds, String fieldName) { final Set roles = new HashSet(); - roles.addAll(roleRepository.findAll(roleIds)); + roles.addAll(roleRepository.findAllById(roleIds)); user.setRoles(roles); userRepository.save(user); } @@ -39,7 +40,7 @@ public class UserToRoleRelationshipRepository implements RelationshipRepositoryV @Override public void addRelations(User user, Iterable roleIds, String fieldName) { final Set roles = user.getRoles(); - roles.addAll(roleRepository.findAll(roleIds)); + roles.addAll(roleRepository.findAllById(roleIds)); user.setRoles(roles); userRepository.save(user); } @@ -47,7 +48,7 @@ public class UserToRoleRelationshipRepository implements RelationshipRepositoryV @Override public void removeRelations(User user, Iterable roleIds, String fieldName) { final Set roles = user.getRoles(); - roles.removeAll(roleRepository.findAll(roleIds)); + roles.removeAll(roleRepository.findAllById(roleIds)); user.setRoles(roles); userRepository.save(user); } @@ -60,7 +61,8 @@ public class UserToRoleRelationshipRepository implements RelationshipRepositoryV @Override public ResourceList findManyTargets(Long sourceId, String fieldName, QuerySpec querySpec) { - final User user = userRepository.findOne(sourceId); + final Optional userOptional = userRepository.findById(sourceId); + User user = userOptional.isPresent() ? userOptional.get() : new User(); return querySpec.apply(user.getRoles()); } diff --git a/spring-katharsis/src/main/resources/application.properties b/spring-katharsis/src/main/resources/application.properties index 120b3c62ee..415ec1723b 100644 --- a/spring-katharsis/src/main/resources/application.properties +++ b/spring-katharsis/src/main/resources/application.properties @@ -6,7 +6,7 @@ spring.jpa.hibernate.ddl-auto = create-drop spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.H2Dialect server.port=8082 -server.context-path=/spring-katharsis +server.servlet.context-path=/spring-katharsis katharsis.domainName=http://localhost:8082/spring-katharsis katharsis.pathPrefix=/ \ No newline at end of file From 531751568cacd590d923b17d1b41940872c46da9 Mon Sep 17 00:00:00 2001 From: Anirban Chatterjee Date: Sun, 30 Aug 2020 13:23:51 +0200 Subject: [PATCH 43/58] Moved to new module --- .../core-kotlin-collections-2/README.md | 7 +++ .../core-kotlin-collections-2/pom.xml | 47 +++++++++++++++++++ .../AggregateOperations.kt | 2 +- .../AggregateOperationsUnitTest.kt | 2 +- core-kotlin-modules/pom.xml | 1 + 5 files changed, 57 insertions(+), 2 deletions(-) create mode 100644 core-kotlin-modules/core-kotlin-collections-2/README.md create mode 100644 core-kotlin-modules/core-kotlin-collections-2/pom.xml rename core-kotlin-modules/{core-kotlin-collections/src/main/kotlin/com/baeldung/kotlin/collections => core-kotlin-collections-2/src/main/kotlin/com.baeldung.aggregate}/AggregateOperations.kt (98%) rename core-kotlin-modules/{core-kotlin-collections/src/test/kotlin/com/baeldung/kotlin/collections => core-kotlin-collections-2/src/test/kotlin/com.baeldung.aggregate}/AggregateOperationsUnitTest.kt (98%) diff --git a/core-kotlin-modules/core-kotlin-collections-2/README.md b/core-kotlin-modules/core-kotlin-collections-2/README.md new file mode 100644 index 0000000000..2dc180b5b3 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections-2/README.md @@ -0,0 +1,7 @@ +## Core Kotlin Collections + +This module contains articles about core Kotlin collections. + +### Relevant articles: + + diff --git a/core-kotlin-modules/core-kotlin-collections-2/pom.xml b/core-kotlin-modules/core-kotlin-collections-2/pom.xml new file mode 100644 index 0000000000..be462eed45 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections-2/pom.xml @@ -0,0 +1,47 @@ + + + 4.0.0 + core-kotlin-collections-2 + core-kotlin-collections-2 + jar + + + com.baeldung.core-kotlin-modules + core-kotlin-modules + 1.0.0-SNAPSHOT + + + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + ${kotlin.version} + + + org.apache.commons + commons-math3 + ${commons-math3.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + org.jetbrains.kotlin + kotlin-test + ${kotlin.version} + test + + + + + 1.3.30 + 3.6.1 + 3.10.0 + + + \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/kotlin/collections/AggregateOperations.kt b/core-kotlin-modules/core-kotlin-collections-2/src/main/kotlin/com.baeldung.aggregate/AggregateOperations.kt similarity index 98% rename from core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/kotlin/collections/AggregateOperations.kt rename to core-kotlin-modules/core-kotlin-collections-2/src/main/kotlin/com.baeldung.aggregate/AggregateOperations.kt index 3a348aafaa..a09e101b59 100644 --- a/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/kotlin/collections/AggregateOperations.kt +++ b/core-kotlin-modules/core-kotlin-collections-2/src/main/kotlin/com.baeldung.aggregate/AggregateOperations.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin.collections +package com.baeldung.aggregate class AggregateOperations { private val numbers = listOf(1, 15, 3, 8) diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/kotlin/collections/AggregateOperationsUnitTest.kt b/core-kotlin-modules/core-kotlin-collections-2/src/test/kotlin/com.baeldung.aggregate/AggregateOperationsUnitTest.kt similarity index 98% rename from core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/kotlin/collections/AggregateOperationsUnitTest.kt rename to core-kotlin-modules/core-kotlin-collections-2/src/test/kotlin/com.baeldung.aggregate/AggregateOperationsUnitTest.kt index 1fb26760fc..a619759b0a 100644 --- a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/kotlin/collections/AggregateOperationsUnitTest.kt +++ b/core-kotlin-modules/core-kotlin-collections-2/src/test/kotlin/com.baeldung.aggregate/AggregateOperationsUnitTest.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin.collections +package com.baeldung.aggregate import org.junit.jupiter.api.Test import kotlin.test.assertEquals diff --git a/core-kotlin-modules/pom.xml b/core-kotlin-modules/pom.xml index 8b626e1c1b..67520a7dee 100644 --- a/core-kotlin-modules/pom.xml +++ b/core-kotlin-modules/pom.xml @@ -21,6 +21,7 @@ core-kotlin-advanced core-kotlin-annotations core-kotlin-collections + core-kotlin-collections-2 core-kotlin-concurrency core-kotlin-date-time core-kotlin-design-patterns From d7e25cb6e99fbdb15566eb601e9a987ddcad5b29 Mon Sep 17 00:00:00 2001 From: mikr Date: Sun, 30 Aug 2020 14:35:18 +0200 Subject: [PATCH 44/58] Java-1462 Reduce logging - Modules core-java-io-2, spring-ejb-beans, spring-boot-security --- .../core-java-io-2/src/main/resources/logback.xml | 12 ++++++++++++ .../src/main/resources/logback.xml | 2 +- .../src/test/resources/application.properties | 2 ++ spring-ejb/ejb-beans/pom.xml | 6 ++++++ .../ejb-beans/src/test/resources/logging.properties | 2 ++ 5 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 core-java-modules/core-java-io-2/src/main/resources/logback.xml create mode 100644 spring-boot-modules/spring-boot-security/src/test/resources/application.properties create mode 100644 spring-ejb/ejb-beans/src/test/resources/logging.properties diff --git a/core-java-modules/core-java-io-2/src/main/resources/logback.xml b/core-java-modules/core-java-io-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..f46a64b3cb --- /dev/null +++ b/core-java-modules/core-java-io-2/src/main/resources/logback.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + diff --git a/spring-boot-modules/spring-boot-security/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-security/src/main/resources/logback.xml index 7d900d8ea8..73dd672c1a 100644 --- a/spring-boot-modules/spring-boot-security/src/main/resources/logback.xml +++ b/spring-boot-modules/spring-boot-security/src/main/resources/logback.xml @@ -7,7 +7,7 @@ - + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-security/src/test/resources/application.properties b/spring-boot-modules/spring-boot-security/src/test/resources/application.properties new file mode 100644 index 0000000000..5494069009 --- /dev/null +++ b/spring-boot-modules/spring-boot-security/src/test/resources/application.properties @@ -0,0 +1,2 @@ +logging.level.root=ERROR +logging.level.com.baeldung.integrationtesting=ERROR diff --git a/spring-ejb/ejb-beans/pom.xml b/spring-ejb/ejb-beans/pom.xml index 299de584ef..d7f875acd0 100644 --- a/spring-ejb/ejb-beans/pom.xml +++ b/spring-ejb/ejb-beans/pom.xml @@ -131,6 +131,12 @@ always + + + java.util.logging.config.file + src/test/resources/logging.properties + + diff --git a/spring-ejb/ejb-beans/src/test/resources/logging.properties b/spring-ejb/ejb-beans/src/test/resources/logging.properties new file mode 100644 index 0000000000..0a0ecef337 --- /dev/null +++ b/spring-ejb/ejb-beans/src/test/resources/logging.properties @@ -0,0 +1,2 @@ +handlers = java.util.logging.ConsoleHandler +java.util.logging.ConsoleHandler.level = SEVERE \ No newline at end of file From 87f19ad21a6773abb6e9433122db951da3fc4771 Mon Sep 17 00:00:00 2001 From: mikr Date: Sun, 30 Aug 2020 16:54:15 +0200 Subject: [PATCH 45/58] Reduce logging - Modules api-gateway, spring-boot-springdoc, spring-zuul-rate-limiting, hibernate-ogm, jpa-hibernate-cascade-type --- .../hibernate-ogm/src/test/resources/logback.xml | 12 ++++++++++++ .../src/test/resources/hibernate.properties | 2 +- .../src/test/resources/logback.xml | 12 ++++++++++++ .../src/test/resources/logback.xml | 12 ++++++++++++ .../api-gateway/src/test/resources/logback.xml | 12 ++++++++++++ .../src/test/resources/application.properties | 1 + .../src/test/resources/logback.xml | 12 ++++++++++++ 7 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 persistence-modules/hibernate-ogm/src/test/resources/logback.xml create mode 100644 persistence-modules/jpa-hibernate-cascade-type/src/test/resources/logback.xml create mode 100644 spring-boot-modules/spring-boot-springdoc/src/test/resources/logback.xml create mode 100644 spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/test/resources/logback.xml create mode 100644 spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/src/test/resources/application.properties create mode 100644 spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/src/test/resources/logback.xml diff --git a/persistence-modules/hibernate-ogm/src/test/resources/logback.xml b/persistence-modules/hibernate-ogm/src/test/resources/logback.xml new file mode 100644 index 0000000000..ab4a5f3a20 --- /dev/null +++ b/persistence-modules/hibernate-ogm/src/test/resources/logback.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + diff --git a/persistence-modules/jpa-hibernate-cascade-type/src/test/resources/hibernate.properties b/persistence-modules/jpa-hibernate-cascade-type/src/test/resources/hibernate.properties index c22da2496b..4999a0e600 100644 --- a/persistence-modules/jpa-hibernate-cascade-type/src/test/resources/hibernate.properties +++ b/persistence-modules/jpa-hibernate-cascade-type/src/test/resources/hibernate.properties @@ -5,6 +5,6 @@ hibernate.connection.autocommit=true jdbc.password= hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.show_sql=true +hibernate.show_sql=false hibernate.hbm2ddl.auto=create-drop diff --git a/persistence-modules/jpa-hibernate-cascade-type/src/test/resources/logback.xml b/persistence-modules/jpa-hibernate-cascade-type/src/test/resources/logback.xml new file mode 100644 index 0000000000..ab4a5f3a20 --- /dev/null +++ b/persistence-modules/jpa-hibernate-cascade-type/src/test/resources/logback.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + diff --git a/spring-boot-modules/spring-boot-springdoc/src/test/resources/logback.xml b/spring-boot-modules/spring-boot-springdoc/src/test/resources/logback.xml new file mode 100644 index 0000000000..ab4a5f3a20 --- /dev/null +++ b/spring-boot-modules/spring-boot-springdoc/src/test/resources/logback.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + diff --git a/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/test/resources/logback.xml b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/test/resources/logback.xml new file mode 100644 index 0000000000..ab4a5f3a20 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/test/resources/logback.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + diff --git a/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/src/test/resources/application.properties b/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/src/test/resources/application.properties new file mode 100644 index 0000000000..640fb2c6a4 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/src/test/resources/application.properties @@ -0,0 +1 @@ +logging.level.root=ERROR \ No newline at end of file diff --git a/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/src/test/resources/logback.xml b/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/src/test/resources/logback.xml new file mode 100644 index 0000000000..ab4a5f3a20 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/src/test/resources/logback.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + From 5bcf243fdbba47e231c91dfe26b6330839c2de6f Mon Sep 17 00:00:00 2001 From: Ali Dehghani Date: Mon, 31 Aug 2020 01:09:36 +0430 Subject: [PATCH 46/58] Revert "Fix the integrations tests in ribbon-client-service" This reverts commit 3e89177d --- .../src/main/resources/application.yml | 1 + .../RibbonRetryFailureIntegrationTest.java | 7 ++----- .../RibbonRetrySuccessIntegrationTest.java | 7 ++----- .../spring/cloud/ribbon/retry/TestUtils.java | 18 ------------------ 4 files changed, 5 insertions(+), 28 deletions(-) delete mode 100644 spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/TestUtils.java diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/resources/application.yml b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/resources/application.yml index a6f67772f2..29d2360793 100644 --- a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/resources/application.yml +++ b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/resources/application.yml @@ -9,6 +9,7 @@ weather-service: ribbon: eureka: enabled: false + listOfServers: http://localhost:8021, http://localhost:8022 ServerListRefreshInterval: 5000 MaxAutoRetries: 3 MaxAutoRetriesNextServer: 1 diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetryFailureIntegrationTest.java b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetryFailureIntegrationTest.java index 6a4fe4bd00..0f0a1c4255 100644 --- a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetryFailureIntegrationTest.java +++ b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetryFailureIntegrationTest.java @@ -10,7 +10,6 @@ import org.springframework.boot.web.server.LocalServerPort; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.http.ResponseEntity; -import static com.baeldung.spring.cloud.ribbon.retry.TestUtils.setUpServices; import static org.junit.jupiter.api.Assertions.assertTrue; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = RibbonClientApp.class) @@ -25,10 +24,8 @@ public class RibbonRetryFailureIntegrationTest { @BeforeAll public static void setup() { - weatherServiceInstance1 = startApp(0); - weatherServiceInstance2 = startApp(0); - - setUpServices(weatherServiceInstance1, weatherServiceInstance2); + weatherServiceInstance1 = startApp(8021); + weatherServiceInstance2 = startApp(8022); } @AfterAll diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetrySuccessIntegrationTest.java b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetrySuccessIntegrationTest.java index 281f69d0bc..6fdad0f2a9 100644 --- a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetrySuccessIntegrationTest.java +++ b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetrySuccessIntegrationTest.java @@ -10,7 +10,6 @@ import org.springframework.boot.web.server.LocalServerPort; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.http.ResponseEntity; -import static com.baeldung.spring.cloud.ribbon.retry.TestUtils.setUpServices; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -26,10 +25,8 @@ public class RibbonRetrySuccessIntegrationTest { @BeforeAll public static void setup() { - weatherServiceInstance1 = startApp(0); - weatherServiceInstance2 = startApp(0); - - setUpServices(weatherServiceInstance1, weatherServiceInstance2); + weatherServiceInstance1 = startApp(8021); + weatherServiceInstance2 = startApp(8022); } private static ConfigurableApplicationContext startApp(int port) { diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/TestUtils.java b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/TestUtils.java deleted file mode 100644 index 67c7847cda..0000000000 --- a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/TestUtils.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.spring.cloud.ribbon.retry; - -import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext; -import org.springframework.context.ConfigurableApplicationContext; - -class TestUtils { - - static int getWebAppPort(ConfigurableApplicationContext ctx) { - return ((AnnotationConfigServletWebServerApplicationContext) ctx).getWebServer().getPort(); - } - - static void setUpServices(ConfigurableApplicationContext service1, ConfigurableApplicationContext service2) { - int port1 = getWebAppPort(service1); - int port2 = getWebAppPort(service2); - String serversList = String.format("http://localhost:%d, http://localhost:%d", port1, port2); - System.setProperty("weather-service.ribbon.listOfServers", serversList); - } -} From 5d7035cb19d39878422bda82e1c3b6b545024ec1 Mon Sep 17 00:00:00 2001 From: Ali Dehghani Date: Mon, 31 Aug 2020 01:25:37 +0430 Subject: [PATCH 47/58] Running two tests sequentially. --- spring-cloud/spring-cloud-ribbon-retry/pom.xml | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/spring-cloud/spring-cloud-ribbon-retry/pom.xml b/spring-cloud/spring-cloud-ribbon-retry/pom.xml index 5318ea6913..27037d6710 100644 --- a/spring-cloud/spring-cloud-ribbon-retry/pom.xml +++ b/spring-cloud/spring-cloud-ribbon-retry/pom.xml @@ -33,8 +33,20 @@ + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 0 + + + + + Hoxton.SR3 - \ No newline at end of file From e0ebf5904faccb404a7e3bc6d8b4eb614b3dc880 Mon Sep 17 00:00:00 2001 From: Sampada <46674082+sampada07@users.noreply.github.com> Date: Mon, 31 Aug 2020 20:41:47 +0530 Subject: [PATCH 48/58] JAVA-84: Move articles out of spring-boot part 1 (#9950) * JAVA-84: Moved 1 article to spring-boot-actuator * JAVA-84: Moved 2 articles to spring-boot-mvc * JAVA-84: README changes for spring-boot module * JAVA-84: Moved classes to com.baeldung pkg to correct compilation issue --- .../{README.MD => README.md} | 1 + .../spring-boot-actuator/pom.xml | 8 ++ .../baeldung/endpoints/info/Application.java | 13 ++++ .../info/TotalUsersInfoContributor.java | 1 - .../com/baeldung/endpoints/info/User.java | 49 ++++++++++++ .../endpoints/info/UserRepository.java | 78 +++++++++++++++++++ .../src/main/resources/application.properties | 8 +- spring-boot-modules/spring-boot-mvc/README.md | 2 + .../SpringBootAnnotatedApp.java | 0 .../SpringBootPlainApp.java | 0 .../components/AttrListener.java | 0 .../components/EchoServlet.java | 0 .../components/HelloFilter.java | 0 .../components/HelloServlet.java | 0 .../InternationalizationApp.java | 0 .../config/MvcConfig.java | 0 .../config/PageController.java | 2 +- .../src/main/resources/messages.properties | 6 +- .../src/main/resources/messages_fr.properties | 6 +- .../resources/static/internationalization.js | 0 .../templates/thymeleaf}/international.html | 0 .../baeldung/SpringContextLiveTest.java | 0 .../baeldung/SpringContextTest.java | 0 ...otWithServletComponentIntegrationTest.java | 26 +++---- ...ithoutServletComponentIntegrationTest.java | 0 spring-boot-modules/spring-boot/README.md | 3 - .../src/main/resources/application.properties | 6 -- .../src/main/resources/messages.properties | 4 - .../src/main/resources/messages_fr.properties | 4 - 29 files changed, 181 insertions(+), 36 deletions(-) rename spring-boot-modules/spring-boot-actuator/{README.MD => README.md} (72%) create mode 100644 spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/Application.java rename spring-boot-modules/{spring-boot => spring-boot-actuator}/src/main/java/com/baeldung/endpoints/info/TotalUsersInfoContributor.java (94%) create mode 100644 spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/User.java create mode 100644 spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/UserRepository.java rename spring-boot-modules/{spring-boot => spring-boot-mvc}/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc}/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc}/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc}/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc}/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc}/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc}/src/main/java/com/baeldung/internationalization/InternationalizationApp.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc}/src/main/java/com/baeldung/internationalization/config/MvcConfig.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc}/src/main/java/com/baeldung/internationalization/config/PageController.java (87%) rename spring-boot-modules/{spring-boot => spring-boot-mvc}/src/main/resources/static/internationalization.js (100%) rename spring-boot-modules/{spring-boot/src/main/resources/templates => spring-boot-mvc/src/main/resources/templates/thymeleaf}/international.html (100%) rename spring-boot-modules/spring-boot-mvc/src/test/java/{org => com}/baeldung/SpringContextLiveTest.java (100%) rename spring-boot-modules/spring-boot-mvc/src/test/java/{org => com}/baeldung/SpringContextTest.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc}/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java (94%) rename spring-boot-modules/{spring-boot => spring-boot-mvc}/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java (100%) delete mode 100644 spring-boot-modules/spring-boot/src/main/resources/messages.properties delete mode 100644 spring-boot-modules/spring-boot/src/main/resources/messages_fr.properties diff --git a/spring-boot-modules/spring-boot-actuator/README.MD b/spring-boot-modules/spring-boot-actuator/README.md similarity index 72% rename from spring-boot-modules/spring-boot-actuator/README.MD rename to spring-boot-modules/spring-boot-actuator/README.md index fbb4dfba0f..6f31ee4a5e 100644 --- a/spring-boot-modules/spring-boot-actuator/README.MD +++ b/spring-boot-modules/spring-boot-actuator/README.md @@ -8,3 +8,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: - [Liveness and Readiness Probes in Spring Boot](https://www.baeldung.com/spring-liveness-readiness-probes) +- [Custom Information in Spring Boot Info Endpoint](https://www.baeldung.com/spring-boot-info-actuator-custom) diff --git a/spring-boot-modules/spring-boot-actuator/pom.xml b/spring-boot-modules/spring-boot-actuator/pom.xml index 701949519e..18da6d3a9a 100644 --- a/spring-boot-modules/spring-boot-actuator/pom.xml +++ b/spring-boot-modules/spring-boot-actuator/pom.xml @@ -24,6 +24,14 @@ org.springframework.boot spring-boot-starter-web + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + org.springframework.boot diff --git a/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/Application.java b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/Application.java new file mode 100644 index 0000000000..75a7182b3c --- /dev/null +++ b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/Application.java @@ -0,0 +1,13 @@ +package com.baeldung.endpoints.info; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/endpoints/info/TotalUsersInfoContributor.java b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/TotalUsersInfoContributor.java similarity index 94% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/endpoints/info/TotalUsersInfoContributor.java rename to spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/TotalUsersInfoContributor.java index c316cabda5..a685660b4f 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/endpoints/info/TotalUsersInfoContributor.java +++ b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/TotalUsersInfoContributor.java @@ -3,7 +3,6 @@ package com.baeldung.endpoints.info; import java.util.HashMap; import java.util.Map; -import com.baeldung.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.info.Info; import org.springframework.boot.actuate.info.InfoContributor; diff --git a/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/User.java b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/User.java new file mode 100644 index 0000000000..db4e69127a --- /dev/null +++ b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/User.java @@ -0,0 +1,49 @@ +package com.baeldung.endpoints.info; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "users") +public class User { + + @Id + @GeneratedValue + private Integer id; + private String name; + private Integer status; + + public User() { + } + + public User(String name, Integer status) { + this.name = name; + this.status = status; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } +} diff --git a/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/UserRepository.java b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/UserRepository.java new file mode 100644 index 0000000000..8af5ef3988 --- /dev/null +++ b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/UserRepository.java @@ -0,0 +1,78 @@ +package com.baeldung.endpoints.info; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Repository; + +import java.util.Collection; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; + +@Repository("userRepository") +public interface UserRepository extends JpaRepository { + + int countByStatus(int status); + + Optional findOneByName(String name); + + @Async + CompletableFuture findOneByStatus(Integer status); + + @Query("SELECT u FROM User u WHERE u.status = 1") + Collection findAllActiveUsers(); + + @Query(value = "SELECT * FROM USERS u WHERE u.status = 1", nativeQuery = true) + Collection findAllActiveUsersNative(); + + @Query("SELECT u FROM User u WHERE u.status = ?1") + User findUserByStatus(Integer status); + + @Query(value = "SELECT * FROM Users u WHERE u.status = ?1", nativeQuery = true) + User findUserByStatusNative(Integer status); + + @Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2") + User findUserByStatusAndName(Integer status, String name); + + @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") + User findUserByStatusAndNameNamedParams(@Param("status") Integer status, @Param("name") String name); + + @Query(value = "SELECT * FROM Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true) + User findUserByStatusAndNameNamedParamsNative(@Param("status") Integer status, @Param("name") String name); + + @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") + User findUserByUserStatusAndUserName(@Param("status") Integer userStatus, @Param("name") String userName); + + @Query("SELECT u FROM User u WHERE u.name like ?1%") + User findUserByNameLike(String name); + + @Query("SELECT u FROM User u WHERE u.name like :name%") + User findUserByNameLikeNamedParam(@Param("name") String name); + + @Query(value = "SELECT * FROM users u WHERE u.name LIKE ?1%", nativeQuery = true) + User findUserByNameLikeNative(String name); + + @Query(value = "SELECT u FROM User u") + List findAllUsers(Sort sort); + + @Query(value = "SELECT u FROM User u ORDER BY id") + Page findAllUsersWithPagination(Pageable pageable); + + @Query(value = "SELECT * FROM Users ORDER BY id \n-- #pageable\n", countQuery = "SELECT count(*) FROM Users", nativeQuery = true) + Page findAllUsersWithPaginationNative(Pageable pageable); + + @Modifying + @Query("update User u set u.status = :status where u.name = :name") + int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name); + + @Modifying + @Query(value = "UPDATE Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true) + int updateUserSetStatusForNameNative(Integer status, String name); + +} diff --git a/spring-boot-modules/spring-boot-actuator/src/main/resources/application.properties b/spring-boot-modules/spring-boot-actuator/src/main/resources/application.properties index 27dba985b8..00100d6d97 100644 --- a/spring-boot-modules/spring-boot-actuator/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-actuator/src/main/resources/application.properties @@ -2,4 +2,10 @@ management.health.probes.enabled=true management.endpoint.health.show-details=always management.endpoint.health.status.http-mapping.down=500 management.endpoint.health.status.http-mapping.out_of_service=503 -management.endpoint.health.status.http-mapping.warning=500 \ No newline at end of file +management.endpoint.health.status.http-mapping.warning=500 + +## Configuring info endpoint +info.app.name=Spring Sample Application +info.app.description=This is my first spring boot application G1 +info.app.version=1.0.0 +info.java-vendor = ${java.specification.vendor} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc/README.md b/spring-boot-modules/spring-boot-mvc/README.md index 41b98063a6..5e9ecded10 100644 --- a/spring-boot-modules/spring-boot-mvc/README.md +++ b/spring-boot-modules/spring-boot-mvc/README.md @@ -9,4 +9,6 @@ This module contains articles about Spring Web MVC in Spring Boot projects. - [A Controller, Service and DAO Example with Spring Boot and JSF](https://www.baeldung.com/jsf-spring-boot-controller-service-dao) - [Setting Up Swagger 2 with a Spring REST API](https://www.baeldung.com/swagger-2-documentation-for-spring-rest-api) - [Using Spring ResponseEntity to Manipulate the HTTP Response](https://www.baeldung.com/spring-response-entity) +- [The @ServletComponentScan Annotation in Spring Boot](https://www.baeldung.com/spring-servletcomponentscan) +- [Guide to Internationalization in Spring Boot](https://www.baeldung.com/spring-boot-internationalization) - More articles: [[next -->]](/spring-boot-modules/spring-boot-mvc-2) diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/internationalization/InternationalizationApp.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/internationalization/InternationalizationApp.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/internationalization/InternationalizationApp.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/internationalization/InternationalizationApp.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/internationalization/config/MvcConfig.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/internationalization/config/MvcConfig.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/internationalization/config/MvcConfig.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/internationalization/config/MvcConfig.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/internationalization/config/PageController.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/internationalization/config/PageController.java similarity index 87% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/internationalization/config/PageController.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/internationalization/config/PageController.java index 96a534b853..efa55b8b33 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/internationalization/config/PageController.java +++ b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/internationalization/config/PageController.java @@ -8,7 +8,7 @@ public class PageController { @GetMapping("/international") public String getInternationalPage() { - return "international"; + return "thymeleaf/international"; } } diff --git a/spring-boot-modules/spring-boot-mvc/src/main/resources/messages.properties b/spring-boot-modules/spring-boot-mvc/src/main/resources/messages.properties index 9794c89651..8f956fe5be 100644 --- a/spring-boot-modules/spring-boot-mvc/src/main/resources/messages.properties +++ b/spring-boot-modules/spring-boot-mvc/src/main/resources/messages.properties @@ -1 +1,5 @@ -email.notempty=Please provide valid email id. \ No newline at end of file +email.notempty=Please provide valid email id. +greeting=Hello! Welcome to our website! +lang.change=Change the language +lang.eng=English +lang.fr=French \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc/src/main/resources/messages_fr.properties b/spring-boot-modules/spring-boot-mvc/src/main/resources/messages_fr.properties index 070f4e0bfc..7ced0d7b0d 100644 --- a/spring-boot-modules/spring-boot-mvc/src/main/resources/messages_fr.properties +++ b/spring-boot-modules/spring-boot-mvc/src/main/resources/messages_fr.properties @@ -1 +1,5 @@ -email.notempty=Veuillez fournir un identifiant de messagerie valide. \ No newline at end of file +email.notempty=Veuillez fournir un identifiant de messagerie valide. +greeting=Bonjour! Bienvenue sur notre site! +lang.change=Changez la langue +lang.eng=Anglais +lang.fr=Francais diff --git a/spring-boot-modules/spring-boot/src/main/resources/static/internationalization.js b/spring-boot-modules/spring-boot-mvc/src/main/resources/static/internationalization.js similarity index 100% rename from spring-boot-modules/spring-boot/src/main/resources/static/internationalization.js rename to spring-boot-modules/spring-boot-mvc/src/main/resources/static/internationalization.js diff --git a/spring-boot-modules/spring-boot/src/main/resources/templates/international.html b/spring-boot-modules/spring-boot-mvc/src/main/resources/templates/thymeleaf/international.html similarity index 100% rename from spring-boot-modules/spring-boot/src/main/resources/templates/international.html rename to spring-boot-modules/spring-boot-mvc/src/main/resources/templates/thymeleaf/international.html diff --git a/spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextLiveTest.java b/spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/SpringContextLiveTest.java similarity index 100% rename from spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextLiveTest.java rename to spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/SpringContextLiveTest.java diff --git a/spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/SpringContextTest.java similarity index 100% rename from spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextTest.java rename to spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/SpringContextTest.java diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java b/spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java similarity index 94% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java rename to spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java index 8c85934fac..92223892d9 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java +++ b/spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java @@ -1,23 +1,21 @@ package com.baeldung.annotation.servletcomponentscan; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; - -import javax.servlet.FilterRegistration; -import javax.servlet.ServletContext; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import javax.servlet.FilterRegistration; +import javax.servlet.ServletContext; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; + @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootAnnotatedApp.class) public class SpringBootWithServletComponentIntegrationTest { diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java b/spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java similarity index 100% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java rename to spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java diff --git a/spring-boot-modules/spring-boot/README.md b/spring-boot-modules/spring-boot/README.md index 510864e339..5a45502fd8 100644 --- a/spring-boot-modules/spring-boot/README.md +++ b/spring-boot-modules/spring-boot/README.md @@ -8,12 +8,9 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: - [A Guide to Spring in Eclipse STS](https://www.baeldung.com/eclipse-sts-spring) -- [The @ServletComponentScan Annotation in Spring Boot](https://www.baeldung.com/spring-servletcomponentscan) - [How to Register a Servlet in Java](https://www.baeldung.com/register-servlet) - [Guide to Spring WebUtils and ServletRequestUtils](https://www.baeldung.com/spring-webutils-servletrequestutils) -- [Guide to Internationalization in Spring Boot](https://www.baeldung.com/spring-boot-internationalization) - [Dynamic DTO Validation Config Retrieved from the Database](https://www.baeldung.com/spring-dynamic-dto-validation) -- [Custom Information in Spring Boot Info Endpoint](https://www.baeldung.com/spring-boot-info-actuator-custom) - [Guide to Spring Type Conversions](https://www.baeldung.com/spring-type-conversions) - [Spring Boot: Configuring a Main Class](https://www.baeldung.com/spring-boot-main-class) - [A Quick Intro to the SpringBootServletInitializer](https://www.baeldung.com/spring-boot-servlet-initializer) diff --git a/spring-boot-modules/spring-boot/src/main/resources/application.properties b/spring-boot-modules/spring-boot/src/main/resources/application.properties index 44649fc1c0..142e6c8e6f 100644 --- a/spring-boot-modules/spring-boot/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot/src/main/resources/application.properties @@ -21,12 +21,6 @@ spring.jmx.enabled=true ## for pretty printing of json when endpoints accessed over HTTP http.mappers.jsonPrettyPrint=true -## Configuring info endpoint -info.app.name=Spring Sample Application -info.app.description=This is my first spring boot application G1 -info.app.version=1.0.0 -info.java-vendor = ${java.specification.vendor} - logging.level.org.springframework=INFO #Servlet Configuration diff --git a/spring-boot-modules/spring-boot/src/main/resources/messages.properties b/spring-boot-modules/spring-boot/src/main/resources/messages.properties deleted file mode 100644 index e4dbc44c3f..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/messages.properties +++ /dev/null @@ -1,4 +0,0 @@ -greeting=Hello! Welcome to our website! -lang.change=Change the language -lang.eng=English -lang.fr=French \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/resources/messages_fr.properties b/spring-boot-modules/spring-boot/src/main/resources/messages_fr.properties deleted file mode 100644 index ac5853717d..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/messages_fr.properties +++ /dev/null @@ -1,4 +0,0 @@ -greeting=Bonjour! Bienvenue sur notre site! -lang.change=Changez la langue -lang.eng=Anglais -lang.fr=Francais \ No newline at end of file From 25b174930886c60d9b7e9b6a0003b1be4d906aed Mon Sep 17 00:00:00 2001 From: Mona Mohamadinia Date: Mon, 31 Aug 2020 20:13:13 +0430 Subject: [PATCH 49/58] BAEL-4530: A Guide to @DynamicPropertySource in Spring (#9877) * A Guide to @DynamicPropertySource in Spring * Moving to a new module * Reverting the Changes in the original module --- testing-modules/pom.xml | 3 +- testing-modules/spring-testing-2/.gitignore | 3 + testing-modules/spring-testing-2/README.md | 1 + testing-modules/spring-testing-2/pom.xml | 57 +++++++++++++++++++ .../baeldung/dynamicproperties/Article.java | 45 +++++++++++++++ .../dynamicproperties/ArticleRepository.java | 6 ++ .../DynamicPropertiesApplication.java | 12 ++++ .../dynamicproperties/ArticleLiveTest.java | 50 ++++++++++++++++ .../ArticleTestFixtureLiveTest.java | 31 ++++++++++ .../ArticleTraditionalLiveTest.java | 57 +++++++++++++++++++ .../PostgreSQLExtension.java | 31 ++++++++++ .../test/resources/application-pg.properties | 2 + 12 files changed, 297 insertions(+), 1 deletion(-) create mode 100644 testing-modules/spring-testing-2/.gitignore create mode 100644 testing-modules/spring-testing-2/README.md create mode 100644 testing-modules/spring-testing-2/pom.xml create mode 100644 testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/Article.java create mode 100644 testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/ArticleRepository.java create mode 100644 testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/DynamicPropertiesApplication.java create mode 100644 testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleLiveTest.java create mode 100644 testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleTestFixtureLiveTest.java create mode 100644 testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleTraditionalLiveTest.java create mode 100644 testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/PostgreSQLExtension.java create mode 100644 testing-modules/spring-testing-2/src/test/resources/application-pg.properties diff --git a/testing-modules/pom.xml b/testing-modules/pom.xml index b467b3c503..f1d30cd7a1 100644 --- a/testing-modules/pom.xml +++ b/testing-modules/pom.xml @@ -31,7 +31,8 @@ rest-assured rest-testing selenium-junit-testng - spring-testing + spring-testing + spring-testing-2 test-containers testing-assertions testng diff --git a/testing-modules/spring-testing-2/.gitignore b/testing-modules/spring-testing-2/.gitignore new file mode 100644 index 0000000000..ffc5bf3bad --- /dev/null +++ b/testing-modules/spring-testing-2/.gitignore @@ -0,0 +1,3 @@ +.idea/** +target/** +*.iml \ No newline at end of file diff --git a/testing-modules/spring-testing-2/README.md b/testing-modules/spring-testing-2/README.md new file mode 100644 index 0000000000..729105e3fd --- /dev/null +++ b/testing-modules/spring-testing-2/README.md @@ -0,0 +1 @@ +## Relevant Articles: diff --git a/testing-modules/spring-testing-2/pom.xml b/testing-modules/spring-testing-2/pom.xml new file mode 100644 index 0000000000..c7ca2804fb --- /dev/null +++ b/testing-modules/spring-testing-2/pom.xml @@ -0,0 +1,57 @@ + + + + 4.0.0 + spring-testing-2 + 0.1-SNAPSHOT + spring-testing-2 + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.postgresql + postgresql + runtime + + + + + org.testcontainers + postgresql + ${testcontainers.version} + test + + + org.testcontainers + junit-jupiter + ${testcontainers.version} + test + + + + + + 2.1.9.RELEASE + 2.1.9.RELEASE + 1.12.2 + + \ No newline at end of file diff --git a/testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/Article.java b/testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/Article.java new file mode 100644 index 0000000000..6b6bfb7bd6 --- /dev/null +++ b/testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/Article.java @@ -0,0 +1,45 @@ +package com.baeldung.dynamicproperties; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Table; + +import static javax.persistence.GenerationType.IDENTITY; + +@Entity +@Table(name = "articles") +public class Article { + + @Id + @GeneratedValue(strategy = IDENTITY) + private Long id; + + private String title; + + private String content; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } +} diff --git a/testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/ArticleRepository.java b/testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/ArticleRepository.java new file mode 100644 index 0000000000..3f3731f6dc --- /dev/null +++ b/testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/ArticleRepository.java @@ -0,0 +1,6 @@ +package com.baeldung.dynamicproperties; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface ArticleRepository extends JpaRepository { +} diff --git a/testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/DynamicPropertiesApplication.java b/testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/DynamicPropertiesApplication.java new file mode 100644 index 0000000000..d64bd965fc --- /dev/null +++ b/testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/DynamicPropertiesApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.dynamicproperties; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class DynamicPropertiesApplication { + + public static void main(String[] args) { + SpringApplication.run(DynamicPropertiesApplication.class, args); + } +} diff --git a/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleLiveTest.java b/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleLiveTest.java new file mode 100644 index 0000000000..74c31229bd --- /dev/null +++ b/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleLiveTest.java @@ -0,0 +1,50 @@ +package com.baeldung.dynamicproperties; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +@Testcontainers +@ActiveProfiles("pg") +public class ArticleLiveTest { + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:11") + .withDatabaseName("prop") + .withUsername("postgres") + .withPassword("pass") + .withExposedPorts(5432); + + @Autowired + private ArticleRepository articleRepository; + + @DynamicPropertySource + static void registerPgProperties(DynamicPropertyRegistry registry) { + registry.add("spring.datasource.url", + () -> String.format("jdbc:postgresql://localhost:%d/prop", postgres.getFirstMappedPort())); + registry.add("spring.datasource.username", () -> "postgres"); + registry.add("spring.datasource.password", () -> "pass"); + } + + @Test + void givenAnArticle_whenPersisted_thenCanBeFoundInTheDb() { + Article article = new Article(); + article.setTitle("A Guide to @DynamicPropertySource in Spring"); + article.setContent("Today's applications..."); + + articleRepository.save(article); + Article persisted = articleRepository.findAll().get(0); + assertThat(persisted.getId()).isNotNull(); + assertThat(persisted.getTitle()).isEqualTo("A Guide to @DynamicPropertySource in Spring"); + assertThat(persisted.getContent()).isEqualTo("Today's applications..."); + } +} diff --git a/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleTestFixtureLiveTest.java b/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleTestFixtureLiveTest.java new file mode 100644 index 0000000000..bb3ad28365 --- /dev/null +++ b/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleTestFixtureLiveTest.java @@ -0,0 +1,31 @@ +package com.baeldung.dynamicproperties; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +@ActiveProfiles("pg") +@ExtendWith(PostgreSQLExtension.class) +public class ArticleTestFixtureLiveTest { + + @Autowired + private ArticleRepository articleRepository; + + @Test + void givenAnArticle_whenPersisted_thenShouldBeAbleToReadIt() { + Article article = new Article(); + article.setTitle("A Guide to @DynamicPropertySource in Spring"); + article.setContent("Today's applications..."); + + articleRepository.save(article); + Article persisted = articleRepository.findAll().get(0); + assertThat(persisted.getId()).isNotNull(); + assertThat(persisted.getTitle()).isEqualTo("A Guide to @DynamicPropertySource in Spring"); + assertThat(persisted.getContent()).isEqualTo("Today's applications..."); + } +} diff --git a/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleTraditionalLiveTest.java b/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleTraditionalLiveTest.java new file mode 100644 index 0000000000..87234505a9 --- /dev/null +++ b/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleTraditionalLiveTest.java @@ -0,0 +1,57 @@ +package com.baeldung.dynamicproperties; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.util.TestPropertyValues; +import org.springframework.context.ApplicationContextInitializer; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +@Testcontainers +@ActiveProfiles("pg") +@ContextConfiguration(initializers = ArticleTraditionalLiveTest.EnvInitializer.class) +class ArticleTraditionalLiveTest { + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:11") + .withDatabaseName("prop") + .withUsername("postgres") + .withPassword("pass") + .withExposedPorts(5432); + + static class EnvInitializer implements ApplicationContextInitializer { + + @Override + public void initialize(ConfigurableApplicationContext applicationContext) { + TestPropertyValues.of( + String.format("spring.datasource.url=jdbc:postgresql://localhost:%d/prop", postgres.getFirstMappedPort()), + "spring.datasource.username=postgres", + "spring.datasource.password=pass" + ).applyTo(applicationContext); + } + } + + @Autowired + private ArticleRepository articleRepository; + + @Test + void givenAnArticle_whenPersisted_thenShouldBeAbleToReadIt() { + Article article = new Article(); + article.setTitle("A Guide to @DynamicPropertySource in Spring"); + article.setContent("Today's applications..."); + + articleRepository.save(article); + Article persisted = articleRepository.findAll().get(0); + assertThat(persisted.getId()).isNotNull(); + assertThat(persisted.getTitle()).isEqualTo("A Guide to @DynamicPropertySource in Spring"); + assertThat(persisted.getContent()).isEqualTo("Today's applications..."); + } +} diff --git a/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/PostgreSQLExtension.java b/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/PostgreSQLExtension.java new file mode 100644 index 0000000000..8c08ad67d7 --- /dev/null +++ b/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/PostgreSQLExtension.java @@ -0,0 +1,31 @@ +package com.baeldung.dynamicproperties; + +import org.junit.jupiter.api.extension.AfterAllCallback; +import org.junit.jupiter.api.extension.BeforeAllCallback; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.testcontainers.containers.PostgreSQLContainer; + +public class PostgreSQLExtension implements BeforeAllCallback, AfterAllCallback { + + private PostgreSQLContainer postgres; + + @Override + public void beforeAll(ExtensionContext context) { + postgres = new PostgreSQLContainer<>("postgres:11") + .withDatabaseName("prop") + .withUsername("postgres") + .withPassword("pass") + .withExposedPorts(5432); + + postgres.start(); + String jdbcUrl = String.format("jdbc:postgresql://localhost:%d/prop", postgres.getFirstMappedPort()); + System.setProperty("spring.datasource.url", jdbcUrl); + System.setProperty("spring.datasource.username", "postgres"); + System.setProperty("spring.datasource.password", "pass"); + } + + @Override + public void afterAll(ExtensionContext context) { + postgres.stop(); + } +} diff --git a/testing-modules/spring-testing-2/src/test/resources/application-pg.properties b/testing-modules/spring-testing-2/src/test/resources/application-pg.properties new file mode 100644 index 0000000000..cb7bff1889 --- /dev/null +++ b/testing-modules/spring-testing-2/src/test/resources/application-pg.properties @@ -0,0 +1,2 @@ +spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect +spring.jpa.hibernate.ddl-auto=create-drop \ No newline at end of file From d4d7059add4837bc0b88e750a52cb09d1d447429 Mon Sep 17 00:00:00 2001 From: Michael Pratt Date: Mon, 31 Aug 2020 10:34:01 -0600 Subject: [PATCH 50/58] Update BlogController.java Update formatting --- .../main/java/com/baeldung/thymeleaf/blog/BlogController.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/blog/BlogController.java b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/blog/BlogController.java index eee2d26409..dfcfdc1117 100644 --- a/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/blog/BlogController.java +++ b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/blog/BlogController.java @@ -10,8 +10,7 @@ import java.util.Random; public class BlogController { @GetMapping("/blog/new") - public String newBlogPost(Model model) - { + public String newBlogPost(Model model) { // Set a random ID so we can see it in the HTML form BlogDTO blog = new BlogDTO(); blog.setBlogId(Math.abs(new Random().nextLong() % 1000000)); From d237c52a1f677b0cac7f59ca71bd0fa7a9ff6c95 Mon Sep 17 00:00:00 2001 From: Maiklins Date: Mon, 31 Aug 2020 19:41:46 +0200 Subject: [PATCH 51/58] Java-75 update intro to reactor core (#9953) * Java-75 Update intro to Reactor Core * Java-75 Create package for introduction * Java-75 Update reactor version and align unit test with article Co-authored-by: mikr --- reactor-core/pom.xml | 2 +- .../{ => introduction}/ReactorIntegrationTest.java | 11 ++++------- 2 files changed, 5 insertions(+), 8 deletions(-) rename reactor-core/src/test/java/com/baeldung/reactor/{ => introduction}/ReactorIntegrationTest.java (91%) diff --git a/reactor-core/pom.xml b/reactor-core/pom.xml index c9917d14df..317cbde6e2 100644 --- a/reactor-core/pom.xml +++ b/reactor-core/pom.xml @@ -34,7 +34,7 @@ - 3.2.6.RELEASE + 3.3.9.RELEASE 3.6.1 diff --git a/reactor-core/src/test/java/com/baeldung/reactor/ReactorIntegrationTest.java b/reactor-core/src/test/java/com/baeldung/reactor/introduction/ReactorIntegrationTest.java similarity index 91% rename from reactor-core/src/test/java/com/baeldung/reactor/ReactorIntegrationTest.java rename to reactor-core/src/test/java/com/baeldung/reactor/introduction/ReactorIntegrationTest.java index e3060b8e02..a1acffac91 100644 --- a/reactor-core/src/test/java/com/baeldung/reactor/ReactorIntegrationTest.java +++ b/reactor-core/src/test/java/com/baeldung/reactor/introduction/ReactorIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.reactor; +package com.baeldung.reactor.introduction; import org.junit.Test; import org.reactivestreams.Subscriber; @@ -15,7 +15,7 @@ import static org.assertj.core.api.Assertions.assertThat; public class ReactorIntegrationTest { @Test - public void givenFlux_whenSubscribing_thenStream() throws InterruptedException { + public void givenFlux_whenSubscribing_thenStream() { List elements = new ArrayList<>(); @@ -48,14 +48,12 @@ public class ReactorIntegrationTest { } @Test - public void givenFlux_whenApplyingBackPressure_thenPushElementsInBatches() throws InterruptedException { + public void givenFlux_whenApplyingBackPressure_thenPushElementsInBatches() { List elements = new ArrayList<>(); Flux.just(1, 2, 3, 4) .log() - .map(i -> i * 2) - .onBackpressureBuffer() .subscribe(new Subscriber() { private Subscription s; int onNextAmount; @@ -81,11 +79,10 @@ public class ReactorIntegrationTest { @Override public void onComplete() { - int ham = 2; } }); - assertThat(elements).containsExactly(2, 4, 6, 8); + assertThat(elements).containsExactly(1, 2, 3, 4); } @Test From c6d95556171005b68cc4a6194de97de2cb5406ff Mon Sep 17 00:00:00 2001 From: Anirban Chatterjee Date: Mon, 31 Aug 2020 20:38:06 +0200 Subject: [PATCH 52/58] Refactored package --- .../baeldung/aggregate}/AggregateOperations.kt | 0 .../baeldung/aggregate}/AggregateOperationsUnitTest.kt | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename core-kotlin-modules/core-kotlin-collections-2/src/main/kotlin/{com.baeldung.aggregate => com/baeldung/aggregate}/AggregateOperations.kt (100%) rename core-kotlin-modules/core-kotlin-collections-2/src/test/kotlin/{com.baeldung.aggregate => com/baeldung/aggregate}/AggregateOperationsUnitTest.kt (100%) diff --git a/core-kotlin-modules/core-kotlin-collections-2/src/main/kotlin/com.baeldung.aggregate/AggregateOperations.kt b/core-kotlin-modules/core-kotlin-collections-2/src/main/kotlin/com/baeldung/aggregate/AggregateOperations.kt similarity index 100% rename from core-kotlin-modules/core-kotlin-collections-2/src/main/kotlin/com.baeldung.aggregate/AggregateOperations.kt rename to core-kotlin-modules/core-kotlin-collections-2/src/main/kotlin/com/baeldung/aggregate/AggregateOperations.kt diff --git a/core-kotlin-modules/core-kotlin-collections-2/src/test/kotlin/com.baeldung.aggregate/AggregateOperationsUnitTest.kt b/core-kotlin-modules/core-kotlin-collections-2/src/test/kotlin/com/baeldung/aggregate/AggregateOperationsUnitTest.kt similarity index 100% rename from core-kotlin-modules/core-kotlin-collections-2/src/test/kotlin/com.baeldung.aggregate/AggregateOperationsUnitTest.kt rename to core-kotlin-modules/core-kotlin-collections-2/src/test/kotlin/com/baeldung/aggregate/AggregateOperationsUnitTest.kt From 026e3c511ef0181dffb883bbe95345f80fca353a Mon Sep 17 00:00:00 2001 From: Ali Dehghani Date: Tue, 1 Sep 2020 04:27:53 +0430 Subject: [PATCH 53/58] Disabling Tomcat URL Stream Factory --- .../cloud/ribbon/retry/RibbonRetryFailureIntegrationTest.java | 2 ++ .../cloud/ribbon/retry/RibbonRetrySuccessIntegrationTest.java | 2 ++ 2 files changed, 4 insertions(+) diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetryFailureIntegrationTest.java b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetryFailureIntegrationTest.java index 0f0a1c4255..decb77e7b9 100644 --- a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetryFailureIntegrationTest.java +++ b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetryFailureIntegrationTest.java @@ -1,5 +1,6 @@ package com.baeldung.spring.cloud.ribbon.retry; +import org.apache.catalina.webresources.TomcatURLStreamHandlerFactory; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -24,6 +25,7 @@ public class RibbonRetryFailureIntegrationTest { @BeforeAll public static void setup() { + TomcatURLStreamHandlerFactory.disable(); weatherServiceInstance1 = startApp(8021); weatherServiceInstance2 = startApp(8022); } diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetrySuccessIntegrationTest.java b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetrySuccessIntegrationTest.java index 6fdad0f2a9..dc50fe76e6 100644 --- a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetrySuccessIntegrationTest.java +++ b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetrySuccessIntegrationTest.java @@ -1,5 +1,6 @@ package com.baeldung.spring.cloud.ribbon.retry; +import org.apache.catalina.webresources.TomcatURLStreamHandlerFactory; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -25,6 +26,7 @@ public class RibbonRetrySuccessIntegrationTest { @BeforeAll public static void setup() { + TomcatURLStreamHandlerFactory.disable(); weatherServiceInstance1 = startApp(8021); weatherServiceInstance2 = startApp(8022); } From 03ac0c0b5d331b1c67fa2af5c0b9e4614d7d5e7f Mon Sep 17 00:00:00 2001 From: Umang Budhwar Date: Tue, 1 Sep 2020 19:13:34 +0530 Subject: [PATCH 54/58] Added two space indent for the line continuation. --- .../configuration/SwaggerConfiguration.java | 38 +++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/configuration/SwaggerConfiguration.java b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/configuration/SwaggerConfiguration.java index 7bacdde4c8..4f85d90f5f 100644 --- a/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/configuration/SwaggerConfiguration.java +++ b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/configuration/SwaggerConfiguration.java @@ -30,10 +30,10 @@ public class SwaggerConfiguration { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()) - .select() - .apis(RequestHandlerSelectors.any()) - .paths(PathSelectors.any()) - .build(); + .select() + .apis(RequestHandlerSelectors.any()) + .paths(PathSelectors.any()) + .build(); } /** @@ -43,21 +43,21 @@ public class SwaggerConfiguration { @Bean UiConfiguration uiConfig() { return UiConfigurationBuilder.builder() - .deepLinking(true) - .displayOperationId(false) - .defaultModelsExpandDepth(1) - .defaultModelExpandDepth(1) - .defaultModelRendering(ModelRendering.EXAMPLE) - .displayRequestDuration(false) - .docExpansion(DocExpansion.NONE) - .filter(false) - .maxDisplayedTags(null) - .operationsSorter(OperationsSorter.ALPHA) - .showExtensions(false) - .tagsSorter(TagsSorter.ALPHA) - .supportedSubmitMethods(UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS) - .validatorUrl(null) - .build(); + .deepLinking(true) + .displayOperationId(false) + .defaultModelsExpandDepth(1) + .defaultModelExpandDepth(1) + .defaultModelRendering(ModelRendering.EXAMPLE) + .displayRequestDuration(false) + .docExpansion(DocExpansion.NONE) + .filter(false) + .maxDisplayedTags(null) + .operationsSorter(OperationsSorter.ALPHA) + .showExtensions(false) + .tagsSorter(TagsSorter.ALPHA) + .supportedSubmitMethods(UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS) + .validatorUrl(null) + .build(); } } From 994e25312b5d770f4aabdf14ac893fdd98b36467 Mon Sep 17 00:00:00 2001 From: Umang Budhwar Date: Tue, 1 Sep 2020 19:28:46 +0530 Subject: [PATCH 55/58] Revert "Added two space indent for the line continuation." This reverts commit 03ac0c0b5d331b1c67fa2af5c0b9e4614d7d5e7f. --- .../configuration/SwaggerConfiguration.java | 38 +++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/configuration/SwaggerConfiguration.java b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/configuration/SwaggerConfiguration.java index 4f85d90f5f..7bacdde4c8 100644 --- a/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/configuration/SwaggerConfiguration.java +++ b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/configuration/SwaggerConfiguration.java @@ -30,10 +30,10 @@ public class SwaggerConfiguration { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()) - .select() - .apis(RequestHandlerSelectors.any()) - .paths(PathSelectors.any()) - .build(); + .select() + .apis(RequestHandlerSelectors.any()) + .paths(PathSelectors.any()) + .build(); } /** @@ -43,21 +43,21 @@ public class SwaggerConfiguration { @Bean UiConfiguration uiConfig() { return UiConfigurationBuilder.builder() - .deepLinking(true) - .displayOperationId(false) - .defaultModelsExpandDepth(1) - .defaultModelExpandDepth(1) - .defaultModelRendering(ModelRendering.EXAMPLE) - .displayRequestDuration(false) - .docExpansion(DocExpansion.NONE) - .filter(false) - .maxDisplayedTags(null) - .operationsSorter(OperationsSorter.ALPHA) - .showExtensions(false) - .tagsSorter(TagsSorter.ALPHA) - .supportedSubmitMethods(UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS) - .validatorUrl(null) - .build(); + .deepLinking(true) + .displayOperationId(false) + .defaultModelsExpandDepth(1) + .defaultModelExpandDepth(1) + .defaultModelRendering(ModelRendering.EXAMPLE) + .displayRequestDuration(false) + .docExpansion(DocExpansion.NONE) + .filter(false) + .maxDisplayedTags(null) + .operationsSorter(OperationsSorter.ALPHA) + .showExtensions(false) + .tagsSorter(TagsSorter.ALPHA) + .supportedSubmitMethods(UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS) + .validatorUrl(null) + .build(); } } From b8bcbeee90aa6b84778909ff94af60b5af78ebe2 Mon Sep 17 00:00:00 2001 From: Umang Budhwar Date: Tue, 1 Sep 2020 19:13:34 +0530 Subject: [PATCH 56/58] Added two space indent for the line continuation. --- .../configuration/SwaggerConfiguration.java | 38 +++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/configuration/SwaggerConfiguration.java b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/configuration/SwaggerConfiguration.java index 7bacdde4c8..4f85d90f5f 100644 --- a/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/configuration/SwaggerConfiguration.java +++ b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/configuration/SwaggerConfiguration.java @@ -30,10 +30,10 @@ public class SwaggerConfiguration { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()) - .select() - .apis(RequestHandlerSelectors.any()) - .paths(PathSelectors.any()) - .build(); + .select() + .apis(RequestHandlerSelectors.any()) + .paths(PathSelectors.any()) + .build(); } /** @@ -43,21 +43,21 @@ public class SwaggerConfiguration { @Bean UiConfiguration uiConfig() { return UiConfigurationBuilder.builder() - .deepLinking(true) - .displayOperationId(false) - .defaultModelsExpandDepth(1) - .defaultModelExpandDepth(1) - .defaultModelRendering(ModelRendering.EXAMPLE) - .displayRequestDuration(false) - .docExpansion(DocExpansion.NONE) - .filter(false) - .maxDisplayedTags(null) - .operationsSorter(OperationsSorter.ALPHA) - .showExtensions(false) - .tagsSorter(TagsSorter.ALPHA) - .supportedSubmitMethods(UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS) - .validatorUrl(null) - .build(); + .deepLinking(true) + .displayOperationId(false) + .defaultModelsExpandDepth(1) + .defaultModelExpandDepth(1) + .defaultModelRendering(ModelRendering.EXAMPLE) + .displayRequestDuration(false) + .docExpansion(DocExpansion.NONE) + .filter(false) + .maxDisplayedTags(null) + .operationsSorter(OperationsSorter.ALPHA) + .showExtensions(false) + .tagsSorter(TagsSorter.ALPHA) + .supportedSubmitMethods(UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS) + .validatorUrl(null) + .build(); } } From 2dc6089b10eb062009fde17d72d2a0352f3fc70d Mon Sep 17 00:00:00 2001 From: kwoyke Date: Tue, 1 Sep 2020 16:49:22 +0200 Subject: [PATCH 57/58] BAEL-4518: Upgrade jooq version (#9955) --- spring-jooq/pom.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/spring-jooq/pom.xml b/spring-jooq/pom.xml index c07d6278cb..95418645fa 100644 --- a/spring-jooq/pom.xml +++ b/spring-jooq/pom.xml @@ -30,6 +30,7 @@ org.jooq jooq + ${org.jooq.version} @@ -201,7 +202,7 @@ - 3.11.7 + 3.12.4 1.0.0 1.5 1.0.0 From 8d2c467e2b4205812fcaaa2140ac0318a657a91f Mon Sep 17 00:00:00 2001 From: majajoksovic Date: Tue, 1 Sep 2020 17:23:00 +0200 Subject: [PATCH 58/58] BAEL-4465 (#9954) * initial commit * fixed indent * removed unused dependencies * some minor code changes and unit tests * fixed file names --- libraries-security/pom.xml | 17 +++-- .../com/baeldung/ssh/apachesshd/SshdDemo.java | 64 +++++++++++++++++++ .../java/com/baeldung/ssh/jsch/JschDemo.java | 52 +++++++++++++++ .../baeldung/ssh/ApacheMinaSshdLiveTest.java | 38 +++++++++++ .../java/com/baeldung/ssh/JSchLiveTest.java | 35 ++++++++++ 5 files changed, 201 insertions(+), 5 deletions(-) create mode 100644 libraries-security/src/main/java/com/baeldung/ssh/apachesshd/SshdDemo.java create mode 100644 libraries-security/src/main/java/com/baeldung/ssh/jsch/JschDemo.java create mode 100644 libraries-security/src/test/java/com/baeldung/ssh/ApacheMinaSshdLiveTest.java create mode 100644 libraries-security/src/test/java/com/baeldung/ssh/JSchLiveTest.java diff --git a/libraries-security/pom.xml b/libraries-security/pom.xml index e02f766141..202b3b8763 100644 --- a/libraries-security/pom.xml +++ b/libraries-security/pom.xml @@ -14,29 +14,24 @@ - org.springframework.boot spring-boot-starter-web - org.springframework.security.oauth spring-security-oauth2 ${spring-boot.version} - org.springframework spring-web - com.github.scribejava scribejava-apis ${scribejava.version} - com.google.crypto.tink tink @@ -72,6 +67,16 @@ jasypt ${jasypt.version} + + com.jcraft + jsch + ${jsch.version} + + + org.apache.sshd + sshd-core + ${apache-mina.version} + @@ -81,6 +86,8 @@ 1.2.2 1.9.2 1.58 + 0.1.55 + 2.5.1 diff --git a/libraries-security/src/main/java/com/baeldung/ssh/apachesshd/SshdDemo.java b/libraries-security/src/main/java/com/baeldung/ssh/apachesshd/SshdDemo.java new file mode 100644 index 0000000000..05d8034040 --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/ssh/apachesshd/SshdDemo.java @@ -0,0 +1,64 @@ +package com.baeldung.ssh.apachesshd; + +import java.io.ByteArrayOutputStream; +import java.io.OutputStream; +import java.util.EnumSet; +import java.util.concurrent.TimeUnit; + +import org.apache.sshd.client.SshClient; +import org.apache.sshd.client.channel.ClientChannel; +import org.apache.sshd.client.channel.ClientChannelEvent; +import org.apache.sshd.client.session.ClientSession; +import org.apache.sshd.common.channel.Channel; + +public class SshdDemo { + + public static void main(String[] args) throws Exception { + String username = "demo"; + String password = "password"; + String host = "test.rebex.net"; + int port = 22; + long defaultTimeoutSeconds = 10l; + String command = "ls\n"; + + listFolderStructure(username, password, host, port, defaultTimeoutSeconds, command); + } + + public static String listFolderStructure(String username, String password, String host, int port, long defaultTimeoutSeconds, String command) throws Exception { + SshClient client = SshClient.setUpDefaultClient(); + client.start(); + try (ClientSession session = client.connect(username, host, port) + .verify(defaultTimeoutSeconds, TimeUnit.SECONDS) + .getSession()) { + session.addPasswordIdentity(password); + session.auth() + .verify(5L, TimeUnit.SECONDS); + try (ByteArrayOutputStream responseStream = new ByteArrayOutputStream(); + ByteArrayOutputStream errorResponseStream = new ByteArrayOutputStream(); + ClientChannel channel = session.createChannel(Channel.CHANNEL_SHELL)) { + channel.setOut(responseStream); + channel.setErr(errorResponseStream); + try { + channel.open() + .verify(defaultTimeoutSeconds, TimeUnit.SECONDS); + try (OutputStream pipedIn = channel.getInvertedIn()) { + pipedIn.write(command.getBytes()); + pipedIn.flush(); + } + channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(defaultTimeoutSeconds)); + String errorString = new String(errorResponseStream.toByteArray()); + if(!errorString.isEmpty()) { + throw new Exception(errorString); + } + String responseString = new String(responseStream.toByteArray()); + return responseString; + } finally { + channel.close(false); + } + } + } finally { + client.stop(); + } + } + +} diff --git a/libraries-security/src/main/java/com/baeldung/ssh/jsch/JschDemo.java b/libraries-security/src/main/java/com/baeldung/ssh/jsch/JschDemo.java new file mode 100644 index 0000000000..34a40318bb --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/ssh/jsch/JschDemo.java @@ -0,0 +1,52 @@ +package com.baeldung.ssh.jsch; + +import java.io.ByteArrayOutputStream; + +import com.jcraft.jsch.ChannelExec; +import com.jcraft.jsch.JSch; +import com.jcraft.jsch.Session; + +public class JschDemo { + + public static void main(String args[]) throws Exception { + String username = "demo"; + String password = "password"; + String host = "test.rebex.net"; + int port = 22; + String command = "ls"; + listFolderStructure(username, password, host, port, command); + } + + public static String listFolderStructure(String username, String password, String host, int port, String command) throws Exception { + Session session = null; + ChannelExec channel = null; + String response = null; + try { + session = new JSch().getSession(username, host, port); + session.setPassword(password); + session.setConfig("StrictHostKeyChecking", "no"); + session.connect(); + channel = (ChannelExec) session.openChannel("exec"); + channel.setCommand(command); + ByteArrayOutputStream responseStream = new ByteArrayOutputStream(); + ByteArrayOutputStream errorResponseStream = new ByteArrayOutputStream(); + channel.setOutputStream(responseStream); + channel.setErrStream(errorResponseStream); + channel.connect(); + while (channel.isConnected()) { + Thread.sleep(100); + } + String errorResponse = new String(errorResponseStream.toByteArray()); + response = new String(responseStream.toByteArray()); + if(!errorResponse.isEmpty()) { + throw new Exception(errorResponse); + } + } finally { + if (session != null) + session.disconnect(); + if (channel != null) + channel.disconnect(); + } + return response; + } +} diff --git a/libraries-security/src/test/java/com/baeldung/ssh/ApacheMinaSshdLiveTest.java b/libraries-security/src/test/java/com/baeldung/ssh/ApacheMinaSshdLiveTest.java new file mode 100644 index 0000000000..3cefca05cb --- /dev/null +++ b/libraries-security/src/test/java/com/baeldung/ssh/ApacheMinaSshdLiveTest.java @@ -0,0 +1,38 @@ +package com.baeldung.ssh; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import org.junit.Test; + +import com.baeldung.ssh.apachesshd.SshdDemo; + +public class ApacheMinaSshdLiveTest { + + @Test + public void givenValidCredentials_whenConnectionIsEstablished_thenServerReturnsResponse() throws Exception { + String username = "demo"; + String password = "password"; + String host = "test.rebex.net"; + int port = 22; + long defaultTimeoutSeconds = 10l; + String command = "ls\n"; + String responseString = SshdDemo.listFolderStructure(username, password, host, port, defaultTimeoutSeconds, command); + + assertNotNull(responseString); + } + + @Test(expected = Exception.class) + public void givenInvalidCredentials_whenConnectionAttemptIsMade_thenServerReturnsErrorResponse() throws Exception { + String username = "invalidUsername"; + String password = "password"; + String host = "test.rebex.net"; + int port = 22; + long defaultTimeoutSeconds = 10l; + String command = "ls\n"; + String responseString = SshdDemo.listFolderStructure(username, password, host, port, defaultTimeoutSeconds, command); + + assertNull(responseString); + } + +} diff --git a/libraries-security/src/test/java/com/baeldung/ssh/JSchLiveTest.java b/libraries-security/src/test/java/com/baeldung/ssh/JSchLiveTest.java new file mode 100644 index 0000000000..c95c3c319c --- /dev/null +++ b/libraries-security/src/test/java/com/baeldung/ssh/JSchLiveTest.java @@ -0,0 +1,35 @@ +package com.baeldung.ssh; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import org.junit.Test; + +import com.baeldung.ssh.jsch.JschDemo; + +public class JSchLiveTest { + + @Test + public void givenValidCredentials_whenConnectionIsEstablished_thenServerReturnsResponse() throws Exception { + String username = "demo"; + String password = "password"; + String host = "test.rebex.net"; + int port = 22; + String command = "ls"; + String responseString = JschDemo.listFolderStructure(username, password, host, port, command); + + assertNotNull(responseString); + } + + @Test(expected = Exception.class) + public void givenInvalidCredentials_whenConnectionAttemptIsMade_thenServerReturnsErrorResponse() throws Exception { + String username = "invalidUsername"; + String password = "password"; + String host = "test.rebex.net"; + int port = 22; + String command = "ls"; + String responseString = JschDemo.listFolderStructure(username, password, host, port, command); + + assertNull(responseString); + } +}