From ba770290825e7a824fd87795fe5e33cef2842643 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Mon, 23 Jul 2018 22:40:47 +0300 Subject: [PATCH 01/22] remove reactive ex --- spring-5/pom.xml | 14 -- .../java/com/baeldung/Spring5Application.java | 2 - .../baeldung/SpringSecurity5Application.java | 34 ----- .../baeldung/config/PersistenceConfig.java | 12 ++ .../ActorController.java | 2 +- .../ActorNotFoundException.java | 2 +- .../ActorService.java | 2 +- .../SpringExceptionApplication.java | 26 ++-- .../com/baeldung/functional/FormHandler.java | 41 ----- .../FunctionalSpringBootApplication.java | 87 ----------- .../functional/FunctionalWebApplication.java | 80 ---------- .../functional/IndexRewriteFilter.java | 25 ---- .../com/baeldung/functional/RootServlet.java | 82 ---------- .../{web/reactive => jupiter}/Task.java | 2 +- .../java/com/baeldung/jupiter/TestConfig.java | 1 - .../baeldung/security/GreetController.java | 37 ----- .../com/baeldung/security/GreetService.java | 15 -- .../com/baeldung/security/SecurityConfig.java | 42 ------ .../reactive/client/WebClientController.java | 83 ----------- ...nctionalWebApplicationIntegrationTest.java | 141 ------------------ ...C.java => GetAutoGenKeyByJDBCIntTest.java} | 110 +++++++------- ...nit5ComposedAnnotationIntegrationTest.java | 1 - .../jupiter/Spring5JUnit5IntegrationTest.java | 1 - ...g5ReactiveServerClientIntegrationTest.java | 94 ------------ .../security/SecurityIntegrationTest.java | 40 ----- .../client/WebTestClientIntegrationTest.java | 62 -------- 26 files changed, 84 insertions(+), 954 deletions(-) delete mode 100644 spring-5/src/main/java/com/baeldung/SpringSecurity5Application.java create mode 100644 spring-5/src/main/java/com/baeldung/config/PersistenceConfig.java rename spring-5/src/main/java/com/baeldung/{execption => exception}/ActorController.java (97%) rename spring-5/src/main/java/com/baeldung/{execption => exception}/ActorNotFoundException.java (92%) rename spring-5/src/main/java/com/baeldung/{execption => exception}/ActorService.java (97%) rename spring-5/src/main/java/com/baeldung/{execption => exception}/SpringExceptionApplication.java (92%) delete mode 100644 spring-5/src/main/java/com/baeldung/functional/FormHandler.java delete mode 100644 spring-5/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java delete mode 100644 spring-5/src/main/java/com/baeldung/functional/FunctionalWebApplication.java delete mode 100644 spring-5/src/main/java/com/baeldung/functional/IndexRewriteFilter.java delete mode 100644 spring-5/src/main/java/com/baeldung/functional/RootServlet.java rename spring-5/src/main/java/com/baeldung/{web/reactive => jupiter}/Task.java (93%) delete mode 100644 spring-5/src/main/java/com/baeldung/security/GreetController.java delete mode 100644 spring-5/src/main/java/com/baeldung/security/GreetService.java delete mode 100644 spring-5/src/main/java/com/baeldung/security/SecurityConfig.java delete mode 100644 spring-5/src/main/java/com/baeldung/web/reactive/client/WebClientController.java delete mode 100644 spring-5/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java rename spring-5/src/test/java/com/baeldung/jdbc/autogenkey/{GetAutoGenKeyByJDBC.java => GetAutoGenKeyByJDBCIntTest.java} (95%) delete mode 100644 spring-5/src/test/java/com/baeldung/jupiter/Spring5ReactiveServerClientIntegrationTest.java delete mode 100644 spring-5/src/test/java/com/baeldung/security/SecurityIntegrationTest.java delete mode 100644 spring-5/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java diff --git a/spring-5/pom.xml b/spring-5/pom.xml index 542cd5023f..e37833ff94 100644 --- a/spring-5/pom.xml +++ b/spring-5/pom.xml @@ -33,19 +33,10 @@ org.springframework.boot spring-boot-starter-web - - org.springframework.boot - spring-boot-starter-webflux - org.springframework.boot spring-boot-starter-hateoas - - org.projectreactor - reactor-spring - ${reactor-spring.version} - javax.json.bind javax.json.bind-api @@ -139,11 +130,6 @@ spring-restdocs-mockmvc test - - org.springframework.restdocs - spring-restdocs-webtestclient - test - org.springframework.restdocs spring-restdocs-restassured diff --git a/spring-5/src/main/java/com/baeldung/Spring5Application.java b/spring-5/src/main/java/com/baeldung/Spring5Application.java index f321871646..41b5c1eed1 100644 --- a/spring-5/src/main/java/com/baeldung/Spring5Application.java +++ b/spring-5/src/main/java/com/baeldung/Spring5Application.java @@ -2,10 +2,8 @@ package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.ComponentScan; @SpringBootApplication -@ComponentScan(basePackages = { "com.baeldung.web" }) public class Spring5Application { public static void main(String[] args) { diff --git a/spring-5/src/main/java/com/baeldung/SpringSecurity5Application.java b/spring-5/src/main/java/com/baeldung/SpringSecurity5Application.java deleted file mode 100644 index 02c91a1879..0000000000 --- a/spring-5/src/main/java/com/baeldung/SpringSecurity5Application.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung; - -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.http.server.reactive.HttpHandler; -import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; -import org.springframework.web.reactive.config.EnableWebFlux; -import org.springframework.web.server.adapter.WebHttpHandlerBuilder; -import reactor.ipc.netty.NettyContext; -import reactor.ipc.netty.http.server.HttpServer; - -@ComponentScan(basePackages = {"com.baeldung.security"}) -@EnableWebFlux -public class SpringSecurity5Application { - - public static void main(String[] args) { - try (AnnotationConfigApplicationContext context = - new AnnotationConfigApplicationContext(SpringSecurity5Application.class)) { - context.getBean(NettyContext.class).onClose().block(); - } - } - - @Bean - public NettyContext nettyContext(ApplicationContext context) { - HttpHandler handler = WebHttpHandlerBuilder.applicationContext(context) - .build(); - ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(handler); - HttpServer httpServer = HttpServer.create("localhost", 8080); - return httpServer.newHandler(adapter).block(); - } - -} diff --git a/spring-5/src/main/java/com/baeldung/config/PersistenceConfig.java b/spring-5/src/main/java/com/baeldung/config/PersistenceConfig.java new file mode 100644 index 0000000000..547685970a --- /dev/null +++ b/spring-5/src/main/java/com/baeldung/config/PersistenceConfig.java @@ -0,0 +1,12 @@ +package com.baeldung.config; + +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; + +@Configuration +@EnableJpaRepositories("com.baeldung.persistence") +@EntityScan("com.baeldung.web") +public class PersistenceConfig { + +} diff --git a/spring-5/src/main/java/com/baeldung/execption/ActorController.java b/spring-5/src/main/java/com/baeldung/exception/ActorController.java similarity index 97% rename from spring-5/src/main/java/com/baeldung/execption/ActorController.java rename to spring-5/src/main/java/com/baeldung/exception/ActorController.java index 6c9c46253a..17a5b80b64 100644 --- a/spring-5/src/main/java/com/baeldung/execption/ActorController.java +++ b/spring-5/src/main/java/com/baeldung/exception/ActorController.java @@ -1,4 +1,4 @@ -package com.baeldung.execption; +package com.baeldung.exception; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; diff --git a/spring-5/src/main/java/com/baeldung/execption/ActorNotFoundException.java b/spring-5/src/main/java/com/baeldung/exception/ActorNotFoundException.java similarity index 92% rename from spring-5/src/main/java/com/baeldung/execption/ActorNotFoundException.java rename to spring-5/src/main/java/com/baeldung/exception/ActorNotFoundException.java index 642c075b5d..7439be414d 100644 --- a/spring-5/src/main/java/com/baeldung/execption/ActorNotFoundException.java +++ b/spring-5/src/main/java/com/baeldung/exception/ActorNotFoundException.java @@ -1,4 +1,4 @@ -package com.baeldung.execption; +package com.baeldung.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; diff --git a/spring-5/src/main/java/com/baeldung/execption/ActorService.java b/spring-5/src/main/java/com/baeldung/exception/ActorService.java similarity index 97% rename from spring-5/src/main/java/com/baeldung/execption/ActorService.java rename to spring-5/src/main/java/com/baeldung/exception/ActorService.java index 956fa92015..0f173d78d6 100644 --- a/spring-5/src/main/java/com/baeldung/execption/ActorService.java +++ b/spring-5/src/main/java/com/baeldung/exception/ActorService.java @@ -1,4 +1,4 @@ -package com.baeldung.execption; +package com.baeldung.exception; import java.util.Arrays; import java.util.List; diff --git a/spring-5/src/main/java/com/baeldung/execption/SpringExceptionApplication.java b/spring-5/src/main/java/com/baeldung/exception/SpringExceptionApplication.java similarity index 92% rename from spring-5/src/main/java/com/baeldung/execption/SpringExceptionApplication.java rename to spring-5/src/main/java/com/baeldung/exception/SpringExceptionApplication.java index 1670da54c3..ed163f7fa7 100644 --- a/spring-5/src/main/java/com/baeldung/execption/SpringExceptionApplication.java +++ b/spring-5/src/main/java/com/baeldung/exception/SpringExceptionApplication.java @@ -1,14 +1,14 @@ -package com.baeldung.execption; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; -import org.springframework.context.annotation.ComponentScan; - -@SpringBootApplication(exclude = SecurityAutoConfiguration.class) -@ComponentScan(basePackages = { "com.baeldung.execption" }) -public class SpringExceptionApplication { - public static void main(String[] args) { - SpringApplication.run(SpringExceptionApplication.class, args); - } +package com.baeldung.exception; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication(exclude = SecurityAutoConfiguration.class) +@ComponentScan(basePackages = { "com.baeldung.execption" }) +public class SpringExceptionApplication { + public static void main(String[] args) { + SpringApplication.run(SpringExceptionApplication.class, args); + } } \ No newline at end of file diff --git a/spring-5/src/main/java/com/baeldung/functional/FormHandler.java b/spring-5/src/main/java/com/baeldung/functional/FormHandler.java deleted file mode 100644 index 05069735bb..0000000000 --- a/spring-5/src/main/java/com/baeldung/functional/FormHandler.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.functional; - -import org.springframework.core.io.buffer.DataBuffer; -import org.springframework.util.MultiValueMap; -import org.springframework.web.reactive.function.server.ServerRequest; -import org.springframework.web.reactive.function.server.ServerResponse; -import reactor.core.publisher.Mono; - -import java.util.List; -import java.util.concurrent.atomic.AtomicLong; - -import static org.springframework.web.reactive.function.BodyExtractors.toDataBuffers; -import static org.springframework.web.reactive.function.BodyExtractors.toFormData; -import static org.springframework.web.reactive.function.BodyInserters.fromObject; -import static org.springframework.web.reactive.function.server.ServerResponse.ok; - -public class FormHandler { - - Mono handleLogin(ServerRequest request) { - return request.body(toFormData()) - .map(MultiValueMap::toSingleValueMap) - .filter(formData -> "baeldung".equals(formData.get("user"))) - .filter(formData -> "you_know_what_to_do".equals(formData.get("token"))) - .flatMap(formData -> ok().body(Mono.just("welcome back!"), String.class)) - .switchIfEmpty(ServerResponse.badRequest() - .build()); - } - - Mono handleUpload(ServerRequest request) { - return request.body(toDataBuffers()) - .collectList() - .flatMap(dataBuffers -> ok().body(fromObject(extractData(dataBuffers).toString()))); - } - - private AtomicLong extractData(List dataBuffers) { - AtomicLong atomicLong = new AtomicLong(0); - dataBuffers.forEach(d -> atomicLong.addAndGet(d.asByteBuffer() - .array().length)); - return atomicLong; - } -} diff --git a/spring-5/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java b/spring-5/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java deleted file mode 100644 index 402b607b19..0000000000 --- a/spring-5/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.baeldung.functional; - -import static org.springframework.web.reactive.function.BodyInserters.fromObject; -import static org.springframework.web.reactive.function.server.RequestPredicates.GET; -import static org.springframework.web.reactive.function.server.RequestPredicates.POST; -import static org.springframework.web.reactive.function.server.RequestPredicates.path; -import static org.springframework.web.reactive.function.server.RouterFunctions.route; -import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler; -import static org.springframework.web.reactive.function.server.ServerResponse.ok; - -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.web.servlet.ServletRegistrationBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; -import org.springframework.core.io.ClassPathResource; -import org.springframework.http.server.reactive.HttpHandler; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.web.reactive.function.server.RouterFunction; -import org.springframework.web.reactive.function.server.RouterFunctions; -import org.springframework.web.reactive.function.server.ServerResponse; -import org.springframework.web.server.WebHandler; -import org.springframework.web.server.adapter.WebHttpHandlerBuilder; - -import reactor.core.publisher.Flux; - -@SpringBootApplication -@ComponentScan(basePackages = { "com.baeldung.functional" }) -public class FunctionalSpringBootApplication { - - private static final Actor BRAD_PITT = new Actor("Brad", "Pitt"); - private static final Actor TOM_HANKS = new Actor("Tom", "Hanks"); - private static final List actors = new CopyOnWriteArrayList<>(Arrays.asList(BRAD_PITT, TOM_HANKS)); - - private RouterFunction routingFunction() { - FormHandler formHandler = new FormHandler(); - - RouterFunction restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class) - .doOnNext(actors::add) - .then(ok().build())); - - return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), formHandler::handleLogin) - .andRoute(POST("/upload"), formHandler::handleUpload) - .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/"))) - .andNest(path("/actor"), restfulRouter) - .filter((request, next) -> { - System.out.println("Before handler invocation: " + request.path()); - return next.handle(request); - }); - } - - @Bean - public ServletRegistrationBean servletRegistrationBean() throws Exception { - HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler((WebHandler) toHttpHandler(routingFunction())) - .filter(new IndexRewriteFilter()) - .build(); - ServletRegistrationBean registrationBean = new ServletRegistrationBean<>(new RootServlet(httpHandler), "/"); - registrationBean.setLoadOnStartup(1); - registrationBean.setAsyncSupported(true); - return registrationBean; - } - - @Configuration - @EnableWebSecurity - @Profile("!https") - static class SecurityConfig extends WebSecurityConfigurerAdapter { - @Override - protected void configure(final HttpSecurity http) throws Exception { - http.authorizeRequests() - .anyRequest() - .permitAll(); - } - } - - public static void main(String[] args) { - SpringApplication.run(FunctionalSpringBootApplication.class, args); - } - -} diff --git a/spring-5/src/main/java/com/baeldung/functional/FunctionalWebApplication.java b/spring-5/src/main/java/com/baeldung/functional/FunctionalWebApplication.java deleted file mode 100644 index 5a7d70d3db..0000000000 --- a/spring-5/src/main/java/com/baeldung/functional/FunctionalWebApplication.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.baeldung.functional; - -import static org.springframework.web.reactive.function.BodyInserters.fromObject; -import static org.springframework.web.reactive.function.server.RequestPredicates.GET; -import static org.springframework.web.reactive.function.server.RequestPredicates.POST; -import static org.springframework.web.reactive.function.server.RequestPredicates.path; -import static org.springframework.web.reactive.function.server.RouterFunctions.route; -import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler; -import static org.springframework.web.reactive.function.server.ServerResponse.ok; - -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; - -import org.apache.catalina.Context; -import org.apache.catalina.startup.Tomcat; -import org.springframework.boot.web.embedded.tomcat.TomcatWebServer; -import org.springframework.boot.web.server.WebServer; -import org.springframework.core.io.ClassPathResource; -import org.springframework.http.server.reactive.HttpHandler; -import org.springframework.http.server.reactive.ServletHttpHandlerAdapter; -import org.springframework.web.reactive.function.server.RouterFunction; -import org.springframework.web.reactive.function.server.RouterFunctions; -import org.springframework.web.reactive.function.server.ServerResponse; -import org.springframework.web.server.WebHandler; -import org.springframework.web.server.adapter.WebHttpHandlerBuilder; - -import reactor.core.publisher.Flux; - -public class FunctionalWebApplication { - - private static final Actor BRAD_PITT = new Actor("Brad", "Pitt"); - private static final Actor TOM_HANKS = new Actor("Tom", "Hanks"); - private static final List actors = new CopyOnWriteArrayList<>(Arrays.asList(BRAD_PITT, TOM_HANKS)); - - private RouterFunction routingFunction() { - FormHandler formHandler = new FormHandler(); - - RouterFunction restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class) - .doOnNext(actors::add) - .then(ok().build())); - - return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), formHandler::handleLogin) - .andRoute(POST("/upload"), formHandler::handleUpload) - .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/"))) - .andNest(path("/actor"), restfulRouter) - .filter((request, next) -> { - System.out.println("Before handler invocation: " + request.path()); - return next.handle(request); - }); - } - - WebServer start() throws Exception { - WebHandler webHandler = (WebHandler) toHttpHandler(routingFunction()); - HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler(webHandler) - .filter(new IndexRewriteFilter()) - .build(); - - Tomcat tomcat = new Tomcat(); - tomcat.setHostname("localhost"); - tomcat.setPort(9090); - Context rootContext = tomcat.addContext("", System.getProperty("java.io.tmpdir")); - ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler); - Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet); - rootContext.addServletMappingDecoded("/", "httpHandlerServlet"); - - TomcatWebServer server = new TomcatWebServer(tomcat); - server.start(); - return server; - - } - - public static void main(String[] args) { - try { - new FunctionalWebApplication().start(); - } catch (Exception e) { - e.printStackTrace(); - } - } -} diff --git a/spring-5/src/main/java/com/baeldung/functional/IndexRewriteFilter.java b/spring-5/src/main/java/com/baeldung/functional/IndexRewriteFilter.java deleted file mode 100644 index 551ea6c84b..0000000000 --- a/spring-5/src/main/java/com/baeldung/functional/IndexRewriteFilter.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.functional; - -import org.springframework.http.server.reactive.ServerHttpRequest; -import org.springframework.web.server.ServerWebExchange; -import org.springframework.web.server.WebFilter; -import org.springframework.web.server.WebFilterChain; -import reactor.core.publisher.Mono; - -class IndexRewriteFilter implements WebFilter { - - @Override - public Mono filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) { - ServerHttpRequest request = serverWebExchange.getRequest(); - if (request.getURI() - .getPath() - .equals("/")) { - return webFilterChain.filter(serverWebExchange.mutate() - .request(builder -> builder.method(request.getMethod()) - .path("/test")) - .build()); - } - return webFilterChain.filter(serverWebExchange); - } - -} diff --git a/spring-5/src/main/java/com/baeldung/functional/RootServlet.java b/spring-5/src/main/java/com/baeldung/functional/RootServlet.java deleted file mode 100644 index 8fe24821de..0000000000 --- a/spring-5/src/main/java/com/baeldung/functional/RootServlet.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.baeldung.functional; - -import static org.springframework.web.reactive.function.BodyExtractors.toDataBuffers; -import static org.springframework.web.reactive.function.BodyExtractors.toFormData; -import static org.springframework.web.reactive.function.BodyInserters.fromObject; -import static org.springframework.web.reactive.function.server.RequestPredicates.GET; -import static org.springframework.web.reactive.function.server.RequestPredicates.POST; -import static org.springframework.web.reactive.function.server.RequestPredicates.path; -import static org.springframework.web.reactive.function.server.RouterFunctions.route; -import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler; -import static org.springframework.web.reactive.function.server.ServerResponse.ok; - -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.atomic.AtomicLong; - -import org.springframework.core.io.ClassPathResource; -import org.springframework.http.server.reactive.HttpHandler; -import org.springframework.http.server.reactive.ServletHttpHandlerAdapter; -import org.springframework.util.MultiValueMap; -import org.springframework.web.reactive.function.server.RouterFunction; -import org.springframework.web.reactive.function.server.RouterFunctions; -import org.springframework.web.reactive.function.server.ServerResponse; -import org.springframework.web.server.WebHandler; -import org.springframework.web.server.adapter.WebHttpHandlerBuilder; - -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -public class RootServlet extends ServletHttpHandlerAdapter { - - public RootServlet() { - this(WebHttpHandlerBuilder.webHandler((WebHandler) toHttpHandler(routingFunction())) - .filter(new IndexRewriteFilter()) - .build()); - } - - RootServlet(HttpHandler httpHandler) { - super(httpHandler); - } - - private static final Actor BRAD_PITT = new Actor("Brad", "Pitt"); - private static final Actor TOM_HANKS = new Actor("Tom", "Hanks"); - private static final List actors = new CopyOnWriteArrayList<>(Arrays.asList(BRAD_PITT, TOM_HANKS)); - - private static RouterFunction routingFunction() { - - return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), serverRequest -> serverRequest.body(toFormData()) - .map(MultiValueMap::toSingleValueMap) - .map(formData -> { - System.out.println("form data: " + formData.toString()); - if ("baeldung".equals(formData.get("user")) && "you_know_what_to_do".equals(formData.get("token"))) { - return ok().body(Mono.just("welcome back!"), String.class) - .block(); - } - return ServerResponse.badRequest() - .build() - .block(); - })) - .andRoute(POST("/upload"), serverRequest -> serverRequest.body(toDataBuffers()) - .collectList() - .map(dataBuffers -> { - AtomicLong atomicLong = new AtomicLong(0); - dataBuffers.forEach(d -> atomicLong.addAndGet(d.asByteBuffer() - .array().length)); - System.out.println("data length:" + atomicLong.get()); - return ok().body(fromObject(atomicLong.toString())) - .block(); - })) - .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/"))) - .andNest(path("/actor"), route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class) - .doOnNext(actors::add) - .then(ok().build()))) - .filter((request, next) -> { - System.out.println("Before handler invocation: " + request.path()); - return next.handle(request); - }); - - } - -} diff --git a/spring-5/src/main/java/com/baeldung/web/reactive/Task.java b/spring-5/src/main/java/com/baeldung/jupiter/Task.java similarity index 93% rename from spring-5/src/main/java/com/baeldung/web/reactive/Task.java rename to spring-5/src/main/java/com/baeldung/jupiter/Task.java index 725fd931e1..2ea977712c 100644 --- a/spring-5/src/main/java/com/baeldung/web/reactive/Task.java +++ b/spring-5/src/main/java/com/baeldung/jupiter/Task.java @@ -1,4 +1,4 @@ -package com.baeldung.web.reactive; +package com.baeldung.jupiter; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/spring-5/src/main/java/com/baeldung/jupiter/TestConfig.java b/spring-5/src/main/java/com/baeldung/jupiter/TestConfig.java index a29f77c5df..ee866007ea 100644 --- a/spring-5/src/main/java/com/baeldung/jupiter/TestConfig.java +++ b/spring-5/src/main/java/com/baeldung/jupiter/TestConfig.java @@ -1,6 +1,5 @@ package com.baeldung.jupiter; -import com.baeldung.web.reactive.Task; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; diff --git a/spring-5/src/main/java/com/baeldung/security/GreetController.java b/spring-5/src/main/java/com/baeldung/security/GreetController.java deleted file mode 100644 index 6b69e3bc9b..0000000000 --- a/spring-5/src/main/java/com/baeldung/security/GreetController.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.security; - -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; -import reactor.core.publisher.Mono; - -import java.security.Principal; - -@RestController -public class GreetController { - - private GreetService greetService; - - public GreetController(GreetService greetService) { - this.greetService = greetService; - } - - @GetMapping("/") - public Mono greet(Mono principal) { - return principal - .map(Principal::getName) - .map(name -> String.format("Hello, %s", name)); - } - - @GetMapping("/admin") - public Mono greetAdmin(Mono principal) { - return principal - .map(Principal::getName) - .map(name -> String.format("Admin access: %s", name)); - } - - @GetMapping("/greetService") - public Mono greetService() { - return greetService.greet(); - } - -} diff --git a/spring-5/src/main/java/com/baeldung/security/GreetService.java b/spring-5/src/main/java/com/baeldung/security/GreetService.java deleted file mode 100644 index 7622b360be..0000000000 --- a/spring-5/src/main/java/com/baeldung/security/GreetService.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.security; - -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Service; -import reactor.core.publisher.Mono; - -@Service -public class GreetService { - - @PreAuthorize("hasRole('ADMIN')") - public Mono greet() { - return Mono.just("Hello from service!"); - } - -} diff --git a/spring-5/src/main/java/com/baeldung/security/SecurityConfig.java b/spring-5/src/main/java/com/baeldung/security/SecurityConfig.java deleted file mode 100644 index a9e44a2eee..0000000000 --- a/spring-5/src/main/java/com/baeldung/security/SecurityConfig.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.security; - -import org.springframework.context.annotation.Bean; -import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity; -import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; -import org.springframework.security.config.web.server.ServerHttpSecurity; -import org.springframework.security.core.userdetails.MapReactiveUserDetailsService; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.web.server.SecurityWebFilterChain; - -@EnableWebFluxSecurity -@EnableReactiveMethodSecurity -public class SecurityConfig { - - @Bean - public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) { - return http.authorizeExchange() - .pathMatchers("/admin").hasAuthority("ROLE_ADMIN") - .anyExchange().authenticated() - .and().formLogin() - .and().build(); - } - - @Bean - public MapReactiveUserDetailsService userDetailsService() { - UserDetails user = User.withDefaultPasswordEncoder() - .username("user") - .password("password") - .roles("USER") - .build(); - - UserDetails admin = User.withDefaultPasswordEncoder() - .username("admin") - .password("password") - .roles("ADMIN") - .build(); - - return new MapReactiveUserDetailsService(user, admin); - } - -} diff --git a/spring-5/src/main/java/com/baeldung/web/reactive/client/WebClientController.java b/spring-5/src/main/java/com/baeldung/web/reactive/client/WebClientController.java deleted file mode 100644 index a719259328..0000000000 --- a/spring-5/src/main/java/com/baeldung/web/reactive/client/WebClientController.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.baeldung.web.reactive.client; - -import org.reactivestreams.Publisher; -import org.reactivestreams.Subscriber; -import org.springframework.http.*; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.ResponseStatus; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.reactive.function.BodyInserter; -import org.springframework.web.reactive.function.BodyInserters; -import org.springframework.web.reactive.function.client.WebClient; -import reactor.core.publisher.Mono; - -import java.net.URI; -import java.nio.charset.Charset; -import java.time.ZonedDateTime; -import java.util.Collections; - -@RestController -public class WebClientController { - - @ResponseStatus(HttpStatus.OK) - @GetMapping("/resource") - public void getResource() { - } - - public void demonstrateWebClient() { - // request - WebClient.UriSpec request1 = createWebClientWithServerURLAndDefaultValues().method(HttpMethod.POST); - WebClient.UriSpec request2 = createWebClientWithServerURLAndDefaultValues().post(); - - // request body specifications - WebClient.RequestBodySpec uri1 = createWebClientWithServerURLAndDefaultValues().method(HttpMethod.POST) - .uri("/resource"); - WebClient.RequestBodySpec uri2 = createWebClientWithServerURLAndDefaultValues().post() - .uri(URI.create("/resource")); - - // request header specification - WebClient.RequestHeadersSpec requestSpec1 = uri1.body(BodyInserters.fromPublisher(Mono.just("data"), String.class)); - WebClient.RequestHeadersSpec requestSpec2 = uri2.body(BodyInserters.fromObject("data")); - - // inserters - BodyInserter, ReactiveHttpOutputMessage> inserter1 = BodyInserters - .fromPublisher(Subscriber::onComplete, String.class); - - LinkedMultiValueMap map = new LinkedMultiValueMap<>(); - map.add("key1", "value1"); - map.add("key2", "value2"); - - // BodyInserter, ClientHttpRequest> inserter2 = BodyInserters.fromMultipartData(map); - BodyInserter inserter3 = BodyInserters.fromObject("body"); - - // responses - WebClient.ResponseSpec response1 = uri1.body(inserter3) - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) - .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) - .acceptCharset(Charset.forName("UTF-8")) - .ifNoneMatch("*") - .ifModifiedSince(ZonedDateTime.now()) - .retrieve(); - WebClient.ResponseSpec response2 = requestSpec2.retrieve(); - - } - - private WebClient createWebClient() { - return WebClient.create(); - } - - private WebClient createWebClientWithServerURL() { - return WebClient.create("http://localhost:8081"); - } - - private WebClient createWebClientWithServerURLAndDefaultValues() { - return WebClient.builder() - .baseUrl("http://localhost:8081") - .defaultCookie("cookieKey", "cookieValue") - .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) - .defaultUriVariables(Collections.singletonMap("url", "http://localhost:8080")) - .build(); - } - -} diff --git a/spring-5/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java b/spring-5/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java deleted file mode 100644 index a7b951b930..0000000000 --- a/spring-5/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java +++ /dev/null @@ -1,141 +0,0 @@ -package com.baeldung.functional; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.springframework.boot.web.server.WebServer; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; -import org.springframework.http.MediaType; -import org.springframework.test.web.reactive.server.WebTestClient; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; -import org.springframework.web.reactive.function.BodyInserters; - -import static org.springframework.web.reactive.function.BodyInserters.fromObject; -import static org.springframework.web.reactive.function.BodyInserters.fromResource; - -public class FunctionalWebApplicationIntegrationTest { - - private static WebTestClient client; - private static WebServer server; - - @BeforeClass - public static void setup() throws Exception { - server = new FunctionalWebApplication().start(); - client = WebTestClient.bindToServer() - .baseUrl("http://localhost:" + server.getPort()) - .build(); - } - - @AfterClass - public static void destroy() { - server.stop(); - } - - @Test - public void givenRouter_whenGetTest_thenGotHelloWorld() throws Exception { - client.get() - .uri("/test") - .exchange() - .expectStatus() - .isOk() - .expectBody(String.class) - .isEqualTo("helloworld"); - } - - @Test - public void givenIndexFilter_whenRequestRoot_thenRewrittenToTest() throws Exception { - client.get() - .uri("/") - .exchange() - .expectStatus() - .isOk() - .expectBody(String.class) - .isEqualTo("helloworld"); - } - - @Test - public void givenLoginForm_whenPostValidToken_thenSuccess() throws Exception { - MultiValueMap formData = new LinkedMultiValueMap<>(1); - formData.add("user", "baeldung"); - formData.add("token", "you_know_what_to_do"); - - client.post() - .uri("/login") - .contentType(MediaType.APPLICATION_FORM_URLENCODED) - .body(BodyInserters.fromFormData(formData)) - .exchange() - .expectStatus() - .isOk() - .expectBody(String.class) - .isEqualTo("welcome back!"); - } - - @Test - public void givenLoginForm_whenRequestWithInvalidToken_thenFail() throws Exception { - MultiValueMap formData = new LinkedMultiValueMap<>(2); - formData.add("user", "baeldung"); - formData.add("token", "try_again"); - - client.post() - .uri("/login") - .contentType(MediaType.APPLICATION_FORM_URLENCODED) - .body(BodyInserters.fromFormData(formData)) - .exchange() - .expectStatus() - .isBadRequest(); - } - - @Test - public void givenUploadForm_whenRequestWithMultipartData_thenSuccess() throws Exception { - Resource resource = new ClassPathResource("/baeldung-weekly.png"); - client.post() - .uri("/upload") - .contentType(MediaType.MULTIPART_FORM_DATA) - .body(fromResource(resource)) - .exchange() - .expectStatus() - .isOk() - .expectBody(String.class) - .isEqualTo(String.valueOf(resource.contentLength())); - } - - @Test - public void givenActors_whenAddActor_thenAdded() throws Exception { - client.get() - .uri("/actor") - .exchange() - .expectStatus() - .isOk() - .expectBodyList(Actor.class) - .hasSize(2); - - client.post() - .uri("/actor") - .body(fromObject(new Actor("Clint", "Eastwood"))) - .exchange() - .expectStatus() - .isOk(); - - client.get() - .uri("/actor") - .exchange() - .expectStatus() - .isOk() - .expectBodyList(Actor.class) - .hasSize(3); - } - - @Test - public void givenResources_whenAccess_thenGot() throws Exception { - client.get() - .uri("/files/hello.txt") - .exchange() - .expectStatus() - .isOk() - .expectBody(String.class) - .isEqualTo("hello"); - } - -} diff --git a/spring-5/src/test/java/com/baeldung/jdbc/autogenkey/GetAutoGenKeyByJDBC.java b/spring-5/src/test/java/com/baeldung/jdbc/autogenkey/GetAutoGenKeyByJDBCIntTest.java similarity index 95% rename from spring-5/src/test/java/com/baeldung/jdbc/autogenkey/GetAutoGenKeyByJDBC.java rename to spring-5/src/test/java/com/baeldung/jdbc/autogenkey/GetAutoGenKeyByJDBCIntTest.java index 45012a95aa..14d2fb736b 100644 --- a/spring-5/src/test/java/com/baeldung/jdbc/autogenkey/GetAutoGenKeyByJDBC.java +++ b/spring-5/src/test/java/com/baeldung/jdbc/autogenkey/GetAutoGenKeyByJDBCIntTest.java @@ -1,55 +1,55 @@ -package com.baeldung.jdbc.autogenkey; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.jdbc.autogenkey.repository.MessageRepositoryJDBCTemplate; -import com.baeldung.jdbc.autogenkey.repository.MessageRepositorySimpleJDBCInsert; - -@RunWith(SpringRunner.class) -@Ignore -public class GetAutoGenKeyByJDBC { - - @Configuration - @EnableAutoConfiguration - @PropertySource("classpath:autogenkey-db.properties") - @ComponentScan(basePackages = { "com.baeldung.jdbc.autogenkey.repository" }) - public static class SpringConfig { - - } - - @Autowired - MessageRepositorySimpleJDBCInsert messageRepositorySimpleJDBCInsert; - - @Autowired - MessageRepositoryJDBCTemplate messageRepositoryJDBCTemplate; - - final String MESSAGE_CONTENT = "Test"; - - @Test - public void insertJDBC_whenLoadMessageByKey_thenGetTheSameMessage() { - long key = messageRepositoryJDBCTemplate.insert(MESSAGE_CONTENT); - String loadedMessage = messageRepositoryJDBCTemplate.getMessageById(key); - - assertEquals(MESSAGE_CONTENT, loadedMessage); - - } - - @Test - public void insertSimpleInsert_whenLoadMessageKey_thenGetTheSameMessage() { - long key = messageRepositorySimpleJDBCInsert.insert(MESSAGE_CONTENT); - String loadedMessage = messageRepositoryJDBCTemplate.getMessageById(key); - - assertEquals(MESSAGE_CONTENT, loadedMessage); - } - -} +package com.baeldung.jdbc.autogenkey; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.jdbc.autogenkey.repository.MessageRepositoryJDBCTemplate; +import com.baeldung.jdbc.autogenkey.repository.MessageRepositorySimpleJDBCInsert; + +@RunWith(SpringRunner.class) +@Ignore +public class GetAutoGenKeyByJDBCIntTest { + + @Configuration + @EnableAutoConfiguration + @PropertySource("classpath:autogenkey-db.properties") + @ComponentScan(basePackages = { "com.baeldung.jdbc.autogenkey.repository" }) + public static class SpringConfig { + + } + + @Autowired + MessageRepositorySimpleJDBCInsert messageRepositorySimpleJDBCInsert; + + @Autowired + MessageRepositoryJDBCTemplate messageRepositoryJDBCTemplate; + + final String MESSAGE_CONTENT = "Test"; + + @Test + public void insertJDBC_whenLoadMessageByKey_thenGetTheSameMessage() { + long key = messageRepositoryJDBCTemplate.insert(MESSAGE_CONTENT); + String loadedMessage = messageRepositoryJDBCTemplate.getMessageById(key); + + assertEquals(MESSAGE_CONTENT, loadedMessage); + + } + + @Test + public void insertSimpleInsert_whenLoadMessageKey_thenGetTheSameMessage() { + long key = messageRepositorySimpleJDBCInsert.insert(MESSAGE_CONTENT); + String loadedMessage = messageRepositoryJDBCTemplate.getMessageById(key); + + assertEquals(MESSAGE_CONTENT, loadedMessage); + } + +} diff --git a/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5ComposedAnnotationIntegrationTest.java b/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5ComposedAnnotationIntegrationTest.java index 42d27b90f4..b9bb470cbd 100644 --- a/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5ComposedAnnotationIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5ComposedAnnotationIntegrationTest.java @@ -1,6 +1,5 @@ package com.baeldung.jupiter; -import com.baeldung.web.reactive.Task; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5IntegrationTest.java b/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5IntegrationTest.java index 0f00a85832..484b366132 100644 --- a/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5IntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5IntegrationTest.java @@ -1,6 +1,5 @@ package com.baeldung.jupiter; -import com.baeldung.web.reactive.Task; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-5/src/test/java/com/baeldung/jupiter/Spring5ReactiveServerClientIntegrationTest.java b/spring-5/src/test/java/com/baeldung/jupiter/Spring5ReactiveServerClientIntegrationTest.java deleted file mode 100644 index bbd852d625..0000000000 --- a/spring-5/src/test/java/com/baeldung/jupiter/Spring5ReactiveServerClientIntegrationTest.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.baeldung.jupiter; - -import com.baeldung.web.reactive.Task; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.springframework.http.server.reactive.HttpHandler; -import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; -import org.springframework.web.reactive.function.server.RouterFunction; -import org.springframework.web.reactive.function.server.RouterFunctions; -import org.springframework.web.reactive.function.server.ServerResponse; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import reactor.ipc.netty.NettyContext; -import reactor.ipc.netty.http.server.HttpServer; - -import java.time.Duration; - -import static org.springframework.web.reactive.function.server.RequestPredicates.GET; -import static org.springframework.web.reactive.function.server.RequestPredicates.POST; - -public class Spring5ReactiveServerClientIntegrationTest { - - private static NettyContext nettyContext; - - @BeforeAll - public static void setUp() throws Exception { - HttpServer server = HttpServer.create("localhost", 8080); - RouterFunction route = RouterFunctions.route(POST("/task/process"), request -> ServerResponse.ok() - .body(request.bodyToFlux(Task.class) - .map(ll -> new Task("TaskName", 1)), Task.class)) - .and(RouterFunctions.route(GET("/task"), request -> ServerResponse.ok() - .body(Mono.just("server is alive"), String.class))); - HttpHandler httpHandler = RouterFunctions.toHttpHandler(route); - ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler); - nettyContext = server.newHandler(adapter) - .block(); - } - - @AfterAll - public static void shutDown() { - nettyContext.dispose(); - } - - // @Test - // public void givenCheckTask_whenServerHandle_thenServerResponseALiveString() throws Exception { - // WebClient client = WebClient.create("http://localhost:8080"); - // Mono result = client - // .get() - // .uri("/task") - // .exchange() - // .then(response -> response.bodyToMono(String.class)); - // - // assertThat(result.block()).isInstanceOf(String.class); - // } - - // @Test - // public void givenThreeTasks_whenServerHandleTheTasks_thenServerResponseATask() throws Exception { - // URI uri = URI.create("http://localhost:8080/task/process"); - // ExchangeFunction exchange = ExchangeFunctions.create(new ReactorClientHttpConnector()); - // ClientRequest request = ClientRequest - // .method(HttpMethod.POST, uri) - // .body(BodyInserters.fromPublisher(getLatLngs(), Task.class)) - // .build(); - // - // Flux taskResponse = exchange - // .exchange(request) - // .flatMap(response -> response.bodyToFlux(Task.class)); - // - // assertThat(taskResponse.blockFirst()).isInstanceOf(Task.class); - // } - - // @Test - // public void givenCheckTask_whenServerHandle_thenOragicServerResponseALiveString() throws Exception { - // URI uri = URI.create("http://localhost:8080/task"); - // ExchangeFunction exchange = ExchangeFunctions.create(new ReactorClientHttpConnector()); - // ClientRequest request = ClientRequest - // .method(HttpMethod.GET, uri) - // .body(BodyInserters.fromPublisher(getLatLngs(), Task.class)) - // .build(); - // - // Flux taskResponse = exchange - // .exchange(request) - // .flatMap(response -> response.bodyToFlux(String.class)); - // - // assertThat(taskResponse.blockFirst()).isInstanceOf(String.class); - // } - - private static Flux getLatLngs() { - return Flux.range(0, 3) - .zipWith(Flux.interval(Duration.ofSeconds(1))) - .map(x -> new Task("taskname", 1)) - .doOnNext(ll -> System.out.println("Produced: {}" + ll)); - } -} diff --git a/spring-5/src/test/java/com/baeldung/security/SecurityIntegrationTest.java b/spring-5/src/test/java/com/baeldung/security/SecurityIntegrationTest.java deleted file mode 100644 index 1f8bb549c7..0000000000 --- a/spring-5/src/test/java/com/baeldung/security/SecurityIntegrationTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.security; - -import com.baeldung.SpringSecurity5Application; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.reactive.server.WebTestClient; - -@RunWith(SpringRunner.class) -@ContextConfiguration(classes = SpringSecurity5Application.class) -public class SecurityIntegrationTest { - - @Autowired - ApplicationContext context; - - private WebTestClient rest; - - @Before - public void setup() { - this.rest = WebTestClient.bindToApplicationContext(this.context).configureClient().build(); - } - - @Test - public void whenNoCredentials_thenRedirectToLogin() { - this.rest.get().uri("/").exchange().expectStatus().is3xxRedirection(); - } - - @Test - @Ignore - @WithMockUser - public void whenHasCredentials_thenSeesGreeting() { - this.rest.get().uri("/").exchange().expectStatus().isOk().expectBody(String.class).isEqualTo("Hello, user"); - } -} diff --git a/spring-5/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java b/spring-5/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java deleted file mode 100644 index f9472452ba..0000000000 --- a/spring-5/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.baeldung.web.client; - -import com.baeldung.Spring5Application; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.reactive.server.WebTestClient; -import org.springframework.web.reactive.function.server.RequestPredicates; -import org.springframework.web.reactive.function.server.RouterFunction; -import org.springframework.web.reactive.function.server.RouterFunctions; -import org.springframework.web.reactive.function.server.ServerResponse; -import org.springframework.web.server.WebHandler; -import reactor.core.publisher.Mono; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Spring5Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@EnableJpaRepositories("com.baeldung.persistence") -public class WebTestClientIntegrationTest { - - @LocalServerPort - private int port; - - private final RouterFunction ROUTER_FUNCTION = RouterFunctions.route(RequestPredicates.GET("/resource"), request -> ServerResponse.ok() - .build()); - private final WebHandler WEB_HANDLER = exchange -> Mono.empty(); - - @Test - public void testWebTestClientWithServerWebHandler() { - WebTestClient.bindToWebHandler(WEB_HANDLER) - .build(); - } - - @Test - public void testWebTestClientWithRouterFunction() { - WebTestClient.bindToRouterFunction(ROUTER_FUNCTION) - .build() - .get() - .uri("/resource") - .exchange() - .expectStatus() - .isOk() - .expectBody() - .isEmpty(); - } - - @Test - public void testWebTestClientWithServerURL() { - WebTestClient.bindToServer() - .baseUrl("http://localhost:" + port) - .build() - .get() - .uri("/resource") - .exchange() - .expectStatus() - .is3xxRedirection() - .expectBody(); - } - -} From fa954ebba7140068a2bedd3b9017fcdea3be163c Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Mon, 23 Jul 2018 23:31:28 +0300 Subject: [PATCH 02/22] move to reactive, extract mongodb ex --- spring-5-mongodb/.gitignore | 12 ++ spring-5-mongodb/README.md | 20 +++ spring-5-mongodb/pom.xml | 157 ++++++++++++++++++ .../reactive/Spring5ReactiveApplication.java | 25 +++ .../com/baeldung/reactive/model/Account.java | 0 .../repository/AccountCrudRepository.java | 0 .../repository/AccountMongoRepository.java | 0 .../repository/AccountRxJavaRepository.java | 0 .../template/AccountTemplateOperations.java | 0 .../src/main/resources/application.properties | 5 + .../src/main/webapp/WEB-INF/web.xml | 21 +++ .../AccountCrudRepositoryIntegrationTest.java | 0 ...AccountMongoRepositoryIntegrationTest.java | 0 ...ccountRxJavaRepositoryIntegrationTest.java | 0 ...ountTemplateOperationsIntegrationTest.java | 0 spring-5-reactive/pom.xml | 9 - .../java/com/baeldung/functional/Actor.java | 23 +++ .../com/baeldung/functional/FormHandler.java | 41 +++++ .../FunctionalSpringBootApplication.java | 87 ++++++++++ .../functional/FunctionalWebApplication.java | 80 +++++++++ .../functional/IndexRewriteFilter.java | 25 +++ .../com/baeldung/functional/MyService.java | 11 ++ .../com/baeldung/functional/RootServlet.java | 82 +++++++++ .../reactive/Spring5ReactiveApplication.java | 10 -- .../reactive/SpringSecurity5Application.java | 34 ++++ .../reactive/actuator/WebSecurityConfig.java | 28 ++++ .../CorsOnAnnotatedElementsApplication.java | 10 +- .../FurtherCorsConfigsController.java | 4 +- .../controllers/RegularRestController.java | 4 +- .../reactive/security/GreetController.java | 37 +++++ .../reactive/security/GreetService.java | 15 ++ .../reactive/security/SecurityConfig.java | 42 +++++ .../java/com/baeldung/web/reactive/Task.java | 28 ++++ .../reactive/client/WebClientController.java | 83 +++++++++ .../{reactive => }/websocket/Event.java | 2 +- .../ReactiveJavaClientWebSocket.java | 2 +- .../ReactiveWebSocketApplication.java | 2 +- .../ReactiveWebSocketConfiguration.java | 2 +- .../websocket/ReactiveWebSocketHandler.java | 2 +- ...nctionalWebApplicationIntegrationTest.java | 141 ++++++++++++++++ ...g5ReactiveServerClientIntegrationTest.java | 96 +++++++++++ ...=> EmployeeControllerIntegrationTest.java} | 6 +- .../security/SecurityIntegrationTest.java | 40 +++++ .../client/WebTestClientIntegrationTest.java | 60 +++++++ 44 files changed, 1207 insertions(+), 39 deletions(-) create mode 100644 spring-5-mongodb/.gitignore create mode 100644 spring-5-mongodb/README.md create mode 100644 spring-5-mongodb/pom.xml create mode 100644 spring-5-mongodb/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java rename {spring-5-reactive => spring-5-mongodb}/src/main/java/com/baeldung/reactive/model/Account.java (100%) rename {spring-5-reactive => spring-5-mongodb}/src/main/java/com/baeldung/reactive/repository/AccountCrudRepository.java (100%) rename {spring-5-reactive => spring-5-mongodb}/src/main/java/com/baeldung/reactive/repository/AccountMongoRepository.java (100%) rename {spring-5-reactive => spring-5-mongodb}/src/main/java/com/baeldung/reactive/repository/AccountRxJavaRepository.java (100%) rename {spring-5-reactive => spring-5-mongodb}/src/main/java/com/baeldung/reactive/template/AccountTemplateOperations.java (100%) create mode 100644 spring-5-mongodb/src/main/resources/application.properties create mode 100644 spring-5-mongodb/src/main/webapp/WEB-INF/web.xml rename {spring-5-reactive => spring-5-mongodb}/src/test/java/com/baeldung/reactive/repository/AccountCrudRepositoryIntegrationTest.java (100%) rename {spring-5-reactive => spring-5-mongodb}/src/test/java/com/baeldung/reactive/repository/AccountMongoRepositoryIntegrationTest.java (100%) rename {spring-5-reactive => spring-5-mongodb}/src/test/java/com/baeldung/reactive/repository/AccountRxJavaRepositoryIntegrationTest.java (100%) rename {spring-5-reactive => spring-5-mongodb}/src/test/java/com/baeldung/reactive/template/AccountTemplateOperationsIntegrationTest.java (100%) create mode 100644 spring-5-reactive/src/main/java/com/baeldung/functional/Actor.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/functional/FormHandler.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalWebApplication.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/functional/IndexRewriteFilter.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/functional/MyService.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/functional/RootServlet.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/reactive/SpringSecurity5Application.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/WebSecurityConfig.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/reactive/security/GreetController.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/reactive/security/GreetService.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/reactive/security/SecurityConfig.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/web/reactive/Task.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/WebClientController.java rename spring-5-reactive/src/main/java/com/baeldung/{reactive => }/websocket/Event.java (79%) rename spring-5-reactive/src/main/java/com/baeldung/{reactive => }/websocket/ReactiveJavaClientWebSocket.java (95%) rename spring-5-reactive/src/main/java/com/baeldung/{reactive => }/websocket/ReactiveWebSocketApplication.java (88%) rename spring-5-reactive/src/main/java/com/baeldung/{reactive => }/websocket/ReactiveWebSocketConfiguration.java (96%) rename spring-5-reactive/src/main/java/com/baeldung/{reactive => }/websocket/ReactiveWebSocketHandler.java (97%) create mode 100644 spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java create mode 100644 spring-5-reactive/src/test/java/com/baeldung/reactive/Spring5ReactiveServerClientIntegrationTest.java rename spring-5-reactive/src/test/java/com/baeldung/reactive/webflux/{EmployeeControllerUnitTest.java => EmployeeControllerIntegrationTest.java} (90%) create mode 100644 spring-5-reactive/src/test/java/com/baeldung/security/SecurityIntegrationTest.java create mode 100644 spring-5-reactive/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java diff --git a/spring-5-mongodb/.gitignore b/spring-5-mongodb/.gitignore new file mode 100644 index 0000000000..dec013dfa4 --- /dev/null +++ b/spring-5-mongodb/.gitignore @@ -0,0 +1,12 @@ +#folders# +.idea +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/spring-5-mongodb/README.md b/spring-5-mongodb/README.md new file mode 100644 index 0000000000..df96d933ba --- /dev/null +++ b/spring-5-mongodb/README.md @@ -0,0 +1,20 @@ +## Spring REST Example Project + +### The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + +### Relevant Articles + +- [Concurrent Test Execution in Spring 5](http://www.baeldung.com/spring-5-concurrent-tests) +- [Introduction to the Functional Web Framework in Spring 5](http://www.baeldung.com/spring-5-functional-web) +- [Exploring the Spring 5 MVC URL Matching Improvements](http://www.baeldung.com/spring-5-mvc-url-matching) +- [Spring 5 WebClient](http://www.baeldung.com/spring-5-webclient) +- [Spring 5 Functional Bean Registration](http://www.baeldung.com/spring-5-functional-beans) +- [The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5](http://www.baeldung.com/spring-5-junit-config) +- [Spring Security 5 for Reactive Applications](http://www.baeldung.com/spring-security-5-reactive) +- [Spring 5 Testing with @EnabledIf Annotation](https://github.com/eugenp/tutorials/tree/master/spring-5) +- [Reactive WebSockets with Spring 5](http://www.baeldung.com/spring-5-reactive-websockets) +- [Spring Boot Actuator](http://www.baeldung.com/spring-boot-actuators) +- [Spring Webflux Filters](http://www.baeldung.com/spring-webflux-filters) +- [Reactive Flow with MongoDB, Kotlin, and Spring WebFlux](http://www.baeldung.com/kotlin-mongodb-spring-webflux) +- [Spring Data Reactive Repositories with MongoDB](http://www.baeldung.com/spring-data-mongodb-reactive) diff --git a/spring-5-mongodb/pom.xml b/spring-5-mongodb/pom.xml new file mode 100644 index 0000000000..2db41ba6c7 --- /dev/null +++ b/spring-5-mongodb/pom.xml @@ -0,0 +1,157 @@ + + + 4.0.0 + + com.baeldung + spring-5-mongodb + 0.0.1-SNAPSHOT + jar + spring-5-mongodb + spring 5 mongodb sample project + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-tomcat + + + org.springframework.boot + spring-boot-starter-webflux + + + org.projectreactor + reactor-spring + ${reactor-spring.version} + + + + org.apache.commons + commons-lang3 + + + + + org.springframework + spring-test + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + test + + + org.projectlombok + lombok + compile + + + + org.junit.jupiter + junit-jupiter-api + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.platform + junit-platform-surefire-provider + ${junit.platform.version} + test + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + org.apache.commons + commons-lang3 + + + + org.springframework.boot + spring-boot-starter-data-mongodb-reactive + + + de.flapdoodle.embed + de.flapdoodle.embed.mongo + test + + + io.reactivex.rxjava2 + rxjava + ${rxjava-version} + + + io.projectreactor + reactor-test + ${project-reactor-test} + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.reactive.Spring5ReactiveApplication + JAR + + + + + org.apache.maven.plugins + maven-surefire-plugin + + 3 + true + methods + true + + **/*IntegrationTest.java + **/*IntTest.java + **/*LiveTest.java + + + + + + + + 1.0.0 + 5.0.2 + 2.20 + 1.0.1.RELEASE + 2.1.12 + 4.1 + 3.1.6.RELEASE + 1.1.3 + 1.0 + 1.0 + + + diff --git a/spring-5-mongodb/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java b/spring-5-mongodb/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java new file mode 100644 index 0000000000..e96767145e --- /dev/null +++ b/spring-5-mongodb/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java @@ -0,0 +1,25 @@ +package com.baeldung.reactive; + +import com.mongodb.reactivestreams.client.MongoClient; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.data.mongodb.core.ReactiveMongoTemplate; + +@SpringBootApplication +public class Spring5ReactiveApplication{ + + public static void main(String[] args) { + SpringApplication.run(Spring5ReactiveApplication.class, args); + } + + @Autowired + MongoClient mongoClient; + + @Bean + public ReactiveMongoTemplate reactiveMongoTemplate() { + return new ReactiveMongoTemplate(mongoClient, "test"); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/model/Account.java b/spring-5-mongodb/src/main/java/com/baeldung/reactive/model/Account.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/model/Account.java rename to spring-5-mongodb/src/main/java/com/baeldung/reactive/model/Account.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountCrudRepository.java b/spring-5-mongodb/src/main/java/com/baeldung/reactive/repository/AccountCrudRepository.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountCrudRepository.java rename to spring-5-mongodb/src/main/java/com/baeldung/reactive/repository/AccountCrudRepository.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountMongoRepository.java b/spring-5-mongodb/src/main/java/com/baeldung/reactive/repository/AccountMongoRepository.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountMongoRepository.java rename to spring-5-mongodb/src/main/java/com/baeldung/reactive/repository/AccountMongoRepository.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountRxJavaRepository.java b/spring-5-mongodb/src/main/java/com/baeldung/reactive/repository/AccountRxJavaRepository.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountRxJavaRepository.java rename to spring-5-mongodb/src/main/java/com/baeldung/reactive/repository/AccountRxJavaRepository.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/template/AccountTemplateOperations.java b/spring-5-mongodb/src/main/java/com/baeldung/reactive/template/AccountTemplateOperations.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/template/AccountTemplateOperations.java rename to spring-5-mongodb/src/main/java/com/baeldung/reactive/template/AccountTemplateOperations.java diff --git a/spring-5-mongodb/src/main/resources/application.properties b/spring-5-mongodb/src/main/resources/application.properties new file mode 100644 index 0000000000..234834b894 --- /dev/null +++ b/spring-5-mongodb/src/main/resources/application.properties @@ -0,0 +1,5 @@ +logging.level.root=INFO + +management.endpoints.web.exposure.include.=* + +info.app.name=Spring Boot 2 actuator Application diff --git a/spring-5-mongodb/src/main/webapp/WEB-INF/web.xml b/spring-5-mongodb/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..bfcf43dad2 --- /dev/null +++ b/spring-5-mongodb/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,21 @@ + + + + Spring Functional Application + + + functional + com.baeldung.functional.RootServlet + 1 + true + + + functional + / + + + + \ No newline at end of file diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountCrudRepositoryIntegrationTest.java b/spring-5-mongodb/src/test/java/com/baeldung/reactive/repository/AccountCrudRepositoryIntegrationTest.java similarity index 100% rename from spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountCrudRepositoryIntegrationTest.java rename to spring-5-mongodb/src/test/java/com/baeldung/reactive/repository/AccountCrudRepositoryIntegrationTest.java diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountMongoRepositoryIntegrationTest.java b/spring-5-mongodb/src/test/java/com/baeldung/reactive/repository/AccountMongoRepositoryIntegrationTest.java similarity index 100% rename from spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountMongoRepositoryIntegrationTest.java rename to spring-5-mongodb/src/test/java/com/baeldung/reactive/repository/AccountMongoRepositoryIntegrationTest.java diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountRxJavaRepositoryIntegrationTest.java b/spring-5-mongodb/src/test/java/com/baeldung/reactive/repository/AccountRxJavaRepositoryIntegrationTest.java similarity index 100% rename from spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountRxJavaRepositoryIntegrationTest.java rename to spring-5-mongodb/src/test/java/com/baeldung/reactive/repository/AccountRxJavaRepositoryIntegrationTest.java diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/template/AccountTemplateOperationsIntegrationTest.java b/spring-5-mongodb/src/test/java/com/baeldung/reactive/template/AccountTemplateOperationsIntegrationTest.java similarity index 100% rename from spring-5-reactive/src/test/java/com/baeldung/reactive/template/AccountTemplateOperationsIntegrationTest.java rename to spring-5-mongodb/src/test/java/com/baeldung/reactive/template/AccountTemplateOperationsIntegrationTest.java diff --git a/spring-5-reactive/pom.xml b/spring-5-reactive/pom.xml index 33fcad4e1d..acc82be0d1 100644 --- a/spring-5-reactive/pom.xml +++ b/spring-5-reactive/pom.xml @@ -127,15 +127,6 @@ commons-lang3 - - org.springframework.boot - spring-boot-starter-data-mongodb-reactive - - - de.flapdoodle.embed - de.flapdoodle.embed.mongo - test - io.reactivex.rxjava2 rxjava diff --git a/spring-5-reactive/src/main/java/com/baeldung/functional/Actor.java b/spring-5-reactive/src/main/java/com/baeldung/functional/Actor.java new file mode 100644 index 0000000000..23c88b89e1 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/functional/Actor.java @@ -0,0 +1,23 @@ +package com.baeldung.functional; + +class Actor { + private String firstname; + private String lastname; + + public Actor() { + } + + public Actor(String firstname, String lastname) { + this.firstname = firstname; + this.lastname = lastname; + } + + public String getFirstname() { + return firstname; + } + + public String getLastname() { + return lastname; + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/functional/FormHandler.java b/spring-5-reactive/src/main/java/com/baeldung/functional/FormHandler.java new file mode 100644 index 0000000000..05069735bb --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/functional/FormHandler.java @@ -0,0 +1,41 @@ +package com.baeldung.functional; + +import org.springframework.core.io.buffer.DataBuffer; +import org.springframework.util.MultiValueMap; +import org.springframework.web.reactive.function.server.ServerRequest; +import org.springframework.web.reactive.function.server.ServerResponse; +import reactor.core.publisher.Mono; + +import java.util.List; +import java.util.concurrent.atomic.AtomicLong; + +import static org.springframework.web.reactive.function.BodyExtractors.toDataBuffers; +import static org.springframework.web.reactive.function.BodyExtractors.toFormData; +import static org.springframework.web.reactive.function.BodyInserters.fromObject; +import static org.springframework.web.reactive.function.server.ServerResponse.ok; + +public class FormHandler { + + Mono handleLogin(ServerRequest request) { + return request.body(toFormData()) + .map(MultiValueMap::toSingleValueMap) + .filter(formData -> "baeldung".equals(formData.get("user"))) + .filter(formData -> "you_know_what_to_do".equals(formData.get("token"))) + .flatMap(formData -> ok().body(Mono.just("welcome back!"), String.class)) + .switchIfEmpty(ServerResponse.badRequest() + .build()); + } + + Mono handleUpload(ServerRequest request) { + return request.body(toDataBuffers()) + .collectList() + .flatMap(dataBuffers -> ok().body(fromObject(extractData(dataBuffers).toString()))); + } + + private AtomicLong extractData(List dataBuffers) { + AtomicLong atomicLong = new AtomicLong(0); + dataBuffers.forEach(d -> atomicLong.addAndGet(d.asByteBuffer() + .array().length)); + return atomicLong; + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java b/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java new file mode 100644 index 0000000000..402b607b19 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java @@ -0,0 +1,87 @@ +package com.baeldung.functional; + +import static org.springframework.web.reactive.function.BodyInserters.fromObject; +import static org.springframework.web.reactive.function.server.RequestPredicates.GET; +import static org.springframework.web.reactive.function.server.RequestPredicates.POST; +import static org.springframework.web.reactive.function.server.RequestPredicates.path; +import static org.springframework.web.reactive.function.server.RouterFunctions.route; +import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler; +import static org.springframework.web.reactive.function.server.ServerResponse.ok; + +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.servlet.ServletRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.server.reactive.HttpHandler; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.web.reactive.function.server.RouterFunction; +import org.springframework.web.reactive.function.server.RouterFunctions; +import org.springframework.web.reactive.function.server.ServerResponse; +import org.springframework.web.server.WebHandler; +import org.springframework.web.server.adapter.WebHttpHandlerBuilder; + +import reactor.core.publisher.Flux; + +@SpringBootApplication +@ComponentScan(basePackages = { "com.baeldung.functional" }) +public class FunctionalSpringBootApplication { + + private static final Actor BRAD_PITT = new Actor("Brad", "Pitt"); + private static final Actor TOM_HANKS = new Actor("Tom", "Hanks"); + private static final List actors = new CopyOnWriteArrayList<>(Arrays.asList(BRAD_PITT, TOM_HANKS)); + + private RouterFunction routingFunction() { + FormHandler formHandler = new FormHandler(); + + RouterFunction restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class) + .doOnNext(actors::add) + .then(ok().build())); + + return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), formHandler::handleLogin) + .andRoute(POST("/upload"), formHandler::handleUpload) + .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/"))) + .andNest(path("/actor"), restfulRouter) + .filter((request, next) -> { + System.out.println("Before handler invocation: " + request.path()); + return next.handle(request); + }); + } + + @Bean + public ServletRegistrationBean servletRegistrationBean() throws Exception { + HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler((WebHandler) toHttpHandler(routingFunction())) + .filter(new IndexRewriteFilter()) + .build(); + ServletRegistrationBean registrationBean = new ServletRegistrationBean<>(new RootServlet(httpHandler), "/"); + registrationBean.setLoadOnStartup(1); + registrationBean.setAsyncSupported(true); + return registrationBean; + } + + @Configuration + @EnableWebSecurity + @Profile("!https") + static class SecurityConfig extends WebSecurityConfigurerAdapter { + @Override + protected void configure(final HttpSecurity http) throws Exception { + http.authorizeRequests() + .anyRequest() + .permitAll(); + } + } + + public static void main(String[] args) { + SpringApplication.run(FunctionalSpringBootApplication.class, args); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalWebApplication.java b/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalWebApplication.java new file mode 100644 index 0000000000..5a7d70d3db --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalWebApplication.java @@ -0,0 +1,80 @@ +package com.baeldung.functional; + +import static org.springframework.web.reactive.function.BodyInserters.fromObject; +import static org.springframework.web.reactive.function.server.RequestPredicates.GET; +import static org.springframework.web.reactive.function.server.RequestPredicates.POST; +import static org.springframework.web.reactive.function.server.RequestPredicates.path; +import static org.springframework.web.reactive.function.server.RouterFunctions.route; +import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler; +import static org.springframework.web.reactive.function.server.ServerResponse.ok; + +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +import org.apache.catalina.Context; +import org.apache.catalina.startup.Tomcat; +import org.springframework.boot.web.embedded.tomcat.TomcatWebServer; +import org.springframework.boot.web.server.WebServer; +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.server.reactive.HttpHandler; +import org.springframework.http.server.reactive.ServletHttpHandlerAdapter; +import org.springframework.web.reactive.function.server.RouterFunction; +import org.springframework.web.reactive.function.server.RouterFunctions; +import org.springframework.web.reactive.function.server.ServerResponse; +import org.springframework.web.server.WebHandler; +import org.springframework.web.server.adapter.WebHttpHandlerBuilder; + +import reactor.core.publisher.Flux; + +public class FunctionalWebApplication { + + private static final Actor BRAD_PITT = new Actor("Brad", "Pitt"); + private static final Actor TOM_HANKS = new Actor("Tom", "Hanks"); + private static final List actors = new CopyOnWriteArrayList<>(Arrays.asList(BRAD_PITT, TOM_HANKS)); + + private RouterFunction routingFunction() { + FormHandler formHandler = new FormHandler(); + + RouterFunction restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class) + .doOnNext(actors::add) + .then(ok().build())); + + return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), formHandler::handleLogin) + .andRoute(POST("/upload"), formHandler::handleUpload) + .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/"))) + .andNest(path("/actor"), restfulRouter) + .filter((request, next) -> { + System.out.println("Before handler invocation: " + request.path()); + return next.handle(request); + }); + } + + WebServer start() throws Exception { + WebHandler webHandler = (WebHandler) toHttpHandler(routingFunction()); + HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler(webHandler) + .filter(new IndexRewriteFilter()) + .build(); + + Tomcat tomcat = new Tomcat(); + tomcat.setHostname("localhost"); + tomcat.setPort(9090); + Context rootContext = tomcat.addContext("", System.getProperty("java.io.tmpdir")); + ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler); + Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet); + rootContext.addServletMappingDecoded("/", "httpHandlerServlet"); + + TomcatWebServer server = new TomcatWebServer(tomcat); + server.start(); + return server; + + } + + public static void main(String[] args) { + try { + new FunctionalWebApplication().start(); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/functional/IndexRewriteFilter.java b/spring-5-reactive/src/main/java/com/baeldung/functional/IndexRewriteFilter.java new file mode 100644 index 0000000000..551ea6c84b --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/functional/IndexRewriteFilter.java @@ -0,0 +1,25 @@ +package com.baeldung.functional; + +import org.springframework.http.server.reactive.ServerHttpRequest; +import org.springframework.web.server.ServerWebExchange; +import org.springframework.web.server.WebFilter; +import org.springframework.web.server.WebFilterChain; +import reactor.core.publisher.Mono; + +class IndexRewriteFilter implements WebFilter { + + @Override + public Mono filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) { + ServerHttpRequest request = serverWebExchange.getRequest(); + if (request.getURI() + .getPath() + .equals("/")) { + return webFilterChain.filter(serverWebExchange.mutate() + .request(builder -> builder.method(request.getMethod()) + .path("/test")) + .build()); + } + return webFilterChain.filter(serverWebExchange); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/functional/MyService.java b/spring-5-reactive/src/main/java/com/baeldung/functional/MyService.java new file mode 100644 index 0000000000..b7b8b13d8b --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/functional/MyService.java @@ -0,0 +1,11 @@ +package com.baeldung.functional; + +import java.util.Random; + +public class MyService { + + public int getRandomNumber() { + return (new Random().nextInt(10)); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/functional/RootServlet.java b/spring-5-reactive/src/main/java/com/baeldung/functional/RootServlet.java new file mode 100644 index 0000000000..8fe24821de --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/functional/RootServlet.java @@ -0,0 +1,82 @@ +package com.baeldung.functional; + +import static org.springframework.web.reactive.function.BodyExtractors.toDataBuffers; +import static org.springframework.web.reactive.function.BodyExtractors.toFormData; +import static org.springframework.web.reactive.function.BodyInserters.fromObject; +import static org.springframework.web.reactive.function.server.RequestPredicates.GET; +import static org.springframework.web.reactive.function.server.RequestPredicates.POST; +import static org.springframework.web.reactive.function.server.RequestPredicates.path; +import static org.springframework.web.reactive.function.server.RouterFunctions.route; +import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler; +import static org.springframework.web.reactive.function.server.ServerResponse.ok; + +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicLong; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.server.reactive.HttpHandler; +import org.springframework.http.server.reactive.ServletHttpHandlerAdapter; +import org.springframework.util.MultiValueMap; +import org.springframework.web.reactive.function.server.RouterFunction; +import org.springframework.web.reactive.function.server.RouterFunctions; +import org.springframework.web.reactive.function.server.ServerResponse; +import org.springframework.web.server.WebHandler; +import org.springframework.web.server.adapter.WebHttpHandlerBuilder; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +public class RootServlet extends ServletHttpHandlerAdapter { + + public RootServlet() { + this(WebHttpHandlerBuilder.webHandler((WebHandler) toHttpHandler(routingFunction())) + .filter(new IndexRewriteFilter()) + .build()); + } + + RootServlet(HttpHandler httpHandler) { + super(httpHandler); + } + + private static final Actor BRAD_PITT = new Actor("Brad", "Pitt"); + private static final Actor TOM_HANKS = new Actor("Tom", "Hanks"); + private static final List actors = new CopyOnWriteArrayList<>(Arrays.asList(BRAD_PITT, TOM_HANKS)); + + private static RouterFunction routingFunction() { + + return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), serverRequest -> serverRequest.body(toFormData()) + .map(MultiValueMap::toSingleValueMap) + .map(formData -> { + System.out.println("form data: " + formData.toString()); + if ("baeldung".equals(formData.get("user")) && "you_know_what_to_do".equals(formData.get("token"))) { + return ok().body(Mono.just("welcome back!"), String.class) + .block(); + } + return ServerResponse.badRequest() + .build() + .block(); + })) + .andRoute(POST("/upload"), serverRequest -> serverRequest.body(toDataBuffers()) + .collectList() + .map(dataBuffers -> { + AtomicLong atomicLong = new AtomicLong(0); + dataBuffers.forEach(d -> atomicLong.addAndGet(d.asByteBuffer() + .array().length)); + System.out.println("data length:" + atomicLong.get()); + return ok().body(fromObject(atomicLong.toString())) + .block(); + })) + .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/"))) + .andNest(path("/actor"), route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class) + .doOnNext(actors::add) + .then(ok().build()))) + .filter((request, next) -> { + System.out.println("Before handler invocation: " + request.path()); + return next.handle(request); + }); + + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java index e96767145e..1656f70221 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java @@ -1,11 +1,9 @@ package com.baeldung.reactive; -import com.mongodb.reactivestreams.client.MongoClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; -import org.springframework.data.mongodb.core.ReactiveMongoTemplate; @SpringBootApplication public class Spring5ReactiveApplication{ @@ -14,12 +12,4 @@ public class Spring5ReactiveApplication{ SpringApplication.run(Spring5ReactiveApplication.class, args); } - @Autowired - MongoClient mongoClient; - - @Bean - public ReactiveMongoTemplate reactiveMongoTemplate() { - return new ReactiveMongoTemplate(mongoClient, "test"); - } - } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/SpringSecurity5Application.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/SpringSecurity5Application.java new file mode 100644 index 0000000000..0e695ff596 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/SpringSecurity5Application.java @@ -0,0 +1,34 @@ +package com.baeldung.reactive; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.http.server.reactive.HttpHandler; +import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; +import org.springframework.web.reactive.config.EnableWebFlux; +import org.springframework.web.server.adapter.WebHttpHandlerBuilder; +import reactor.ipc.netty.NettyContext; +import reactor.ipc.netty.http.server.HttpServer; + +@ComponentScan(basePackages = {"com.baeldung.security"}) +@EnableWebFlux +public class SpringSecurity5Application { + + public static void main(String[] args) { + try (AnnotationConfigApplicationContext context = + new AnnotationConfigApplicationContext(SpringSecurity5Application.class)) { + context.getBean(NettyContext.class).onClose().block(); + } + } + + @Bean + public NettyContext nettyContext(ApplicationContext context) { + HttpHandler handler = WebHttpHandlerBuilder.applicationContext(context) + .build(); + ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(handler); + HttpServer httpServer = HttpServer.create("localhost", 8080); + return httpServer.newHandler(adapter).block(); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/WebSecurityConfig.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/WebSecurityConfig.java new file mode 100644 index 0000000000..427fd70a6c --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/WebSecurityConfig.java @@ -0,0 +1,28 @@ +package com.baeldung.reactive.actuator; + +import org.springframework.boot.actuate.autoconfigure.security.reactive.EndpointRequest; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.web.server.SecurityWebFilterChain; + +@Configuration +@EnableWebFluxSecurity +public class WebSecurityConfig { + + + @Bean + public SecurityWebFilterChain securitygWebFilterChain( + ServerHttpSecurity http) { + return http + + .authorizeExchange() + .matchers(EndpointRequest.to( + FeaturesEndpoint.class + )).permitAll().and().csrf().disable().build(); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/CorsOnAnnotatedElementsApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/CorsOnAnnotatedElementsApplication.java index 87efe72a1b..d990928abe 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/CorsOnAnnotatedElementsApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/CorsOnAnnotatedElementsApplication.java @@ -4,16 +4,8 @@ import java.util.Collections; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration; -import org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration; -import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; -import org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration; -@SpringBootApplication(exclude = { MongoAutoConfiguration.class, - MongoDataAutoConfiguration.class, - MongoReactiveDataAutoConfiguration.class, - MongoReactiveAutoConfiguration.class } -) +@SpringBootApplication public class CorsOnAnnotatedElementsApplication { public static void main(String[] args) { diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/controllers/FurtherCorsConfigsController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/controllers/FurtherCorsConfigsController.java index 4f9b9bd037..bc5b483935 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/controllers/FurtherCorsConfigsController.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/controllers/FurtherCorsConfigsController.java @@ -8,8 +8,8 @@ import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Mono; -@RestController -@RequestMapping("/web-filter-and-more-on-annotated") +//@RestController +//@RequestMapping("/web-filter-and-more-on-annotated") public class FurtherCorsConfigsController { @DeleteMapping("/further-mixed-config-endpoint") diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/controllers/RegularRestController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/controllers/RegularRestController.java index 6985810aa5..1d382b222a 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/controllers/RegularRestController.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/controllers/RegularRestController.java @@ -7,8 +7,8 @@ import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Mono; -@RestController -@RequestMapping("/web-filter-on-annotated") +//@RestController +//@RequestMapping("/web-filter-on-annotated") public class RegularRestController { @PutMapping("/regular-put-endpoint") diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/security/GreetController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/security/GreetController.java new file mode 100644 index 0000000000..99b79d88ea --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/security/GreetController.java @@ -0,0 +1,37 @@ +package com.baeldung.reactive.security; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import reactor.core.publisher.Mono; + +import java.security.Principal; + +@RestController +public class GreetController { + + private GreetService greetService; + + public GreetController(GreetService greetService) { + this.greetService = greetService; + } + + @GetMapping("/") + public Mono greet(Mono principal) { + return principal + .map(Principal::getName) + .map(name -> String.format("Hello, %s", name)); + } + + @GetMapping("/admin") + public Mono greetAdmin(Mono principal) { + return principal + .map(Principal::getName) + .map(name -> String.format("Admin access: %s", name)); + } + + @GetMapping("/greetService") + public Mono greetService() { + return greetService.greet(); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/security/GreetService.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/security/GreetService.java new file mode 100644 index 0000000000..93df64bced --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/security/GreetService.java @@ -0,0 +1,15 @@ +package com.baeldung.reactive.security; + +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Service; +import reactor.core.publisher.Mono; + +@Service +public class GreetService { + + @PreAuthorize("hasRole('ADMIN')") + public Mono greet() { + return Mono.just("Hello from service!"); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/security/SecurityConfig.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/security/SecurityConfig.java new file mode 100644 index 0000000000..cb1e7d1312 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/security/SecurityConfig.java @@ -0,0 +1,42 @@ +package com.baeldung.reactive.security; + +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity; +import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.core.userdetails.MapReactiveUserDetailsService; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.web.server.SecurityWebFilterChain; + +@EnableWebFluxSecurity +@EnableReactiveMethodSecurity +public class SecurityConfig { + + @Bean + public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) { + return http.authorizeExchange() + .pathMatchers("/admin").hasAuthority("ROLE_ADMIN") + .anyExchange().permitAll() + .and().formLogin() + .and().build(); + } + + @Bean + public MapReactiveUserDetailsService userDetailsService() { + UserDetails user = User.withDefaultPasswordEncoder() + .username("user") + .password("password") + .roles("USER") + .build(); + + UserDetails admin = User.withDefaultPasswordEncoder() + .username("admin") + .password("password") + .roles("ADMIN") + .build(); + + return new MapReactiveUserDetailsService(user, admin); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/web/reactive/Task.java b/spring-5-reactive/src/main/java/com/baeldung/web/reactive/Task.java new file mode 100644 index 0000000000..725fd931e1 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/web/reactive/Task.java @@ -0,0 +1,28 @@ +package com.baeldung.web.reactive; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Task { + + private final String name; + + private final int id; + + public Task(@JsonProperty("name") String name, @JsonProperty("id") int id) { + this.name = name; + this.id = id; + } + + public String getName() { + return this.name; + } + + public int getId() { + return this.id; + } + + @Override + public String toString() { + return "Task{" + "name='" + name + '\'' + ", id=" + id + '}'; + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/WebClientController.java b/spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/WebClientController.java new file mode 100644 index 0000000000..a719259328 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/WebClientController.java @@ -0,0 +1,83 @@ +package com.baeldung.web.reactive.client; + +import org.reactivestreams.Publisher; +import org.reactivestreams.Subscriber; +import org.springframework.http.*; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.reactive.function.BodyInserter; +import org.springframework.web.reactive.function.BodyInserters; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Mono; + +import java.net.URI; +import java.nio.charset.Charset; +import java.time.ZonedDateTime; +import java.util.Collections; + +@RestController +public class WebClientController { + + @ResponseStatus(HttpStatus.OK) + @GetMapping("/resource") + public void getResource() { + } + + public void demonstrateWebClient() { + // request + WebClient.UriSpec request1 = createWebClientWithServerURLAndDefaultValues().method(HttpMethod.POST); + WebClient.UriSpec request2 = createWebClientWithServerURLAndDefaultValues().post(); + + // request body specifications + WebClient.RequestBodySpec uri1 = createWebClientWithServerURLAndDefaultValues().method(HttpMethod.POST) + .uri("/resource"); + WebClient.RequestBodySpec uri2 = createWebClientWithServerURLAndDefaultValues().post() + .uri(URI.create("/resource")); + + // request header specification + WebClient.RequestHeadersSpec requestSpec1 = uri1.body(BodyInserters.fromPublisher(Mono.just("data"), String.class)); + WebClient.RequestHeadersSpec requestSpec2 = uri2.body(BodyInserters.fromObject("data")); + + // inserters + BodyInserter, ReactiveHttpOutputMessage> inserter1 = BodyInserters + .fromPublisher(Subscriber::onComplete, String.class); + + LinkedMultiValueMap map = new LinkedMultiValueMap<>(); + map.add("key1", "value1"); + map.add("key2", "value2"); + + // BodyInserter, ClientHttpRequest> inserter2 = BodyInserters.fromMultipartData(map); + BodyInserter inserter3 = BodyInserters.fromObject("body"); + + // responses + WebClient.ResponseSpec response1 = uri1.body(inserter3) + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) + .acceptCharset(Charset.forName("UTF-8")) + .ifNoneMatch("*") + .ifModifiedSince(ZonedDateTime.now()) + .retrieve(); + WebClient.ResponseSpec response2 = requestSpec2.retrieve(); + + } + + private WebClient createWebClient() { + return WebClient.create(); + } + + private WebClient createWebClientWithServerURL() { + return WebClient.create("http://localhost:8081"); + } + + private WebClient createWebClientWithServerURLAndDefaultValues() { + return WebClient.builder() + .baseUrl("http://localhost:8081") + .defaultCookie("cookieKey", "cookieValue") + .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .defaultUriVariables(Collections.singletonMap("url", "http://localhost:8080")) + .build(); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/websocket/Event.java b/spring-5-reactive/src/main/java/com/baeldung/websocket/Event.java similarity index 79% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/websocket/Event.java rename to spring-5-reactive/src/main/java/com/baeldung/websocket/Event.java index 90f83a566f..5d0260928c 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/websocket/Event.java +++ b/spring-5-reactive/src/main/java/com/baeldung/websocket/Event.java @@ -1,4 +1,4 @@ -package com.baeldung.reactive.websocket; +package com.baeldung.websocket; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/websocket/ReactiveJavaClientWebSocket.java b/spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveJavaClientWebSocket.java similarity index 95% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/websocket/ReactiveJavaClientWebSocket.java rename to spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveJavaClientWebSocket.java index c9a333c044..efb4dc238a 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/websocket/ReactiveJavaClientWebSocket.java +++ b/spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveJavaClientWebSocket.java @@ -1,4 +1,4 @@ -package com.baeldung.reactive.websocket; +package com.baeldung.websocket; import java.net.URI; import java.time.Duration; diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/websocket/ReactiveWebSocketApplication.java b/spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveWebSocketApplication.java similarity index 88% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/websocket/ReactiveWebSocketApplication.java rename to spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveWebSocketApplication.java index 43b5e50387..0e71673df6 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/websocket/ReactiveWebSocketApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveWebSocketApplication.java @@ -1,4 +1,4 @@ -package com.baeldung.reactive.websocket; +package com.baeldung.websocket; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/websocket/ReactiveWebSocketConfiguration.java b/spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveWebSocketConfiguration.java similarity index 96% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/websocket/ReactiveWebSocketConfiguration.java rename to spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveWebSocketConfiguration.java index 974def5a91..ef8d81d3c2 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/websocket/ReactiveWebSocketConfiguration.java +++ b/spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveWebSocketConfiguration.java @@ -1,4 +1,4 @@ -package com.baeldung.reactive.websocket; +package com.baeldung.websocket; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/websocket/ReactiveWebSocketHandler.java b/spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveWebSocketHandler.java similarity index 97% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/websocket/ReactiveWebSocketHandler.java rename to spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveWebSocketHandler.java index 2e93c0c0dc..5adad6bf15 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/websocket/ReactiveWebSocketHandler.java +++ b/spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveWebSocketHandler.java @@ -1,4 +1,4 @@ -package com.baeldung.reactive.websocket; +package com.baeldung.websocket; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java new file mode 100644 index 0000000000..a7b951b930 --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java @@ -0,0 +1,141 @@ +package com.baeldung.functional; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.springframework.boot.web.server.WebServer; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.http.MediaType; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.reactive.function.BodyInserters; + +import static org.springframework.web.reactive.function.BodyInserters.fromObject; +import static org.springframework.web.reactive.function.BodyInserters.fromResource; + +public class FunctionalWebApplicationIntegrationTest { + + private static WebTestClient client; + private static WebServer server; + + @BeforeClass + public static void setup() throws Exception { + server = new FunctionalWebApplication().start(); + client = WebTestClient.bindToServer() + .baseUrl("http://localhost:" + server.getPort()) + .build(); + } + + @AfterClass + public static void destroy() { + server.stop(); + } + + @Test + public void givenRouter_whenGetTest_thenGotHelloWorld() throws Exception { + client.get() + .uri("/test") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("helloworld"); + } + + @Test + public void givenIndexFilter_whenRequestRoot_thenRewrittenToTest() throws Exception { + client.get() + .uri("/") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("helloworld"); + } + + @Test + public void givenLoginForm_whenPostValidToken_thenSuccess() throws Exception { + MultiValueMap formData = new LinkedMultiValueMap<>(1); + formData.add("user", "baeldung"); + formData.add("token", "you_know_what_to_do"); + + client.post() + .uri("/login") + .contentType(MediaType.APPLICATION_FORM_URLENCODED) + .body(BodyInserters.fromFormData(formData)) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("welcome back!"); + } + + @Test + public void givenLoginForm_whenRequestWithInvalidToken_thenFail() throws Exception { + MultiValueMap formData = new LinkedMultiValueMap<>(2); + formData.add("user", "baeldung"); + formData.add("token", "try_again"); + + client.post() + .uri("/login") + .contentType(MediaType.APPLICATION_FORM_URLENCODED) + .body(BodyInserters.fromFormData(formData)) + .exchange() + .expectStatus() + .isBadRequest(); + } + + @Test + public void givenUploadForm_whenRequestWithMultipartData_thenSuccess() throws Exception { + Resource resource = new ClassPathResource("/baeldung-weekly.png"); + client.post() + .uri("/upload") + .contentType(MediaType.MULTIPART_FORM_DATA) + .body(fromResource(resource)) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo(String.valueOf(resource.contentLength())); + } + + @Test + public void givenActors_whenAddActor_thenAdded() throws Exception { + client.get() + .uri("/actor") + .exchange() + .expectStatus() + .isOk() + .expectBodyList(Actor.class) + .hasSize(2); + + client.post() + .uri("/actor") + .body(fromObject(new Actor("Clint", "Eastwood"))) + .exchange() + .expectStatus() + .isOk(); + + client.get() + .uri("/actor") + .exchange() + .expectStatus() + .isOk() + .expectBodyList(Actor.class) + .hasSize(3); + } + + @Test + public void givenResources_whenAccess_thenGot() throws Exception { + client.get() + .uri("/files/hello.txt") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("hello"); + } + +} diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/Spring5ReactiveServerClientIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/Spring5ReactiveServerClientIntegrationTest.java new file mode 100644 index 0000000000..8707c27fb3 --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/Spring5ReactiveServerClientIntegrationTest.java @@ -0,0 +1,96 @@ +package com.baeldung.reactive; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.springframework.http.server.reactive.HttpHandler; +import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; +import org.springframework.web.reactive.function.server.RouterFunction; +import org.springframework.web.reactive.function.server.RouterFunctions; +import org.springframework.web.reactive.function.server.ServerResponse; + +import com.baeldung.web.reactive.Task; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.ipc.netty.NettyContext; +import reactor.ipc.netty.http.server.HttpServer; + +import java.time.Duration; + +import static org.springframework.web.reactive.function.server.RequestPredicates.GET; +import static org.springframework.web.reactive.function.server.RequestPredicates.POST; + +public class Spring5ReactiveServerClientIntegrationTest { + + private static NettyContext nettyContext; + + @BeforeAll + public static void setUp() throws Exception { + HttpServer server = HttpServer.create("localhost", 8080); + RouterFunction route = RouterFunctions.route(POST("/task/process"), request -> ServerResponse.ok() + .body(request.bodyToFlux(Task.class) + .map(ll -> new Task("TaskName", 1)), Task.class)) + .and(RouterFunctions.route(GET("/task"), request -> ServerResponse.ok() + .body(Mono.just("server is alive"), String.class))); + HttpHandler httpHandler = RouterFunctions.toHttpHandler(route); + ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler); + nettyContext = server.newHandler(adapter) + .block(); + } + + @AfterAll + public static void shutDown() { + nettyContext.dispose(); + } + + // @Test + // public void givenCheckTask_whenServerHandle_thenServerResponseALiveString() throws Exception { + // WebClient client = WebClient.create("http://localhost:8080"); + // Mono result = client + // .get() + // .uri("/task") + // .exchange() + // .then(response -> response.bodyToMono(String.class)); + // + // assertThat(result.block()).isInstanceOf(String.class); + // } + + // @Test + // public void givenThreeTasks_whenServerHandleTheTasks_thenServerResponseATask() throws Exception { + // URI uri = URI.create("http://localhost:8080/task/process"); + // ExchangeFunction exchange = ExchangeFunctions.create(new ReactorClientHttpConnector()); + // ClientRequest request = ClientRequest + // .method(HttpMethod.POST, uri) + // .body(BodyInserters.fromPublisher(getLatLngs(), Task.class)) + // .build(); + // + // Flux taskResponse = exchange + // .exchange(request) + // .flatMap(response -> response.bodyToFlux(Task.class)); + // + // assertThat(taskResponse.blockFirst()).isInstanceOf(Task.class); + // } + + // @Test + // public void givenCheckTask_whenServerHandle_thenOragicServerResponseALiveString() throws Exception { + // URI uri = URI.create("http://localhost:8080/task"); + // ExchangeFunction exchange = ExchangeFunctions.create(new ReactorClientHttpConnector()); + // ClientRequest request = ClientRequest + // .method(HttpMethod.GET, uri) + // .body(BodyInserters.fromPublisher(getLatLngs(), Task.class)) + // .build(); + // + // Flux taskResponse = exchange + // .exchange(request) + // .flatMap(response -> response.bodyToFlux(String.class)); + // + // assertThat(taskResponse.blockFirst()).isInstanceOf(String.class); + // } + + private static Flux getLatLngs() { + return Flux.range(0, 3) + .zipWith(Flux.interval(Duration.ofSeconds(1))) + .map(x -> new Task("taskname", 1)) + .doOnNext(ll -> System.out.println("Produced: {}" + ll)); + } +} diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/webflux/EmployeeControllerUnitTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/webflux/EmployeeControllerIntegrationTest.java similarity index 90% rename from spring-5-reactive/src/test/java/com/baeldung/reactive/webflux/EmployeeControllerUnitTest.java rename to spring-5-reactive/src/test/java/com/baeldung/reactive/webflux/EmployeeControllerIntegrationTest.java index 640f28c331..e8c8c25723 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/webflux/EmployeeControllerUnitTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/webflux/EmployeeControllerIntegrationTest.java @@ -15,13 +15,15 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; +import com.baeldung.reactive.Spring5ReactiveApplication; + import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes=Spring5ReactiveApplication.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class EmployeeControllerUnitTest { +public class EmployeeControllerIntegrationTest { @Autowired private WebTestClient testClient; diff --git a/spring-5-reactive/src/test/java/com/baeldung/security/SecurityIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/security/SecurityIntegrationTest.java new file mode 100644 index 0000000000..a59ef57db8 --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/security/SecurityIntegrationTest.java @@ -0,0 +1,40 @@ +package com.baeldung.security; + +import com.baeldung.reactive.SpringSecurity5Application; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.reactive.server.WebTestClient; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = SpringSecurity5Application.class) +public class SecurityIntegrationTest { + + @Autowired + ApplicationContext context; + + private WebTestClient rest; + + @Before + public void setup() { + this.rest = WebTestClient.bindToApplicationContext(this.context).configureClient().build(); + } + + @Test + public void whenNoCredentials_thenRedirectToLogin() { + this.rest.get().uri("/").exchange().expectStatus().is3xxRedirection(); + } + + @Test + @Ignore + @WithMockUser + public void whenHasCredentials_thenSeesGreeting() { + this.rest.get().uri("/").exchange().expectStatus().isOk().expectBody(String.class).isEqualTo("Hello, user"); + } +} diff --git a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java new file mode 100644 index 0000000000..a1c0eecb8f --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java @@ -0,0 +1,60 @@ +package com.baeldung.web.client; + +import com.baeldung.reactive.Spring5ReactiveApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.web.reactive.function.server.RequestPredicates; +import org.springframework.web.reactive.function.server.RouterFunction; +import org.springframework.web.reactive.function.server.RouterFunctions; +import org.springframework.web.reactive.function.server.ServerResponse; +import org.springframework.web.server.WebHandler; +import reactor.core.publisher.Mono; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Spring5ReactiveApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class WebTestClientIntegrationTest { + + @LocalServerPort + private int port; + + private final RouterFunction ROUTER_FUNCTION = RouterFunctions.route(RequestPredicates.GET("/resource"), request -> ServerResponse.ok() + .build()); + private final WebHandler WEB_HANDLER = exchange -> Mono.empty(); + + @Test + public void testWebTestClientWithServerWebHandler() { + WebTestClient.bindToWebHandler(WEB_HANDLER) + .build(); + } + + @Test + public void testWebTestClientWithRouterFunction() { + WebTestClient.bindToRouterFunction(ROUTER_FUNCTION) + .build() + .get() + .uri("/resource") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .isEmpty(); + } + + @Test + public void testWebTestClientWithServerURL() { + WebTestClient.bindToServer() + .baseUrl("http://localhost:" + port) + .build() + .get() + .uri("/resource") + .exchange() + .expectStatus() + .is3xxRedirection() + .expectBody(); + } + +} From bb3afbc9f8df00aa6fd5c78e5466a3ac9b37ffed Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Tue, 24 Jul 2018 16:48:19 +0200 Subject: [PATCH 03/22] Update README.md (#4706) --- spring-boot-ops/README.md | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/spring-boot-ops/README.md b/spring-boot-ops/README.md index e5e03e4d63..9760e73576 100644 --- a/spring-boot-ops/README.md +++ b/spring-boot-ops/README.md @@ -1,4 +1,11 @@ -### Relevant Articles: -================================ - -- [Spring Boot Console Application](http://www.baeldung.com/spring-boot-console-app) +### Relevant Articles: + - [Deploy a Spring Boot WAR into a Tomcat Server](http://www.baeldung.com/spring-boot-war-tomcat-deploy) + - [Spring Boot Dependency Management with a Custom Parent](http://www.baeldung.com/spring-boot-dependency-management-custom-parent) + - [A Custom Data Binder in Spring MVC](http://www.baeldung.com/spring-mvc-custom-data-binder) + - [Create a Fat Jar App with Spring Boot](http://www.baeldung.com/deployable-fat-jar-spring-boot) + - [Introduction to WebJars](http://www.baeldung.com/maven-webjars) + - [Intro to Spring Boot Starters](http://www.baeldung.com/spring-boot-starters) + - [A Quick Guide to Maven Wrapper](http://www.baeldung.com/maven-wrapper) + - [Shutdown a Spring Boot Application](http://www.baeldung.com/spring-boot-shutdown) + - [Spring Boot Console Application](http://www.baeldung.com/spring-boot-console-app) + From f431a4c3ff87ab678d96f88de07e38cffe13bed6 Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Wed, 25 Jul 2018 01:21:55 +0800 Subject: [PATCH 04/22] add links (#4804) * Update README.md * Update README.md * Update README.md * Update README.md * Create README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.MD * Create README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md --- apache-meecrowave/README.md | 3 +++ core-java-8/README.md | 2 ++ core-java-collections/README.md | 1 + core-java-io/README.md | 2 ++ core-java/README.md | 5 +++++ core-kotlin/README.md | 2 ++ google-web-toolkit/README.md | 2 ++ libraries/README.md | 2 +- patterns/README.md | 2 +- patterns/design-patterns/README.md | 1 + rxjava/README.md | 1 + spring-5-reactive/README.md | 1 + spring-boot/README.MD | 1 + spring-mvc-java/README.md | 2 ++ spring-rest/README.md | 1 + 15 files changed, 26 insertions(+), 2 deletions(-) create mode 100644 apache-meecrowave/README.md create mode 100644 google-web-toolkit/README.md diff --git a/apache-meecrowave/README.md b/apache-meecrowave/README.md new file mode 100644 index 0000000000..42b93a383e --- /dev/null +++ b/apache-meecrowave/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: +================================ +- [Building a Microservice with Apache Meecrowave](http://www.baeldung.com/apache-meecrowave) diff --git a/core-java-8/README.md b/core-java-8/README.md index 90ba74de0f..8e4e5f95b5 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -54,3 +54,5 @@ - [Java 8 Unsigned Arithmetic Support](http://www.baeldung.com/java-unsigned-arithmetic) - [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end) - [Generalized Target-Type Inference in Java](http://www.baeldung.com/java-generalized-target-type-inference) +- [Image to Base64 String Conversion](http://www.baeldung.com/java-base64-image-string) +- [Calculate Age in Java](http://www.baeldung.com/java-get-age) diff --git a/core-java-collections/README.md b/core-java-collections/README.md index 510eac9dbc..7b3745b486 100644 --- a/core-java-collections/README.md +++ b/core-java-collections/README.md @@ -30,3 +30,4 @@ - [How to TDD a List Implementation in Java](http://www.baeldung.com/java-test-driven-list) - [How to Store Duplicate Keys in a Map in Java?](http://www.baeldung.com/java-map-duplicate-keys) - [Getting the Size of an Iterable in Java](http://www.baeldung.com/java-iterable-size) +- [Iterating Backward Through a List](http://www.baeldung.com/java-list-iterate-backwards) diff --git a/core-java-io/README.md b/core-java-io/README.md index 011282af12..5e5ddf42b4 100644 --- a/core-java-io/README.md +++ b/core-java-io/README.md @@ -28,3 +28,5 @@ - [Guide to Java NIO2 Asynchronous Channel APIs](http://www.baeldung.com/java-nio-2-async-channels) - [A Guide to NIO2 Asynchronous Socket Channel](http://www.baeldung.com/java-nio2-async-socket-channel) - [Download a File From an URL in Java](http://www.baeldung.com/java-download-file) +- [Create a Symbolic Link with Java](http://www.baeldung.com/java-symlink) +- [Quick Use of FilenameFilter](http://www.baeldung.com/java-filename-filter) diff --git a/core-java/README.md b/core-java/README.md index 185b3e4eb7..e22ee505ba 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -163,3 +163,8 @@ - [Console I/O in Java](http://www.baeldung.com/java-console-input-output) - [Guide to the java.util.Arrays Class](http://www.baeldung.com/java-util-arrays) - [Create a Custom Exception in Java](http://www.baeldung.com/java-new-custom-exception) +- [Guide to java.util.GregorianCalendar](http://www.baeldung.com/java-gregorian-calendar) +- [Java Global Exception Handler](http://www.baeldung.com/java-global-exception-handler) +- [Encrypting and Decrypting Files in Java](http://www.baeldung.com/java-cipher-input-output-stream) +- [How to Get the Size of an Object in Java](http://www.baeldung.com/java-size-of-object) +- [Exception Handling in Java](http://www.baeldung.com/java-exceptions) diff --git a/core-kotlin/README.md b/core-kotlin/README.md index 83f37dda85..51a99ea20c 100644 --- a/core-kotlin/README.md +++ b/core-kotlin/README.md @@ -34,3 +34,5 @@ - [Java EE 8 Security API](http://www.baeldung.com/java-ee-8-security) - [Kotlin with Ktor](http://www.baeldung.com/kotlin-ktor) - [Working with Enums in Kotlin](http://www.baeldung.com/kotlin-enum) +- [Create a Java and Kotlin Project with Maven](http://www.baeldung.com/kotlin-maven-java-project) +- [Reflection with Kotlin](http://www.baeldung.com/kotlin-reflection) diff --git a/google-web-toolkit/README.md b/google-web-toolkit/README.md new file mode 100644 index 0000000000..3526fe9962 --- /dev/null +++ b/google-web-toolkit/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Introduction to GWT](http://www.baeldung.com/gwt) diff --git a/libraries/README.md b/libraries/README.md index 09ad4ffcdf..3d06442bae 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -85,7 +85,7 @@ - [Implementing a FTP-Client in Java](http://www.baeldung.com/java-ftp-client) - [Convert String to Date in Java](http://www.baeldung.com/java-string-to-date) - [Histograms with Apache Commons Frequency](http://www.baeldung.com/apache-commons-frequency) - +- [Guide to Resilience4j](http://www.baeldung.com/resilience4j) The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own. diff --git a/patterns/README.md b/patterns/README.md index 7d58260cf0..221cba6456 100644 --- a/patterns/README.md +++ b/patterns/README.md @@ -1,4 +1,4 @@ -###Relevant Articles: +### Relevant Articles: - [A Guide to the Front Controller Pattern in Java](http://www.baeldung.com/java-front-controller-pattern) - [Introduction to Intercepting Filter Pattern in Java](http://www.baeldung.com/intercepting-filter-pattern-in-java) - [Implementing the Template Method Pattern in Java](http://www.baeldung.com/java-template-method-pattern) diff --git a/patterns/design-patterns/README.md b/patterns/design-patterns/README.md index 8b9d7a8193..5fb8f735ab 100644 --- a/patterns/design-patterns/README.md +++ b/patterns/design-patterns/README.md @@ -10,3 +10,4 @@ - [Composite Design Pattern in Java](http://www.baeldung.com/java-composite-pattern) - [Visitor Design Pattern in Java](http://www.baeldung.com/java-visitor-pattern) - [The DAO Pattern in Java](http://www.baeldung.com/java-dao-pattern) +- [Interpreter Design Pattern in Java](http://www.baeldung.com/java-interpreter-pattern) diff --git a/rxjava/README.md b/rxjava/README.md index 3376c49426..5c60e3bbce 100644 --- a/rxjava/README.md +++ b/rxjava/README.md @@ -15,3 +15,4 @@ - [RxJava Maybe](http://www.baeldung.com/rxjava-maybe) - [Introduction to RxRelay for RxJava](http://www.baeldung.com/rx-relay) - [Filtering Observables in RxJava](http://www.baeldung.com/rxjava-filtering) +- [RxJava One Observable, Multiple Subscribers](http://www.baeldung.com/rxjava-multiple-subscribers-observable) diff --git a/spring-5-reactive/README.md b/spring-5-reactive/README.md index df96d933ba..b6b2769f1e 100644 --- a/spring-5-reactive/README.md +++ b/spring-5-reactive/README.md @@ -18,3 +18,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Webflux Filters](http://www.baeldung.com/spring-webflux-filters) - [Reactive Flow with MongoDB, Kotlin, and Spring WebFlux](http://www.baeldung.com/kotlin-mongodb-spring-webflux) - [Spring Data Reactive Repositories with MongoDB](http://www.baeldung.com/spring-data-mongodb-reactive) +- [How to Set a Header on a Response with Spring 5](http://www.baeldung.com/spring-response-header) diff --git a/spring-boot/README.MD b/spring-boot/README.MD index 66e7c923c9..a572a16b67 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -34,3 +34,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Boot Exit Codes](http://www.baeldung.com/spring-boot-exit-codes) - [Guide to the Favicon in Spring Boot](http://www.baeldung.com/spring-boot-favicon) - [Spring Shutdown Callbacks](http://www.baeldung.com/spring-shutdown-callbacks) +- [Spring Boot Integration Testing with Embedded MongoDB](http://www.baeldung.com/spring-boot-embedded-mongodb) diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index b97b961e60..6b05ef569c 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -32,3 +32,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Scheduling Annotations](http://www.baeldung.com/spring-scheduling-annotations) - [Spring Web Annotations](http://www.baeldung.com/spring-mvc-annotations) - [Spring Core Annotations](http://www.baeldung.com/spring-core-annotations) +- [Using Spring ResponseEntity to Manipulate the HTTP Response](http://www.baeldung.com/spring-response-entity) +- [Using Spring @ResponseStatus to Set HTTP Status Code](http://www.baeldung.com/spring-response-status) diff --git a/spring-rest/README.md b/spring-rest/README.md index b717a5001d..6ef86ad015 100644 --- a/spring-rest/README.md +++ b/spring-rest/README.md @@ -24,3 +24,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Using the Spring RestTemplate Interceptor](http://www.baeldung.com/spring-rest-template-interceptor) - [Configure a RestTemplate with RestTemplateBuilder](http://www.baeldung.com/spring-rest-template-builder) - [Get and Post Lists of Objects with RestTemplate](http://www.baeldung.com/spring-rest-template-list) +- [How to Set a Header on a Response with Spring 5](http://www.baeldung.com/spring-response-header) From 8baa17446dd0d7d77ef9b4b8acf2dbb34a356896 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Tue, 24 Jul 2018 21:47:40 +0300 Subject: [PATCH 05/22] move mongodb ex --- spring-5-mongodb/.gitignore | 12 -- spring-5-mongodb/README.md | 20 --- spring-5-mongodb/pom.xml | 157 ------------------ .../src/main/resources/application.properties | 5 - .../src/main/webapp/WEB-INF/web.xml | 21 --- spring-5-reactive/README.md | 10 +- spring-data-5-reactive/README.md | 8 + spring-data-5-reactive/pom.xml | 126 +++++++++++--- .../reactive/Spring5ReactiveApplication.java | 0 .../com/baeldung/reactive/model/Account.java | 0 .../repository/AccountCrudRepository.java | 0 .../repository/AccountMongoRepository.java | 0 .../repository/AccountRxJavaRepository.java | 0 .../template/AccountTemplateOperations.java | 0 .../kotlin/com/baeldung/EventRepository.kt | 3 - .../AccountCrudRepositoryIntegrationTest.java | 0 ...AccountMongoRepositoryIntegrationTest.java | 0 ...ccountRxJavaRepositoryIntegrationTest.java | 0 ...ountTemplateOperationsIntegrationTest.java | 0 19 files changed, 109 insertions(+), 253 deletions(-) delete mode 100644 spring-5-mongodb/.gitignore delete mode 100644 spring-5-mongodb/README.md delete mode 100644 spring-5-mongodb/pom.xml delete mode 100644 spring-5-mongodb/src/main/resources/application.properties delete mode 100644 spring-5-mongodb/src/main/webapp/WEB-INF/web.xml create mode 100644 spring-data-5-reactive/README.md rename {spring-5-mongodb => spring-data-5-reactive}/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java (100%) rename {spring-5-mongodb => spring-data-5-reactive}/src/main/java/com/baeldung/reactive/model/Account.java (100%) rename {spring-5-mongodb => spring-data-5-reactive}/src/main/java/com/baeldung/reactive/repository/AccountCrudRepository.java (100%) rename {spring-5-mongodb => spring-data-5-reactive}/src/main/java/com/baeldung/reactive/repository/AccountMongoRepository.java (100%) rename {spring-5-mongodb => spring-data-5-reactive}/src/main/java/com/baeldung/reactive/repository/AccountRxJavaRepository.java (100%) rename {spring-5-mongodb => spring-data-5-reactive}/src/main/java/com/baeldung/reactive/template/AccountTemplateOperations.java (100%) rename {spring-5-mongodb => spring-data-5-reactive}/src/test/java/com/baeldung/reactive/repository/AccountCrudRepositoryIntegrationTest.java (100%) rename {spring-5-mongodb => spring-data-5-reactive}/src/test/java/com/baeldung/reactive/repository/AccountMongoRepositoryIntegrationTest.java (100%) rename {spring-5-mongodb => spring-data-5-reactive}/src/test/java/com/baeldung/reactive/repository/AccountRxJavaRepositoryIntegrationTest.java (100%) rename {spring-5-mongodb => spring-data-5-reactive}/src/test/java/com/baeldung/reactive/template/AccountTemplateOperationsIntegrationTest.java (100%) diff --git a/spring-5-mongodb/.gitignore b/spring-5-mongodb/.gitignore deleted file mode 100644 index dec013dfa4..0000000000 --- a/spring-5-mongodb/.gitignore +++ /dev/null @@ -1,12 +0,0 @@ -#folders# -.idea -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/spring-5-mongodb/README.md b/spring-5-mongodb/README.md deleted file mode 100644 index df96d933ba..0000000000 --- a/spring-5-mongodb/README.md +++ /dev/null @@ -1,20 +0,0 @@ -## Spring REST Example Project - -### The Course -The "REST With Spring" Classes: http://bit.ly/restwithspring - -### Relevant Articles - -- [Concurrent Test Execution in Spring 5](http://www.baeldung.com/spring-5-concurrent-tests) -- [Introduction to the Functional Web Framework in Spring 5](http://www.baeldung.com/spring-5-functional-web) -- [Exploring the Spring 5 MVC URL Matching Improvements](http://www.baeldung.com/spring-5-mvc-url-matching) -- [Spring 5 WebClient](http://www.baeldung.com/spring-5-webclient) -- [Spring 5 Functional Bean Registration](http://www.baeldung.com/spring-5-functional-beans) -- [The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5](http://www.baeldung.com/spring-5-junit-config) -- [Spring Security 5 for Reactive Applications](http://www.baeldung.com/spring-security-5-reactive) -- [Spring 5 Testing with @EnabledIf Annotation](https://github.com/eugenp/tutorials/tree/master/spring-5) -- [Reactive WebSockets with Spring 5](http://www.baeldung.com/spring-5-reactive-websockets) -- [Spring Boot Actuator](http://www.baeldung.com/spring-boot-actuators) -- [Spring Webflux Filters](http://www.baeldung.com/spring-webflux-filters) -- [Reactive Flow with MongoDB, Kotlin, and Spring WebFlux](http://www.baeldung.com/kotlin-mongodb-spring-webflux) -- [Spring Data Reactive Repositories with MongoDB](http://www.baeldung.com/spring-data-mongodb-reactive) diff --git a/spring-5-mongodb/pom.xml b/spring-5-mongodb/pom.xml deleted file mode 100644 index 2db41ba6c7..0000000000 --- a/spring-5-mongodb/pom.xml +++ /dev/null @@ -1,157 +0,0 @@ - - - 4.0.0 - - com.baeldung - spring-5-mongodb - 0.0.1-SNAPSHOT - jar - spring-5-mongodb - spring 5 mongodb sample project - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter-validation - - - org.springframework.boot - spring-boot-starter-tomcat - - - org.springframework.boot - spring-boot-starter-webflux - - - org.projectreactor - reactor-spring - ${reactor-spring.version} - - - - org.apache.commons - commons-lang3 - - - - - org.springframework - spring-test - - - org.springframework.boot - spring-boot-starter-test - test - - - - org.apache.commons - commons-collections4 - ${commons-collections4.version} - test - - - org.projectlombok - lombok - compile - - - - org.junit.jupiter - junit-jupiter-api - - - org.junit.jupiter - junit-jupiter-engine - test - - - org.junit.platform - junit-platform-surefire-provider - ${junit.platform.version} - test - - - org.junit.platform - junit-platform-runner - ${junit.platform.version} - test - - - org.apache.commons - commons-lang3 - - - - org.springframework.boot - spring-boot-starter-data-mongodb-reactive - - - de.flapdoodle.embed - de.flapdoodle.embed.mongo - test - - - io.reactivex.rxjava2 - rxjava - ${rxjava-version} - - - io.projectreactor - reactor-test - ${project-reactor-test} - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - com.baeldung.reactive.Spring5ReactiveApplication - JAR - - - - - org.apache.maven.plugins - maven-surefire-plugin - - 3 - true - methods - true - - **/*IntegrationTest.java - **/*IntTest.java - **/*LiveTest.java - - - - - - - - 1.0.0 - 5.0.2 - 2.20 - 1.0.1.RELEASE - 2.1.12 - 4.1 - 3.1.6.RELEASE - 1.1.3 - 1.0 - 1.0 - - - diff --git a/spring-5-mongodb/src/main/resources/application.properties b/spring-5-mongodb/src/main/resources/application.properties deleted file mode 100644 index 234834b894..0000000000 --- a/spring-5-mongodb/src/main/resources/application.properties +++ /dev/null @@ -1,5 +0,0 @@ -logging.level.root=INFO - -management.endpoints.web.exposure.include.=* - -info.app.name=Spring Boot 2 actuator Application diff --git a/spring-5-mongodb/src/main/webapp/WEB-INF/web.xml b/spring-5-mongodb/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index bfcf43dad2..0000000000 --- a/spring-5-mongodb/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - Spring Functional Application - - - functional - com.baeldung.functional.RootServlet - 1 - true - - - functional - / - - - - \ No newline at end of file diff --git a/spring-5-reactive/README.md b/spring-5-reactive/README.md index df96d933ba..40d0c23231 100644 --- a/spring-5-reactive/README.md +++ b/spring-5-reactive/README.md @@ -5,16 +5,8 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles -- [Concurrent Test Execution in Spring 5](http://www.baeldung.com/spring-5-concurrent-tests) - [Introduction to the Functional Web Framework in Spring 5](http://www.baeldung.com/spring-5-functional-web) -- [Exploring the Spring 5 MVC URL Matching Improvements](http://www.baeldung.com/spring-5-mvc-url-matching) - [Spring 5 WebClient](http://www.baeldung.com/spring-5-webclient) -- [Spring 5 Functional Bean Registration](http://www.baeldung.com/spring-5-functional-beans) -- [The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5](http://www.baeldung.com/spring-5-junit-config) - [Spring Security 5 for Reactive Applications](http://www.baeldung.com/spring-security-5-reactive) -- [Spring 5 Testing with @EnabledIf Annotation](https://github.com/eugenp/tutorials/tree/master/spring-5) - [Reactive WebSockets with Spring 5](http://www.baeldung.com/spring-5-reactive-websockets) -- [Spring Boot Actuator](http://www.baeldung.com/spring-boot-actuators) -- [Spring Webflux Filters](http://www.baeldung.com/spring-webflux-filters) -- [Reactive Flow with MongoDB, Kotlin, and Spring WebFlux](http://www.baeldung.com/kotlin-mongodb-spring-webflux) -- [Spring Data Reactive Repositories with MongoDB](http://www.baeldung.com/spring-data-mongodb-reactive) +- [Spring Webflux Filters](http://www.baeldung.com/spring-webflux-filters) \ No newline at end of file diff --git a/spring-data-5-reactive/README.md b/spring-data-5-reactive/README.md new file mode 100644 index 0000000000..f8886ac18b --- /dev/null +++ b/spring-data-5-reactive/README.md @@ -0,0 +1,8 @@ +## Spring Data Reactive Project + +### The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + +### Relevant Articles +- [Reactive Flow with MongoDB, Kotlin, and Spring WebFlux](http://www.baeldung.com/kotlin-mongodb-spring-webflux) +- [Spring Data Reactive Repositories with MongoDB](http://www.baeldung.com/spring-data-mongodb-reactive) diff --git a/spring-data-5-reactive/pom.xml b/spring-data-5-reactive/pom.xml index bcf37f1da4..806eafa2d6 100644 --- a/spring-data-5-reactive/pom.xml +++ b/spring-data-5-reactive/pom.xml @@ -23,11 +23,6 @@ org.springframework.boot spring-boot-starter-web - - javax.ws.rs - javax.ws.rs-api - ${javax.ws.rs-api.version} - com.fasterxml.jackson.module jackson-module-kotlin @@ -54,34 +49,51 @@ kotlin-stdlib-jdk8 ${kotlin.version} - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - ${kotlin.version} - org.jetbrains.kotlin kotlin-test ${kotlin.version} test + + io.reactivex.rxjava2 + rxjava + + - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - ${kotlin.version} + org.springframework + spring-test + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.junit.jupiter + junit-jupiter-api + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.platform + junit-platform-surefire-provider + ${junit.platform.version} + test + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test - - - spring-libs-snapshot - Spring Snapshot Repository - http://repo.spring.io/libs-snapshot - - - - src/main/kotlin org.springframework.boot @@ -89,21 +101,30 @@ kotlin-maven-plugin - ${kotlin.version} - + compile - compile compile + + + ${project.basedir}/src/main/kotlin + ${project.basedir}/src/main/java + + test-compile - test-compile test-compile + + + ${project.basedir}/src/test/kotlin + ${project.basedir}/src/test/java + + org.jetbrains.kotlin @@ -124,6 +145,57 @@ + + org.apache.maven.plugins + maven-compiler-plugin + + ${java.version} + ${java.version} + + + + + default-compile + none + + + + default-testCompile + none + + + java-compile + compile + + compile + + + + java-test-compile + test-compile + + testCompile + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + 3 + true + methods + true + + **/*IntegrationTest.java + **/*IntTest.java + **/*LiveTest.java + + + @@ -132,6 +204,8 @@ UTF-8 1.8 1.2.40 + 1.0.0 + 5.0.2 diff --git a/spring-5-mongodb/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java b/spring-data-5-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java similarity index 100% rename from spring-5-mongodb/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java rename to spring-data-5-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java diff --git a/spring-5-mongodb/src/main/java/com/baeldung/reactive/model/Account.java b/spring-data-5-reactive/src/main/java/com/baeldung/reactive/model/Account.java similarity index 100% rename from spring-5-mongodb/src/main/java/com/baeldung/reactive/model/Account.java rename to spring-data-5-reactive/src/main/java/com/baeldung/reactive/model/Account.java diff --git a/spring-5-mongodb/src/main/java/com/baeldung/reactive/repository/AccountCrudRepository.java b/spring-data-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountCrudRepository.java similarity index 100% rename from spring-5-mongodb/src/main/java/com/baeldung/reactive/repository/AccountCrudRepository.java rename to spring-data-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountCrudRepository.java diff --git a/spring-5-mongodb/src/main/java/com/baeldung/reactive/repository/AccountMongoRepository.java b/spring-data-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountMongoRepository.java similarity index 100% rename from spring-5-mongodb/src/main/java/com/baeldung/reactive/repository/AccountMongoRepository.java rename to spring-data-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountMongoRepository.java diff --git a/spring-5-mongodb/src/main/java/com/baeldung/reactive/repository/AccountRxJavaRepository.java b/spring-data-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountRxJavaRepository.java similarity index 100% rename from spring-5-mongodb/src/main/java/com/baeldung/reactive/repository/AccountRxJavaRepository.java rename to spring-data-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountRxJavaRepository.java diff --git a/spring-5-mongodb/src/main/java/com/baeldung/reactive/template/AccountTemplateOperations.java b/spring-data-5-reactive/src/main/java/com/baeldung/reactive/template/AccountTemplateOperations.java similarity index 100% rename from spring-5-mongodb/src/main/java/com/baeldung/reactive/template/AccountTemplateOperations.java rename to spring-data-5-reactive/src/main/java/com/baeldung/reactive/template/AccountTemplateOperations.java diff --git a/spring-data-5-reactive/src/main/kotlin/com/baeldung/EventRepository.kt b/spring-data-5-reactive/src/main/kotlin/com/baeldung/EventRepository.kt index a73ef8c807..e66af71ea6 100644 --- a/spring-data-5-reactive/src/main/kotlin/com/baeldung/EventRepository.kt +++ b/spring-data-5-reactive/src/main/kotlin/com/baeldung/EventRepository.kt @@ -4,6 +4,3 @@ import org.springframework.data.mongodb.core.mapping.Document import org.springframework.data.mongodb.repository.ReactiveMongoRepository interface EventRepository : ReactiveMongoRepository - -@Document -data class Event(val id: String, val name: String) diff --git a/spring-5-mongodb/src/test/java/com/baeldung/reactive/repository/AccountCrudRepositoryIntegrationTest.java b/spring-data-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountCrudRepositoryIntegrationTest.java similarity index 100% rename from spring-5-mongodb/src/test/java/com/baeldung/reactive/repository/AccountCrudRepositoryIntegrationTest.java rename to spring-data-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountCrudRepositoryIntegrationTest.java diff --git a/spring-5-mongodb/src/test/java/com/baeldung/reactive/repository/AccountMongoRepositoryIntegrationTest.java b/spring-data-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountMongoRepositoryIntegrationTest.java similarity index 100% rename from spring-5-mongodb/src/test/java/com/baeldung/reactive/repository/AccountMongoRepositoryIntegrationTest.java rename to spring-data-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountMongoRepositoryIntegrationTest.java diff --git a/spring-5-mongodb/src/test/java/com/baeldung/reactive/repository/AccountRxJavaRepositoryIntegrationTest.java b/spring-data-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountRxJavaRepositoryIntegrationTest.java similarity index 100% rename from spring-5-mongodb/src/test/java/com/baeldung/reactive/repository/AccountRxJavaRepositoryIntegrationTest.java rename to spring-data-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountRxJavaRepositoryIntegrationTest.java diff --git a/spring-5-mongodb/src/test/java/com/baeldung/reactive/template/AccountTemplateOperationsIntegrationTest.java b/spring-data-5-reactive/src/test/java/com/baeldung/reactive/template/AccountTemplateOperationsIntegrationTest.java similarity index 100% rename from spring-5-mongodb/src/test/java/com/baeldung/reactive/template/AccountTemplateOperationsIntegrationTest.java rename to spring-data-5-reactive/src/test/java/com/baeldung/reactive/template/AccountTemplateOperationsIntegrationTest.java From 12989ac2281f763bf6b148059eabe039b27eb009 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Wed, 25 Jul 2018 07:22:41 +0300 Subject: [PATCH 06/22] fix readme files --- spring-5-reactive/README.md | 2 ++ .../main/java/com/baeldung/functional/MyService.java | 11 ----------- spring-5/README.md | 5 ----- 3 files changed, 2 insertions(+), 16 deletions(-) delete mode 100644 spring-5-reactive/src/main/java/com/baeldung/functional/MyService.java diff --git a/spring-5-reactive/README.md b/spring-5-reactive/README.md index 40d0c23231..7925aa9d2b 100644 --- a/spring-5-reactive/README.md +++ b/spring-5-reactive/README.md @@ -7,6 +7,8 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Introduction to the Functional Web Framework in Spring 5](http://www.baeldung.com/spring-5-functional-web) - [Spring 5 WebClient](http://www.baeldung.com/spring-5-webclient) +- [Spring Boot Actuator](http://www.baeldung.com/spring-boot-actuators) +- [Exploring the Spring 5 MVC URL Matching Improvements](http://www.baeldung.com/spring-5-mvc-url-matching) - [Spring Security 5 for Reactive Applications](http://www.baeldung.com/spring-security-5-reactive) - [Reactive WebSockets with Spring 5](http://www.baeldung.com/spring-5-reactive-websockets) - [Spring Webflux Filters](http://www.baeldung.com/spring-webflux-filters) \ No newline at end of file diff --git a/spring-5-reactive/src/main/java/com/baeldung/functional/MyService.java b/spring-5-reactive/src/main/java/com/baeldung/functional/MyService.java deleted file mode 100644 index b7b8b13d8b..0000000000 --- a/spring-5-reactive/src/main/java/com/baeldung/functional/MyService.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.functional; - -import java.util.Random; - -public class MyService { - - public int getRandomNumber() { - return (new Random().nextInt(10)); - } - -} diff --git a/spring-5/README.md b/spring-5/README.md index de42d965f5..baf03fb3b3 100644 --- a/spring-5/README.md +++ b/spring-5/README.md @@ -6,14 +6,9 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles - [Concurrent Test Execution in Spring 5](http://www.baeldung.com/spring-5-concurrent-tests) -- [Introduction to the Functional Web Framework in Spring 5](http://www.baeldung.com/spring-5-functional-web) -- [Exploring the Spring 5 MVC URL Matching Improvements](http://www.baeldung.com/spring-5-mvc-url-matching) -- [Spring 5 WebClient](http://www.baeldung.com/spring-5-webclient) - [Spring 5 Functional Bean Registration](http://www.baeldung.com/spring-5-functional-beans) - [The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5](http://www.baeldung.com/spring-5-junit-config) -- [Spring Security 5 for Reactive Applications](http://www.baeldung.com/spring-security-5-reactive) - [Spring 5 Testing with @EnabledIf Annotation](http://www.baeldung.com/spring-5-enabledIf) - [Introduction to Spring REST Docs](http://www.baeldung.com/spring-rest-docs) -- [Spring Security 5 – OAuth2 Login](http://www.baeldung.com/spring-security-5-oauth2-login) - [Spring ResponseStatusException](http://www.baeldung.com/spring-response-status-exception) - [Spring Assert Statements](http://www.baeldung.com/spring-assert) From 189e62603bd41641f418a6992ea7fc010809d6da Mon Sep 17 00:00:00 2001 From: Mher Baghinyan Date: Wed, 25 Jul 2018 08:26:18 +0400 Subject: [PATCH 07/22] Bael 1832 (#4748) * @Primary annotation * @Primary annotation Employee name * Update PrimaryApplication.java * @Primary annotation with @Component --- .../java/org/baeldung/primary/Config.java | 22 +++++++++++++++++++ .../baeldung/primary/DepartmentManager.java | 11 ++++++++++ .../java/org/baeldung/primary/Employee.java | 20 +++++++++++++++++ .../org/baeldung/primary/GeneralManager.java | 14 ++++++++++++ .../java/org/baeldung/primary/Manager.java | 8 +++++++ .../org/baeldung/primary/ManagerService.java | 17 ++++++++++++++ .../baeldung/primary/PrimaryApplication.java | 20 +++++++++++++++++ 7 files changed, 112 insertions(+) create mode 100644 spring-all/src/main/java/org/baeldung/primary/Config.java create mode 100644 spring-all/src/main/java/org/baeldung/primary/DepartmentManager.java create mode 100644 spring-all/src/main/java/org/baeldung/primary/Employee.java create mode 100644 spring-all/src/main/java/org/baeldung/primary/GeneralManager.java create mode 100644 spring-all/src/main/java/org/baeldung/primary/Manager.java create mode 100644 spring-all/src/main/java/org/baeldung/primary/ManagerService.java create mode 100644 spring-all/src/main/java/org/baeldung/primary/PrimaryApplication.java diff --git a/spring-all/src/main/java/org/baeldung/primary/Config.java b/spring-all/src/main/java/org/baeldung/primary/Config.java new file mode 100644 index 0000000000..b39f2b9db3 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/primary/Config.java @@ -0,0 +1,22 @@ +package org.baeldung.primary; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; + +@Configuration +@ComponentScan(basePackages="org.baeldung.primary") +public class Config { + + @Bean + public Employee JohnEmployee(){ + return new Employee("John"); + } + + @Bean + @Primary + public Employee TonyEmployee(){ + return new Employee("Tony"); + } +} diff --git a/spring-all/src/main/java/org/baeldung/primary/DepartmentManager.java b/spring-all/src/main/java/org/baeldung/primary/DepartmentManager.java new file mode 100644 index 0000000000..2603951b4e --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/primary/DepartmentManager.java @@ -0,0 +1,11 @@ +package org.baeldung.primary; + +import org.springframework.stereotype.Component; + +@Component +public class DepartmentManager implements Manager { + @Override + public String getManagerName() { + return "Department manager"; + } +} diff --git a/spring-all/src/main/java/org/baeldung/primary/Employee.java b/spring-all/src/main/java/org/baeldung/primary/Employee.java new file mode 100644 index 0000000000..9168387613 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/primary/Employee.java @@ -0,0 +1,20 @@ +package org.baeldung.primary; + +/** + * Created by Gebruiker on 7/17/2018. + */ +public class Employee { + + private String name; + + public Employee(String name) { + this.name = name; + } + + @Override + public String toString() { + return "Employee{" + + "name='" + name + '\'' + + '}'; + } +} diff --git a/spring-all/src/main/java/org/baeldung/primary/GeneralManager.java b/spring-all/src/main/java/org/baeldung/primary/GeneralManager.java new file mode 100644 index 0000000000..0a94f0f96a --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/primary/GeneralManager.java @@ -0,0 +1,14 @@ +package org.baeldung.primary; + +import org.springframework.context.annotation.Primary; +import org.springframework.stereotype.Component; + +@Component +@Primary +public class GeneralManager implements Manager { + + @Override + public String getManagerName() { + return "General manager"; + } +} diff --git a/spring-all/src/main/java/org/baeldung/primary/Manager.java b/spring-all/src/main/java/org/baeldung/primary/Manager.java new file mode 100644 index 0000000000..4666a1babf --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/primary/Manager.java @@ -0,0 +1,8 @@ +package org.baeldung.primary; + +/** + * Created by Gebruiker on 7/19/2018. + */ +public interface Manager { + String getManagerName(); +} diff --git a/spring-all/src/main/java/org/baeldung/primary/ManagerService.java b/spring-all/src/main/java/org/baeldung/primary/ManagerService.java new file mode 100644 index 0000000000..94ea6785c9 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/primary/ManagerService.java @@ -0,0 +1,17 @@ +package org.baeldung.primary; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +/** + * Created by Gebruiker on 7/19/2018. + */@Service +public class ManagerService { + + @Autowired + private Manager manager; + + public Manager getManager() { + return manager; + } +} diff --git a/spring-all/src/main/java/org/baeldung/primary/PrimaryApplication.java b/spring-all/src/main/java/org/baeldung/primary/PrimaryApplication.java new file mode 100644 index 0000000000..ffa2a4028d --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/primary/PrimaryApplication.java @@ -0,0 +1,20 @@ +package org.baeldung.primary; + +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + + +public class PrimaryApplication { + + public static void main(String[] args) { + AnnotationConfigApplicationContext context + = new AnnotationConfigApplicationContext(Config.class); + + Employee employee = context.getBean(Employee.class); + System.out.println(employee); + + ManagerService service = context.getBean(ManagerService.class); + Manager manager = service.getManager(); + System.out.println(manager.getManagerName()); + } + +} From 8b5232c1b6300e3504813530b729f76ab9be5556 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Wed, 25 Jul 2018 22:53:14 +0300 Subject: [PATCH 08/22] add security exc --- .../reactive/security/SecurityConfig.java | 35 ++++++++++++------- 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/security/SecurityConfig.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/security/SecurityConfig.java index cb1e7d1312..d3468f0a0f 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/security/SecurityConfig.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/security/SecurityConfig.java @@ -1,5 +1,6 @@ package com.baeldung.reactive.security; +import org.springframework.boot.actuate.autoconfigure.security.reactive.EndpointRequest; import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity; import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; @@ -9,6 +10,8 @@ import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.server.SecurityWebFilterChain; +import com.baeldung.reactive.actuator.FeaturesEndpoint; + @EnableWebFluxSecurity @EnableReactiveMethodSecurity public class SecurityConfig { @@ -16,25 +19,33 @@ public class SecurityConfig { @Bean public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) { return http.authorizeExchange() - .pathMatchers("/admin").hasAuthority("ROLE_ADMIN") - .anyExchange().permitAll() - .and().formLogin() - .and().build(); + .pathMatchers("/admin") + .hasAuthority("ROLE_ADMIN") + .matchers(EndpointRequest.to(FeaturesEndpoint.class)) + .permitAll() + .anyExchange() + .permitAll() + .and() + .formLogin() + .and() + .csrf() + .disable() + .build(); } @Bean public MapReactiveUserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() - .username("user") - .password("password") - .roles("USER") - .build(); + .username("user") + .password("password") + .roles("USER") + .build(); UserDetails admin = User.withDefaultPasswordEncoder() - .username("admin") - .password("password") - .roles("ADMIN") - .build(); + .username("admin") + .password("password") + .roles("ADMIN") + .build(); return new MapReactiveUserDetailsService(user, admin); } From 4ee81a2fd9f06b30b55d029ac4e4a97f2fb1c5df Mon Sep 17 00:00:00 2001 From: myluckagain Date: Thu, 26 Jul 2018 11:12:23 +0500 Subject: [PATCH 09/22] BAEL-2030 remove first element from list (#4803) --- .../RemoveFirstElementUnitTest.java | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 core-java-collections/src/test/java/com/baeldung/list/removefirst/RemoveFirstElementUnitTest.java diff --git a/core-java-collections/src/test/java/com/baeldung/list/removefirst/RemoveFirstElementUnitTest.java b/core-java-collections/src/test/java/com/baeldung/list/removefirst/RemoveFirstElementUnitTest.java new file mode 100644 index 0000000000..09f0bb248c --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/list/removefirst/RemoveFirstElementUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.list.removefirst; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +public class RemoveFirstElementUnitTest { + + private List list = new ArrayList<>(); + private LinkedList linkedList = new LinkedList<>(); + + @Before + public void init() { + + list.add("cat"); + list.add("dog"); + list.add("pig"); + list.add("cow"); + list.add("goat"); + + linkedList.add("cat"); + linkedList.add("dog"); + linkedList.add("pig"); + linkedList.add("cow"); + linkedList.add("goat"); + } + + @Test + public void givenList_whenRemoveFirst_thenRemoved() { + list.remove(0); + + assertThat(list, hasSize(4)); + assertThat(list, not(contains("cat"))); + } + + @Test + public void givenLinkedList_whenRemoveFirst_thenRemoved() { + + linkedList.removeFirst(); + + assertThat(linkedList, hasSize(4)); + assertThat(linkedList, not(contains("cat"))); + } + +} From a92283f0ddbf94af8cbcf424631df15451f239ce Mon Sep 17 00:00:00 2001 From: Sjmillington Date: Thu, 26 Jul 2018 16:19:07 +0100 Subject: [PATCH 10/22] BAEL-2042 JavaFaker unit tests --- java-faker/pom.xml | 29 +++++ .../test/java/com/baeldung/JavaFakerTest.java | 115 ++++++++++++++++++ 2 files changed, 144 insertions(+) create mode 100644 java-faker/pom.xml create mode 100644 java-faker/src/test/java/com/baeldung/JavaFakerTest.java diff --git a/java-faker/pom.xml b/java-faker/pom.xml new file mode 100644 index 0000000000..4ac5368e24 --- /dev/null +++ b/java-faker/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + + com.baeldung + java-faker + 1.0-SNAPSHOT + + + + com.github.javafaker + javafaker + 0.15 + + + + + junit + junit + 4.12 + test + + + + + + diff --git a/java-faker/src/test/java/com/baeldung/JavaFakerTest.java b/java-faker/src/test/java/com/baeldung/JavaFakerTest.java new file mode 100644 index 0000000000..8d89fa0ab2 --- /dev/null +++ b/java-faker/src/test/java/com/baeldung/JavaFakerTest.java @@ -0,0 +1,115 @@ +package com.baeldung; + +import com.github.javafaker.Faker; +import com.github.javafaker.service.FakeValuesService; +import com.github.javafaker.service.FakerIDN; +import com.github.javafaker.service.LocaleDoesNotExistException; +import com.github.javafaker.service.RandomService; +import javafx.scene.Parent; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import java.util.Locale; +import java.util.Random; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +public class JavaFakerTest { + + private Faker faker; + + @Before + public void setUp() throws Exception { + faker = new Faker(); + } + + @Test + public void givenJavaFaker_whenAddressObjectCalled_checkValidAddressInfoGiven() throws Exception { + + Faker faker = new Faker(); + + String streetName = faker.address().streetName(); + String number = faker.address().buildingNumber(); + String city = faker.address().city(); + String country = faker.address().country(); + + System.out.println(String.format("%s\n%s\n%s\n%s", + number, + streetName, + city, + country)); + + } + + @Test + public void givenJavaFakersWithSameSeed_whenNameCalled_CheckSameName() throws Exception { + + Faker faker1 = new Faker(new Random(24)); + Faker faker2 = new Faker(new Random(24)); + + assertEquals(faker1.name().firstName(), faker2.name().firstName()); + } + + @Test + public void givenJavaFakersWithDifferentLocals_checkZipCodesMatchRegex() throws Exception { + + Faker ukFaker = new Faker(new Locale("en-GB")); + Faker usFaker = new Faker(new Locale("en-US")); + + System.out.println(String.format("American zipcode: %s", usFaker.address().zipCode())); + System.out.println(String.format("British postcode: %s", ukFaker.address().zipCode())); + + Pattern ukPattern = Pattern.compile("([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))\\s?[0-9][A-Za-z]{2})"); + Matcher ukMatcher = ukPattern.matcher(ukFaker.address().zipCode()); + + assertTrue(ukMatcher.find()); + + Matcher usMatcher = Pattern.compile("^\\d{5}(?:[-\\s]\\d{4})?$").matcher(usFaker.address().zipCode()); + + assertTrue(usMatcher.find()); + + } + + @Test + public void givenJavaFakerService_testFakersCreated() throws Exception { + + RandomService randomService = new RandomService(); + + System.out.println(randomService.nextBoolean()); + System.out.println(randomService.nextDouble()); + + Faker faker = new Faker(new Random(randomService.nextLong())); + + System.out.println(faker.address().city()); + + } + + @Test + public void testFakeValuesService() throws Exception { + + FakeValuesService fakeValuesService = new FakeValuesService(new Locale("en-GB"), new RandomService()); + + String email = fakeValuesService.bothify("????##@gmail.com"); + Matcher emailMatcher = Pattern.compile("\\w{4}\\d{2}@gmail.com").matcher(email); + assertTrue(emailMatcher.find()); + + String alphaNumericString = fakeValuesService.regexify("[a-z1-9]{10}"); + Matcher alphaNumericMatcher = Pattern.compile("[a-z1-9]{10}").matcher(alphaNumericString); + assertTrue(alphaNumericMatcher.find()); + + } + + + @Test(expected = LocaleDoesNotExistException.class) + public void givenWrongLocale_whenFakerIsInitialised_testLocaleDoesNotExistExceptionIsThrown() throws Exception { + + Faker wrongLocaleFaker = new Faker(new Locale("en-seaWorld")); + + } +} From 015240a99e54780f391ac3784557c3ce3a219c31 Mon Sep 17 00:00:00 2001 From: Sjmillington Date: Thu, 26 Jul 2018 19:17:51 +0100 Subject: [PATCH 11/22] Moved javafaker unit tests to testing-modules --- {java-faker => testing-modules/java-faker}/pom.xml | 0 .../java-faker}/src/test/java/com/baeldung/JavaFakerTest.java | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename {java-faker => testing-modules/java-faker}/pom.xml (100%) rename {java-faker => testing-modules/java-faker}/src/test/java/com/baeldung/JavaFakerTest.java (100%) diff --git a/java-faker/pom.xml b/testing-modules/java-faker/pom.xml similarity index 100% rename from java-faker/pom.xml rename to testing-modules/java-faker/pom.xml diff --git a/java-faker/src/test/java/com/baeldung/JavaFakerTest.java b/testing-modules/java-faker/src/test/java/com/baeldung/JavaFakerTest.java similarity index 100% rename from java-faker/src/test/java/com/baeldung/JavaFakerTest.java rename to testing-modules/java-faker/src/test/java/com/baeldung/JavaFakerTest.java From 5b489423d8ca1cc785e00b26f88689b58f55a4a2 Mon Sep 17 00:00:00 2001 From: geroza Date: Tue, 24 Jul 2018 00:40:13 -0300 Subject: [PATCH 12/22] * added examples of filtering collections using Streams, Apache CollectionUtils, Guava and Eclipse Collections --- core-java-collections/pom.xml | 17 +++++++ .../CollectionUtilsCollectionFilter.java | 22 +++++++++ .../EclipseCollectionsCollectionFilter.java | 32 +++++++++++++ .../java/filtering/GuavaCollectionFilter.java | 22 +++++++++ .../filtering/StreamsCollectionFilter.java | 37 +++++++++++++++ .../filtering/CollectionFiltersUnitTest.java | 46 +++++++++++++++++++ 6 files changed, 176 insertions(+) create mode 100644 core-java-collections/src/main/java/com/baeldung/java/filtering/CollectionUtilsCollectionFilter.java create mode 100644 core-java-collections/src/main/java/com/baeldung/java/filtering/EclipseCollectionsCollectionFilter.java create mode 100644 core-java-collections/src/main/java/com/baeldung/java/filtering/GuavaCollectionFilter.java create mode 100644 core-java-collections/src/main/java/com/baeldung/java/filtering/StreamsCollectionFilter.java create mode 100644 core-java-collections/src/test/java/com/baeldung/java/filtering/CollectionFiltersUnitTest.java diff --git a/core-java-collections/pom.xml b/core-java-collections/pom.xml index a5aea49c14..d63f4d2a45 100644 --- a/core-java-collections/pom.xml +++ b/core-java-collections/pom.xml @@ -36,15 +36,32 @@ commons-lang3 ${commons-lang3.version} + + org.eclipse.collections + eclipse-collections-api + 9.2.0 + + + org.eclipse.collections + eclipse-collections + 9.2.0 + org.assertj assertj-core ${assertj.version} test + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + 1.2.0 3.5 4.1 4.01 diff --git a/core-java-collections/src/main/java/com/baeldung/java/filtering/CollectionUtilsCollectionFilter.java b/core-java-collections/src/main/java/com/baeldung/java/filtering/CollectionUtilsCollectionFilter.java new file mode 100644 index 0000000000..4d6a3d62fd --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/java/filtering/CollectionUtilsCollectionFilter.java @@ -0,0 +1,22 @@ +package com.baeldung.java.filtering; + +import java.util.Collection; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.Predicate; + +public class CollectionUtilsCollectionFilter { + + static public Collection findEvenNumbers(Collection baseCollection) { + Predicate apacheEventNumberPredicate = new Predicate() { + + @Override + public boolean evaluate(Integer object) { + return object % 2 == 0; + } + }; + + CollectionUtils.filter(baseCollection, apacheEventNumberPredicate); + return baseCollection; + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/java/filtering/EclipseCollectionsCollectionFilter.java b/core-java-collections/src/main/java/com/baeldung/java/filtering/EclipseCollectionsCollectionFilter.java new file mode 100644 index 0000000000..981d6ca241 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/java/filtering/EclipseCollectionsCollectionFilter.java @@ -0,0 +1,32 @@ +package com.baeldung.java.filtering; + +import java.util.Collection; + +import org.eclipse.collections.api.block.predicate.Predicate; +import org.eclipse.collections.impl.factory.Lists; +import org.eclipse.collections.impl.utility.Iterate; + +public class EclipseCollectionsCollectionFilter { + + static public Collection findEvenNumbers(Collection baseCollection) { + Predicate eclipsePredicate = item -> item % 2 == 0; + Collection filteredList = Lists.mutable.ofAll(baseCollection) + .select(eclipsePredicate); + + return filteredList; + } + + static public Collection findEvenNumbersUsingIterate(Collection baseCollection) { + Predicate eclipsePredicate = new Predicate() { + private static final long serialVersionUID = 1L; + + @Override + public boolean accept(Integer arg0) { + return arg0 % 2 == 0; + } + }; + Collection filteredList = Iterate.select(baseCollection, eclipsePredicate); + + return filteredList; + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/java/filtering/GuavaCollectionFilter.java b/core-java-collections/src/main/java/com/baeldung/java/filtering/GuavaCollectionFilter.java new file mode 100644 index 0000000000..f5a27f0bdb --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/java/filtering/GuavaCollectionFilter.java @@ -0,0 +1,22 @@ +package com.baeldung.java.filtering; + +import java.util.Collection; + +import com.google.common.base.Predicate; +import com.google.common.collect.Collections2; + +public class GuavaCollectionFilter { + + static public Collection findEvenNumbers(Collection baseCollection) { + Predicate guavaPredicate = new Predicate() { + + @Override + public boolean apply(Integer input) { + return input % 2 == 0; + } + }; + Collection filteredCollection = Collections2.filter(baseCollection, guavaPredicate); + return filteredCollection; + } + +} diff --git a/core-java-collections/src/main/java/com/baeldung/java/filtering/StreamsCollectionFilter.java b/core-java-collections/src/main/java/com/baeldung/java/filtering/StreamsCollectionFilter.java new file mode 100644 index 0000000000..d51283de55 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/java/filtering/StreamsCollectionFilter.java @@ -0,0 +1,37 @@ +package com.baeldung.java.filtering; + +import java.util.Collection; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +public class StreamsCollectionFilter { + + public static Collection filterCollectionHelperMethod(Collection baseCollection, Predicate predicate) { + return baseCollection.stream() + .filter(predicate) + .collect(Collectors.toList()); + } + + static public Collection findEvenNumbersUsingHelperMethod(Collection baseCollection) { + return filterCollectionHelperMethod(baseCollection, item -> item % 2 == 0); + } + + static public Collection findEvenNumbersUsingLambda(Collection baseCollection) { + return baseCollection.stream() + .filter(item -> item % 2 == 0) + .collect(Collectors.toList()); + } + + static public Collection findEvenNumbersUsingPredicate(Collection baseCollection) { + Predicate evenNumberPredicate = new Predicate() { + @Override + public boolean test(Integer i) { + return i % 2 == 0; + } + }; + + return baseCollection.stream() + .filter(evenNumberPredicate) + .collect(Collectors.toList()); + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/java/filtering/CollectionFiltersUnitTest.java b/core-java-collections/src/test/java/com/baeldung/java/filtering/CollectionFiltersUnitTest.java new file mode 100644 index 0000000000..c85b7a526d --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/java/filtering/CollectionFiltersUnitTest.java @@ -0,0 +1,46 @@ +package com.baeldung.java.filtering; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; + +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +@RunWith(JUnitPlatform.class) +public class CollectionFiltersUnitTest { + + private static final Collection BASE_INTEGER_COLLECTION = Arrays.asList(9, 14, 2, 7, 1, 5, 8); + private static final Collection EXPECTED_EVEN_FILTERED_COLLECTION = Arrays.asList(14, 2, 8); + + @Test + public void givenAStringCollection_whenFilteringFourLetterWords_thenObtainTheFilteredCollection() { + final Collection baseStrings = Arrays.asList("java", "baeldung", "type", "example", "other"); + + Collection filtered = StreamsCollectionFilter.filterCollectionHelperMethod(baseStrings, item -> item.length() == 4); + + assertThat(filtered).containsExactlyInAnyOrder("java", "type"); + } + + @Test + public void givenAnIntegerCollection_whenFilteringEvenValues_thenObtainTheFilteredCollectionForAllCases() { + Collection filteredWithStreams1 = StreamsCollectionFilter.findEvenNumbersUsingLambda(BASE_INTEGER_COLLECTION); + Collection filteredWithStreams2 = StreamsCollectionFilter.findEvenNumbersUsingPredicate(BASE_INTEGER_COLLECTION); + Collection filteredWithCollectionUtils = CollectionUtilsCollectionFilter.findEvenNumbers(new ArrayList<>(BASE_INTEGER_COLLECTION)); + Collection filteredWithEclipseCollections = EclipseCollectionsCollectionFilter.findEvenNumbers(BASE_INTEGER_COLLECTION); + Collection filteredWithEclipseCollectionsUsingIterate = EclipseCollectionsCollectionFilter.findEvenNumbersUsingIterate(BASE_INTEGER_COLLECTION); + Collection filteredWithGuava = GuavaCollectionFilter.findEvenNumbers(BASE_INTEGER_COLLECTION); + + assertThat(filteredWithStreams1).hasSameElementsAs(filteredWithStreams2) + .hasSameElementsAs(filteredWithCollectionUtils) + .hasSameElementsAs(filteredWithEclipseCollections) + .hasSameElementsAs(filteredWithEclipseCollectionsUsingIterate) + .hasSameElementsAs(filteredWithEclipseCollectionsUsingIterate) + .hasSameElementsAs(filteredWithGuava) + .hasSameElementsAs(EXPECTED_EVEN_FILTERED_COLLECTION); + } + +} From 6b2fb615a746b979a1c08b85793fa29f9996edf8 Mon Sep 17 00:00:00 2001 From: geroza Date: Wed, 25 Jul 2018 11:41:51 -0300 Subject: [PATCH 13/22] * Added examples for java-9 filtering collector --- core-java-9/pom.xml | 14 +++++ .../StreamsGroupingCollectionFilter.java | 27 ++++++++++ .../stream/CollectionFilterUnitTest.java | 53 +++++++++++++++++++ 3 files changed, 94 insertions(+) create mode 100644 core-java-9/src/main/java/com/baeldung/java9/language/stream/StreamsGroupingCollectionFilter.java create mode 100644 core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectionFilterUnitTest.java diff --git a/core-java-9/pom.xml b/core-java-9/pom.xml index 4ba06f7c0d..f22d0a3ed9 100644 --- a/core-java-9/pom.xml +++ b/core-java-9/pom.xml @@ -19,11 +19,23 @@ ${awaitility.version} test + + org.assertj + assertj-core + ${assertj.version} + test + com.google.guava guava ${guava.version} + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + @@ -50,6 +62,8 @@ + 3.10.0 + 1.2.0 1.7.0 1.9 1.9 diff --git a/core-java-9/src/main/java/com/baeldung/java9/language/stream/StreamsGroupingCollectionFilter.java b/core-java-9/src/main/java/com/baeldung/java9/language/stream/StreamsGroupingCollectionFilter.java new file mode 100644 index 0000000000..84d2e63c6c --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/language/stream/StreamsGroupingCollectionFilter.java @@ -0,0 +1,27 @@ +package com.baeldung.java9.language.stream; + +import static java.util.stream.Collectors.filtering; +import static java.util.stream.Collectors.groupingBy; +import static java.util.stream.Collectors.toList; + +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.function.Function; + +public class StreamsGroupingCollectionFilter { + + static public Map> findEvenNumbersAfterGroupingByQuantityOfDigits(Collection baseCollection) { + Function getQuantityOfDigits = item -> (int) Math.log10(item) + 1; + + return baseCollection.stream() + .collect(groupingBy(getQuantityOfDigits, filtering(item -> item % 2 == 0, toList()))); + } + + static public Map> findEvenNumbersBeforeGroupingByQuantityOfDigits(Collection baseCollection) { + + return baseCollection.stream() + .filter(item -> item % 2 == 0) + .collect(groupingBy(item -> (int) Math.log10(item) + 1, toList())); + } +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectionFilterUnitTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectionFilterUnitTest.java new file mode 100644 index 0000000000..0a6424fa81 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectionFilterUnitTest.java @@ -0,0 +1,53 @@ +package com.baeldung.java9.language.stream; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +@RunWith(JUnitPlatform.class) +public class CollectionFilterUnitTest { + + private static final Collection BASE_INTEGER_COLLECTION = Arrays.asList(9, 12, 55, 56, 101, 115, 8002, 223, 2668, 19, 8); + private static final Map> EXPECTED_EVEN_FILTERED_AFTER_GROUPING_MAP = createExpectedFilterAfterGroupingMap(); + + private static Map> createExpectedFilterAfterGroupingMap() { + Map> map = new HashMap<>(); + map.put(1, Arrays.asList(8)); + map.put(2, Arrays.asList(12, 56)); + map.put(3, Collections.emptyList()); + map.put(4, Arrays.asList(8002, 2668)); + return map; + + } + + private static final Map> EXPECTED_EVEN_FILTERED_BEFORE_GROUPING_MAP = createExpectedFilterBeforeGroupingMap(); + + private static Map> createExpectedFilterBeforeGroupingMap() { + Map> map = new HashMap<>(); + map.put(1, Arrays.asList(8)); + map.put(2, Arrays.asList(12, 56)); + map.put(4, Arrays.asList(8002, 2668)); + return map; + + } + + @Test + public void givenAStringCollection_whenFilteringFourLetterWords_thenObtainTheFilteredCollection() { + Map> filteredAfterGroupingMap = StreamsGroupingCollectionFilter.findEvenNumbersAfterGroupingByQuantityOfDigits(BASE_INTEGER_COLLECTION); + Map> filteredBeforeGroupingMap = StreamsGroupingCollectionFilter.findEvenNumbersBeforeGroupingByQuantityOfDigits(BASE_INTEGER_COLLECTION); + + assertThat(filteredAfterGroupingMap).containsAllEntriesOf(EXPECTED_EVEN_FILTERED_AFTER_GROUPING_MAP); + assertThat(filteredBeforeGroupingMap).doesNotContainKey(3) + .containsAllEntriesOf(EXPECTED_EVEN_FILTERED_BEFORE_GROUPING_MAP); + } + +} From 81027b7fbd3f67e4809d29e6b8218653c23ca12d Mon Sep 17 00:00:00 2001 From: geroza Date: Wed, 25 Jul 2018 17:36:17 -0300 Subject: [PATCH 14/22] * minor fixes and cleaning duties --- .../stream/CollectionFilterUnitTest.java | 2 -- core-java-collections/pom.xml | 5 +++-- .../CollectionUtilsCollectionFilter.java | 8 +------- .../java/filtering/GuavaCollectionFilter.java | 7 +------ .../java/filtering/StreamsCollectionFilter.java | 17 +++-------------- .../filtering/CollectionFiltersUnitTest.java | 6 ++---- 6 files changed, 10 insertions(+), 35 deletions(-) diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectionFilterUnitTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectionFilterUnitTest.java index 0a6424fa81..1b9315678a 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectionFilterUnitTest.java +++ b/core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectionFilterUnitTest.java @@ -18,7 +18,6 @@ public class CollectionFilterUnitTest { private static final Collection BASE_INTEGER_COLLECTION = Arrays.asList(9, 12, 55, 56, 101, 115, 8002, 223, 2668, 19, 8); private static final Map> EXPECTED_EVEN_FILTERED_AFTER_GROUPING_MAP = createExpectedFilterAfterGroupingMap(); - private static Map> createExpectedFilterAfterGroupingMap() { Map> map = new HashMap<>(); map.put(1, Arrays.asList(8)); @@ -30,7 +29,6 @@ public class CollectionFilterUnitTest { } private static final Map> EXPECTED_EVEN_FILTERED_BEFORE_GROUPING_MAP = createExpectedFilterBeforeGroupingMap(); - private static Map> createExpectedFilterBeforeGroupingMap() { Map> map = new HashMap<>(); map.put(1, Arrays.asList(8)); diff --git a/core-java-collections/pom.xml b/core-java-collections/pom.xml index d63f4d2a45..ff06714bfe 100644 --- a/core-java-collections/pom.xml +++ b/core-java-collections/pom.xml @@ -39,12 +39,12 @@ org.eclipse.collections eclipse-collections-api - 9.2.0 + ${eclipse.collections.version} org.eclipse.collections eclipse-collections - 9.2.0 + ${eclipse.collections.version} org.assertj @@ -67,5 +67,6 @@ 4.01 1.7.0 3.6.1 + 9.2.0 diff --git a/core-java-collections/src/main/java/com/baeldung/java/filtering/CollectionUtilsCollectionFilter.java b/core-java-collections/src/main/java/com/baeldung/java/filtering/CollectionUtilsCollectionFilter.java index 4d6a3d62fd..58f9f6af54 100644 --- a/core-java-collections/src/main/java/com/baeldung/java/filtering/CollectionUtilsCollectionFilter.java +++ b/core-java-collections/src/main/java/com/baeldung/java/filtering/CollectionUtilsCollectionFilter.java @@ -8,13 +8,7 @@ import org.apache.commons.collections4.Predicate; public class CollectionUtilsCollectionFilter { static public Collection findEvenNumbers(Collection baseCollection) { - Predicate apacheEventNumberPredicate = new Predicate() { - - @Override - public boolean evaluate(Integer object) { - return object % 2 == 0; - } - }; + Predicate apacheEventNumberPredicate = item -> item % 2 == 0; CollectionUtils.filter(baseCollection, apacheEventNumberPredicate); return baseCollection; diff --git a/core-java-collections/src/main/java/com/baeldung/java/filtering/GuavaCollectionFilter.java b/core-java-collections/src/main/java/com/baeldung/java/filtering/GuavaCollectionFilter.java index f5a27f0bdb..88338fd6d4 100644 --- a/core-java-collections/src/main/java/com/baeldung/java/filtering/GuavaCollectionFilter.java +++ b/core-java-collections/src/main/java/com/baeldung/java/filtering/GuavaCollectionFilter.java @@ -8,13 +8,8 @@ import com.google.common.collect.Collections2; public class GuavaCollectionFilter { static public Collection findEvenNumbers(Collection baseCollection) { - Predicate guavaPredicate = new Predicate() { + Predicate guavaPredicate = item -> item % 2 == 0; - @Override - public boolean apply(Integer input) { - return input % 2 == 0; - } - }; Collection filteredCollection = Collections2.filter(baseCollection, guavaPredicate); return filteredCollection; } diff --git a/core-java-collections/src/main/java/com/baeldung/java/filtering/StreamsCollectionFilter.java b/core-java-collections/src/main/java/com/baeldung/java/filtering/StreamsCollectionFilter.java index d51283de55..f074f74199 100644 --- a/core-java-collections/src/main/java/com/baeldung/java/filtering/StreamsCollectionFilter.java +++ b/core-java-collections/src/main/java/com/baeldung/java/filtering/StreamsCollectionFilter.java @@ -16,22 +16,11 @@ public class StreamsCollectionFilter { return filterCollectionHelperMethod(baseCollection, item -> item % 2 == 0); } - static public Collection findEvenNumbersUsingLambda(Collection baseCollection) { - return baseCollection.stream() - .filter(item -> item % 2 == 0) - .collect(Collectors.toList()); - } - - static public Collection findEvenNumbersUsingPredicate(Collection baseCollection) { - Predicate evenNumberPredicate = new Predicate() { - @Override - public boolean test(Integer i) { - return i % 2 == 0; - } - }; + static public Collection findEvenNumbers(Collection baseCollection) { + Predicate streamsPredicate = item -> item % 2 == 0; return baseCollection.stream() - .filter(evenNumberPredicate) + .filter(streamsPredicate) .collect(Collectors.toList()); } } diff --git a/core-java-collections/src/test/java/com/baeldung/java/filtering/CollectionFiltersUnitTest.java b/core-java-collections/src/test/java/com/baeldung/java/filtering/CollectionFiltersUnitTest.java index c85b7a526d..b30805d471 100644 --- a/core-java-collections/src/test/java/com/baeldung/java/filtering/CollectionFiltersUnitTest.java +++ b/core-java-collections/src/test/java/com/baeldung/java/filtering/CollectionFiltersUnitTest.java @@ -27,15 +27,13 @@ public class CollectionFiltersUnitTest { @Test public void givenAnIntegerCollection_whenFilteringEvenValues_thenObtainTheFilteredCollectionForAllCases() { - Collection filteredWithStreams1 = StreamsCollectionFilter.findEvenNumbersUsingLambda(BASE_INTEGER_COLLECTION); - Collection filteredWithStreams2 = StreamsCollectionFilter.findEvenNumbersUsingPredicate(BASE_INTEGER_COLLECTION); + Collection filteredWithStreams1 = StreamsCollectionFilter.findEvenNumbers(BASE_INTEGER_COLLECTION); Collection filteredWithCollectionUtils = CollectionUtilsCollectionFilter.findEvenNumbers(new ArrayList<>(BASE_INTEGER_COLLECTION)); Collection filteredWithEclipseCollections = EclipseCollectionsCollectionFilter.findEvenNumbers(BASE_INTEGER_COLLECTION); Collection filteredWithEclipseCollectionsUsingIterate = EclipseCollectionsCollectionFilter.findEvenNumbersUsingIterate(BASE_INTEGER_COLLECTION); Collection filteredWithGuava = GuavaCollectionFilter.findEvenNumbers(BASE_INTEGER_COLLECTION); - assertThat(filteredWithStreams1).hasSameElementsAs(filteredWithStreams2) - .hasSameElementsAs(filteredWithCollectionUtils) + assertThat(filteredWithStreams1).hasSameElementsAs(filteredWithCollectionUtils) .hasSameElementsAs(filteredWithEclipseCollections) .hasSameElementsAs(filteredWithEclipseCollectionsUsingIterate) .hasSameElementsAs(filteredWithEclipseCollectionsUsingIterate) From a1ba371c73f10635ce02939db16ad9bba7978940 Mon Sep 17 00:00:00 2001 From: Felipe Santiago Corro Date: Thu, 26 Jul 2018 17:19:03 -0300 Subject: [PATCH 15/22] add elements to list (#4814) --- .../baeldung/list/AddElementsUnitTest.java | 87 +++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 core-java-8/src/test/java/com/baeldung/list/AddElementsUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/list/AddElementsUnitTest.java b/core-java-8/src/test/java/com/baeldung/list/AddElementsUnitTest.java new file mode 100644 index 0000000000..93c28812bd --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/list/AddElementsUnitTest.java @@ -0,0 +1,87 @@ +package com.baeldung.list; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.*; + +import static org.junit.Assert.*; + +public class AddElementsUnitTest { + + List flowers; + + @Before + public void init() { + this.flowers = new ArrayList<>(Arrays.asList( + new Flower("Poppy", 12), + new Flower("Anemone", 8), + new Flower("Catmint", 12))); + } + + @Test + public void givenAList_whenTargetListIsEmpty_thenReturnTargetListWithNewItems() { + List anotherList = new ArrayList<>(); + anotherList.addAll(flowers); + + assertEquals(anotherList.size(), flowers.size()); + Assert.assertTrue(anotherList.containsAll(flowers)); + } + + @Test + public void givenAList_whenTargetListIsEmpty_thenReturnTargetListWithOneModifiedElementByConstructor() { + List anotherList = new ArrayList<>(); + anotherList.addAll(flowers); + + Flower flower = anotherList.get(0); + flower.setPetals(flowers.get(0).getPetals() * 3); + + assertEquals(anotherList.size(), flowers.size()); + Assert.assertTrue(anotherList.containsAll(flowers)); + } + + @Test + public void givenAListAndElements_whenUseCollectionsAddAll_thenAddElementsToTargetList() { + List target = new ArrayList<>(); + + Collections.addAll(target, flowers.get(0), flowers.get(1), flowers.get(2), flowers.get(0)); + + assertEquals(target.size(), 4); + } + + @Test + public void givenTwoList_whenSourceListDoesNotHaveNullElements_thenAddElementsToTargetListSkipFirstElementByStreamProcess() { + List flowerVase = new ArrayList<>(); + + flowers.stream() + .skip(1) + .forEachOrdered(flowerVase::add); + + assertEquals(flowerVase.size() + 1, flowers.size()); + assertFalse(flowerVase.containsAll(flowers)); + } + + @Test + public void givenTwoList_whenSourceListDoesNotHaveNullElements_thenAddElementsToTargetListFilteringElementsByStreamProcess() { + List flowerVase = new ArrayList<>(); + + flowers.stream() + .filter(f -> f.getPetals() > 10) + .forEachOrdered(flowerVase::add); + + assertEquals(flowerVase.size() + 1, flowers.size()); + assertFalse(flowerVase.containsAll(flowers)); + } + + @Test + public void givenAList_whenListIsNotNull_thenAddElementsToListByStreamProcessWihtOptional() { + List target = new ArrayList<>(); + + Optional.ofNullable(flowers) + .ifPresent(target::addAll); + + assertNotNull(target); + assertEquals(target.size(), 3); + } +} From 7070f25400c070ec499461a795b424b802665047 Mon Sep 17 00:00:00 2001 From: Shreyash Date: Fri, 27 Jul 2018 02:27:19 +0530 Subject: [PATCH 16/22] BAEL-1960: Custom appender for log4j (#4731) * BAEL-1960: Custom appender for log4j * Changes as per suggestion to BAEL-1960 * Changes as [er review for BAEL-1960 * Changes for formatting as per suggestion. * BAEL-1960. Copied pom.xml from master and pasted my changes against it. * Chnages for spaces instead of tabs. * Changes for spaces instead of tabs. --- logging-modules/log4j2/pom.xml | 9 +++- .../logging/log4j2/appender/MapAppender.java | 54 +++++++++++++++++++ .../appender/MapAppenderIntegrationTest.java | 35 ++++++++++++ .../log4j2/src/test/resources/log4j2.xml | 6 ++- 4 files changed, 101 insertions(+), 3 deletions(-) create mode 100644 logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/appender/MapAppender.java create mode 100644 logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/appender/MapAppenderIntegrationTest.java diff --git a/logging-modules/log4j2/pom.xml b/logging-modules/log4j2/pom.xml index 89d37e789c..65da318636 100644 --- a/logging-modules/log4j2/pom.xml +++ b/logging-modules/log4j2/pom.xml @@ -18,6 +18,13 @@ log4j-core ${log4j-core.version} + + + + org.apache.logging.log4j + log4j-api + ${log4j-core.version} + @@ -114,4 +121,4 @@ yyyyMMddHHmmss - + \ No newline at end of file diff --git a/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/appender/MapAppender.java b/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/appender/MapAppender.java new file mode 100644 index 0000000000..2015b6d573 --- /dev/null +++ b/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/appender/MapAppender.java @@ -0,0 +1,54 @@ +/** + * + */ +package com.baeldung.logging.log4j2.appender; + +import java.time.Instant; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.core.Appender; +import org.apache.logging.log4j.core.Core; +import org.apache.logging.log4j.core.Filter; +import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.core.appender.AbstractAppender; +import org.apache.logging.log4j.core.config.plugins.Plugin; +import org.apache.logging.log4j.core.config.plugins.PluginAttribute; +import org.apache.logging.log4j.core.config.plugins.PluginElement; +import org.apache.logging.log4j.core.config.plugins.PluginFactory; + +@Plugin(name = "MapAppender", category = Core.CATEGORY_NAME, elementType = Appender.ELEMENT_TYPE) +public class MapAppender extends AbstractAppender { + + private ConcurrentMap eventMap = new ConcurrentHashMap<>(); + + protected MapAppender(String name, Filter filter) { + super(name, filter, null); + } + + @PluginFactory + public static MapAppender createAppender(@PluginAttribute("name") String name, @PluginElement("Filter") final Filter filter) { + return new MapAppender(name, filter); + } + + @Override + public void append(LogEvent event) { + if (event.getLevel() + .isLessSpecificThan(Level.WARN)) { + error("Unable to log less than WARN level."); + return; + } + eventMap.put(Instant.now() + .toString(), event); + } + + public ConcurrentMap getEventMap() { + return eventMap; + } + + public void setEventMap(ConcurrentMap eventMap) { + this.eventMap = eventMap; + } + +} diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/appender/MapAppenderIntegrationTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/appender/MapAppenderIntegrationTest.java new file mode 100644 index 0000000000..020aaafc74 --- /dev/null +++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/appender/MapAppenderIntegrationTest.java @@ -0,0 +1,35 @@ +package com.baeldung.logging.log4j2.appender; + +import static org.junit.Assert.assertEquals; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.core.LoggerContext; +import org.apache.logging.log4j.core.config.Configuration; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class MapAppenderIntegrationTest { + + private Logger logger; + + @Before + public void setup() { + logger = LogManager.getLogger(MapAppenderIntegrationTest.class); + } + + @Test + public void whenLoggerEmitsLoggingEvent_thenAppenderReceivesEvent() throws Exception { + logger.info("Test from {}", this.getClass() + .getSimpleName()); + LoggerContext context = LoggerContext.getContext(false); + Configuration config = context.getConfiguration(); + MapAppender appender = config.getAppender("MapAppender"); + assertEquals(appender.getEventMap() + .size(), 1); + } + +} diff --git a/logging-modules/log4j2/src/test/resources/log4j2.xml b/logging-modules/log4j2/src/test/resources/log4j2.xml index 83b664a507..246ffb0707 100644 --- a/logging-modules/log4j2/src/test/resources/log4j2.xml +++ b/logging-modules/log4j2/src/test/resources/log4j2.xml @@ -1,6 +1,6 @@ - + @@ -50,6 +50,7 @@ size="17 kB" /> + + \ No newline at end of file From ffbeb78ee1b6d7899a33f18dc9adc9ae03d6bcb4 Mon Sep 17 00:00:00 2001 From: Mher Baghinyan Date: Fri, 27 Jul 2018 21:00:13 +0400 Subject: [PATCH 17/22] Bael 1743 improved (#4826) * compile only for firefox * added parent module * changed artifact id --- google-web-toolkit/pom.xml | 8 +++++++- .../src/main/java/com/baeldung/Google_web_toolkit.gwt.xml | 2 ++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/google-web-toolkit/pom.xml b/google-web-toolkit/pom.xml index e392ce4e8c..b2f7cab355 100644 --- a/google-web-toolkit/pom.xml +++ b/google-web-toolkit/pom.xml @@ -6,10 +6,16 @@ 4.0.0 com.baeldung - google-web-toolkit + google_web_toolkit war 1.0-SNAPSHOT + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + diff --git a/google-web-toolkit/src/main/java/com/baeldung/Google_web_toolkit.gwt.xml b/google-web-toolkit/src/main/java/com/baeldung/Google_web_toolkit.gwt.xml index 1d8ca819d9..9bd74ccb50 100644 --- a/google-web-toolkit/src/main/java/com/baeldung/Google_web_toolkit.gwt.xml +++ b/google-web-toolkit/src/main/java/com/baeldung/Google_web_toolkit.gwt.xml @@ -22,6 +22,8 @@ + + From 0a1e10b128551eb0a5b459893d443cc3b28c6818 Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Fri, 27 Jul 2018 22:56:18 +0300 Subject: [PATCH 18/22] commenting out problematic modules in the integration-lite build --- pom.xml | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/pom.xml b/pom.xml index 06ec82e5f0..7386eed4a6 100644 --- a/pom.xml +++ b/pom.xml @@ -906,7 +906,7 @@ linkrest logging-modules/log-mdc logging-modules/log4j - logging-modules/log4j2 + logging-modules/logback lombok mapstruct @@ -962,19 +962,19 @@ spring-cucumber spring-ejb spring-aop - spring-data-couchbase-2 + persistence-modules/spring-data-dynamodb spring-data-keyvalue spring-data-mongodb persistence-modules/spring-data-neo4j - persistence-modules/spring-data-redis + spring-data-rest persistence-modules/spring-data-solr spring-dispatcher-servlet spring-exceptions spring-freemarker persistence-modules/spring-hibernate-3 - spring-hibernate4 + persistence-modules/spring-hibernate-5 persistence-modules/spring-data-eclipselink spring-integration @@ -1041,13 +1041,13 @@ testing-modules/testing testing-modules/testng video-tutorials - xml + xmlunit-2 struts-2 apache-velocity apache-solrj rabbitmq - vertx + persistence-modules/spring-data-gemfire mybatis spring-drools @@ -1082,6 +1082,13 @@ ejb persistence-modules/java-cassandra persistence-modules/spring-data-cassandra + logging-modules/log4j2 + spring-data-couchbase-2 + persistence-modules/spring-data-redis + spring-hibernate4 + xml + vertx + --> From 738e3af007bbf81bbe3432e69975283f86b8242f Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Fri, 27 Jul 2018 23:32:13 +0300 Subject: [PATCH 19/22] integratio-lite profile work --- pom.xml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 7386eed4a6..2fea45e612 100644 --- a/pom.xml +++ b/pom.xml @@ -877,7 +877,7 @@ spring-static-resources hazelcast hbase - httpclient + hystrix image-processing immutables @@ -910,7 +910,7 @@ logging-modules/logback lombok mapstruct - metrics + maven mesos-marathon msf4j @@ -1088,7 +1088,8 @@ spring-hibernate4 xml vertx - + metrics + httpclient --> From 25fb0c94c281d2e8119ff7a38a66aae3088b49c0 Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Sat, 28 Jul 2018 00:17:37 +0300 Subject: [PATCH 20/22] integration-lite work --- pom.xml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 2fea45e612..263e4df637 100644 --- a/pom.xml +++ b/pom.xml @@ -980,7 +980,7 @@ spring-integration spring-jenkins-pipeline spring-jersey - jmeter + spring-jms spring-jooq persistence-modules/spring-jpa @@ -1090,6 +1090,8 @@ vertx metrics httpclient + + jmeter --> From fc02400f5f01084a82ba39a851e053dad946c49a Mon Sep 17 00:00:00 2001 From: Alejandro Gervasio Date: Sat, 28 Jul 2018 03:44:51 -0300 Subject: [PATCH 21/22] BAEL-1818 A Simple Guide to Connection Pooling in Java (#4823) * Initial Commit * Update parent pom.xml * Update BasicConnectionPool class * Update BasicConnectionPool class * BAEL-1818 removed code from core-java module, cleaned up a little pom files * BAEL-1818 moved the code from connectionpool.connectionpools package to connectionpool --- core-java-persistence/pom.xml | 59 ++++++ .../connectionpool}/BasicConnectionPool.java | 177 +++++++++--------- .../connectionpool}/C3poDataSource.java | 54 +++--- .../connectionpool}/ConnectionPool.java | 40 ++-- .../connectionpool}/DBCPDataSource.java | 50 ++--- .../connectionpool}/HikariCPDataSource.java | 56 +++--- .../BasicConnectionPoolUnitTest.java | 4 +- .../C3poDataSourceUnitTest.java | 1 - .../DBCPDataSourceUnitTest.java | 1 - .../HikariCPDataSourceUnitTest.java | 1 - core-java/pom.xml | 20 -- pom.xml | 25 ++- 12 files changed, 267 insertions(+), 221 deletions(-) create mode 100644 core-java-persistence/pom.xml rename {core-java/src/main/java/com/baeldung/connectionpool/connectionpools => core-java-persistence/src/main/java/com/baeldung/connectionpool}/BasicConnectionPool.java (93%) rename {core-java/src/main/java/com/baeldung/connectionpool/connectionpools => core-java-persistence/src/main/java/com/baeldung/connectionpool}/C3poDataSource.java (89%) rename {core-java/src/main/java/com/baeldung/connectionpool/connectionpools => core-java-persistence/src/main/java/com/baeldung/connectionpool}/ConnectionPool.java (66%) rename {core-java/src/main/java/com/baeldung/connectionpool/connectionpools => core-java-persistence/src/main/java/com/baeldung/connectionpool}/DBCPDataSource.java (88%) rename {core-java/src/main/java/com/baeldung/connectionpool/connectionpools => core-java-persistence/src/main/java/com/baeldung/connectionpool}/HikariCPDataSource.java (91%) rename {core-java => core-java-persistence}/src/test/java/com/baeldung/connectionpool/BasicConnectionPoolUnitTest.java (91%) rename {core-java => core-java-persistence}/src/test/java/com/baeldung/connectionpool/C3poDataSourceUnitTest.java (81%) rename {core-java => core-java-persistence}/src/test/java/com/baeldung/connectionpool/DBCPDataSourceUnitTest.java (81%) rename {core-java => core-java-persistence}/src/test/java/com/baeldung/connectionpool/HikariCPDataSourceUnitTest.java (81%) diff --git a/core-java-persistence/pom.xml b/core-java-persistence/pom.xml new file mode 100644 index 0000000000..0cb142c7b8 --- /dev/null +++ b/core-java-persistence/pom.xml @@ -0,0 +1,59 @@ + + 4.0.0 + com.baeldung.core-java-persistence + core-java-persistence + 0.1.0-SNAPSHOT + jar + core-java-persistence + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + com.h2database + h2 + ${h2database.version} + + + org.apache.commons + commons-dbcp2 + ${commons-dbcp2.version} + + + com.zaxxer + HikariCP + ${HikariCP.version} + + + com.mchange + c3p0 + ${c3p0.version} + + + + core-java-persistence + + + src/main/resources + true + + + + + 3.10.0 + 1.4.197 + 2.4.0 + 3.2.0 + 0.9.5.2 + + \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/BasicConnectionPool.java b/core-java-persistence/src/main/java/com/baeldung/connectionpool/BasicConnectionPool.java similarity index 93% rename from core-java/src/main/java/com/baeldung/connectionpool/connectionpools/BasicConnectionPool.java rename to core-java-persistence/src/main/java/com/baeldung/connectionpool/BasicConnectionPool.java index 1934d0cfc2..289db18c53 100644 --- a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/BasicConnectionPool.java +++ b/core-java-persistence/src/main/java/com/baeldung/connectionpool/BasicConnectionPool.java @@ -1,85 +1,92 @@ -package com.baeldung.connectionpool.connectionpools; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - -public class BasicConnectionPool implements ConnectionPool { - - private final String url; - private final String user; - private final String password; - private final List connectionPool; - private final List usedConnections = new ArrayList<>(); - private static final int INITIAL_POOL_SIZE = 10; - private final int MAX_POOL_SIZE = 20; - - public static BasicConnectionPool create(String url, String user, String password) throws SQLException { - List pool = new ArrayList<>(INITIAL_POOL_SIZE); - for (int i = 0; i < INITIAL_POOL_SIZE; i++) { - pool.add(createConnection(url, user, password)); - } - return new BasicConnectionPool(url, user, password, pool); - } - - private BasicConnectionPool(String url, String user, String password, List connectionPool) { - this.url = url; - this.user = user; - this.password = password; - this.connectionPool = connectionPool; - } - - @Override - public Connection getConnection() throws SQLException { - if (connectionPool.isEmpty()) { - if (usedConnections.size() < MAX_POOL_SIZE) { - connectionPool.add(createConnection(url, user, password)); - } else { - throw new RuntimeException("Maximum pool size reached, no available connections!"); - } - } - - Connection connection = connectionPool.remove(connectionPool.size() - 1); - usedConnections.add(connection); - return connection; - } - - @Override - public boolean releaseConnection(Connection connection) { - connectionPool.add(connection); - return usedConnections.remove(connection); - } - - private static Connection createConnection(String url, String user, String password) throws SQLException { - return DriverManager.getConnection(url, user, password); - } - - public int getSize() { - return connectionPool.size() + usedConnections.size(); - } - - @Override - public String getUrl() { - return url; - } - - @Override - public String getUser() { - return user; - } - - @Override - public String getPassword() { - return password; - } - - public void shutdown() throws SQLException { - usedConnections.forEach(this::releaseConnection); - for (Connection c : connectionPool) { - c.close(); - } - connectionPool.clear(); - } -} +package com.baeldung.connectionpool; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +public class BasicConnectionPool implements ConnectionPool { + + private final String url; + private final String user; + private final String password; + private final List connectionPool; + private final List usedConnections = new ArrayList<>(); + private static final int INITIAL_POOL_SIZE = 10; + private final int MAX_POOL_SIZE = 20; + + public static BasicConnectionPool create(String url, String user, String password) throws SQLException { + List pool = new ArrayList<>(INITIAL_POOL_SIZE); + for (int i = 0; i < INITIAL_POOL_SIZE; i++) { + pool.add(createConnection(url, user, password)); + } + return new BasicConnectionPool(url, user, password, pool); + } + + private BasicConnectionPool(String url, String user, String password, List connectionPool) { + this.url = url; + this.user = user; + this.password = password; + this.connectionPool = connectionPool; + } + + @Override + public Connection getConnection() throws SQLException { + if (connectionPool.isEmpty()) { + if (usedConnections.size() < MAX_POOL_SIZE) { + connectionPool.add(createConnection(url, user, password)); + } else { + throw new RuntimeException("Maximum pool size reached, no available connections!"); + } + } + + Connection connection = connectionPool.remove(connectionPool.size() - 1); + usedConnections.add(connection); + return connection; + } + + @Override + public boolean releaseConnection(Connection connection) { + connectionPool.add(connection); + return usedConnections.remove(connection); + } + + private static Connection createConnection(String url, String user, String password) throws SQLException { + return DriverManager.getConnection(url, user, password); + } + + @Override + public int getSize() { + return connectionPool.size() + usedConnections.size(); + } + + @Override + public List getConnectionPool() { + return connectionPool; + } + + @Override + public String getUrl() { + return url; + } + + @Override + public String getUser() { + return user; + } + + @Override + public String getPassword() { + return password; + } + + @Override + public void shutdown() throws SQLException { + usedConnections.forEach(this::releaseConnection); + for (Connection c : connectionPool) { + c.close(); + } + connectionPool.clear(); + } +} diff --git a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/C3poDataSource.java b/core-java-persistence/src/main/java/com/baeldung/connectionpool/C3poDataSource.java similarity index 89% rename from core-java/src/main/java/com/baeldung/connectionpool/connectionpools/C3poDataSource.java rename to core-java-persistence/src/main/java/com/baeldung/connectionpool/C3poDataSource.java index 5b91f707a9..78642459d5 100644 --- a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/C3poDataSource.java +++ b/core-java-persistence/src/main/java/com/baeldung/connectionpool/C3poDataSource.java @@ -1,28 +1,28 @@ -package com.baeldung.connectionpool.connectionpools; - -import com.mchange.v2.c3p0.ComboPooledDataSource; -import java.beans.PropertyVetoException; -import java.sql.Connection; -import java.sql.SQLException; - -public class C3poDataSource { - - private static final ComboPooledDataSource cpds = new ComboPooledDataSource(); - - static { - try { - cpds.setDriverClass("org.h2.Driver"); - cpds.setJdbcUrl("jdbc:h2:mem:test"); - cpds.setUser("user"); - cpds.setPassword("password"); - } catch (PropertyVetoException e) { - e.printStackTrace(); - } - } - - public static Connection getConnection() throws SQLException { - return cpds.getConnection(); - } - - private C3poDataSource(){} +package com.baeldung.connectionpool; + +import com.mchange.v2.c3p0.ComboPooledDataSource; +import java.beans.PropertyVetoException; +import java.sql.Connection; +import java.sql.SQLException; + +public class C3poDataSource { + + private static final ComboPooledDataSource cpds = new ComboPooledDataSource(); + + static { + try { + cpds.setDriverClass("org.h2.Driver"); + cpds.setJdbcUrl("jdbc:h2:mem:test"); + cpds.setUser("user"); + cpds.setPassword("password"); + } catch (PropertyVetoException e) { + e.printStackTrace(); + } + } + + public static Connection getConnection() throws SQLException { + return cpds.getConnection(); + } + + private C3poDataSource(){} } \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/ConnectionPool.java b/core-java-persistence/src/main/java/com/baeldung/connectionpool/ConnectionPool.java similarity index 66% rename from core-java/src/main/java/com/baeldung/connectionpool/connectionpools/ConnectionPool.java rename to core-java-persistence/src/main/java/com/baeldung/connectionpool/ConnectionPool.java index 3d5ad06c3d..fa9355721b 100644 --- a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/ConnectionPool.java +++ b/core-java-persistence/src/main/java/com/baeldung/connectionpool/ConnectionPool.java @@ -1,18 +1,24 @@ -package com.baeldung.connectionpool.connectionpools; - -import java.sql.Connection; -import java.sql.SQLException; -import java.util.List; - -public interface ConnectionPool { - - Connection getConnection() throws SQLException; - - boolean releaseConnection(Connection connection); - - String getUrl(); - - String getUser(); - - String getPassword(); +package com.baeldung.connectionpool; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.List; + +public interface ConnectionPool { + + Connection getConnection() throws SQLException; + + boolean releaseConnection(Connection connection); + + List getConnectionPool(); + + int getSize(); + + String getUrl(); + + String getUser(); + + String getPassword(); + + void shutdown() throws SQLException;; } \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/DBCPDataSource.java b/core-java-persistence/src/main/java/com/baeldung/connectionpool/DBCPDataSource.java similarity index 88% rename from core-java/src/main/java/com/baeldung/connectionpool/connectionpools/DBCPDataSource.java rename to core-java-persistence/src/main/java/com/baeldung/connectionpool/DBCPDataSource.java index 2f33cde883..1e33a08d46 100644 --- a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/DBCPDataSource.java +++ b/core-java-persistence/src/main/java/com/baeldung/connectionpool/DBCPDataSource.java @@ -1,25 +1,25 @@ -package com.baeldung.connectionpool.connectionpools; - -import java.sql.Connection; -import java.sql.SQLException; -import org.apache.commons.dbcp2.BasicDataSource; - -public class DBCPDataSource { - - private static final BasicDataSource ds = new BasicDataSource(); - - static { - ds.setUrl("jdbc:h2:mem:test"); - ds.setUsername("user"); - ds.setPassword("password"); - ds.setMinIdle(5); - ds.setMaxIdle(10); - ds.setMaxOpenPreparedStatements(100); - } - - public static Connection getConnection() throws SQLException { - return ds.getConnection(); - } - - private DBCPDataSource(){} -} +package com.baeldung.connectionpool; + +import java.sql.Connection; +import java.sql.SQLException; +import org.apache.commons.dbcp2.BasicDataSource; + +public class DBCPDataSource { + + private static final BasicDataSource ds = new BasicDataSource(); + + static { + ds.setUrl("jdbc:h2:mem:test"); + ds.setUsername("user"); + ds.setPassword("password"); + ds.setMinIdle(5); + ds.setMaxIdle(10); + ds.setMaxOpenPreparedStatements(100); + } + + public static Connection getConnection() throws SQLException { + return ds.getConnection(); + } + + private DBCPDataSource(){} +} diff --git a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/HikariCPDataSource.java b/core-java-persistence/src/main/java/com/baeldung/connectionpool/HikariCPDataSource.java similarity index 91% rename from core-java/src/main/java/com/baeldung/connectionpool/connectionpools/HikariCPDataSource.java rename to core-java-persistence/src/main/java/com/baeldung/connectionpool/HikariCPDataSource.java index 5ed2de181d..cc0cc24520 100644 --- a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/HikariCPDataSource.java +++ b/core-java-persistence/src/main/java/com/baeldung/connectionpool/HikariCPDataSource.java @@ -1,28 +1,28 @@ -package com.baeldung.connectionpool.connectionpools; - -import com.zaxxer.hikari.HikariConfig; -import com.zaxxer.hikari.HikariDataSource; -import java.sql.Connection; -import java.sql.SQLException; - -public class HikariCPDataSource { - - private static final HikariConfig config = new HikariConfig(); - private static final HikariDataSource ds; - - static { - config.setJdbcUrl("jdbc:h2:mem:test"); - config.setUsername("user"); - config.setPassword("password"); - config.addDataSourceProperty("cachePrepStmts", "true"); - config.addDataSourceProperty("prepStmtCacheSize", "250"); - config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); - ds = new HikariDataSource(config); - } - - public static Connection getConnection() throws SQLException { - return ds.getConnection(); - } - - private HikariCPDataSource(){} -} +package com.baeldung.connectionpool; + +import com.zaxxer.hikari.HikariConfig; +import com.zaxxer.hikari.HikariDataSource; +import java.sql.Connection; +import java.sql.SQLException; + +public class HikariCPDataSource { + + private static final HikariConfig config = new HikariConfig(); + private static final HikariDataSource ds; + + static { + config.setJdbcUrl("jdbc:h2:mem:test"); + config.setUsername("user"); + config.setPassword("password"); + config.addDataSourceProperty("cachePrepStmts", "true"); + config.addDataSourceProperty("prepStmtCacheSize", "250"); + config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); + ds = new HikariDataSource(config); + } + + public static Connection getConnection() throws SQLException { + return ds.getConnection(); + } + + private HikariCPDataSource(){} +} diff --git a/core-java/src/test/java/com/baeldung/connectionpool/BasicConnectionPoolUnitTest.java b/core-java-persistence/src/test/java/com/baeldung/connectionpool/BasicConnectionPoolUnitTest.java similarity index 91% rename from core-java/src/test/java/com/baeldung/connectionpool/BasicConnectionPoolUnitTest.java rename to core-java-persistence/src/test/java/com/baeldung/connectionpool/BasicConnectionPoolUnitTest.java index 5edc6bba94..479cd0db25 100644 --- a/core-java/src/test/java/com/baeldung/connectionpool/BasicConnectionPoolUnitTest.java +++ b/core-java-persistence/src/test/java/com/baeldung/connectionpool/BasicConnectionPoolUnitTest.java @@ -1,10 +1,8 @@ package com.baeldung.connectionpool; -import com.baeldung.connectionpool.connectionpools.BasicConnectionPool; -import com.baeldung.connectionpool.connectionpools.ConnectionPool; import java.sql.Connection; import java.sql.SQLException; -import java.util.List; + import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; diff --git a/core-java/src/test/java/com/baeldung/connectionpool/C3poDataSourceUnitTest.java b/core-java-persistence/src/test/java/com/baeldung/connectionpool/C3poDataSourceUnitTest.java similarity index 81% rename from core-java/src/test/java/com/baeldung/connectionpool/C3poDataSourceUnitTest.java rename to core-java-persistence/src/test/java/com/baeldung/connectionpool/C3poDataSourceUnitTest.java index a02daa40f6..a07fa9e74b 100644 --- a/core-java/src/test/java/com/baeldung/connectionpool/C3poDataSourceUnitTest.java +++ b/core-java-persistence/src/test/java/com/baeldung/connectionpool/C3poDataSourceUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.connectionpool; -import com.baeldung.connectionpool.connectionpools.C3poDataSource; import java.sql.SQLException; import static org.junit.Assert.assertTrue; import org.junit.Test; diff --git a/core-java/src/test/java/com/baeldung/connectionpool/DBCPDataSourceUnitTest.java b/core-java-persistence/src/test/java/com/baeldung/connectionpool/DBCPDataSourceUnitTest.java similarity index 81% rename from core-java/src/test/java/com/baeldung/connectionpool/DBCPDataSourceUnitTest.java rename to core-java-persistence/src/test/java/com/baeldung/connectionpool/DBCPDataSourceUnitTest.java index 9583eedf4b..43aaf330b6 100644 --- a/core-java/src/test/java/com/baeldung/connectionpool/DBCPDataSourceUnitTest.java +++ b/core-java-persistence/src/test/java/com/baeldung/connectionpool/DBCPDataSourceUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.connectionpool; -import com.baeldung.connectionpool.connectionpools.DBCPDataSource; import java.sql.SQLException; import static org.junit.Assert.assertTrue; import org.junit.Test; diff --git a/core-java/src/test/java/com/baeldung/connectionpool/HikariCPDataSourceUnitTest.java b/core-java-persistence/src/test/java/com/baeldung/connectionpool/HikariCPDataSourceUnitTest.java similarity index 81% rename from core-java/src/test/java/com/baeldung/connectionpool/HikariCPDataSourceUnitTest.java rename to core-java-persistence/src/test/java/com/baeldung/connectionpool/HikariCPDataSourceUnitTest.java index 6b78815797..b20ce70efd 100644 --- a/core-java/src/test/java/com/baeldung/connectionpool/HikariCPDataSourceUnitTest.java +++ b/core-java-persistence/src/test/java/com/baeldung/connectionpool/HikariCPDataSourceUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.connectionpool; -import com.baeldung.connectionpool.connectionpools.HikariCPDataSource; import java.sql.SQLException; import static org.junit.Assert.assertTrue; import org.junit.Test; diff --git a/core-java/pom.xml b/core-java/pom.xml index 0b69685e14..b83cb478d4 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -158,21 +158,6 @@ jmimemagic ${jmime-magic.version} - - org.apache.commons - commons-dbcp2 - ${commons-dbcp2.version} - - - com.zaxxer - HikariCP - ${HikariCP.version} - - - com.mchange - c3p0 - ${c3p0.version} - org.javassist @@ -544,11 +529,6 @@ 3.10.0 - - 2.4.0 - 3.2.0 - 0.9.5.2 - 2.19.1 4.3.4.RELEASE diff --git a/pom.xml b/pom.xml index 263e4df637..1730449509 100644 --- a/pom.xml +++ b/pom.xml @@ -312,6 +312,7 @@ core-java-collections core-java-io core-java-8 + core-java-persistence core-kotlin core-groovy core-java-concurrency @@ -877,7 +878,7 @@ spring-static-resources hazelcast hbase - + hystrix image-processing immutables @@ -906,11 +907,11 @@ linkrest logging-modules/log-mdc logging-modules/log4j - + logging-modules/logback lombok mapstruct - + maven mesos-marathon msf4j @@ -962,25 +963,25 @@ spring-cucumber spring-ejb spring-aop - + persistence-modules/spring-data-dynamodb spring-data-keyvalue spring-data-mongodb persistence-modules/spring-data-neo4j - + spring-data-rest persistence-modules/spring-data-solr spring-dispatcher-servlet spring-exceptions spring-freemarker persistence-modules/spring-hibernate-3 - + persistence-modules/spring-hibernate-5 persistence-modules/spring-data-eclipselink spring-integration spring-jenkins-pipeline spring-jersey - + spring-jms spring-jooq persistence-modules/spring-jpa @@ -1041,13 +1042,13 @@ testing-modules/testing testing-modules/testng video-tutorials - + xmlunit-2 struts-2 apache-velocity apache-solrj rabbitmq - + persistence-modules/spring-data-gemfire mybatis spring-drools @@ -1090,7 +1091,7 @@ vertx metrics httpclient - + jmeter --> @@ -1233,6 +1234,4 @@ 3.8 - - - + \ No newline at end of file From 33889d0cd7bcb78efd3586e2d1082edf6d8487d2 Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Sat, 28 Jul 2018 11:01:48 +0300 Subject: [PATCH 22/22] integration-lite trying out a few modules --- pom.xml | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/pom.xml b/pom.xml index 1730449509..6f2351b56f 100644 --- a/pom.xml +++ b/pom.xml @@ -859,7 +859,7 @@ core-java-io core-java-8 core-groovy - core-java-concurrency + couchbase deltaspike dozer @@ -1078,6 +1078,12 @@ apache-meecrowave testing-modules/junit-abstract + spring-hibernate4 + xml + vertx + metrics + httpclient + @@ -1108,6 +1109,7 @@ core-java google-web-toolkit spring-security-mvc-custom + core-java-concurrency --> @@ -1170,7 +1172,7 @@ spring-security-mvc-custom hibernate5 spring-data-elasticsearch - + core-java-concurrency