Skip to content

Commit d3e57d3

Browse files
Tian Baoqiangpivovarit
authored andcommitted
#BAEL-636 (eugenp#1468)
* jira #BAEL-636 * remove redundant dependency spring-boot-starter-reactive
1 parent 52eb7c2 commit d3e57d3

8 files changed

Lines changed: 348 additions & 0 deletions

File tree

‎spring-5/pom.xml‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,17 @@
3535
<groupId>org.springframework.boot</groupId>
3636
<artifactId>spring-boot-starter-web</artifactId>
3737
</dependency>
38+
<dependency>
39+
<groupId>org.springframework.boot</groupId>
40+
<artifactId>spring-boot-starter-webflux</artifactId>
41+
</dependency>
42+
43+
<!-- a fix for spring-boot dependency on Reactor -->
44+
<dependency>
45+
<groupId>io.projectreactor</groupId>
46+
<artifactId>reactor-core</artifactId>
47+
<version>3.0.6.BUILD-SNAPSHOT</version>
48+
</dependency>
3849

3950
<!-- utils -->
4051
<dependency>
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.baeldung.functional;
2+
3+
class Actor {
4+
private String firstname;
5+
private String lastname;
6+
7+
public Actor() {
8+
}
9+
10+
public Actor(String firstname, String lastname) {
11+
this.firstname = firstname;
12+
this.lastname = lastname;
13+
}
14+
15+
public String getFirstname() {
16+
return firstname;
17+
}
18+
19+
public String getLastname() {
20+
return lastname;
21+
}
22+
23+
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package com.baeldung.functional;
2+
3+
import org.springframework.util.MultiValueMap;
4+
import org.springframework.web.reactive.function.server.ServerRequest;
5+
import org.springframework.web.reactive.function.server.ServerResponse;
6+
import reactor.core.publisher.Mono;
7+
8+
import java.util.concurrent.atomic.AtomicLong;
9+
10+
import static org.springframework.web.reactive.function.BodyExtractors.toDataBuffers;
11+
import static org.springframework.web.reactive.function.BodyExtractors.toFormData;
12+
import static org.springframework.web.reactive.function.BodyInserters.fromObject;
13+
import static org.springframework.web.reactive.function.server.ServerResponse.ok;
14+
15+
public class FormHandler {
16+
17+
Mono<ServerResponse> handleLogin(ServerRequest request) {
18+
return request
19+
.body(toFormData())
20+
.map(MultiValueMap::toSingleValueMap)
21+
.map(formData -> {
22+
System.out.println("form data: " + formData.toString());
23+
if ("baeldung".equals(formData.get("user")) && "you_know_what_to_do".equals(formData.get("token"))) {
24+
return ok()
25+
.body(Mono.just("welcome back!"), String.class)
26+
.block();
27+
}
28+
return ServerResponse
29+
.badRequest()
30+
.build()
31+
.block();
32+
});
33+
}
34+
35+
Mono<ServerResponse> handleUpload(ServerRequest request) {
36+
return request
37+
.body(toDataBuffers())
38+
.collectList()
39+
.map(dataBuffers -> {
40+
AtomicLong atomicLong = new AtomicLong(0);
41+
dataBuffers.forEach(d -> atomicLong.addAndGet(d
42+
.asByteBuffer()
43+
.array().length));
44+
System.out.println("data length:" + atomicLong.get());
45+
return ok()
46+
.body(fromObject(atomicLong.toString()))
47+
.block();
48+
});
49+
}
50+
}
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
package com.baeldung.functional;
2+
3+
import org.apache.catalina.Context;
4+
import org.apache.catalina.startup.Tomcat;
5+
import org.springframework.boot.web.embedded.tomcat.TomcatWebServer;
6+
import org.springframework.boot.web.server.WebServer;
7+
import org.springframework.core.io.ClassPathResource;
8+
import org.springframework.http.server.reactive.HttpHandler;
9+
import org.springframework.http.server.reactive.ServletHttpHandlerAdapter;
10+
import org.springframework.web.reactive.function.server.RouterFunction;
11+
import org.springframework.web.reactive.function.server.RouterFunctions;
12+
import org.springframework.web.reactive.function.server.ServerResponse;
13+
import org.springframework.web.server.WebHandler;
14+
import org.springframework.web.server.adapter.WebHttpHandlerBuilder;
15+
import reactor.core.publisher.Flux;
16+
17+
import java.util.Arrays;
18+
import java.util.List;
19+
import java.util.concurrent.CopyOnWriteArrayList;
20+
21+
import static org.springframework.web.reactive.function.BodyInserters.fromObject;
22+
import static org.springframework.web.reactive.function.server.RequestPredicates.*;
23+
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
24+
import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler;
25+
import static org.springframework.web.reactive.function.server.ServerResponse.ok;
26+
27+
public class FunctionalWebApplication {
28+
29+
private static final Actor BRAD_PITT = new Actor("Brad", "Pitt");
30+
private static final Actor TOM_HANKS = new Actor("Tom", "Hanks");
31+
private static final List<Actor> actors = new CopyOnWriteArrayList<>(Arrays.asList(BRAD_PITT, TOM_HANKS));
32+
33+
private RouterFunction<ServerResponse> routingFunction() {
34+
FormHandler formHandler = new FormHandler();
35+
36+
RouterFunction<ServerResponse> restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest
37+
.bodyToMono(Actor.class)
38+
.doOnNext(actors::add)
39+
.then(ok().build()));
40+
41+
return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld")))
42+
.andRoute(POST("/login"), formHandler::handleLogin)
43+
.andRoute(POST("/upload"), formHandler::handleUpload)
44+
.and(RouterFunctions.resources("/files/**", new ClassPathResource("files/")))
45+
.andNest(path("/actor"), restfulRouter)
46+
.filter((request, next) -> {
47+
System.out.println("Before handler invocation: " + request.path());
48+
return next.handle(request);
49+
});
50+
}
51+
52+
WebServer start() throws Exception {
53+
WebHandler webHandler = toHttpHandler(routingFunction());
54+
HttpHandler httpHandler = WebHttpHandlerBuilder
55+
.webHandler(webHandler)
56+
.prependFilter(new IndexRewriteFilter())
57+
.build();
58+
59+
Tomcat tomcat = new Tomcat();
60+
tomcat.setHostname("localhost");
61+
tomcat.setPort(9090);
62+
Context rootContext = tomcat.addContext("", System.getProperty("java.io.tmpdir"));
63+
ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler);
64+
Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet);
65+
rootContext.addServletMappingDecoded("/", "httpHandlerServlet");
66+
67+
TomcatWebServer server = new TomcatWebServer(tomcat);
68+
server.start();
69+
return server;
70+
71+
}
72+
73+
public static void main(String[] args) {
74+
try {
75+
new FunctionalWebApplication().start();
76+
} catch (Exception e) {
77+
e.printStackTrace();
78+
}
79+
}
80+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.baeldung.functional;
2+
3+
import org.springframework.http.server.reactive.ServerHttpRequest;
4+
import org.springframework.web.server.ServerWebExchange;
5+
import org.springframework.web.server.WebFilter;
6+
import org.springframework.web.server.WebFilterChain;
7+
import reactor.core.publisher.Mono;
8+
9+
class IndexRewriteFilter implements WebFilter {
10+
11+
@Override
12+
public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
13+
ServerHttpRequest request = serverWebExchange.getRequest();
14+
if (request
15+
.getURI()
16+
.getPath()
17+
.equals("/")) {
18+
return webFilterChain.filter(serverWebExchange
19+
.mutate()
20+
.request(builder -> builder
21+
.method(request.getMethod())
22+
.contextPath(request.getContextPath())
23+
.path("/test"))
24+
.build());
25+
}
26+
return webFilterChain.filter(serverWebExchange);
27+
}
28+
29+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
hello
Lines changed: 154 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
1+
package com.baeldung.functional;
2+
3+
import org.junit.AfterClass;
4+
import org.junit.BeforeClass;
5+
import org.junit.Test;
6+
import org.springframework.boot.web.server.WebServer;
7+
import org.springframework.core.io.ClassPathResource;
8+
import org.springframework.core.io.Resource;
9+
import org.springframework.http.MediaType;
10+
import org.springframework.test.web.reactive.server.WebTestClient;
11+
import org.springframework.util.LinkedMultiValueMap;
12+
import org.springframework.util.MultiValueMap;
13+
import org.springframework.web.reactive.function.BodyInserters;
14+
15+
import static org.springframework.web.reactive.function.BodyInserters.fromObject;
16+
import static org.springframework.web.reactive.function.BodyInserters.fromResource;
17+
18+
public class FunctionalWebApplicationIntegrationTest {
19+
20+
private static WebTestClient client;
21+
private static WebServer server;
22+
23+
@BeforeClass
24+
public static void setup() throws Exception {
25+
server = new FunctionalWebApplication().start();
26+
client = WebTestClient
27+
.bindToServer()
28+
.baseUrl("http://localhost:" + server.getPort())
29+
.build();
30+
}
31+
32+
@AfterClass
33+
public static void destroy() {
34+
server.stop();
35+
}
36+
37+
@Test
38+
public void givenRouter_whenGetTest_thenGotHelloWorld() throws Exception {
39+
client
40+
.get()
41+
.uri("/test")
42+
.exchange()
43+
.expectStatus()
44+
.isOk()
45+
.expectBody(String.class)
46+
.value()
47+
.isEqualTo("helloworld");
48+
}
49+
50+
@Test
51+
public void givenIndexFilter_whenRequestRoot_thenRewrittenToTest() throws Exception {
52+
client
53+
.get()
54+
.uri("/")
55+
.exchange()
56+
.expectStatus()
57+
.isOk()
58+
.expectBody(String.class)
59+
.value()
60+
.isEqualTo("helloworld");
61+
}
62+
63+
@Test
64+
public void givenLoginForm_whenPostValidToken_thenSuccess() throws Exception {
65+
MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(1);
66+
formData.add("user", "baeldung");
67+
formData.add("token", "you_know_what_to_do");
68+
69+
client
70+
.post()
71+
.uri("/login")
72+
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
73+
.exchange(BodyInserters.fromFormData(formData))
74+
.expectStatus()
75+
.isOk()
76+
.expectBody(String.class)
77+
.value()
78+
.isEqualTo("welcome back!");
79+
}
80+
81+
@Test
82+
public void givenLoginForm_whenRequestWithInvalidToken_thenFail() throws Exception {
83+
MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(2);
84+
formData.add("user", "baeldung");
85+
formData.add("token", "try_again");
86+
87+
client
88+
.post()
89+
.uri("/login")
90+
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
91+
.exchange(BodyInserters.fromFormData(formData))
92+
.expectStatus()
93+
.isBadRequest();
94+
}
95+
96+
@Test
97+
public void givenUploadForm_whenRequestWithMultipartData_thenSuccess() throws Exception {
98+
Resource resource = new ClassPathResource("/baeldung-weekly.png");
99+
client
100+
.post()
101+
.uri("/upload")
102+
.contentType(MediaType.MULTIPART_FORM_DATA)
103+
.exchange(fromResource(resource))
104+
.expectStatus()
105+
.isOk()
106+
.expectBody(String.class)
107+
.value()
108+
.isEqualTo(String.valueOf(resource.contentLength()));
109+
}
110+
111+
@Test
112+
public void givenActors_whenAddActor_thenAdded() throws Exception {
113+
client
114+
.get()
115+
.uri("/actor")
116+
.exchange()
117+
.expectStatus()
118+
.isOk()
119+
.expectBody(Actor.class)
120+
.list()
121+
.hasSize(2);
122+
123+
client
124+
.post()
125+
.uri("/actor")
126+
.exchange(fromObject(new Actor("Clint", "Eastwood")))
127+
.expectStatus()
128+
.isOk();
129+
130+
client
131+
.get()
132+
.uri("/actor")
133+
.exchange()
134+
.expectStatus()
135+
.isOk()
136+
.expectBody(Actor.class)
137+
.list()
138+
.hasSize(3);
139+
}
140+
141+
@Test
142+
public void givenResources_whenAccess_thenGot() throws Exception {
143+
client
144+
.get()
145+
.uri("/files/hello.txt")
146+
.exchange()
147+
.expectStatus()
148+
.isOk()
149+
.expectBody(String.class)
150+
.value()
151+
.isEqualTo("hello");
152+
}
153+
154+
}
21.8 KB
Loading

0 commit comments

Comments
 (0)