From 0f22f7b82ab0e5ae7c4f96b2a85bc1ca440589d4 Mon Sep 17 00:00:00 2001 From: eugenp Date: Wed, 13 Sep 2017 14:41:03 +0300 Subject: [PATCH] formatting work --- .../test/kotlin/com/baeldung/LiveTest.java | 22 +-- .../java/com/baeldung/Spring5Application.java | 2 +- .../com/baeldung/functional/FormHandler.java | 27 ++-- .../FunctionalSpringBootApplication.java | 38 ++--- .../functional/FunctionalWebApplication.java | 31 ++-- .../functional/IndexRewriteFilter.java | 20 ++- .../com/baeldung/functional/MyService.java | 4 +- .../com/baeldung/functional/RootServlet.java | 63 ++++---- .../jupiter/ParameterAutowireUtils.java | 10 +- .../com/baeldung/jupiter/SpringExtension.java | 38 ++--- .../baeldung/jupiter/SpringJUnit5Config.java | 3 +- .../baeldung/persistence/DataSetupBean.java | 3 +- .../java/com/baeldung/web/FooController.java | 6 +- .../java/com/baeldung/web/reactive/Task.java | 5 +- .../reactive/client/WebClientController.java | 38 +++-- .../com/baeldung/ParallelIntegrationTest.java | 4 +- ...pring5JUnit4ConcurrentIntegrationTest.java | 2 - ...nctionalWebApplicationIntegrationTest.java | 148 ++++++++---------- .../Spring5JUnit5ParallelIntegrationTest.java | 8 +- ...pring5Java8NewFeaturesIntegrationTest.java | 14 +- ...g5ReactiveServerClientIntegrationTest.java | 110 ++++++------- ...ernsUsingHandlerMethodIntegrationTest.java | 82 +++++----- .../web/client/WebTestClientTest.java | 42 ++--- 23 files changed, 334 insertions(+), 386 deletions(-) diff --git a/spring-5-mvc/src/test/kotlin/com/baeldung/LiveTest.java b/spring-5-mvc/src/test/kotlin/com/baeldung/LiveTest.java index 1b52f89117..b2f2852dbe 100644 --- a/spring-5-mvc/src/test/kotlin/com/baeldung/LiveTest.java +++ b/spring-5-mvc/src/test/kotlin/com/baeldung/LiveTest.java @@ -14,16 +14,19 @@ public class LiveTest { private static String APP_ROOT = "http://localhost:8081"; - @Test public void givenUser_whenResourceCreatedWithNullName_then400BadRequest() { - final Response response = givenAuth("user", "pass").contentType(MediaType.APPLICATION_JSON.toString()).body(resourceWithNullName()).post(APP_ROOT + "/foos"); + final Response response = givenAuth("user", "pass").contentType(MediaType.APPLICATION_JSON.toString()) + .body(resourceWithNullName()) + .post(APP_ROOT + "/foos"); assertEquals(400, response.getStatusCode()); } - + @Test public void givenUser_whenResourceCreated_then201Created() { - final Response response = givenAuth("user", "pass").contentType(MediaType.APPLICATION_JSON.toString()).body(resourceString()).post(APP_ROOT + "/foos"); + final Response response = givenAuth("user", "pass").contentType(MediaType.APPLICATION_JSON.toString()) + .body(resourceString()) + .post(APP_ROOT + "/foos"); assertEquals(201, response.getStatusCode()); } @@ -32,21 +35,22 @@ public class LiveTest { final Response response = givenAuth("user", "pass").get(APP_ROOT + "/foos"); assertEquals(200, response.getStatusCode()); }*/ - - // private final String resourceWithNullName() { return "{\"name\":null}"; } - + private final String resourceString() { return "{\"name\":\"" + randomAlphabetic(8) + "\"}"; - } + } private final RequestSpecification givenAuth(String username, String password) { - return RestAssured.given().auth().preemptive().basic(username, password); + return RestAssured.given() + .auth() + .preemptive() + .basic(username, password); } } \ No newline at end of file diff --git a/spring-5/src/main/java/com/baeldung/Spring5Application.java b/spring-5/src/main/java/com/baeldung/Spring5Application.java index aaff1797ff..f321871646 100644 --- a/spring-5/src/main/java/com/baeldung/Spring5Application.java +++ b/spring-5/src/main/java/com/baeldung/Spring5Application.java @@ -5,7 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication -@ComponentScan(basePackages = {"com.baeldung.web"}) +@ComponentScan(basePackages = { "com.baeldung.web" }) public class Spring5Application { public static void main(String[] args) { diff --git a/spring-5/src/main/java/com/baeldung/functional/FormHandler.java b/spring-5/src/main/java/com/baeldung/functional/FormHandler.java index 857d22a67f..05069735bb 100644 --- a/spring-5/src/main/java/com/baeldung/functional/FormHandler.java +++ b/spring-5/src/main/java/com/baeldung/functional/FormHandler.java @@ -17,28 +17,25 @@ 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()); + 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()))); + 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)); + 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 index 8a808fc83a..f181dcb8e8 100644 --- a/spring-5/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java +++ b/spring-5/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java @@ -40,28 +40,25 @@ public class FunctionalSpringBootApplication { 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())); + 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); - }); + 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())) - .prependFilter(new IndexRewriteFilter()) - .build(); + HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler((WebHandler) toHttpHandler(routingFunction())) + .prependFilter(new IndexRewriteFilter()) + .build(); ServletRegistrationBean registrationBean = new ServletRegistrationBean<>(new RootServlet(httpHandler), "/"); registrationBean.setLoadOnStartup(1); registrationBean.setAsyncSupported(true); @@ -74,10 +71,9 @@ public class FunctionalSpringBootApplication { static class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(final HttpSecurity http) throws Exception { - http - .authorizeRequests() - .anyRequest() - .permitAll(); + http.authorizeRequests() + .anyRequest() + .permitAll(); } } diff --git a/spring-5/src/main/java/com/baeldung/functional/FunctionalWebApplication.java b/spring-5/src/main/java/com/baeldung/functional/FunctionalWebApplication.java index 29f9ea43da..2a4642c484 100644 --- a/spring-5/src/main/java/com/baeldung/functional/FunctionalWebApplication.java +++ b/spring-5/src/main/java/com/baeldung/functional/FunctionalWebApplication.java @@ -33,28 +33,25 @@ public class FunctionalWebApplication { 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())); + 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); - }); + 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) - .prependFilter(new IndexRewriteFilter()) - .build(); + HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler(webHandler) + .prependFilter(new IndexRewriteFilter()) + .build(); Tomcat tomcat = new Tomcat(); tomcat.setHostname("localhost"); diff --git a/spring-5/src/main/java/com/baeldung/functional/IndexRewriteFilter.java b/spring-5/src/main/java/com/baeldung/functional/IndexRewriteFilter.java index d218bba581..3e91a0354b 100644 --- a/spring-5/src/main/java/com/baeldung/functional/IndexRewriteFilter.java +++ b/spring-5/src/main/java/com/baeldung/functional/IndexRewriteFilter.java @@ -11,17 +11,15 @@ 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()) - .contextPath(request.getPath().toString()) - .path("/test")) - .build()); + if (request.getURI() + .getPath() + .equals("/")) { + return webFilterChain.filter(serverWebExchange.mutate() + .request(builder -> builder.method(request.getMethod()) + .contextPath(request.getPath() + .toString()) + .path("/test")) + .build()); } return webFilterChain.filter(serverWebExchange); } diff --git a/spring-5/src/main/java/com/baeldung/functional/MyService.java b/spring-5/src/main/java/com/baeldung/functional/MyService.java index 1e555a5e1b..b7b8b13d8b 100644 --- a/spring-5/src/main/java/com/baeldung/functional/MyService.java +++ b/spring-5/src/main/java/com/baeldung/functional/MyService.java @@ -4,8 +4,8 @@ import java.util.Random; public class MyService { - public int getRandomNumber(){ + public int getRandomNumber() { return (new Random().nextInt(10)); } - + } diff --git a/spring-5/src/main/java/com/baeldung/functional/RootServlet.java b/spring-5/src/main/java/com/baeldung/functional/RootServlet.java index 922809e563..c0dd54cb4a 100644 --- a/spring-5/src/main/java/com/baeldung/functional/RootServlet.java +++ b/spring-5/src/main/java/com/baeldung/functional/RootServlet.java @@ -28,10 +28,9 @@ import org.springframework.web.server.WebHandler; public class RootServlet extends ServletHttpHandlerAdapter { public RootServlet() { - this(WebHttpHandlerBuilder - .webHandler((WebHandler) toHttpHandler(routingFunction())) - .prependFilter(new IndexRewriteFilter()) - .build()); + this(WebHttpHandlerBuilder.webHandler((WebHandler) toHttpHandler(routingFunction())) + .prependFilter(new IndexRewriteFilter()) + .build()); } RootServlet(HttpHandler httpHandler) { @@ -44,44 +43,36 @@ public class RootServlet extends ServletHttpHandlerAdapter { private static RouterFunction routingFunction() { - return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))) - .andRoute(POST("/login"), serverRequest -> serverRequest - .body(toFormData()) + 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 ok().body(Mono.just("welcome back!"), String.class) + .block(); } - return ServerResponse - .badRequest() - .build() - .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); - }); + .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/jupiter/ParameterAutowireUtils.java b/spring-5/src/main/java/com/baeldung/jupiter/ParameterAutowireUtils.java index 068c6af381..d1a4cc8b29 100644 --- a/spring-5/src/main/java/com/baeldung/jupiter/ParameterAutowireUtils.java +++ b/spring-5/src/main/java/com/baeldung/jupiter/ParameterAutowireUtils.java @@ -27,16 +27,14 @@ abstract class ParameterAutowireUtils { public static Object resolveDependency(Parameter parameter, Class containingClass, ApplicationContext applicationContext) { - boolean required = findMergedAnnotation(parameter, Autowired.class) - .map(Autowired::required) - .orElse(true); + boolean required = findMergedAnnotation(parameter, Autowired.class).map(Autowired::required) + .orElse(true); MethodParameter methodParameter = (parameter.getDeclaringExecutable() instanceof Method ? MethodParameterFactory.createSynthesizingMethodParameter(parameter) : MethodParameterFactory.createMethodParameter(parameter)); DependencyDescriptor descriptor = new DependencyDescriptor(methodParameter, required); descriptor.setContainingClass(containingClass); - return applicationContext - .getAutowireCapableBeanFactory() - .resolveDependency(descriptor, null); + return applicationContext.getAutowireCapableBeanFactory() + .resolveDependency(descriptor, null); } private static Optional findMergedAnnotation(AnnotatedElement element, Class annotationType) { diff --git a/spring-5/src/main/java/com/baeldung/jupiter/SpringExtension.java b/spring-5/src/main/java/com/baeldung/jupiter/SpringExtension.java index 08fa0c4768..0eb7c861f1 100644 --- a/spring-5/src/main/java/com/baeldung/jupiter/SpringExtension.java +++ b/spring-5/src/main/java/com/baeldung/jupiter/SpringExtension.java @@ -26,11 +26,9 @@ public class SpringExtension implements BeforeAllCallback, AfterAllCallback, Tes try { getTestContextManager(context).afterTestClass(); } finally { - context - .getStore(namespace) - .remove(context - .getTestClass() - .get()); + context.getStore(namespace) + .remove(context.getTestClass() + .get()); } } @@ -42,21 +40,18 @@ public class SpringExtension implements BeforeAllCallback, AfterAllCallback, Tes @Override public void beforeEach(TestExtensionContext context) throws Exception { Object testInstance = context.getTestInstance(); - Method testMethod = context - .getTestMethod() - .get(); + Method testMethod = context.getTestMethod() + .get(); getTestContextManager(context).beforeTestMethod(testInstance, testMethod); } @Override public void afterEach(TestExtensionContext context) throws Exception { Object testInstance = context.getTestInstance(); - Method testMethod = context - .getTestMethod() - .get(); - Throwable testException = context - .getTestException() - .orElse(null); + Method testMethod = context.getTestMethod() + .get(); + Throwable testException = context.getTestException() + .orElse(null); getTestContextManager(context).afterTestMethod(testInstance, testMethod, testException); } @@ -70,24 +65,21 @@ public class SpringExtension implements BeforeAllCallback, AfterAllCallback, Tes @Override public Object resolve(ParameterContext parameterContext, ExtensionContext extensionContext) { Parameter parameter = parameterContext.getParameter(); - Class testClass = extensionContext - .getTestClass() - .get(); + Class testClass = extensionContext.getTestClass() + .get(); ApplicationContext applicationContext = getApplicationContext(extensionContext); return ParameterAutowireUtils.resolveDependency(parameter, testClass, applicationContext); } private ApplicationContext getApplicationContext(ExtensionContext context) { - return getTestContextManager(context) - .getTestContext() - .getApplicationContext(); + return getTestContextManager(context).getTestContext() + .getApplicationContext(); } private TestContextManager getTestContextManager(ExtensionContext context) { Assert.notNull(context, "ExtensionContext must not be null"); - Class testClass = context - .getTestClass() - .get(); + Class testClass = context.getTestClass() + .get(); ExtensionContext.Store store = context.getStore(namespace); return store.getOrComputeIfAbsent(testClass, TestContextManager::new, TestContextManager.class); } diff --git a/spring-5/src/main/java/com/baeldung/jupiter/SpringJUnit5Config.java b/spring-5/src/main/java/com/baeldung/jupiter/SpringJUnit5Config.java index e8b9cc500f..8f02d71d49 100644 --- a/spring-5/src/main/java/com/baeldung/jupiter/SpringJUnit5Config.java +++ b/spring-5/src/main/java/com/baeldung/jupiter/SpringJUnit5Config.java @@ -26,8 +26,7 @@ public @interface SpringJUnit5Config { String[] locations() default {}; @AliasFor(annotation = ContextConfiguration.class) - Class>[] initializers() default {}; + Class>[] initializers() default {}; @AliasFor(annotation = ContextConfiguration.class) boolean inheritLocations() default true; diff --git a/spring-5/src/main/java/com/baeldung/persistence/DataSetupBean.java b/spring-5/src/main/java/com/baeldung/persistence/DataSetupBean.java index 7936a2b7af..9f5d9ff6c2 100644 --- a/spring-5/src/main/java/com/baeldung/persistence/DataSetupBean.java +++ b/spring-5/src/main/java/com/baeldung/persistence/DataSetupBean.java @@ -20,7 +20,8 @@ public class DataSetupBean implements InitializingBean { @Override public void afterPropertiesSet() throws Exception { - IntStream.range(1, 20).forEach(i -> repo.save(new Foo(randomAlphabetic(8)))); + IntStream.range(1, 20) + .forEach(i -> repo.save(new Foo(randomAlphabetic(8)))); } } diff --git a/spring-5/src/main/java/com/baeldung/web/FooController.java b/spring-5/src/main/java/com/baeldung/web/FooController.java index 0e7c94bd8f..925f2b49f4 100644 --- a/spring-5/src/main/java/com/baeldung/web/FooController.java +++ b/spring-5/src/main/java/com/baeldung/web/FooController.java @@ -23,7 +23,8 @@ public class FooController { @ResponseBody @Validated public Foo findById(@PathVariable @Min(0) final long id) { - return repo.findById(id).orElse(null); + return repo.findById(id) + .orElse(null); } @GetMapping @@ -36,7 +37,8 @@ public class FooController { @ResponseBody @Validated public List findPaginated(@RequestParam("page") @Min(0) final int page, @Max(100) @RequestParam("size") final int size) { - return repo.findAll(PageRequest.of(page, size)).getContent(); + return repo.findAll(PageRequest.of(page, size)) + .getContent(); } // API - write diff --git a/spring-5/src/main/java/com/baeldung/web/reactive/Task.java b/spring-5/src/main/java/com/baeldung/web/reactive/Task.java index 84193d9354..725fd931e1 100644 --- a/spring-5/src/main/java/com/baeldung/web/reactive/Task.java +++ b/spring-5/src/main/java/com/baeldung/web/reactive/Task.java @@ -23,9 +23,6 @@ public class Task { @Override public String toString() { - return "Task{" + - "name='" + name + '\'' + - ", id=" + id + - '}'; + return "Task{" + "name='" + name + '\'' + ", id=" + id + '}'; } } 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 index 3a2e1b1a75..7bab288bab 100644 --- 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 @@ -33,17 +33,17 @@ public class WebClientController { 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")); + 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); - + BodyInserter, ReactiveHttpOutputMessage> inserter1 = BodyInserters.fromPublisher(Subscriber::onComplete, String.class); LinkedMultiValueMap map = new LinkedMultiValueMap<>(); map.add("key1", "value1"); @@ -53,14 +53,13 @@ public class WebClientController { 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 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(); } @@ -74,13 +73,12 @@ public class WebClientController { } 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(); + 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/ParallelIntegrationTest.java b/spring-5/src/test/java/com/baeldung/ParallelIntegrationTest.java index cbb7a2867b..1ce96de4ef 100644 --- a/spring-5/src/test/java/com/baeldung/ParallelIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/ParallelIntegrationTest.java @@ -9,14 +9,14 @@ public class ParallelIntegrationTest { @Test public void runTests() { - final Class[] classes = {Example1IntegrationTest.class, Example2IntegrationTest.class}; + final Class[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class }; JUnitCore.runClasses(new Computer(), classes); } @Test public void runTestsInParallel() { - final Class[] classes = {Example1IntegrationTest.class, Example2IntegrationTest.class}; + final Class[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class }; JUnitCore.runClasses(new ParallelComputer(true, true), classes); } diff --git a/spring-5/src/test/java/com/baeldung/Spring5JUnit4ConcurrentIntegrationTest.java b/spring-5/src/test/java/com/baeldung/Spring5JUnit4ConcurrentIntegrationTest.java index a155de20fa..7e494465b2 100644 --- a/spring-5/src/test/java/com/baeldung/Spring5JUnit4ConcurrentIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/Spring5JUnit4ConcurrentIntegrationTest.java @@ -50,5 +50,3 @@ public class Spring5JUnit4ConcurrentIntegrationTest implements ApplicationContex } } - - diff --git a/spring-5/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java b/spring-5/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java index 6f39f11b00..a7b951b930 100644 --- a/spring-5/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java @@ -23,10 +23,9 @@ public class FunctionalWebApplicationIntegrationTest { @BeforeClass public static void setup() throws Exception { server = new FunctionalWebApplication().start(); - client = WebTestClient - .bindToServer() - .baseUrl("http://localhost:" + server.getPort()) - .build(); + client = WebTestClient.bindToServer() + .baseUrl("http://localhost:" + server.getPort()) + .build(); } @AfterClass @@ -36,26 +35,24 @@ public class FunctionalWebApplicationIntegrationTest { @Test public void givenRouter_whenGetTest_thenGotHelloWorld() throws Exception { - client - .get() - .uri("/test") - .exchange() - .expectStatus() - .isOk() - .expectBody(String.class) - .isEqualTo("helloworld"); + 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"); + client.get() + .uri("/") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("helloworld"); } @Test @@ -64,16 +61,15 @@ public class FunctionalWebApplicationIntegrationTest { 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!"); + client.post() + .uri("/login") + .contentType(MediaType.APPLICATION_FORM_URLENCODED) + .body(BodyInserters.fromFormData(formData)) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("welcome back!"); } @Test @@ -82,70 +78,64 @@ public class FunctionalWebApplicationIntegrationTest { 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(); + 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())); + 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.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.post() + .uri("/actor") + .body(fromObject(new Actor("Clint", "Eastwood"))) + .exchange() + .expectStatus() + .isOk(); - client - .get() - .uri("/actor") - .exchange() - .expectStatus() - .isOk() - .expectBodyList(Actor.class) - .hasSize(3); + 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"); + client.get() + .uri("/files/hello.txt") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("hello"); } } diff --git a/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5ParallelIntegrationTest.java b/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5ParallelIntegrationTest.java index fb6bb27684..55b0fcf267 100644 --- a/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5ParallelIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/jupiter/Spring5JUnit5ParallelIntegrationTest.java @@ -11,18 +11,14 @@ class Spring5JUnit5ParallelIntegrationTest { @Test void givenTwoTestClasses_whenJUnitRunParallel_thenTheTestsExecutingParallel() { - final Class[] classes = { - Example1IntegrationTest.class, Example2IntegrationTest.class - }; + final Class[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class }; JUnitCore.runClasses(new ParallelComputer(true, true), classes); } @Test void givenTwoTestClasses_whenJUnitRunParallel_thenTheTestsExecutingLinear() { - final Class[] classes = { - Example1IntegrationTest.class, Example2IntegrationTest.class - }; + final Class[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class }; JUnitCore.runClasses(new Computer(), classes); } diff --git a/spring-5/src/test/java/com/baeldung/jupiter/Spring5Java8NewFeaturesIntegrationTest.java b/spring-5/src/test/java/com/baeldung/jupiter/Spring5Java8NewFeaturesIntegrationTest.java index 2c3a71fb3e..f58bf9f3cd 100644 --- a/spring-5/src/test/java/com/baeldung/jupiter/Spring5Java8NewFeaturesIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/jupiter/Spring5Java8NewFeaturesIntegrationTest.java @@ -16,18 +16,16 @@ class Spring5Java8NewFeaturesIntegrationTest { } public class StringUtils { - FunctionalInterfaceExample - functionLambdaString = s -> Pattern.compile(" +").splitAsStream(s) - .map(word -> new StringBuilder(word).reverse()) - .collect(Collectors.joining(" ")); + FunctionalInterfaceExample functionLambdaString = s -> Pattern.compile(" +") + .splitAsStream(s) + .map(word -> new StringBuilder(word).reverse()) + .collect(Collectors.joining(" ")); } @Test - void givenStringUtil_whenSupplierCall_thenFunctionalInterfaceReverseString() - throws Exception { + void givenStringUtil_whenSupplierCall_thenFunctionalInterfaceReverseString() throws Exception { Supplier stringUtilsSupplier = StringUtils::new; - assertEquals(stringUtilsSupplier.get().functionLambdaString - .reverseString("hello"), "olleh"); + assertEquals(stringUtilsSupplier.get().functionLambdaString.reverseString("hello"), "olleh"); } } diff --git a/spring-5/src/test/java/com/baeldung/jupiter/Spring5ReactiveServerClientIntegrationTest.java b/spring-5/src/test/java/com/baeldung/jupiter/Spring5ReactiveServerClientIntegrationTest.java index 5c289c3e34..bbd852d625 100644 --- a/spring-5/src/test/java/com/baeldung/jupiter/Spring5ReactiveServerClientIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/jupiter/Spring5ReactiveServerClientIntegrationTest.java @@ -25,20 +25,15 @@ public class Spring5ReactiveServerClientIntegrationTest { @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))); + 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(); + nettyContext = server.newHandler(adapter) + .block(); } @AfterAll @@ -46,55 +41,54 @@ public class Spring5ReactiveServerClientIntegrationTest { 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 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 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); -// } + // @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)); + 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/web/PathPatternsUsingHandlerMethodIntegrationTest.java b/spring-5/src/test/java/com/baeldung/web/PathPatternsUsingHandlerMethodIntegrationTest.java index 90e3e7c445..c2ed8ff071 100644 --- a/spring-5/src/test/java/com/baeldung/web/PathPatternsUsingHandlerMethodIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/web/PathPatternsUsingHandlerMethodIntegrationTest.java @@ -17,85 +17,85 @@ public class PathPatternsUsingHandlerMethodIntegrationTest { @BeforeClass public static void setUp() { client = WebTestClient.bindToController(new PathPatternController()) - .build(); + .build(); } @Test public void givenHandlerMethod_whenMultipleURIVariablePattern_then200() { client.get() - .uri("/spring5/ab/cd") - .exchange() - .expectStatus() - .is2xxSuccessful() - .expectBody() - .equals("/ab/cd"); + .uri("/spring5/ab/cd") + .exchange() + .expectStatus() + .is2xxSuccessful() + .expectBody() + .equals("/ab/cd"); } @Test public void givenHandlerMethod_whenURLWithWildcardTakingZeroOrMoreChar_then200() { client.get() - .uri("/spring5/userid") - .exchange() - .expectStatus() - .is2xxSuccessful() - .expectBody() - .equals("/spring5/*id"); + .uri("/spring5/userid") + .exchange() + .expectStatus() + .is2xxSuccessful() + .expectBody() + .equals("/spring5/*id"); } @Test public void givenHandlerMethod_whenURLWithWildcardTakingExactlyOneChar_then200() { client.get() - .uri("/string5") - .exchange() - .expectStatus() - .is2xxSuccessful() - .expectBody() - .equals("/s?ring5"); + .uri("/string5") + .exchange() + .expectStatus() + .is2xxSuccessful() + .expectBody() + .equals("/s?ring5"); } @Test public void givenHandlerMethod_whenURLWithWildcardTakingZeroOrMorePathSegments_then200() { client.get() - .uri("/resources/baeldung") - .exchange() - .expectStatus() - .is2xxSuccessful() - .expectBody() - .equals("/resources/**"); + .uri("/resources/baeldung") + .exchange() + .expectStatus() + .is2xxSuccessful() + .expectBody() + .equals("/resources/**"); } @Test public void givenHandlerMethod_whenURLWithRegexInPathVariable_thenExpectedOutput() { client.get() - .uri("/abc") - .exchange() - .expectStatus() - .is2xxSuccessful() - .expectBody() - .equals("abc"); + .uri("/abc") + .exchange() + .expectStatus() + .is2xxSuccessful() + .expectBody() + .equals("abc"); client.get() - .uri("/123") - .exchange() - .expectStatus() - .is4xxClientError(); + .uri("/123") + .exchange() + .expectStatus() + .is4xxClientError(); } @Test public void givenHandlerMethod_whenURLWithMultiplePathVariablesInSameSegment_then200() { client.get() - .uri("/baeldung_tutorial") - .exchange() - .expectStatus() - .is2xxSuccessful() - .expectBody() - .equals("Two variables are var1=baeldung and var2=tutorial"); + .uri("/baeldung_tutorial") + .exchange() + .expectStatus() + .is2xxSuccessful() + .expectBody() + .equals("Two variables are var1=baeldung and var2=tutorial"); } } diff --git a/spring-5/src/test/java/com/baeldung/web/client/WebTestClientTest.java b/spring-5/src/test/java/com/baeldung/web/client/WebTestClientTest.java index 4127f22c01..b05f903b4b 100644 --- a/spring-5/src/test/java/com/baeldung/web/client/WebTestClientTest.java +++ b/spring-5/src/test/java/com/baeldung/web/client/WebTestClientTest.java @@ -21,38 +21,40 @@ public class WebTestClientTest { @LocalServerPort private int port; - private final RouterFunction ROUTER_FUNCTION = RouterFunctions.route( - RequestPredicates.GET("/resource"), - request -> ServerResponse.ok().build() - ); + 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(); + WebTestClient.bindToWebHandler(WEB_HANDLER) + .build(); } @Test public void testWebTestClientWithRouterFunction() { - WebTestClient - .bindToRouterFunction(ROUTER_FUNCTION) - .build().get().uri("/resource") - .exchange() - .expectStatus().isOk() - .expectBody().isEmpty(); + 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().is4xxClientError() - .expectBody(); + WebTestClient.bindToServer() + .baseUrl("http://localhost:" + port) + .build() + .get() + .uri("/resource") + .exchange() + .expectStatus() + .is4xxClientError() + .expectBody(); } }