How to use OpenApi annotations in spring-webflux RouterFunction endpoints? - spring-boot

I am currently working on a project where I use spring functional web programming. I usually use annotations of swagger 2 in restController but with functional web programming I can not find where ! The place to tell the app to do a search for endpoints (like basepackage in Docket) and load swagger in an html page.
Here is my code:
#Configuration
public class RouterClient{
#Bean
public RouterFunction<ServerResponse> routes(ClientHandler client){
return route(GET("/api/client"), client::findAll)
.andRoute(POST("/api/client"),client::add);
}
}
Config Class:
#Configuration
public class OpenApiConfiguration{
#Bean
public GroupedOpenApi groupOpenApi() {
String paths[] = {"/api/**"};
String packagesToscan[] = {"com.demo.client"};
return GroupedOpenApi.builder().setGroup("groups").pathsToMatch(paths).packagesToScan(packagesToscan)
.build();
}
}
The dependencies:
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-webflux-core</artifactId>
<version>1.2.32</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-webflux-ui</artifactId>
<version>1.2.32</version>
</dependency>
The result :

Functional endpoints are supported since 1.3.8 (early May). See releases on GitHub.
Have a look at this: https://springdoc.org/#spring-webfluxwebmvc-fn-with-functional-endpoints
The easiest way to see your endpoints on the Swagger UI is to add the #RouterOperation annotation to your RouterFunction methods (containing a single route), and specify the beanClass and beanMethod used in it. However, in your case, there are multiple routes on a single method, so you must also use the #RouterOperations annotation. These cases are well documented in the link above.
It seems like the current implementation of springdoc-openapi only allows to manually add the documentation.

set
springdoc.api-docs.enabled=false
This will skip classpath scanning (springfox) for the API annotations. (OAS3 replaced these in v3) and replace them with reading in the spec file (json/yaml).
Put the documentation in the Spec files, as one can generate any number of clients from these. Easiest way to start with legacy code is to copy the /api-docs/ files generated by springfox.
You can go to editor.swagger.io, load in the version 2 yaml and convert it to version 3 if springfox still doesn't do that. Then work with yaml files. (it's a contract UP-Front specification for a reason)

https://springdoc.org/
You need springdoc-openapi-webflux-ui and #RouterOperation.

spring-webflux with Functional Endpoints, will be available in the future release

Related

How to disable /application.wadl in OpenAPI spec with Jersey

Setup
I use a Spring Boot app from the Initializr with Jersey dependency included and add io.swagger.core.v3:swagger-jaxrs2:2.1.13 as an additional dependency. Then I create the following ResourceConfig (registering other resource classes omitted for brevity):
#Component
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
this.registerClasses(
OpenApiResource.class
);
}
}
When I start the application and have a look at the generated API spec at http://localhost:8080/openapi.json, I find two paths:
GET /application.wadl/{path} and
GET /application.wadl
In Swagger UI, it looks like this:
When I send a request to the WADL endpoint, I get a 404 response in this setup. I already tried to disable the WADL feature with this line, but the spec still contains the two paths:
this.property(ServerProperties.WADL_FEATURE_DISABLE, true);
Question
How do I disable or hide these two paths in the OpenAPI spec properly?
May be you can try packages-to-scan property
springdoc:
packages-to-scan:
- com.myapp.appName.controller

How to use and config caching in Spring MVC

I want to cache the following getMessagesList method. I want to call one time When user log into the system. Therefor I think caching is the best solution for that. And I need to remove when user log out. How I can do this.
public List<String> getMessagesList(String username)
{ // return messages list in DB by username}
My project was create using Maven 4.0 and Spring MVC. spring version 5.3
Assuming you use Spring Security as part of your app, it should be managing your session, and every time you log out, it will create a new session. Unless you had posted this code, I'm not going to be able to help you there. However, assuming you can log in/out, this should be covered already.
As for the cacheing, in general, this sounds like a Database Caching need, which is something that you would use Spring Boot Caching on.
To use this in Spring Boot, you would add the following dependency to maven (or the equivalent in Gradle, etc):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
Adjust your application to allow using Cacheing, which can be done by adding the annotation #EnableCaching to your Spring Boot application
#SpringBootApplication
#EnableCaching
public class MyApplication {
...
}
Create a Java Service Object, called something like MessagesService.class:
#CacheConfig(cacheNames={"Messages"})
public class MessagesService {
#Cacheable(value="cacheMessages")
List<String> getMessages() {
//access the database to load data here
...
}
...
}

Use Micrometer with OpenFeign in spring-boot application

The OpenApi documentation says that it supports micrometer. How does the integration works? I could not find anything except this little documentation.
I have a FeignClient in a spring boot application
#FeignClient(name = "SomeService", url = "xxx", configuration = FeignConfiguration.class)
public interface SomeService {
#GET
#Path("/something")
Something getSomething();
}
with the configuration
public class FeignConfiguration {
#Bean
public Capability capability() {
return new MicrometerCapability();
}
}
and the micrometer integration as a dependency
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-micrometer</artifactId>
<version>10.12</version>
</dependency>
The code makes a call but I could not find any new metrics via the actuator overview, expecting some general information about my HTTP requests. What part is missing?
Update
I added the support for this to spring-cloud-openfeign. After the next release (2020.0.2), if micrometer is set-up, the only thing you need to do is putting feign-micrometer onto your classpath.
Old answer
I'm not sure if you do but I recommend to use spring-cloud-openfeign which autoconfigures Feign components for you. Unfortunately, it seems it does not autoconfigure Capability (that's one reason why your solution does not work) so you need to do it manually, please see the docs how to do it.
I was able to make this work combining the examples in the OpenFeign and Spring Cloud OpenFeign docs:
#Import(FeignClientsConfiguration.class)
class FooController {
private final FooClient fooClient;
public FooController(Decoder decoder, Encoder encoder, Contract contract, MeterRegistry meterRegistry) {
this.fooClient = Feign.builder()
.encoder(encoder)
.decoder(decoder)
.contract(contract)
.addCapability(new MicrometerCapability(meterRegistry))
.target(FooClient.class, "https://PROD-SVC");
}
}
What I did:
Used spring-cloud-openfeign
Added feign-micrometer (see feign-bom)
Created the client in the way you can see above
Importing FeignClientsConfiguration and passing MeterRegistry to MicrometerCapability are vital
After these, and calling the client, I had new metrics:
feign.Client
feign.Feign
feign.codec.Decoder
feign.codec.Decoder.response_size

nodeBuilder() is removed by Elasticsearch, but still spring-data-elasticsearch documentation contains configuration which uses nodeBuilder()

I was following the Spring-Data-Elasticseach documentaion and was following the configuration as mentioned in the above link.
#Configuration
#EnableElasticsearchRepositories(basePackages = "org/springframework/data/elasticsearch/repositories")
static class Config {
#Bean
public ElasticsearchOperations elasticsearchTemplate() {
return new ElasticsearchTemplate(nodeBuilder().local(true).node().client());
}
}
Since import for nodeBuilder() is not mentioned in the documentation I assumed it from org.elasticsearch.node.NodeBuilder.* as mentioned in elasticsearch Java API.
But in the later releases, the API got changed and NodeBuilder no longer exists. So why/how the spring documentation still using the NodeBuilder?
If that's an issue with the documentation, what's the right configuration?
The dependencies I am using
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
with the boot version 2.1.1.RELEASE
This looks like a documentation issue. I've raise DATAES-574 to have that fixed.
With Spring Boot 2.1, the usual way to create a Client bean is to set a spring.data.elasticsearch.cluster-nodes property. Behind the scenes this will create the Client as a org.elasticsearch.client.transport.TransportClient instance.
You can also define that bean yourself if you so wish.
In the future, TransportClient is also going to been deprecated by Elasticsearch. At that point you'll need to use the higher level REST API. See https://jira.spring.io/browse/DATAES-407 for the details.

Axon 4 XStream configuration

When running my Spring Boot app which includes Axon 4 I see the following in my output console:
Security framework of XStream not initialized, XStream is probably vulnerable.
How do I go about securing the XStream included in Axon 4?
For clarification, I am speaking about how to configure the XStream that Axon 4 uses. I am not certain if this should be done in the YAML file or in one of the Configuration classes. Every where I have tried the information detailed in this answer does not affect the XStream configuration and I still get the same warning.
Update:
Based on the answers below, this question seems to be two fold. Thanks to the answers below I managed to get this working as follows (based on information posted at this answer):
//AxonConfig.java
#Bean
XStream xstream(){
XStream xstream = new XStream();
// clear out existing permissions and set own ones
xstream.addPermission(NoTypePermission.NONE);
// allow any type from the same package
xstream.allowTypesByWildcard(new String[] {
"com.ourpackages.**",
"org.axonframework.**",
"java.**",
"com.thoughtworks.xstream.**"
});
return xstream;
}
#Bean
#Primary
public Serializer serializer(XStream xStream) {
return XStreamSerializer.builder().xStream(xStream).build();
}
I didn't want to answer my own question as I think Jan got the correct answer combined with Steven pointing to the Spring Boot config.
I am certain I will need to whittle away at the package scopes and will do so in due course. Thanks Jan and Steven for your assistance.
This is not Axon specific, check this question for background and solution: Security framework of XStream not initialized, XStream is probably vulnerable
Jan Galinski is right in that this isn't an Axon specific issue per say. More so a shift within the XStream package. Regardless, the link Jan shares is very valuable.
From there, you can create your own XStream object, instead of using the one the XStreamSerializer creates for you when utilizing Axon. You can then feed that object to the builder() of the XStreamSerializer.
As you are using Spring Boot too, simply having a bean creation function like so would suffice:
// The XStream should be configured in such a way that a security solution is provided
#Bean
public Serializer serializer(XStream xStream) {
return XStreamSerializer.builder().xStream(xStream).build();
}
Hope this helps!

Resources