From 04fe3387070c98e508d7091625cfd332130d92e7 Mon Sep 17 00:00:00 2001 From: Sorin Zamfir Date: Sat, 15 Aug 2020 14:42:21 +0300 Subject: [PATCH 01/25] 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 e36678d920f1b4af224e19cdb598f7622bcce91e Mon Sep 17 00:00:00 2001 From: maryarm Date: Sat, 15 Aug 2020 14:20:40 +0200 Subject: [PATCH 02/25] BAEL-4107: Spring MVC Async vs Spring WebFlux --- spring-5-webflux/.gitignore | 3 +- .../spring/asyncvsflux/AsyncVsWebFluxApp.java | 11 ++++++ .../spring/asyncvsflux/WebFluxController.java | 17 ++++++++++ .../spring/asyncvsflux/WebFluxFilter.java | 20 +++++++++++ .../baeldung/asyncvsflux/AsyncController.java | 23 +++++++++++++ .../com/baeldung/asyncvsflux/AsyncFilter.java | 34 +++++++++++++++++++ .../asyncvsflux/AsyncVsWebFluxApp.java | 13 +++++++ 7 files changed, 120 insertions(+), 1 deletion(-) create mode 100644 spring-5-webflux/src/main/java/com/baeldung/spring/asyncvsflux/AsyncVsWebFluxApp.java create mode 100644 spring-5-webflux/src/main/java/com/baeldung/spring/asyncvsflux/WebFluxController.java create mode 100644 spring-5-webflux/src/main/java/com/baeldung/spring/asyncvsflux/WebFluxFilter.java create mode 100644 spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/asyncvsflux/AsyncController.java create mode 100644 spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/asyncvsflux/AsyncFilter.java create mode 100644 spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/asyncvsflux/AsyncVsWebFluxApp.java diff --git a/spring-5-webflux/.gitignore b/spring-5-webflux/.gitignore index aa4871eeea..b2a03f1b15 100644 --- a/spring-5-webflux/.gitignore +++ b/spring-5-webflux/.gitignore @@ -1,2 +1,3 @@ # Files # -*.log \ No newline at end of file +*.log +*.ipr \ No newline at end of file diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/asyncvsflux/AsyncVsWebFluxApp.java b/spring-5-webflux/src/main/java/com/baeldung/spring/asyncvsflux/AsyncVsWebFluxApp.java new file mode 100644 index 0000000000..5ae6784536 --- /dev/null +++ b/spring-5-webflux/src/main/java/com/baeldung/spring/asyncvsflux/AsyncVsWebFluxApp.java @@ -0,0 +1,11 @@ +package com.baeldung.spring.asyncvsflux; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AsyncVsWebFluxApp { + public static void main(String[] args) { + SpringApplication.run(AsyncVsWebFluxApp.class, args); + } +} \ No newline at end of file diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/asyncvsflux/WebFluxController.java b/spring-5-webflux/src/main/java/com/baeldung/spring/asyncvsflux/WebFluxController.java new file mode 100644 index 0000000000..8ef1ef3e7e --- /dev/null +++ b/spring-5-webflux/src/main/java/com/baeldung/spring/asyncvsflux/WebFluxController.java @@ -0,0 +1,17 @@ +package com.baeldung.spring.asyncvsflux; + +import java.time.Duration; +import org.springframework.http.server.reactive.ServerHttpRequest; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import reactor.core.publisher.Mono; + +@RestController +public class WebFluxController { + + @GetMapping("/flux_result") + public Mono getResult(ServerHttpRequest request) { + return Mono.defer(() -> Mono.just("Result is ready!")) + .delaySubscription(Duration.ofMillis(500)); + } +} diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/asyncvsflux/WebFluxFilter.java b/spring-5-webflux/src/main/java/com/baeldung/spring/asyncvsflux/WebFluxFilter.java new file mode 100644 index 0000000000..3a78047ab8 --- /dev/null +++ b/spring-5-webflux/src/main/java/com/baeldung/spring/asyncvsflux/WebFluxFilter.java @@ -0,0 +1,20 @@ +package com.baeldung.spring.asyncvsflux; + +import java.time.Duration; +import org.springframework.stereotype.Component; +import org.springframework.web.server.ServerWebExchange; +import org.springframework.web.server.WebFilterChain; +import reactor.core.publisher.Mono; + +@Component +public class WebFluxFilter implements org.springframework.web.server.WebFilter { + + @Override + public Mono filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) { + return Mono + .delay(Duration.ofMillis(200)) + .then( + webFilterChain.filter(serverWebExchange) + ); + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/asyncvsflux/AsyncController.java b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/asyncvsflux/AsyncController.java new file mode 100644 index 0000000000..ece06f3fc5 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/asyncvsflux/AsyncController.java @@ -0,0 +1,23 @@ +package com.baeldung.asyncvsflux; + +import java.util.concurrent.CompletableFuture; +import javax.servlet.http.HttpServletRequest; +import org.springframework.scheduling.annotation.Async; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class AsyncController { + + @GetMapping("/async_result") + @Async + public CompletableFuture getResultAsyc(HttpServletRequest request) { + try { + Thread.sleep(500); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return CompletableFuture.completedFuture("Result is ready!"); + } + +} diff --git a/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/asyncvsflux/AsyncFilter.java b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/asyncvsflux/AsyncFilter.java new file mode 100644 index 0000000000..5a8ac4d9df --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/asyncvsflux/AsyncFilter.java @@ -0,0 +1,34 @@ +package com.baeldung.asyncvsflux; + +import java.io.IOException; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import org.springframework.stereotype.Component; + +@Component +public class AsyncFilter implements Filter { + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + try { + Thread.sleep(200); + } catch (InterruptedException e) { + e.printStackTrace(); + } + filterChain.doFilter(servletRequest, servletResponse); + } + + @Override + public void destroy() { + + } +} diff --git a/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/asyncvsflux/AsyncVsWebFluxApp.java b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/asyncvsflux/AsyncVsWebFluxApp.java new file mode 100644 index 0000000000..3905199468 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/asyncvsflux/AsyncVsWebFluxApp.java @@ -0,0 +1,13 @@ +package com.baeldung.asyncvsflux; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableAsync; + +@SpringBootApplication +@EnableAsync +public class AsyncVsWebFluxApp { + public static void main(String[] args) { + SpringApplication.run(AsyncVsWebFluxApp.class, args); + } +} \ No newline at end of file From 6b75e0cbed0eb62f96df5f60228b1ec1170dd4dd Mon Sep 17 00:00:00 2001 From: Sorin Zamfir Date: Sun, 16 Aug 2020 22:39:00 +0300 Subject: [PATCH 03/25] 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 eac28eb90f89acc2be018013ac31348ec64705b9 Mon Sep 17 00:00:00 2001 From: azhwani <> Date: Mon, 17 Aug 2020 15:12:50 +0100 Subject: [PATCH 04/25] 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 05/25] 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 06/25] 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 07/25] 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 7e07ee688d911d33b8e4914dd016fb273e443d00 Mon Sep 17 00:00:00 2001 From: maryarm <45322329+maryarm@users.noreply.github.com> Date: Fri, 21 Aug 2020 22:33:19 +0200 Subject: [PATCH 08/25] Update .gitignore BAEL-4107 - Undo changes of .gitignore --- spring-5-webflux/.gitignore | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-5-webflux/.gitignore b/spring-5-webflux/.gitignore index b2a03f1b15..4dff7c9a4b 100644 --- a/spring-5-webflux/.gitignore +++ b/spring-5-webflux/.gitignore @@ -1,3 +1,2 @@ # Files # *.log -*.ipr \ No newline at end of file From 122127321655fdd6f925591c6533a4d8df3c14de Mon Sep 17 00:00:00 2001 From: Sorin Zamfir Date: Sun, 23 Aug 2020 00:03:45 +0300 Subject: [PATCH 09/25] 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 26cbe68348ad6029090012d72ccaf7e60cf1895f Mon Sep 17 00:00:00 2001 From: Philippe Date: Sun, 23 Aug 2020 14:25:54 -0300 Subject: [PATCH 10/25] [BAEL-4381] Duplicate Baker Smurf --- .../baeldung/archunit/smurfs/persistence/SmurfsRepository.java | 1 - 1 file changed, 1 deletion(-) diff --git a/libraries-testing/src/main/java/com/baeldung/archunit/smurfs/persistence/SmurfsRepository.java b/libraries-testing/src/main/java/com/baeldung/archunit/smurfs/persistence/SmurfsRepository.java index 5d90d0f288..171f2f17db 100644 --- a/libraries-testing/src/main/java/com/baeldung/archunit/smurfs/persistence/SmurfsRepository.java +++ b/libraries-testing/src/main/java/com/baeldung/archunit/smurfs/persistence/SmurfsRepository.java @@ -24,7 +24,6 @@ public class SmurfsRepository { smurfs.put("Architect", new Smurf("Architect", true, true)); smurfs.put("Baby", new Smurf("Baby", true, true)); smurfs.put("Baker", new Smurf("Baker", true, true)); - smurfs.put("Baker", new Smurf("Baker", true, true)); } public List findAll() { From bbeb322d413302bdc51d10bb3b4a2ce03b29a882 Mon Sep 17 00:00:00 2001 From: Cristian Stancalau Date: Mon, 24 Aug 2020 17:36:21 +0300 Subject: [PATCH 11/25] BAEL-4172 - How to Turn Off Swagger-ui in Production in http-2 (#9858) * How to disable swagger in production example. * Add new module in main pom. * fix pom formatting * Replace tabs with spaces. * Move to article-specific package. Co-authored-by: Cristian Stancalau --- pom.xml | 1 + spring-rest-http-2/README.md | 10 +++++ spring-rest-http-2/pom.xml | 38 ++++++++++++++++++ .../baeldung/SpringBootRest2Application.java | 12 ++++++ .../disable/config/SwaggerConfig.java | 38 ++++++++++++++++++ .../controllers/VersionController.java | 40 +++++++++++++++++++ 6 files changed, 139 insertions(+) create mode 100644 spring-rest-http-2/README.md create mode 100644 spring-rest-http-2/pom.xml create mode 100644 spring-rest-http-2/src/main/java/com/baeldung/SpringBootRest2Application.java create mode 100644 spring-rest-http-2/src/main/java/com/baeldung/swaggerui/disable/config/SwaggerConfig.java create mode 100644 spring-rest-http-2/src/main/java/com/baeldung/swaggerui/disable/controllers/VersionController.java diff --git a/pom.xml b/pom.xml index 3565c2dc4b..ffdfe4cffa 100644 --- a/pom.xml +++ b/pom.xml @@ -701,6 +701,7 @@ spring-rest-compress spring-rest-hal-browser spring-rest-http + spring-rest-http-2 spring-rest-query-language spring-rest-shell spring-rest-simple diff --git a/spring-rest-http-2/README.md b/spring-rest-http-2/README.md new file mode 100644 index 0000000000..74ec59e0b5 --- /dev/null +++ b/spring-rest-http-2/README.md @@ -0,0 +1,10 @@ +## Spring REST HTTP 2 + +This module contains articles about HTTP in REST APIs with Spring + +### The Course +The "REST With Spring 2" Classes: http://bit.ly/restwithspring + +### Relevant Articles: + + diff --git a/spring-rest-http-2/pom.xml b/spring-rest-http-2/pom.xml new file mode 100644 index 0000000000..8678d7243d --- /dev/null +++ b/spring-rest-http-2/pom.xml @@ -0,0 +1,38 @@ + + + 4.0.0 + spring-rest-http-2 + 0.1-SNAPSHOT + spring-rest-http-2 + war + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + io.springfox + springfox-swagger2 + ${swagger2.version} + + + io.springfox + springfox-swagger-ui + ${swagger2.version} + + + + + 2.9.2 + + + diff --git a/spring-rest-http-2/src/main/java/com/baeldung/SpringBootRest2Application.java b/spring-rest-http-2/src/main/java/com/baeldung/SpringBootRest2Application.java new file mode 100644 index 0000000000..f8127f3686 --- /dev/null +++ b/spring-rest-http-2/src/main/java/com/baeldung/SpringBootRest2Application.java @@ -0,0 +1,12 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootRest2Application { + + public static void main(String[] args) { + SpringApplication.run(SpringBootRest2Application.class, args); + } +} diff --git a/spring-rest-http-2/src/main/java/com/baeldung/swaggerui/disable/config/SwaggerConfig.java b/spring-rest-http-2/src/main/java/com/baeldung/swaggerui/disable/config/SwaggerConfig.java new file mode 100644 index 0000000000..8a9a921036 --- /dev/null +++ b/spring-rest-http-2/src/main/java/com/baeldung/swaggerui/disable/config/SwaggerConfig.java @@ -0,0 +1,38 @@ +package com.baeldung.swaggerui.disable.config; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +@Profile("!prod") +// @Profile("swagger") +// @Profile("!prod && swagger") +// @ConditionalOnExpression(value = "${useSwagger:false}") +@Configuration +@EnableSwagger2 +public class SwaggerConfig implements WebMvcConfigurer { + + @Bean + public Docket api() { + return new Docket(DocumentationType.SWAGGER_2).select() + .apis(RequestHandlerSelectors.basePackage("com.baeldung")) + .paths(PathSelectors.regex("/.*")) + .build(); + } + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("swagger-ui.html") + .addResourceLocations("classpath:/META-INF/resources/"); + registry.addResourceHandler("/webjars/**") + .addResourceLocations("classpath:/META-INF/resources/webjars/"); + } +} diff --git a/spring-rest-http-2/src/main/java/com/baeldung/swaggerui/disable/controllers/VersionController.java b/spring-rest-http-2/src/main/java/com/baeldung/swaggerui/disable/controllers/VersionController.java new file mode 100644 index 0000000000..8f8115197e --- /dev/null +++ b/spring-rest-http-2/src/main/java/com/baeldung/swaggerui/disable/controllers/VersionController.java @@ -0,0 +1,40 @@ +package com.baeldung.swaggerui.disable.controllers; + +import io.swagger.annotations.ApiOperation; +import org.springframework.core.env.Environment; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class VersionController { + + private final Environment environment; + + public VersionController(Environment environment) { + this.environment = environment; + } + + @ApiOperation(value = "Get the currently deployed API version and active Spring profiles") + @GetMapping("/api/version") + public Version getVersion() { + return new Version("1.0", environment.getActiveProfiles()); + } + + private static class Version { + private final String version; + private String[] activeProfiles; + + private Version(String version, String[] activeProfiles) { + this.version = version; + this.activeProfiles = activeProfiles; + } + + public String getVersion() { + return version; + } + + public String[] getActiveProfiles() { + return activeProfiles; + } + } +} From aa966494587024879fd1f71a68812f170b8ef23c Mon Sep 17 00:00:00 2001 From: Amy DeGregorio Date: Mon, 24 Aug 2020 11:20:26 -0400 Subject: [PATCH 12/25] BAEL 4401 (#9913) * BAEL-4401 * Update with master and resolve conflicts --- .../core-java-exceptions-3/pom.xml | 3 +-- .../NullParameterExample.java | 17 +++++++++++++++++ .../NullParameterExampleUnitTest.java | 17 +++++++++++++++++ 3 files changed, 35 insertions(+), 2 deletions(-) create mode 100644 core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/nullmethodparameter/NullParameterExample.java create mode 100644 core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/nullmethodparameter/NullParameterExampleUnitTest.java diff --git a/core-java-modules/core-java-exceptions-3/pom.xml b/core-java-modules/core-java-exceptions-3/pom.xml index 32c522dab5..b909572afe 100644 --- a/core-java-modules/core-java-exceptions-3/pom.xml +++ b/core-java-modules/core-java-exceptions-3/pom.xml @@ -30,5 +30,4 @@ 3.10.0 - - \ No newline at end of file + diff --git a/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/nullmethodparameter/NullParameterExample.java b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/nullmethodparameter/NullParameterExample.java new file mode 100644 index 0000000000..c2c76bdc46 --- /dev/null +++ b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/nullmethodparameter/NullParameterExample.java @@ -0,0 +1,17 @@ +package com.baeldung.nullmethodparameter; + +public class NullParameterExample { + public void processSomethingNotNull(Object myParameter) { + if (myParameter == null) { + throw new IllegalArgumentException("Parameter 'myParameter' cannot be null"); + } + //Do something with the parameter + } + + public void processSomethingElseNotNull(Object myParameter) { + if (myParameter == null) { + throw new NullPointerException("Parameter 'myParameter' cannot be null"); + } + //Do something with the parameter + } +} diff --git a/core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/nullmethodparameter/NullParameterExampleUnitTest.java b/core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/nullmethodparameter/NullParameterExampleUnitTest.java new file mode 100644 index 0000000000..aa4b332e52 --- /dev/null +++ b/core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/nullmethodparameter/NullParameterExampleUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.nullmethodparameter; + +import org.junit.Test; + +public class NullParameterExampleUnitTest { + @Test(expected = IllegalArgumentException.class) + public void givenNullParameter_whenProcessSomethingNotNull_thenIllegalArgumentException() { + NullParameterExample example = new NullParameterExample(); + example.processSomethingNotNull(null); + } + + @Test(expected = NullPointerException.class) + public void givenNullParameter_whenProcessSomethingElseNotNull_thenNullPointerException() { + NullParameterExample example = new NullParameterExample(); + example.processSomethingElseNotNull(null); + } +} From 839bd3fd092531b7f33ef525a620899d487a948c Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Mon, 24 Aug 2020 21:05:12 +0200 Subject: [PATCH 13/25] JAVA-2428: Migrate cdi to spring-parent-5 --- cdi/pom.xml | 27 ++++++++++----------------- 1 file changed, 10 insertions(+), 17 deletions(-) diff --git a/cdi/pom.xml b/cdi/pom.xml index fec12a9b16..226ca529e1 100644 --- a/cdi/pom.xml +++ b/cdi/pom.xml @@ -1,8 +1,8 @@ + xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 cdi 1.0-SNAPSHOT @@ -10,9 +10,9 @@ com.baeldung - parent-spring-4 + parent-spring-5 0.0.1-SNAPSHOT - ../parent-spring-4 + ../parent-spring-5 @@ -26,28 +26,22 @@ weld-se-core ${weld-se-core.version} - - org.hamcrest - hamcrest - ${hamcrest.version} - test - org.assertj assertj-core ${assertj-core.version} test - - org.springframework - spring-context - ${spring.version} - org.aspectj aspectjweaver ${aspectjweaver.version} + + org.springframework + spring-context + ${spring.version} + org.springframework spring-test @@ -61,7 +55,6 @@ 3.0.5.Final 1.9.2 3.10.0 - 5.1.2.RELEASE From 37b3882b55200ade7b5d5fb2355cfbf8392ea943 Mon Sep 17 00:00:00 2001 From: Philippe Date: Tue, 25 Aug 2020 08:54:26 -0300 Subject: [PATCH 14/25] [BAEL-4381] Formatting --- .../com/baeldung/archunit/smurfs/persistence/domain/Smurf.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/libraries-testing/src/main/java/com/baeldung/archunit/smurfs/persistence/domain/Smurf.java b/libraries-testing/src/main/java/com/baeldung/archunit/smurfs/persistence/domain/Smurf.java index 255a024cdc..938257ba17 100644 --- a/libraries-testing/src/main/java/com/baeldung/archunit/smurfs/persistence/domain/Smurf.java +++ b/libraries-testing/src/main/java/com/baeldung/archunit/smurfs/persistence/domain/Smurf.java @@ -5,8 +5,6 @@ public class Smurf { private boolean comic; private boolean cartoon; - public Smurf() {} - public Smurf(String name, boolean comic, boolean cartoon) { this.name = name; this.comic = comic; From fdd41010f41fe4cceef2495e321cbc7c96a81f41 Mon Sep 17 00:00:00 2001 From: Krzysztof Woyke Date: Tue, 25 Aug 2020 16:26:31 +0200 Subject: [PATCH 15/25] JAVA-2282: Update spring-cloud-stream-binder-kinesis version --- .../spring-cloud-stream/spring-cloud-stream-kinesis/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kinesis/pom.xml b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kinesis/pom.xml index bb515fcb36..9e706cc239 100644 --- a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kinesis/pom.xml +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kinesis/pom.xml @@ -41,7 +41,7 @@ 1.11.632 - 1.2.1.RELEASE + 2.0.2.RELEASE 2.2.1.RELEASE 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 16/25] 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 17/25] 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 4fac6a711c4edcdf375e36998ad155de76a9c389 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Wed, 26 Aug 2020 21:38:26 +0200 Subject: [PATCH 18/25] 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 19/25] 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 20/25] 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 21/25] 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 482357866eb215d3e1becabd7d06961e0d1a24f1 Mon Sep 17 00:00:00 2001 From: kwoyke Date: Fri, 28 Aug 2020 08:01:12 +0200 Subject: [PATCH 22/25] 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 23/25] 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 44d66d9a0fe04ebc8e39b5f9e1651c1a5243537e Mon Sep 17 00:00:00 2001 From: kwoyke Date: Sat, 29 Aug 2020 10:49:40 +0200 Subject: [PATCH 24/25] 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 25/25] [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")); + } + +}