formatting work

This commit is contained in:
eugenp 2017-09-13 14:41:03 +03:00
parent 75c1003451
commit 0f22f7b82a
23 changed files with 334 additions and 386 deletions

View File

@ -14,16 +14,19 @@ public class LiveTest {
private static String APP_ROOT = "http://localhost:8081"; private static String APP_ROOT = "http://localhost:8081";
@Test @Test
public void givenUser_whenResourceCreatedWithNullName_then400BadRequest() { 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()); assertEquals(400, response.getStatusCode());
} }
@Test @Test
public void givenUser_whenResourceCreated_then201Created() { 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()); assertEquals(201, response.getStatusCode());
} }
@ -33,8 +36,6 @@ public class LiveTest {
assertEquals(200, response.getStatusCode()); assertEquals(200, response.getStatusCode());
}*/ }*/
// //
private final String resourceWithNullName() { private final String resourceWithNullName() {
@ -43,10 +44,13 @@ public class LiveTest {
private final String resourceString() { private final String resourceString() {
return "{\"name\":\"" + randomAlphabetic(8) + "\"}"; return "{\"name\":\"" + randomAlphabetic(8) + "\"}";
} }
private final RequestSpecification givenAuth(String username, String password) { private final RequestSpecification givenAuth(String username, String password) {
return RestAssured.given().auth().preemptive().basic(username, password); return RestAssured.given()
.auth()
.preemptive()
.basic(username, password);
} }
} }

View File

@ -5,7 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication @SpringBootApplication
@ComponentScan(basePackages = {"com.baeldung.web"}) @ComponentScan(basePackages = { "com.baeldung.web" })
public class Spring5Application { public class Spring5Application {
public static void main(String[] args) { public static void main(String[] args) {

View File

@ -17,28 +17,25 @@ import static org.springframework.web.reactive.function.server.ServerResponse.ok
public class FormHandler { public class FormHandler {
Mono<ServerResponse> handleLogin(ServerRequest request) { Mono<ServerResponse> handleLogin(ServerRequest request) {
return request return request.body(toFormData())
.body(toFormData()) .map(MultiValueMap::toSingleValueMap)
.map(MultiValueMap::toSingleValueMap) .filter(formData -> "baeldung".equals(formData.get("user")))
.filter(formData -> "baeldung".equals(formData.get("user"))) .filter(formData -> "you_know_what_to_do".equals(formData.get("token")))
.filter(formData -> "you_know_what_to_do".equals(formData.get("token"))) .flatMap(formData -> ok().body(Mono.just("welcome back!"), String.class))
.flatMap(formData -> ok().body(Mono.just("welcome back!"), String.class)) .switchIfEmpty(ServerResponse.badRequest()
.switchIfEmpty(ServerResponse.badRequest().build()); .build());
} }
Mono<ServerResponse> handleUpload(ServerRequest request) { Mono<ServerResponse> handleUpload(ServerRequest request) {
return request return request.body(toDataBuffers())
.body(toDataBuffers()) .collectList()
.collectList() .flatMap(dataBuffers -> ok().body(fromObject(extractData(dataBuffers).toString())));
.flatMap(dataBuffers -> ok()
.body(fromObject(extractData(dataBuffers).toString())));
} }
private AtomicLong extractData(List<DataBuffer> dataBuffers) { private AtomicLong extractData(List<DataBuffer> dataBuffers) {
AtomicLong atomicLong = new AtomicLong(0); AtomicLong atomicLong = new AtomicLong(0);
dataBuffers.forEach(d -> atomicLong.addAndGet(d dataBuffers.forEach(d -> atomicLong.addAndGet(d.asByteBuffer()
.asByteBuffer() .array().length));
.array().length));
return atomicLong; return atomicLong;
} }
} }

View File

@ -40,28 +40,25 @@ public class FunctionalSpringBootApplication {
private RouterFunction<ServerResponse> routingFunction() { private RouterFunction<ServerResponse> routingFunction() {
FormHandler formHandler = new FormHandler(); FormHandler formHandler = new FormHandler();
RouterFunction<ServerResponse> restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest RouterFunction<ServerResponse> restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class)
.bodyToMono(Actor.class) .doOnNext(actors::add)
.doOnNext(actors::add) .then(ok().build()));
.then(ok().build()));
return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))) return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), formHandler::handleLogin)
.andRoute(POST("/login"), formHandler::handleLogin) .andRoute(POST("/upload"), formHandler::handleUpload)
.andRoute(POST("/upload"), formHandler::handleUpload) .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/")))
.and(RouterFunctions.resources("/files/**", new ClassPathResource("files/"))) .andNest(path("/actor"), restfulRouter)
.andNest(path("/actor"), restfulRouter) .filter((request, next) -> {
.filter((request, next) -> { System.out.println("Before handler invocation: " + request.path());
System.out.println("Before handler invocation: " + request.path()); return next.handle(request);
return next.handle(request); });
});
} }
@Bean @Bean
public ServletRegistrationBean servletRegistrationBean() throws Exception { public ServletRegistrationBean servletRegistrationBean() throws Exception {
HttpHandler httpHandler = WebHttpHandlerBuilder HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler((WebHandler) toHttpHandler(routingFunction()))
.webHandler((WebHandler) toHttpHandler(routingFunction())) .prependFilter(new IndexRewriteFilter())
.prependFilter(new IndexRewriteFilter()) .build();
.build();
ServletRegistrationBean registrationBean = new ServletRegistrationBean<>(new RootServlet(httpHandler), "/"); ServletRegistrationBean registrationBean = new ServletRegistrationBean<>(new RootServlet(httpHandler), "/");
registrationBean.setLoadOnStartup(1); registrationBean.setLoadOnStartup(1);
registrationBean.setAsyncSupported(true); registrationBean.setAsyncSupported(true);
@ -74,10 +71,9 @@ public class FunctionalSpringBootApplication {
static class SecurityConfig extends WebSecurityConfigurerAdapter { static class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(final HttpSecurity http) throws Exception { protected void configure(final HttpSecurity http) throws Exception {
http http.authorizeRequests()
.authorizeRequests() .anyRequest()
.anyRequest() .permitAll();
.permitAll();
} }
} }

View File

@ -33,28 +33,25 @@ public class FunctionalWebApplication {
private RouterFunction<ServerResponse> routingFunction() { private RouterFunction<ServerResponse> routingFunction() {
FormHandler formHandler = new FormHandler(); FormHandler formHandler = new FormHandler();
RouterFunction<ServerResponse> restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest RouterFunction<ServerResponse> restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class)
.bodyToMono(Actor.class) .doOnNext(actors::add)
.doOnNext(actors::add) .then(ok().build()));
.then(ok().build()));
return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))) return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), formHandler::handleLogin)
.andRoute(POST("/login"), formHandler::handleLogin) .andRoute(POST("/upload"), formHandler::handleUpload)
.andRoute(POST("/upload"), formHandler::handleUpload) .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/")))
.and(RouterFunctions.resources("/files/**", new ClassPathResource("files/"))) .andNest(path("/actor"), restfulRouter)
.andNest(path("/actor"), restfulRouter) .filter((request, next) -> {
.filter((request, next) -> { System.out.println("Before handler invocation: " + request.path());
System.out.println("Before handler invocation: " + request.path()); return next.handle(request);
return next.handle(request); });
});
} }
WebServer start() throws Exception { WebServer start() throws Exception {
WebHandler webHandler = (WebHandler) toHttpHandler(routingFunction()); WebHandler webHandler = (WebHandler) toHttpHandler(routingFunction());
HttpHandler httpHandler = WebHttpHandlerBuilder HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler(webHandler)
.webHandler(webHandler) .prependFilter(new IndexRewriteFilter())
.prependFilter(new IndexRewriteFilter()) .build();
.build();
Tomcat tomcat = new Tomcat(); Tomcat tomcat = new Tomcat();
tomcat.setHostname("localhost"); tomcat.setHostname("localhost");

View File

@ -11,17 +11,15 @@ class IndexRewriteFilter implements WebFilter {
@Override @Override
public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) { public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
ServerHttpRequest request = serverWebExchange.getRequest(); ServerHttpRequest request = serverWebExchange.getRequest();
if (request if (request.getURI()
.getURI() .getPath()
.getPath() .equals("/")) {
.equals("/")) { return webFilterChain.filter(serverWebExchange.mutate()
return webFilterChain.filter(serverWebExchange .request(builder -> builder.method(request.getMethod())
.mutate() .contextPath(request.getPath()
.request(builder -> builder .toString())
.method(request.getMethod()) .path("/test"))
.contextPath(request.getPath().toString()) .build());
.path("/test"))
.build());
} }
return webFilterChain.filter(serverWebExchange); return webFilterChain.filter(serverWebExchange);
} }

View File

@ -4,7 +4,7 @@ import java.util.Random;
public class MyService { public class MyService {
public int getRandomNumber(){ public int getRandomNumber() {
return (new Random().nextInt(10)); return (new Random().nextInt(10));
} }

View File

@ -28,10 +28,9 @@ import org.springframework.web.server.WebHandler;
public class RootServlet extends ServletHttpHandlerAdapter { public class RootServlet extends ServletHttpHandlerAdapter {
public RootServlet() { public RootServlet() {
this(WebHttpHandlerBuilder this(WebHttpHandlerBuilder.webHandler((WebHandler) toHttpHandler(routingFunction()))
.webHandler((WebHandler) toHttpHandler(routingFunction())) .prependFilter(new IndexRewriteFilter())
.prependFilter(new IndexRewriteFilter()) .build());
.build());
} }
RootServlet(HttpHandler httpHandler) { RootServlet(HttpHandler httpHandler) {
@ -44,44 +43,36 @@ public class RootServlet extends ServletHttpHandlerAdapter {
private static RouterFunction<?> routingFunction() { private static RouterFunction<?> routingFunction() {
return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))) return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), serverRequest -> serverRequest.body(toFormData())
.andRoute(POST("/login"), serverRequest -> serverRequest
.body(toFormData())
.map(MultiValueMap::toSingleValueMap) .map(MultiValueMap::toSingleValueMap)
.map(formData -> { .map(formData -> {
System.out.println("form data: " + formData.toString()); System.out.println("form data: " + formData.toString());
if ("baeldung".equals(formData.get("user")) && "you_know_what_to_do".equals(formData.get("token"))) { if ("baeldung".equals(formData.get("user")) && "you_know_what_to_do".equals(formData.get("token"))) {
return ok() return ok().body(Mono.just("welcome back!"), String.class)
.body(Mono.just("welcome back!"), String.class) .block();
.block();
} }
return ServerResponse return ServerResponse.badRequest()
.badRequest() .build()
.build() .block();
.block();
})) }))
.andRoute(POST("/upload"), serverRequest -> serverRequest .andRoute(POST("/upload"), serverRequest -> serverRequest.body(toDataBuffers())
.body(toDataBuffers()) .collectList()
.collectList() .map(dataBuffers -> {
.map(dataBuffers -> { AtomicLong atomicLong = new AtomicLong(0);
AtomicLong atomicLong = new AtomicLong(0); dataBuffers.forEach(d -> atomicLong.addAndGet(d.asByteBuffer()
dataBuffers.forEach(d -> atomicLong.addAndGet(d .array().length));
.asByteBuffer() System.out.println("data length:" + atomicLong.get());
.array().length)); return ok().body(fromObject(atomicLong.toString()))
System.out.println("data length:" + atomicLong.get()); .block();
return ok() }))
.body(fromObject(atomicLong.toString())) .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/")))
.block(); .andNest(path("/actor"), route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class)
})) .doOnNext(actors::add)
.and(RouterFunctions.resources("/files/**", new ClassPathResource("files/"))) .then(ok().build())))
.andNest(path("/actor"), route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest .filter((request, next) -> {
.bodyToMono(Actor.class) System.out.println("Before handler invocation: " + request.path());
.doOnNext(actors::add) return next.handle(request);
.then(ok().build()))) });
.filter((request, next) -> {
System.out.println("Before handler invocation: " + request.path());
return next.handle(request);
});
} }

View File

@ -27,16 +27,14 @@ abstract class ParameterAutowireUtils {
public static Object resolveDependency(Parameter parameter, Class<?> containingClass, ApplicationContext applicationContext) { public static Object resolveDependency(Parameter parameter, Class<?> containingClass, ApplicationContext applicationContext) {
boolean required = findMergedAnnotation(parameter, Autowired.class) boolean required = findMergedAnnotation(parameter, Autowired.class).map(Autowired::required)
.map(Autowired::required) .orElse(true);
.orElse(true);
MethodParameter methodParameter = (parameter.getDeclaringExecutable() instanceof Method ? MethodParameterFactory.createSynthesizingMethodParameter(parameter) : MethodParameterFactory.createMethodParameter(parameter)); MethodParameter methodParameter = (parameter.getDeclaringExecutable() instanceof Method ? MethodParameterFactory.createSynthesizingMethodParameter(parameter) : MethodParameterFactory.createMethodParameter(parameter));
DependencyDescriptor descriptor = new DependencyDescriptor(methodParameter, required); DependencyDescriptor descriptor = new DependencyDescriptor(methodParameter, required);
descriptor.setContainingClass(containingClass); descriptor.setContainingClass(containingClass);
return applicationContext return applicationContext.getAutowireCapableBeanFactory()
.getAutowireCapableBeanFactory() .resolveDependency(descriptor, null);
.resolveDependency(descriptor, null);
} }
private static <A extends Annotation> Optional<A> findMergedAnnotation(AnnotatedElement element, Class<A> annotationType) { private static <A extends Annotation> Optional<A> findMergedAnnotation(AnnotatedElement element, Class<A> annotationType) {

View File

@ -26,11 +26,9 @@ public class SpringExtension implements BeforeAllCallback, AfterAllCallback, Tes
try { try {
getTestContextManager(context).afterTestClass(); getTestContextManager(context).afterTestClass();
} finally { } finally {
context context.getStore(namespace)
.getStore(namespace) .remove(context.getTestClass()
.remove(context .get());
.getTestClass()
.get());
} }
} }
@ -42,21 +40,18 @@ public class SpringExtension implements BeforeAllCallback, AfterAllCallback, Tes
@Override @Override
public void beforeEach(TestExtensionContext context) throws Exception { public void beforeEach(TestExtensionContext context) throws Exception {
Object testInstance = context.getTestInstance(); Object testInstance = context.getTestInstance();
Method testMethod = context Method testMethod = context.getTestMethod()
.getTestMethod() .get();
.get();
getTestContextManager(context).beforeTestMethod(testInstance, testMethod); getTestContextManager(context).beforeTestMethod(testInstance, testMethod);
} }
@Override @Override
public void afterEach(TestExtensionContext context) throws Exception { public void afterEach(TestExtensionContext context) throws Exception {
Object testInstance = context.getTestInstance(); Object testInstance = context.getTestInstance();
Method testMethod = context Method testMethod = context.getTestMethod()
.getTestMethod() .get();
.get(); Throwable testException = context.getTestException()
Throwable testException = context .orElse(null);
.getTestException()
.orElse(null);
getTestContextManager(context).afterTestMethod(testInstance, testMethod, testException); getTestContextManager(context).afterTestMethod(testInstance, testMethod, testException);
} }
@ -70,24 +65,21 @@ public class SpringExtension implements BeforeAllCallback, AfterAllCallback, Tes
@Override @Override
public Object resolve(ParameterContext parameterContext, ExtensionContext extensionContext) { public Object resolve(ParameterContext parameterContext, ExtensionContext extensionContext) {
Parameter parameter = parameterContext.getParameter(); Parameter parameter = parameterContext.getParameter();
Class<?> testClass = extensionContext Class<?> testClass = extensionContext.getTestClass()
.getTestClass() .get();
.get();
ApplicationContext applicationContext = getApplicationContext(extensionContext); ApplicationContext applicationContext = getApplicationContext(extensionContext);
return ParameterAutowireUtils.resolveDependency(parameter, testClass, applicationContext); return ParameterAutowireUtils.resolveDependency(parameter, testClass, applicationContext);
} }
private ApplicationContext getApplicationContext(ExtensionContext context) { private ApplicationContext getApplicationContext(ExtensionContext context) {
return getTestContextManager(context) return getTestContextManager(context).getTestContext()
.getTestContext() .getApplicationContext();
.getApplicationContext();
} }
private TestContextManager getTestContextManager(ExtensionContext context) { private TestContextManager getTestContextManager(ExtensionContext context) {
Assert.notNull(context, "ExtensionContext must not be null"); Assert.notNull(context, "ExtensionContext must not be null");
Class<?> testClass = context Class<?> testClass = context.getTestClass()
.getTestClass() .get();
.get();
ExtensionContext.Store store = context.getStore(namespace); ExtensionContext.Store store = context.getStore(namespace);
return store.getOrComputeIfAbsent(testClass, TestContextManager::new, TestContextManager.class); return store.getOrComputeIfAbsent(testClass, TestContextManager::new, TestContextManager.class);
} }

View File

@ -26,8 +26,7 @@ public @interface SpringJUnit5Config {
String[] locations() default {}; String[] locations() default {};
@AliasFor(annotation = ContextConfiguration.class) @AliasFor(annotation = ContextConfiguration.class)
Class<? extends ApplicationContextInitializer<? Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>[] initializers() default {};
extends ConfigurableApplicationContext>>[] initializers() default {};
@AliasFor(annotation = ContextConfiguration.class) @AliasFor(annotation = ContextConfiguration.class)
boolean inheritLocations() default true; boolean inheritLocations() default true;

View File

@ -20,7 +20,8 @@ public class DataSetupBean implements InitializingBean {
@Override @Override
public void afterPropertiesSet() throws Exception { 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))));
} }
} }

View File

@ -23,7 +23,8 @@ public class FooController {
@ResponseBody @ResponseBody
@Validated @Validated
public Foo findById(@PathVariable @Min(0) final long id) { public Foo findById(@PathVariable @Min(0) final long id) {
return repo.findById(id).orElse(null); return repo.findById(id)
.orElse(null);
} }
@GetMapping @GetMapping
@ -36,7 +37,8 @@ public class FooController {
@ResponseBody @ResponseBody
@Validated @Validated
public List<Foo> findPaginated(@RequestParam("page") @Min(0) final int page, @Max(100) @RequestParam("size") final int size) { public List<Foo> 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 // API - write

View File

@ -23,9 +23,6 @@ public class Task {
@Override @Override
public String toString() { public String toString() {
return "Task{" + return "Task{" + "name='" + name + '\'' + ", id=" + id + '}';
"name='" + name + '\'' +
", id=" + id +
'}';
} }
} }

View File

@ -33,17 +33,17 @@ public class WebClientController {
WebClient.UriSpec<WebClient.RequestBodySpec> request2 = createWebClientWithServerURLAndDefaultValues().post(); WebClient.UriSpec<WebClient.RequestBodySpec> request2 = createWebClientWithServerURLAndDefaultValues().post();
// request body specifications // request body specifications
WebClient.RequestBodySpec uri1 = createWebClientWithServerURLAndDefaultValues().method(HttpMethod.POST).uri("/resource"); WebClient.RequestBodySpec uri1 = createWebClientWithServerURLAndDefaultValues().method(HttpMethod.POST)
WebClient.RequestBodySpec uri2 = createWebClientWithServerURLAndDefaultValues().post().uri(URI.create("/resource")); .uri("/resource");
WebClient.RequestBodySpec uri2 = createWebClientWithServerURLAndDefaultValues().post()
.uri(URI.create("/resource"));
// request header specification // request header specification
WebClient.RequestHeadersSpec<?> requestSpec1 = uri1.body(BodyInserters.fromPublisher(Mono.just("data"), String.class)); WebClient.RequestHeadersSpec<?> requestSpec1 = uri1.body(BodyInserters.fromPublisher(Mono.just("data"), String.class));
WebClient.RequestHeadersSpec<?> requestSpec2 = uri2.body(BodyInserters.fromObject("data")); WebClient.RequestHeadersSpec<?> requestSpec2 = uri2.body(BodyInserters.fromObject("data"));
// inserters // inserters
BodyInserter<Publisher<String>, ReactiveHttpOutputMessage> inserter1 = BodyInserters BodyInserter<Publisher<String>, ReactiveHttpOutputMessage> inserter1 = BodyInserters.fromPublisher(Subscriber::onComplete, String.class);
.fromPublisher(Subscriber::onComplete, String.class);
LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap<>(); LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("key1", "value1"); map.add("key1", "value1");
@ -53,14 +53,13 @@ public class WebClientController {
BodyInserter<String, ReactiveHttpOutputMessage> inserter3 = BodyInserters.fromObject("body"); BodyInserter<String, ReactiveHttpOutputMessage> inserter3 = BodyInserters.fromObject("body");
// responses // responses
WebClient.ResponseSpec response1 = uri1 WebClient.ResponseSpec response1 = uri1.body(inserter3)
.body(inserter3) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML)
.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) .acceptCharset(Charset.forName("UTF-8"))
.acceptCharset(Charset.forName("UTF-8")) .ifNoneMatch("*")
.ifNoneMatch("*") .ifModifiedSince(ZonedDateTime.now())
.ifModifiedSince(ZonedDateTime.now()) .retrieve();
.retrieve();
WebClient.ResponseSpec response2 = requestSpec2.retrieve(); WebClient.ResponseSpec response2 = requestSpec2.retrieve();
} }
@ -74,13 +73,12 @@ public class WebClientController {
} }
private WebClient createWebClientWithServerURLAndDefaultValues() { private WebClient createWebClientWithServerURLAndDefaultValues() {
return WebClient return WebClient.builder()
.builder() .baseUrl("http://localhost:8081")
.baseUrl("http://localhost:8081") .defaultCookie("cookieKey", "cookieValue")
.defaultCookie("cookieKey", "cookieValue") .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .defaultUriVariables(Collections.singletonMap("url", "http://localhost:8080"))
.defaultUriVariables(Collections.singletonMap("url", "http://localhost:8080")) .build();
.build();
} }
} }

View File

@ -9,14 +9,14 @@ public class ParallelIntegrationTest {
@Test @Test
public void runTests() { public void runTests() {
final Class<?>[] classes = {Example1IntegrationTest.class, Example2IntegrationTest.class}; final Class<?>[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class };
JUnitCore.runClasses(new Computer(), classes); JUnitCore.runClasses(new Computer(), classes);
} }
@Test @Test
public void runTestsInParallel() { public void runTestsInParallel() {
final Class<?>[] classes = {Example1IntegrationTest.class, Example2IntegrationTest.class}; final Class<?>[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class };
JUnitCore.runClasses(new ParallelComputer(true, true), classes); JUnitCore.runClasses(new ParallelComputer(true, true), classes);
} }

View File

@ -50,5 +50,3 @@ public class Spring5JUnit4ConcurrentIntegrationTest implements ApplicationContex
} }
} }

View File

@ -23,10 +23,9 @@ public class FunctionalWebApplicationIntegrationTest {
@BeforeClass @BeforeClass
public static void setup() throws Exception { public static void setup() throws Exception {
server = new FunctionalWebApplication().start(); server = new FunctionalWebApplication().start();
client = WebTestClient client = WebTestClient.bindToServer()
.bindToServer() .baseUrl("http://localhost:" + server.getPort())
.baseUrl("http://localhost:" + server.getPort()) .build();
.build();
} }
@AfterClass @AfterClass
@ -36,26 +35,24 @@ public class FunctionalWebApplicationIntegrationTest {
@Test @Test
public void givenRouter_whenGetTest_thenGotHelloWorld() throws Exception { public void givenRouter_whenGetTest_thenGotHelloWorld() throws Exception {
client client.get()
.get() .uri("/test")
.uri("/test") .exchange()
.exchange() .expectStatus()
.expectStatus() .isOk()
.isOk() .expectBody(String.class)
.expectBody(String.class) .isEqualTo("helloworld");
.isEqualTo("helloworld");
} }
@Test @Test
public void givenIndexFilter_whenRequestRoot_thenRewrittenToTest() throws Exception { public void givenIndexFilter_whenRequestRoot_thenRewrittenToTest() throws Exception {
client client.get()
.get() .uri("/")
.uri("/") .exchange()
.exchange() .expectStatus()
.expectStatus() .isOk()
.isOk() .expectBody(String.class)
.expectBody(String.class) .isEqualTo("helloworld");
.isEqualTo("helloworld");
} }
@Test @Test
@ -64,16 +61,15 @@ public class FunctionalWebApplicationIntegrationTest {
formData.add("user", "baeldung"); formData.add("user", "baeldung");
formData.add("token", "you_know_what_to_do"); formData.add("token", "you_know_what_to_do");
client client.post()
.post() .uri("/login")
.uri("/login") .contentType(MediaType.APPLICATION_FORM_URLENCODED)
.contentType(MediaType.APPLICATION_FORM_URLENCODED) .body(BodyInserters.fromFormData(formData))
.body(BodyInserters.fromFormData(formData)) .exchange()
.exchange() .expectStatus()
.expectStatus() .isOk()
.isOk() .expectBody(String.class)
.expectBody(String.class) .isEqualTo("welcome back!");
.isEqualTo("welcome back!");
} }
@Test @Test
@ -82,70 +78,64 @@ public class FunctionalWebApplicationIntegrationTest {
formData.add("user", "baeldung"); formData.add("user", "baeldung");
formData.add("token", "try_again"); formData.add("token", "try_again");
client client.post()
.post() .uri("/login")
.uri("/login") .contentType(MediaType.APPLICATION_FORM_URLENCODED)
.contentType(MediaType.APPLICATION_FORM_URLENCODED) .body(BodyInserters.fromFormData(formData))
.body(BodyInserters.fromFormData(formData)) .exchange()
.exchange() .expectStatus()
.expectStatus() .isBadRequest();
.isBadRequest();
} }
@Test @Test
public void givenUploadForm_whenRequestWithMultipartData_thenSuccess() throws Exception { public void givenUploadForm_whenRequestWithMultipartData_thenSuccess() throws Exception {
Resource resource = new ClassPathResource("/baeldung-weekly.png"); Resource resource = new ClassPathResource("/baeldung-weekly.png");
client client.post()
.post() .uri("/upload")
.uri("/upload") .contentType(MediaType.MULTIPART_FORM_DATA)
.contentType(MediaType.MULTIPART_FORM_DATA) .body(fromResource(resource))
.body(fromResource(resource)) .exchange()
.exchange() .expectStatus()
.expectStatus() .isOk()
.isOk() .expectBody(String.class)
.expectBody(String.class) .isEqualTo(String.valueOf(resource.contentLength()));
.isEqualTo(String.valueOf(resource.contentLength()));
} }
@Test @Test
public void givenActors_whenAddActor_thenAdded() throws Exception { public void givenActors_whenAddActor_thenAdded() throws Exception {
client client.get()
.get() .uri("/actor")
.uri("/actor") .exchange()
.exchange() .expectStatus()
.expectStatus() .isOk()
.isOk() .expectBodyList(Actor.class)
.expectBodyList(Actor.class) .hasSize(2);
.hasSize(2);
client client.post()
.post() .uri("/actor")
.uri("/actor") .body(fromObject(new Actor("Clint", "Eastwood")))
.body(fromObject(new Actor("Clint", "Eastwood"))) .exchange()
.exchange() .expectStatus()
.expectStatus() .isOk();
.isOk();
client client.get()
.get() .uri("/actor")
.uri("/actor") .exchange()
.exchange() .expectStatus()
.expectStatus() .isOk()
.isOk() .expectBodyList(Actor.class)
.expectBodyList(Actor.class) .hasSize(3);
.hasSize(3);
} }
@Test @Test
public void givenResources_whenAccess_thenGot() throws Exception { public void givenResources_whenAccess_thenGot() throws Exception {
client client.get()
.get() .uri("/files/hello.txt")
.uri("/files/hello.txt") .exchange()
.exchange() .expectStatus()
.expectStatus() .isOk()
.isOk() .expectBody(String.class)
.expectBody(String.class) .isEqualTo("hello");
.isEqualTo("hello");
} }
} }

View File

@ -11,18 +11,14 @@ class Spring5JUnit5ParallelIntegrationTest {
@Test @Test
void givenTwoTestClasses_whenJUnitRunParallel_thenTheTestsExecutingParallel() { void givenTwoTestClasses_whenJUnitRunParallel_thenTheTestsExecutingParallel() {
final Class<?>[] classes = { final Class<?>[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class };
Example1IntegrationTest.class, Example2IntegrationTest.class
};
JUnitCore.runClasses(new ParallelComputer(true, true), classes); JUnitCore.runClasses(new ParallelComputer(true, true), classes);
} }
@Test @Test
void givenTwoTestClasses_whenJUnitRunParallel_thenTheTestsExecutingLinear() { void givenTwoTestClasses_whenJUnitRunParallel_thenTheTestsExecutingLinear() {
final Class<?>[] classes = { final Class<?>[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class };
Example1IntegrationTest.class, Example2IntegrationTest.class
};
JUnitCore.runClasses(new Computer(), classes); JUnitCore.runClasses(new Computer(), classes);
} }

View File

@ -16,18 +16,16 @@ class Spring5Java8NewFeaturesIntegrationTest {
} }
public class StringUtils { public class StringUtils {
FunctionalInterfaceExample<String, String> FunctionalInterfaceExample<String, String> functionLambdaString = s -> Pattern.compile(" +")
functionLambdaString = s -> Pattern.compile(" +").splitAsStream(s) .splitAsStream(s)
.map(word -> new StringBuilder(word).reverse()) .map(word -> new StringBuilder(word).reverse())
.collect(Collectors.joining(" ")); .collect(Collectors.joining(" "));
} }
@Test @Test
void givenStringUtil_whenSupplierCall_thenFunctionalInterfaceReverseString() void givenStringUtil_whenSupplierCall_thenFunctionalInterfaceReverseString() throws Exception {
throws Exception {
Supplier<StringUtils> stringUtilsSupplier = StringUtils::new; Supplier<StringUtils> stringUtilsSupplier = StringUtils::new;
assertEquals(stringUtilsSupplier.get().functionLambdaString assertEquals(stringUtilsSupplier.get().functionLambdaString.reverseString("hello"), "olleh");
.reverseString("hello"), "olleh");
} }
} }

View File

@ -25,20 +25,15 @@ public class Spring5ReactiveServerClientIntegrationTest {
@BeforeAll @BeforeAll
public static void setUp() throws Exception { public static void setUp() throws Exception {
HttpServer server = HttpServer.create("localhost", 8080); HttpServer server = HttpServer.create("localhost", 8080);
RouterFunction<?> route = RouterFunctions RouterFunction<?> route = RouterFunctions.route(POST("/task/process"), request -> ServerResponse.ok()
.route(POST("/task/process"), request -> ServerResponse .body(request.bodyToFlux(Task.class)
.ok() .map(ll -> new Task("TaskName", 1)), Task.class))
.body(request .and(RouterFunctions.route(GET("/task"), request -> ServerResponse.ok()
.bodyToFlux(Task.class) .body(Mono.just("server is alive"), String.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); HttpHandler httpHandler = RouterFunctions.toHttpHandler(route);
ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler); ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler);
nettyContext = server nettyContext = server.newHandler(adapter)
.newHandler(adapter) .block();
.block();
} }
@AfterAll @AfterAll
@ -46,55 +41,54 @@ public class Spring5ReactiveServerClientIntegrationTest {
nettyContext.dispose(); nettyContext.dispose();
} }
// @Test // @Test
// public void givenCheckTask_whenServerHandle_thenServerResponseALiveString() throws Exception { // public void givenCheckTask_whenServerHandle_thenServerResponseALiveString() throws Exception {
// WebClient client = WebClient.create("http://localhost:8080"); // WebClient client = WebClient.create("http://localhost:8080");
// Mono<String> result = client // Mono<String> result = client
// .get() // .get()
// .uri("/task") // .uri("/task")
// .exchange() // .exchange()
// .then(response -> response.bodyToMono(String.class)); // .then(response -> response.bodyToMono(String.class));
// //
// assertThat(result.block()).isInstanceOf(String.class); // assertThat(result.block()).isInstanceOf(String.class);
// } // }
// @Test // @Test
// public void givenThreeTasks_whenServerHandleTheTasks_thenServerResponseATask() throws Exception { // public void givenThreeTasks_whenServerHandleTheTasks_thenServerResponseATask() throws Exception {
// URI uri = URI.create("http://localhost:8080/task/process"); // URI uri = URI.create("http://localhost:8080/task/process");
// ExchangeFunction exchange = ExchangeFunctions.create(new ReactorClientHttpConnector()); // ExchangeFunction exchange = ExchangeFunctions.create(new ReactorClientHttpConnector());
// ClientRequest request = ClientRequest // ClientRequest request = ClientRequest
// .method(HttpMethod.POST, uri) // .method(HttpMethod.POST, uri)
// .body(BodyInserters.fromPublisher(getLatLngs(), Task.class)) // .body(BodyInserters.fromPublisher(getLatLngs(), Task.class))
// .build(); // .build();
// //
// Flux<Task> taskResponse = exchange // Flux<Task> taskResponse = exchange
// .exchange(request) // .exchange(request)
// .flatMap(response -> response.bodyToFlux(Task.class)); // .flatMap(response -> response.bodyToFlux(Task.class));
// //
// assertThat(taskResponse.blockFirst()).isInstanceOf(Task.class); // assertThat(taskResponse.blockFirst()).isInstanceOf(Task.class);
// } // }
// @Test // @Test
// public void givenCheckTask_whenServerHandle_thenOragicServerResponseALiveString() throws Exception { // public void givenCheckTask_whenServerHandle_thenOragicServerResponseALiveString() throws Exception {
// URI uri = URI.create("http://localhost:8080/task"); // URI uri = URI.create("http://localhost:8080/task");
// ExchangeFunction exchange = ExchangeFunctions.create(new ReactorClientHttpConnector()); // ExchangeFunction exchange = ExchangeFunctions.create(new ReactorClientHttpConnector());
// ClientRequest request = ClientRequest // ClientRequest request = ClientRequest
// .method(HttpMethod.GET, uri) // .method(HttpMethod.GET, uri)
// .body(BodyInserters.fromPublisher(getLatLngs(), Task.class)) // .body(BodyInserters.fromPublisher(getLatLngs(), Task.class))
// .build(); // .build();
// //
// Flux<String> taskResponse = exchange // Flux<String> taskResponse = exchange
// .exchange(request) // .exchange(request)
// .flatMap(response -> response.bodyToFlux(String.class)); // .flatMap(response -> response.bodyToFlux(String.class));
// //
// assertThat(taskResponse.blockFirst()).isInstanceOf(String.class); // assertThat(taskResponse.blockFirst()).isInstanceOf(String.class);
// } // }
private static Flux<Task> getLatLngs() { private static Flux<Task> getLatLngs() {
return Flux return Flux.range(0, 3)
.range(0, 3) .zipWith(Flux.interval(Duration.ofSeconds(1)))
.zipWith(Flux.interval(Duration.ofSeconds(1))) .map(x -> new Task("taskname", 1))
.map(x -> new Task("taskname", 1)) .doOnNext(ll -> System.out.println("Produced: {}" + ll));
.doOnNext(ll -> System.out.println("Produced: {}" + ll));
} }
} }

View File

@ -17,85 +17,85 @@ public class PathPatternsUsingHandlerMethodIntegrationTest {
@BeforeClass @BeforeClass
public static void setUp() { public static void setUp() {
client = WebTestClient.bindToController(new PathPatternController()) client = WebTestClient.bindToController(new PathPatternController())
.build(); .build();
} }
@Test @Test
public void givenHandlerMethod_whenMultipleURIVariablePattern_then200() { public void givenHandlerMethod_whenMultipleURIVariablePattern_then200() {
client.get() client.get()
.uri("/spring5/ab/cd") .uri("/spring5/ab/cd")
.exchange() .exchange()
.expectStatus() .expectStatus()
.is2xxSuccessful() .is2xxSuccessful()
.expectBody() .expectBody()
.equals("/ab/cd"); .equals("/ab/cd");
} }
@Test @Test
public void givenHandlerMethod_whenURLWithWildcardTakingZeroOrMoreChar_then200() { public void givenHandlerMethod_whenURLWithWildcardTakingZeroOrMoreChar_then200() {
client.get() client.get()
.uri("/spring5/userid") .uri("/spring5/userid")
.exchange() .exchange()
.expectStatus() .expectStatus()
.is2xxSuccessful() .is2xxSuccessful()
.expectBody() .expectBody()
.equals("/spring5/*id"); .equals("/spring5/*id");
} }
@Test @Test
public void givenHandlerMethod_whenURLWithWildcardTakingExactlyOneChar_then200() { public void givenHandlerMethod_whenURLWithWildcardTakingExactlyOneChar_then200() {
client.get() client.get()
.uri("/string5") .uri("/string5")
.exchange() .exchange()
.expectStatus() .expectStatus()
.is2xxSuccessful() .is2xxSuccessful()
.expectBody() .expectBody()
.equals("/s?ring5"); .equals("/s?ring5");
} }
@Test @Test
public void givenHandlerMethod_whenURLWithWildcardTakingZeroOrMorePathSegments_then200() { public void givenHandlerMethod_whenURLWithWildcardTakingZeroOrMorePathSegments_then200() {
client.get() client.get()
.uri("/resources/baeldung") .uri("/resources/baeldung")
.exchange() .exchange()
.expectStatus() .expectStatus()
.is2xxSuccessful() .is2xxSuccessful()
.expectBody() .expectBody()
.equals("/resources/**"); .equals("/resources/**");
} }
@Test @Test
public void givenHandlerMethod_whenURLWithRegexInPathVariable_thenExpectedOutput() { public void givenHandlerMethod_whenURLWithRegexInPathVariable_thenExpectedOutput() {
client.get() client.get()
.uri("/abc") .uri("/abc")
.exchange() .exchange()
.expectStatus() .expectStatus()
.is2xxSuccessful() .is2xxSuccessful()
.expectBody() .expectBody()
.equals("abc"); .equals("abc");
client.get() client.get()
.uri("/123") .uri("/123")
.exchange() .exchange()
.expectStatus() .expectStatus()
.is4xxClientError(); .is4xxClientError();
} }
@Test @Test
public void givenHandlerMethod_whenURLWithMultiplePathVariablesInSameSegment_then200() { public void givenHandlerMethod_whenURLWithMultiplePathVariablesInSameSegment_then200() {
client.get() client.get()
.uri("/baeldung_tutorial") .uri("/baeldung_tutorial")
.exchange() .exchange()
.expectStatus() .expectStatus()
.is2xxSuccessful() .is2xxSuccessful()
.expectBody() .expectBody()
.equals("Two variables are var1=baeldung and var2=tutorial"); .equals("Two variables are var1=baeldung and var2=tutorial");
} }
} }

View File

@ -21,38 +21,40 @@ public class WebTestClientTest {
@LocalServerPort @LocalServerPort
private int port; private int port;
private final RouterFunction ROUTER_FUNCTION = RouterFunctions.route( private final RouterFunction ROUTER_FUNCTION = RouterFunctions.route(RequestPredicates.GET("/resource"), request -> ServerResponse.ok()
RequestPredicates.GET("/resource"), .build());
request -> ServerResponse.ok().build()
);
private final WebHandler WEB_HANDLER = exchange -> Mono.empty(); private final WebHandler WEB_HANDLER = exchange -> Mono.empty();
@Test @Test
public void testWebTestClientWithServerWebHandler() { public void testWebTestClientWithServerWebHandler() {
WebTestClient.bindToWebHandler(WEB_HANDLER).build(); WebTestClient.bindToWebHandler(WEB_HANDLER)
.build();
} }
@Test @Test
public void testWebTestClientWithRouterFunction() { public void testWebTestClientWithRouterFunction() {
WebTestClient WebTestClient.bindToRouterFunction(ROUTER_FUNCTION)
.bindToRouterFunction(ROUTER_FUNCTION) .build()
.build().get().uri("/resource") .get()
.exchange() .uri("/resource")
.expectStatus().isOk() .exchange()
.expectBody().isEmpty(); .expectStatus()
.isOk()
.expectBody()
.isEmpty();
} }
@Test @Test
public void testWebTestClientWithServerURL() { public void testWebTestClientWithServerURL() {
WebTestClient WebTestClient.bindToServer()
.bindToServer() .baseUrl("http://localhost:" + port)
.baseUrl("http://localhost:" + port) .build()
.build() .get()
.get() .uri("/resource")
.uri("/resource") .exchange()
.exchange() .expectStatus()
.expectStatus().is4xxClientError() .is4xxClientError()
.expectBody(); .expectBody();
} }
} }