I’m migrating an application from Netflix/Zuul to Spring Cloud Gateway:
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest)exchange.getRequest();
ServletServerHttpResponse serverHttpResponse = (ServletServerHttpResponse)exchange.getResponse();
if (shouldFilter(exchange)) {
try {
log.debug("Invoking authorization interceptor");
if (!checkRequest(
serverHttpRequest.getServletRequest(),
serverHttpResponse.getServletResponse(),
null)) {
return Mono.error(new RuntimeException("Invalid request"));
}
return chain.filter(exchange);
} catch (Exception exception) {
log.error(ERROR_MESSAGE, exception);
return Mono.error(exception);
}
}
return Mono.empty();
}
The test case I wrote is as follows:
private GatewayFilterChain filterChain
private static ServerWebExchange exchange;
def setup() {
exchange = mock(ServerWebExchange.class)
ServerHttpRequest request = mock(ServerHttpRequest.class)
ServerHttpResponse response = mock(ServerHttpResponse.class)
filterChain = mock(GatewayFilterChain.class)
when(filterChain.filter(exchange)).thenReturn(Mono.empty())
when(exchange.getRequest()).thenReturn(request)
when(exchange.getResponse()).thenReturn(response)
}
However, when testing, I’m getting the following error:
java.lang.ClassCastException: class org.springframework.http.server.reactive.ServerHttpRequest$MockitoMock$6YiKyP1Z cannot be cast to class org.springframework.http.server.ServletServerHttpRequest (org.springframework.http.server.reactive.ServerHttpRequest$MockitoMock$6YiKyP1Z and org.springframework.http.server.ServletServerHttpRequest are in unnamed module of loader 'app')
I do have to stick with HttpServletRequest
and HttpServletResponse
in jakarta
, otherwise would be a nightmare to re-implement the downstream service. What would be the best way to cast/convert ServerHttpRequest to HttpServletRequest?