Spring WebFlux Handler Interceptor Adapter - java

I am migrating a Spring MVC library to Spring WebFlux. There is a feature that lets our clients annotate their controller methods to perform custom validation (and applying some business rules) on incoming headers before granting access to the API.
In Spring MVC we had that accomplished by using HandlerInterceptorAdapter. Since WebFlux doesn't have anything similar I was trying out the solution as suggested by Rossen here. However it doesn't work for this use case since the method handler info is only available in onSuccess operator and its too late to get the info for annotation processing.
I was trying out the other approach suggested there using #ModelAttribute method on a #ControllerAdvice but that only work if the annotation is applied to the Controller class in our case the annotation is applied on methods of controller class.
Here is a sample https://github.com/ranarula/handleInterceptor with the issue
Any pointers on how to go about implementing the annotation processing in WebFlux will help.

Related

Is it possible to have mapping between rest controller and controller advice in spring boot 2.4.4 rest java 11 application?

I have a spring boot 2.4.4 java 11 application with many Rest Controllers. I am using #ControllerAdvice for handling all exceptions including custom exceptions.
Is there anyway to map or identify which controller is involved at the time of execution?
or
Is there any way to map one #ControllerAdvice with one #RestController?
Please advice. Thank you..
You can add which controller class you want to be handled using:
#ControllerAdvice(basePackageClasses = {SomeController.class, AnotherController.class})
Also, you can set a package:
#ControllerAdvice(basePackages = {"com.myapp.controllers"})

Is there "The Proper way" of using Spring validator?

I was looking up on how to perform validation in Spring MVC.
Manually call Spring Annotation Validation
Spring MVC: How to perform validation?
The above to links are couple of those. What I was wondering is that calling the Validator.validate manually is considered a bad practice compared to that of using #Valid/#Validated annotations ?

How to output all endpoints exposed by Spring

I'd like to have a way how to expose all endpoints that exposed by my Spring application. Is there a simple way to check, for each #profile which are exposed?
Example:
GET /api/resource
GET /api/resource/list
POST /api/resource
PUT /api/resource
In the past, I have used a web application made in Laravel, and they had a simple cli method for checking the exposed methods.
I assume based on how the questions is worded that you are not using Spring Boot, if you were, the actuator mappings endpoint does this for you, but your answer lies in how the mappings endpoint is build in actuator. There is a RequestMappingHandlerMapping object you leverage.
In this scenario you can use two approaches:
Spring Boot Actuator feature. Your endpoints of application will be available at http://host/actuator/mappings
Swagger library can also be used to list all endpoints of a REST API
The best solution is to use Spring boot actuator and hit the endpoint /actuator/mappings to get all the endpoints.
But if you can't use actuator or can't add it as dependency you can retrieve all the endpoints programmatically the mapping handlers, Spring get shipped with three implementations of this interface (HandlerMapping):
RequestMappingHandlerMapping: which is responsible for endpoints that annotated with #RequestMapping and its variants #GetMapping, #PostMapping .. etc
BeanNameUrlHandlerMapping: as the name suggest it will resolve the endpoint(URL) directly to a bean in the application context. for example if you hit the endpoint /resource it will look for a bean with the name /resource.
RouterFunctionMapping: it will scan the application context for RouterFunction beans and dispatch the request to that function.
Anyways, to answer your question you can autowire the bean RequestMappingHandlerMapping and print out all the handler methods. Something similar to this:
#Autowired
RequestMappingHandlerMapping requestMappingHandlerMapping;
#PostConstruct
public void printEnpoints() {
requestMappingHandlerMapping.getHandlerMethods().forEach((k,v) -> System.out.println(k + " : "+ v));
}

Testing #MessageMapping WebSocket methods of Spring MVC controllers

I am currently experimenting with the support for WebSockets added in Spring 4.0, as described in this guide. As demonstrated in the guide, methods annotated with #MessageMapping can be added to any Spring MVC controller, which may also contain #RequestMapping methods.
The spring-test module has support for writing integration tests for #RequestMapping methods (as described here) in a very simple and fluid way:
#Test
public void getAccount() throws Exception {
this.mockMvc.perform(get("/accounts/1").accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json"))
.andExpect(jsonPath("$.name").value("Lee"));
}
Is there similar support for testing #MessageMapping methods using WebSockets? I have not found anything in any of the Spring modules, and none of the WebSocket guides contain any tests. If not, would I need to actually deploy the application and use a WebSocketConnectionManager to connect a test client? Or is there some API I can build on from spring-test?
This sample project contains such a small test client, but I would prefer to integrate this into the actual tests without requiring me to deploy the application and hardcode the deployed path in the tests.
There is nothing like Spring MVC Test for #MessageMapping methods yet. However, a similar approach to testing should be possible even without the fluent API. There is a ticket in JIRA (see https://jira.spring.io/browse/SPR-11266) to provide documentation so watch that ticket for more details in the very near future.

Spring 3 JSON with MVC

Is there a way to build Spring Web calls that consume and produce application/json formatted requests and responses respectively?
Maybe this isn't Spring MVC, I'm not sure. I'm looking for Spring libraries that behave in a similar fashion to Jersey/JSON. The best case would be if there was an annotation that I could add to the Controller classes that would turn them into JSON service calls.
A tutorial showing how to build Spring Web Services with JSON would be great.
EDIT: I'm looking for an annotation based approach (similar to Jersey).
EDIT2: Like Jersey, I am looking for REST support (POST,GET,DELETE,PUT).
EDIT3: Most preferably, this will be the pom.xml entries and some information on using the spring-js with jackson Spring native version of things.
In case other ppl get here later:
http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/
was the most useful link for me. That finally made me understand the model (after less than a day of searching).
You can certainly have controllers that return a View which is in JSON output. Take a look at the Spring-JSON project.
To consume requests in JSON I would assume you would just want a controller to pass a request parameter off to a JSON library which could parse the data?
There is no pre-packaged way to do what you want as Jersey is nicely integrated with Spring via the Jersey-Spring API so there's really no reason to re-invent the wheel.
Check this one out
Adding support for JSON and XML views
Source code for Spring Finance Manager
Since spring-mvc 3.0 official support for Ajax remoting with JSON is provided as part of Spring MVC. This includes support for generating JSON responses and binding JSON requests using the Spring MVC #Controller programming model.
see here
This feature is now part of Spring since version 3.0. You can simply use the #ResponseBody annotation to specify that you want the return value from your request handler methods to be serialized to JSON and sent as the response body. See http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/
It seems that DWR framework looks very close to what you want to get.
You can configure Spring MVC interceptors through handler mappings and then use the mappings to transform the returning data to JSON. The handler configuration can be done in xml (no need to recompile), and this can be completely transparent to the rest of the application.
It's fairly easy to annotate controllers with some annotation, and then hook up the BeanFactory bootstrap process to register the controllers within some handler mapping process.
I have used this approach to transform the result from spring controllers into GWT RPC calls.
You can also use Spring AOP to intercept controller method calls and unwrap/wrap the requests from/to JSON.

Categories