How to get Locale in Webflux Functional Endpoints? - spring

I am using Spring's Functional Endpoints with Kotlin to create a web service, and I'm trying to figure out the idiomatic way to resolve the Locale off using the standard Accept-Language header.
Here's an example of what the code looks like:
val repository: PersonRepository = ...
val handler = PersonHandler(repository)
val route = coRouter {
GET("/person", handler::getPeople)
}
class PersonHandler(private val repository: PersonRepository) {
suspend fun getPeople(request: ServerRequest): ServerResponse {
val locale = /* ??? */
// create and return response
}
}
Spring documentation references using a LocaleContextResolver that resolves the Locale as part of the request, but I don't see a way to use it when using Functional Endpoints. You can get the raw values passed into the Accept-Language header off of ServiceRequest.headers().acceptLanguage() like so...
suspend fun getPeople(request: ServerRequest): ServerResponse {
val locale =
Locale.lookup(request.headers().acceptLanguage(), supportedLocales)
?: Locale.getDefault()
// create and return response
}
.... but isn't that just reimplementing the responsibility of LocaleContextResolver in every single Handler Function?
What is the idiomatic way to convert the Accept-Language header into the single/best supported Locale within Spring's Functional Endpoints?

I was able to do this with a before filter:
val repository: PersonRepository = ...
val handler = PersonHandler(repository)
val route = coRouter {
GET("/person", handler::getPeople)
before(::parseLocale)
}
fun parseLocale(request: ServerRequest): ServerRequest {
val locale = try {
Locale.lookup(request.headers().acceptLanguage(), wellKnownSupportedLocales) ?: wellKnownDefaultLocale
} catch (exception: RuntimeException) {
wellKnownDefaultLocale
}
return ServerRequest
.from(request)
.attribute("locale", locale)
.body(request.bodyToFlux())
.build()
}
class PersonHandler(private val repository: PersonRepository) {
suspend fun getPeople(request: ServerRequest): ServerResponse {
val locale = request.attributes("locale").get() as Locale
// create and return response
}
}

Related

Websocket request not routed through gateway global filter

Problem
I have setup a global filter for all requests that adds user information to the headers. This filter works for all my http requests but doesnt apply them to my websocket requests.
Questions
Do websocket requests got through GlobalFilters?
If websocket requests do not go through GlobalFilters is there a way to specify a filter for websockets?
Are there any approaches that will allow me to inject user info into the websocket requests via spring-cloud-gateway?
Setup
Gateway configuration
gateway:
routes:
- id: example
uri: http://localhost:80
predicates:
- Path=/example/**
filters:
- RewritePath=/example/(?<path>.*), /$\{path}
GloablFilter
#Component
class CustomGlobalFilter(private val jwtDecoder: ReactiveJwtDecoder) : GlobalFilter {
private val logger = KotlinLogging.logger {}
/**
* Given exchange, extract Authorization header value and modify to retrieve JWT token.
*/
fun extractJwtToken(exchange: ServerWebExchange): String {
return (exchange.request.headers["Authorization"]
?: throw JwtExtractionException("Request does not contain Authorization header"))[0]
.replace("Bearer ", "")
}
/**
* Modify request headers to add `username`.
*/
fun modifyHeaders(exchange: ServerWebExchange): Mono<ServerWebExchange> {
return try {
val jwt = extractJwtToken(exchange)
jwtDecoder
.decode(jwt)
.map {
val username = it.claims["username"] as String
val modRequest = exchange
.request
.mutate()
.header("username", username)
.build()
exchange.mutate()
.request(modRequest)
.build()
}
} catch (e: JwtExtractionException) {
exchange.toMono() // fall back on default exchange
}
}
/**
* Filter all outgoing requests to modify headers.
*/
override fun filter(exchange: ServerWebExchange, chain: GatewayFilterChain): Mono<Void> {
return modifyHeaders(exchange)
.flatMap { chain.filter(it) }
}
}
I was able to fix the routing issue by setting the custom filter order before the WebsocketRoutingFilter
#Component
class CustomGlobalFilter(
private val authFilterUtil: AuthFilterUtil,
) : GlobalFilter, Ordered {
override fun filter(exchange: ServerWebExchange, chain: GatewayFilterChain): Mono<Void> {
return authFilterUtil
.modifyHeaders(exchange)
.flatMap { chain.filter(it) }
}
override fun getOrder(): Int {
return Ordered.HIGHEST_PRECEDENCE
}
}

How to handle login failure with Spring API on server and Retrofit2 on Android?

On server side I have created simple Spring API with authentication. I have just added implementation("org.springframework.boot:spring-boot-starter-security") dependency and when I go to url with browser - it shows login page when I'm not logged in.
For now I'm using basic authentication, my username and password set in configuration file like this (resources/application.properties file):
spring.security.user.name=myusername
spring.security.user.password=mypassword
spring.security.user.roles=manager
I'm also using Spring Data REST, so Spring creates API automatically for JPA repositories that exist in my project. I had to set up my database, create JPA repositories for tables and add implementation("org.springframework.boot:spring-boot-starter-data-rest") to my dependencies to make it work.
On Android side I call my API with this Adapter and Client.
interface ApiClient {
#GET("inventoryItems/1")
suspend fun getFirstInventoryItem(): Response<InventoryItemDto>
}
object ApiAdapter {
private const val API_BASE_URL = "http://some.url/"
private const val API_USERNAME = "myusername"
private const val API_PASSWORD = "mypassword"
val apiClient: ApiClient = Retrofit.Builder()
.baseUrl(API_BASE_URL)
.client(getHttpClient(API_USERNAME, API_PASSWORD))
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(ApiClient::class.java)
private fun getHttpClient(user: String, pass: String): OkHttpClient =
OkHttpClient
.Builder()
.authenticator(getBasicAuth(user,pass))
.build()
private fun getBasicAuth(username: String?, password: String?): Authenticator? =
object : Authenticator {
override fun authenticate(route: Route?, response: okhttp3.Response): Request? {
return response
.request()
.newBuilder()
.addHeader("Authorization", Credentials.basic(username, password))
.build()
}
}
}
And this is how I call my API on Android:
(I'm calling this from onViewCreated on my view Fragment)
lifecycleScope.launch {
val item: InventoryItemDto? = ApiAdapter.apiClient.getFirstInventoryItem().body()
binding?.tvTest?.text = item.toString()
}
When I provide correct password everything works.
But when I provide wrong password my Android app crashes because java.net.ProtocolException: Too many follow-up requests: 21 is thrown.
It looks like my Android client goes to requested url (inventoryItems/1) and then it is redirected to login page. Then my clients tries to authenticate on that page again, because I have .addHeader("Authorization", Credentials.basic(username, password)) added to every request (I assume). Login is failed again, so it is redirected again to login page where it sends wrong credentials again and again is redirected...
My question 1: how to deal with login failed properly on Android and/or Spring?
My question 2: how to handle other errors (like bad request) properly on Android and/or Spring?
What I have tried:
Disable followRedirects and followSslRedirects on Android side like this:
private fun getHttpClient(user: String, pass: String): OkHttpClient =
OkHttpClient
.Builder()
.followRedirects(false)
.followSslRedirects(talse)
.authenticator(getBasicAuth(user,pass))
.build()
Add .addHeader("X-Requested-With", "XMLHttpRequest") header, also on Android side:
private fun getBasicAuth(username: String?, password: String?):Authenticator? =
object : Authenticator {
override fun authenticate(route: Route?, response: okhttp3.Response): Request? {
return response
.request()
.newBuilder()
.addHeader("Authorization", Credentials.basic(username, password))
.addHeader("X-Requested-With", "XMLHttpRequest")
.build()
}
}
OK, I got this (answering my own question). Solution is based on this: link
I will not accept my answer, maybe someone will propose some solution without deprecated class, and maybe with good explanation.
I have created my own AuthenticationFailureHandler, like this:
class CustomAuthenticationFailureHandler : AuthenticationFailureHandler {
private val objectMapper = ObjectMapper()
#Throws(IOException::class, ServletException::class)
override fun onAuthenticationFailure(
request: HttpServletRequest?,
response: HttpServletResponse,
exception: AuthenticationException
) {
response.status = HttpStatus.UNAUTHORIZED.value()
val data: MutableMap<String, Any> = HashMap()
data["timestamp"] = Calendar.getInstance().time
data["exception"] = exception.message.toString()
response.outputStream.println(objectMapper.writeValueAsString(data))
}
}
I had to configure security manually by creating this class:
#Configuration
#EnableWebSecurity
class SecurityConfiguration : WebSecurityConfigurerAdapter() {
#Throws(Exception::class)
override fun configure(auth: AuthenticationManagerBuilder) {
auth.inMemoryAuthentication()
.withUser(API_USERNAME)
.password(passwordEncoder().encode(API_PASSWORD))
.roles(API_ROLE)
}
#Throws(Exception::class)
override fun configure(http: HttpSecurity) {
http
.authorizeRequests()
.anyRequest()
.authenticated()
}
#Bean
fun authenticationFailureHandler(): AuthenticationFailureHandler = CustomAuthenticationFailureHandler()
#Bean
fun passwordEncoder(): PasswordEncoder = BCryptPasswordEncoder()
companion object {
private const val API_USERNAME = "user1"
private const val API_PASSWORD = "user1"
private const val API_ROLE = "USER"
}
}
Unfortunately WebSecurityConfigurerAdapter class is deprected. I will deal with that later.

Throw exception spring boot webflux

I am trying to make a condition, which if not satisfied, throw an exception. But I tried in many ways and without success.
My restcontroller:
#GetMapping(value = ["/{id}"])
fun find(#PathVariable id: String): Mono<ResponseEntity<Mono<Person>>> {
return ResponseEntity.ok().body(service.find(id)).toMono()
}
My service
override fun find(id: String): Mono<Person> {
return repository.findById(id).doOnError { throw DataNotFound("Person not found")}
}
If I enter an existing ID, it returns me a registered person.
But if I enter a nonexistent ID, instead of throwing the exception, it returns me a 200 with empty body.
How do I solve this? Could anyone help?
Try this:
#GetMapping(value = ["/{id}"])
fun find(#PathVariable id: String): Mono<ResponseEntity<?>> {
service.find(id).map(person -> ResponseEntity.ok().body(person))
.onErrorResume(DataNotFound.class, exception -> ResponseEntity.notFound())
}
fun find(id: String): Mono<Person> {
repository.findById(id).onErrorMap(error -> new DataNotFound("Person not found"))
}
It returns OK response if a person exists and NOT_FOUND otherwise.
Usually, in a more complex scenario, you want to do a translation from exceptions to some kind of error resource.
In this scenario, you will use the same response type for your method which handles the HTTP request. More precisely, in your case:
#GetMapping(value = ["/{id}"])
fun find(#PathVariable id: String): Mono<ResponseEntity<Mono<Person>>> {
return ResponseEntity.ok().body(service.find(id)).toMono()
}
(this will remain as it is!)
And next, you will provide a so-called ControllerAdvice which can look in your case like in the following snippet:
#ControllerAdvice(assignableTypes = [YourRestController::class]
class ControllerAdvice {
#ExceptionHandler
fun handle(ex: DataNotFoundException): ResponseEntity<DataNotFoundErrorResource> {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(DataNotFoundErrorResource.from(ex)
}
}
Note: Be aware that I've not used a Kotlin compiler, but I've compiled it in my mind :) I hope that it will be ok!

What is the best way to validate request in a Spring Webflux functional application

In a traditional web application it is easy to validate the request body in the controller method, eg.
ResponseEntity create(#Valid #ResponseBody Post post) {
}
If it is a MVC application, we can gather the errors by injecting a BindingResult, and decide if there is some validation errors from the input form.
In the pages, there are some helpers existed for Freemarker and Thymeleaf to display the messages.
But when I come to Webflux and try to use RouterFunction to define the routing in the applications. For example,
Mono<ServerResponse> create(ServerRequest req) {
return req.bodyToMono(Post.class)
.flatMap { this.posts.save(it) }
.flatMap { ServerResponse.created(URI.create("/posts/".concat(it.getId()))).build() }
}
#Bean
RouterFunction<ServerResponse> routes(PostHandler postController) {
return route(GET("/posts"), postController.&all)
.andRoute(POST("/posts"), postController.&create)
.andRoute(GET("/posts/{id}"), postController.&get)
.andRoute(PUT("/posts/{id}"), postController.&update)
.andRoute(DELETE("/posts/{id}"), postController.&delete)
}
A possible approach is converting the request data(Mono or Flux) to blocking and injecting a Validator and validate them manually.
But I think the codes will look a little ugly.
How to process the validation of request body or form data gracefully?
Is there a better to validate the request body or form data and do not lost the functional and reactive features for both WEB(rendering a view) and REST applications?
I've developed "Yet Another Validator" for this porpose.
https://github.com/making/yavi
It would be great if YAVI could meet your expectation.
Validation code will look like following:
static RouterFunction<ServerResponse> routes() {
return route(POST("/"), req -> req.bodyToMono(User.class) //
.flatMap(body -> validator.validateToEither(body) //
.leftMap(violations -> {
Map<String, Object> error = new LinkedHashMap<>();
error.put("message", "Invalid request body");
error.put("details", violations.details());
return error;
})
.fold(error -> badRequest().syncBody(error), //
user -> ok().syncBody(user))));
}
One of the ways I've managed to do it in my application is the following (code is in Kotlin but the idea is the same). I've declared RequestHandler class which performs validation:
#Component
class RequestHandler(private val validator: Validator) {
fun <BODY> withValidBody(
block: (Mono<BODY>) -> Mono<ServerResponse>,
request: ServerRequest, bodyClass: Class<BODY>): Mono<ServerResponse> {
return request
.bodyToMono(bodyClass)
.flatMap { body ->
val violations = validator.validate(body)
if (violations.isEmpty())
block.invoke(Mono.just(body))
else
throw ConstraintViolationException(violations)
}
}
}
Request objects can contain java validation annotations in this way:
data class TokenRequest constructor(#get:NotBlank val accessToken: String) {
constructor() : this("")
}
And handler classes use RequestHandler to perform validation:
fun process(request: ServerRequest): Mono<ServerResponse> {
return requestHandler.withValidBody({
tokenRequest -> tokenRequest
.flatMap { token -> tokenService.process(token.accessToken) }
.map { result -> TokenResponse(result) }
.flatMap { ServerResponse.ok()
.contentType(MediaType.APPLICATION_JSON_UTF8)
.body(Mono.just(it), TokenResponse::class.java)
}
}, request, TokenRequest::class.java)
}
Got the idea from this blog post.

How to log request and response bodies in Spring WebFlux

I want to have centralised logging for requests and responses in my REST API on Spring WebFlux with Kotlin. So far I've tried this approaches
#Bean
fun apiRouter() = router {
(accept(MediaType.APPLICATION_JSON) and "/api").nest {
"/user".nest {
GET("/", userHandler::listUsers)
POST("/{userId}", userHandler::updateUser)
}
}
}.filter { request, next ->
logger.info { "Processing request $request with body ${request.bodyToMono<String>()}" }
next.handle(request).doOnSuccess { logger.info { "Handling with response $it" } }
}
Here request method and path log successfully but the body is Mono, so how should I log it? Should it be the other way around and I have to subscribe on request body Mono and log it in the callback?
Another problem is that ServerResponse interface here doesn't have access to the response body. How can I get it here?
Another approach I've tried is using WebFilter
#Bean
fun loggingFilter(): WebFilter =
WebFilter { exchange, chain ->
val request = exchange.request
logger.info { "Processing request method=${request.method} path=${request.path.pathWithinApplication()} params=[${request.queryParams}] body=[${request.body}]" }
val result = chain.filter(exchange)
logger.info { "Handling with response ${exchange.response}" }
return#WebFilter result
}
Same problem here: request body is Flux and no response body.
Is there a way to access full request and response for logging from some filters? What don't I understand?
This is more or less similar to the situation in Spring MVC.
In Spring MVC, you can use a AbstractRequestLoggingFilter filter and ContentCachingRequestWrapper and/or ContentCachingResponseWrapper. Many tradeoffs here:
if you'd like to access servlet request attributes, you need to actually read and parse the request body
logging the request body means buffering the request body, which can use a significant amount of memory
if you'd like to access the response body, you need to wrap the response and buffer the response body as it's being written, for later retrieval
ContentCaching*Wrapper classes don't exist in WebFlux but you could create similar ones. But keep in mind other points here:
buffering data in memory somehow goes against the reactive stack, since we're trying there to be very efficient with the available resources
you should not tamper with the actual flow of data and flush more/less often than expected, otherwise you'd risk breaking streaming uses cases
at that level, you only have access to DataBuffer instances, which are (roughly) memory-efficient byte arrays. Those belong to buffer pools and are recycled for other exchanges. If those aren't properly retained/released, memory leaks are created (and buffering data for later consumption certainly fits that scenario)
again at that level, it's only bytes and you don't have access to any codec to parse the HTTP body. I'd forget about buffering the content if it's not human-readable in the first place
Other answers to your question:
yes, the WebFilter is probably the best approach
no, you shouldn't subscribe to the request body otherwise you'd consume data that the handler won't be able to read; you can flatMap on the request and buffer data in doOn operators
wrapping the response should give you access to the response body as it's being written; don't forget about memory leaks, though
I didn't find a good way to log request/response bodies, but if you are just interested in meta data then you can do it like follows.
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.http.server.reactive.ServerHttpResponse
import org.springframework.stereotype.Component
import org.springframework.web.server.ServerWebExchange
import org.springframework.web.server.WebFilter
import org.springframework.web.server.WebFilterChain
import reactor.core.publisher.Mono
#Component
class LoggingFilter(val requestLogger: RequestLogger, val requestIdFactory: RequestIdFactory) : WebFilter {
val logger = logger()
override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> {
logger.info(requestLogger.getRequestMessage(exchange))
val filter = chain.filter(exchange)
exchange.response.beforeCommit {
logger.info(requestLogger.getResponseMessage(exchange))
Mono.empty()
}
return filter
}
}
#Component
class RequestLogger {
fun getRequestMessage(exchange: ServerWebExchange): String {
val request = exchange.request
val method = request.method
val path = request.uri.path
val acceptableMediaTypes = request.headers.accept
val contentType = request.headers.contentType
return ">>> $method $path ${HttpHeaders.ACCEPT}: $acceptableMediaTypes ${HttpHeaders.CONTENT_TYPE}: $contentType"
}
fun getResponseMessage(exchange: ServerWebExchange): String {
val request = exchange.request
val response = exchange.response
val method = request.method
val path = request.uri.path
val statusCode = getStatus(response)
val contentType = response.headers.contentType
return "<<< $method $path HTTP${statusCode.value()} ${statusCode.reasonPhrase} ${HttpHeaders.CONTENT_TYPE}: $contentType"
}
private fun getStatus(response: ServerHttpResponse): HttpStatus =
try {
response.statusCode
} catch (ex: Exception) {
HttpStatus.CONTINUE
}
}
This is what I came up with for java.
public class RequestResponseLoggingFilter implements WebFilter {
#Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
ServerHttpRequest httpRequest = exchange.getRequest();
final String httpUrl = httpRequest.getURI().toString();
ServerHttpRequestDecorator loggingServerHttpRequestDecorator = new ServerHttpRequestDecorator(exchange.getRequest()) {
String requestBody = "";
#Override
public Flux<DataBuffer> getBody() {
return super.getBody().doOnNext(dataBuffer -> {
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
Channels.newChannel(byteArrayOutputStream).write(dataBuffer.asByteBuffer().asReadOnlyBuffer());
requestBody = IOUtils.toString(byteArrayOutputStream.toByteArray(), "UTF-8");
commonLogger.info(LogMessage.builder()
.step(httpUrl)
.message("log incoming http request")
.stringPayload(requestBody)
.build());
} catch (IOException e) {
commonLogger.error(LogMessage.builder()
.step("log incoming request for " + httpUrl)
.message("fail to log incoming http request")
.errorType("IO exception")
.stringPayload(requestBody)
.build(), e);
}
});
}
};
ServerHttpResponseDecorator loggingServerHttpResponseDecorator = new ServerHttpResponseDecorator(exchange.getResponse()) {
String responseBody = "";
#Override
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
Mono<DataBuffer> buffer = Mono.from(body);
return super.writeWith(buffer.doOnNext(dataBuffer -> {
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
Channels.newChannel(byteArrayOutputStream).write(dataBuffer.asByteBuffer().asReadOnlyBuffer());
responseBody = IOUtils.toString(byteArrayOutputStream.toByteArray(), "UTF-8");
commonLogger.info(LogMessage.builder()
.step("log outgoing response for " + httpUrl)
.message("incoming http request")
.stringPayload(responseBody)
.build());
} catch (Exception e) {
commonLogger.error(LogMessage.builder()
.step("log outgoing response for " + httpUrl)
.message("fail to log http response")
.errorType("IO exception")
.stringPayload(responseBody)
.build(), e);
}
}));
}
};
return chain.filter(exchange.mutate().request(loggingServerHttpRequestDecorator).response(loggingServerHttpResponseDecorator).build());
}
}
You can actually enable DEBUG logging for Netty and Reactor-Netty related to see full picture of what's happening. You could play with the below and see what you want and don't. That was the best I could.
reactor.ipc.netty.channel.ChannelOperationsHandler: DEBUG
reactor.ipc.netty.http.server.HttpServer: DEBUG
reactor.ipc.netty.http.client: DEBUG
io.reactivex.netty.protocol.http.client: DEBUG
io.netty.handler: DEBUG
io.netty.handler.proxy.HttpProxyHandler: DEBUG
io.netty.handler.proxy.ProxyHandler: DEBUG
org.springframework.web.reactive.function.client: DEBUG
reactor.ipc.netty.channel: DEBUG
Since Spring Boot 2.2.x, Spring Webflux supports Kotlin coroutines. With coroutines, you can have the advantages of non-blocking calls without having to handle Mono and Flux wrapped objects. It adds extensions to ServerRequest and ServerResponse, adding methods like ServerRequest#awaitBody() and ServerResponse.BodyBuilder.bodyValueAndAwait(body: Any). So you could rewrite you code like this:
#Bean
fun apiRouter() = coRouter {
(accept(MediaType.APPLICATION_JSON) and "/api").nest {
"/user".nest {
/* the handler methods now use ServerRequest and ServerResponse directly
you just need to add suspend before your function declaration:
suspend fun listUsers(ServerRequest req, ServerResponse res) */
GET("/", userHandler::listUsers)
POST("/{userId}", userHandler::updateUser)
}
}
// this filter will be applied to all routes built by this coRouter
filter { request, next ->
// using non-blocking request.awayBody<T>()
logger.info("Processing $request with body ${request.awaitBody<String>()}")
val res = next(request)
logger.info("Handling with Content-Type ${res.headers().contentType} and status code ${res.rawStatusCode()}")
res
}
}
In order to create a WebFilter Bean with coRoutines, I think you can use this CoroutineWebFilter interface (I haven't tested it, I don't know if it works).
I am pretty new to Spring WebFlux, and I don't know how to do it in Kotlin, but should be the same as in Java using WebFilter:
public class PayloadLoggingWebFilter implements WebFilter {
public static final ByteArrayOutputStream EMPTY_BYTE_ARRAY_OUTPUT_STREAM = new ByteArrayOutputStream(0);
private final Logger logger;
private final boolean encodeBytes;
public PayloadLoggingWebFilter(Logger logger) {
this(logger, false);
}
public PayloadLoggingWebFilter(Logger logger, boolean encodeBytes) {
this.logger = logger;
this.encodeBytes = encodeBytes;
}
#Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
if (logger.isInfoEnabled()) {
return chain.filter(decorate(exchange));
} else {
return chain.filter(exchange);
}
}
private ServerWebExchange decorate(ServerWebExchange exchange) {
final ServerHttpRequest decorated = new ServerHttpRequestDecorator(exchange.getRequest()) {
#Override
public Flux<DataBuffer> getBody() {
if (logger.isDebugEnabled()) {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
return super.getBody().map(dataBuffer -> {
try {
Channels.newChannel(baos).write(dataBuffer.asByteBuffer().asReadOnlyBuffer());
} catch (IOException e) {
logger.error("Unable to log input request due to an error", e);
}
return dataBuffer;
}).doOnComplete(() -> flushLog(baos));
} else {
return super.getBody().doOnComplete(() -> flushLog(EMPTY_BYTE_ARRAY_OUTPUT_STREAM));
}
}
};
return new ServerWebExchangeDecorator(exchange) {
#Override
public ServerHttpRequest getRequest() {
return decorated;
}
private void flushLog(ByteArrayOutputStream baos) {
ServerHttpRequest request = super.getRequest();
if (logger.isInfoEnabled()) {
StringBuffer data = new StringBuffer();
data.append('[').append(request.getMethodValue())
.append("] '").append(String.valueOf(request.getURI()))
.append("' from ")
.append(
Optional.ofNullable(request.getRemoteAddress())
.map(addr -> addr.getHostString())
.orElse("null")
);
if (logger.isDebugEnabled()) {
data.append(" with payload [\n");
if (encodeBytes) {
data.append(new HexBinaryAdapter().marshal(baos.toByteArray()));
} else {
data.append(baos.toString());
}
data.append("\n]");
logger.debug(data.toString());
} else {
logger.info(data.toString());
}
}
}
};
}
}
Here some tests on this: github
I think this is what Brian Clozel (#brian-clozel) meant.
Here is the GitHub Repo with complete implementation to log both request and response body along with http headers for webflux/java based application...
What Brian said. In addition, logging request/response bodies don't make sense for reactive streaming. If you imagine the data flowing through a pipe as a stream, you don't have the full content at any time unless you buffer it, which defeats the whole point. For small request/response, you can get away with buffering, but then why use the reactive model (other than to impress your coworkers :-) )?
The only reason for logging request/response that I could conjure up is debugging, but with the reactive programming model, debugging method has to be modified too. Project Reactor doc has an excellent section on debugging that you can refer to: http://projectreactor.io/docs/core/snapshot/reference/#debugging
Assuming we are dealing with a simple JSON or XML response, if debug level for corresponding loggers is not sufficient for some reason, one can use string representation before transforming it to object:
Mono<Response> mono = WebClient.create()
.post()
.body(Mono.just(request), Request.class)
.retrieve()
.bodyToMono(String.class)
.doOnNext(this::sideEffectWithResponseAsString)
.map(this::transformToResponse);
the following are the side-effect and transformation methods:
private void sideEffectWithResponseAsString(String response) { ... }
private Response transformToResponse(String response) { /*use Jackson or JAXB*/ }
If your using controller instead of handler best way is aop with annotating you controller class with #Log annotation.And FYI this takes plain json object as request not mono.
#Target(AnnotationTarget.FUNCTION)
#Retention(AnnotationRetention.RUNTIME)
annotation class Log
#Aspect
#Component
class LogAspect {
companion object {
val log = KLogging().logger
}
#Around("#annotation(Log)")
#Throws(Throwable::class)
fun logAround(joinPoint: ProceedingJoinPoint): Any? {
val start = System.currentTimeMillis()
val result = joinPoint.proceed()
return if (result is Mono<*>) result.doOnSuccess(getConsumer(joinPoint, start)) else result
}
fun getConsumer(joinPoint: ProceedingJoinPoint, start: Long): Consumer<Any>? {
return Consumer {
var response = ""
if (Objects.nonNull(it)) response = it.toString()
log.info(
"Enter: {}.{}() with argument[s] = {}",
joinPoint.signature.declaringTypeName, joinPoint.signature.name,
joinPoint.args
)
log.info(
"Exit: {}.{}() had arguments = {}, with result = {}, Execution time = {} ms",
joinPoint.signature.declaringTypeName, joinPoint.signature.name,
joinPoint.args[0],
response, System.currentTimeMillis() - start
)
}
}
}
I think the appropriate thing to do here is to write the contents of each request to a file in an asynchronous manner (java.nio) and set up an interval that reads those request body files asynchrolusly and writes them to the log in a memory usage aware manner (atleast one file at a time but up too 100 mb at a time) and after logging them removes the files from disk.
Ivan Lymar's answer but in Kotlin:
import org.apache.commons.io.IOUtils
import org.reactivestreams.Publisher
import org.springframework.core.io.buffer.DataBuffer
import org.springframework.http.server.reactive.ServerHttpRequestDecorator
import org.springframework.http.server.reactive.ServerHttpResponseDecorator
import org.springframework.stereotype.Component
import org.springframework.web.server.ServerWebExchange
import org.springframework.web.server.WebFilter
import org.springframework.web.server.WebFilterChain
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.nio.channels.Channels
#Component
class LoggingWebFilter : WebFilter {
override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> {
val httpRequest = exchange.request
val httpUrl = httpRequest.uri.toString()
val loggingServerHttpRequestDecorator: ServerHttpRequestDecorator =
object : ServerHttpRequestDecorator(exchange.request) {
var requestBody = ""
override fun getBody(): Flux<DataBuffer> {
return super.getBody().doOnNext { dataBuffer: DataBuffer ->
try {
ByteArrayOutputStream().use { byteArrayOutputStream ->
Channels.newChannel(byteArrayOutputStream)
.write(dataBuffer.asByteBuffer().asReadOnlyBuffer())
requestBody =
IOUtils.toString(
byteArrayOutputStream.toByteArray(),
"UTF-8"
)
log.info(
"Logging Request Filter: {} {}",
httpUrl,
requestBody
)
}
} catch (e: IOException) {
log.error(
"Logging Request Filter Error: {} {}",
httpUrl,
requestBody,
e
)
}
}
}
}
val loggingServerHttpResponseDecorator: ServerHttpResponseDecorator =
object : ServerHttpResponseDecorator(exchange.response) {
var responseBody = ""
override fun writeWith(body: Publisher<out DataBuffer>): Mono<Void> {
val buffer: Mono<DataBuffer> = Mono.from(body)
return super.writeWith(
buffer.doOnNext { dataBuffer: DataBuffer ->
try {
ByteArrayOutputStream().use { byteArrayOutputStream ->
Channels.newChannel(byteArrayOutputStream)
.write(
dataBuffer
.asByteBuffer()
.asReadOnlyBuffer()
)
responseBody = IOUtils.toString(
byteArrayOutputStream.toByteArray(),
"UTF-8"
)
log.info(
"Logging Response Filter: {} {}",
httpUrl,
responseBody
)
}
} catch (e: Exception) {
log.error(
"Logging Response Filter Error: {} {}",
httpUrl,
responseBody,
e
)
}
}
)
}
}
return chain.filter(
exchange.mutate().request(loggingServerHttpRequestDecorator)
.response(loggingServerHttpResponseDecorator)
.build()
)
}
}

Resources