How to change the Span Name for a REST Endpoint with Spring Cloud Sleuth - spring-boot

I am using Spring Cloud Sleuth to create traces.
I am exposing a REST endpoint using Spring Boot like this:
#SpanName("calculate-reviews")
#GetMapping(path = "/reviews/{productId}")
public Reviews bookReviewsById(#PathVariable String productId) {
...
}
My expectation would be that the span that is created by Spring Cloud Sleuth is named calculate-reviews, however, that's not the case. Instead the default span name is generated which looks like this: get /reviews/{productId}
Is there a chance to change the span name for a REST endpoint at all? How would I achieve this?

I'm not sure it is a good idea to modify it. It gives you additional information that could be valuable if you don't know the service that you are calling by heart (most of the cases).
You can modify the Span using a SpanHandler: see the docs or inject the tracer, get the current span and change the name.

Related

Is it a good idea to handle optional JWT Authentication in Filter?

I am new to Spring Boot and my current project is a REST API developed in Spring Webflux. The goal is to have an endpoint which has an optional JWT Token, allowing you ti create things anonymously or not. But all the starter guides to Spring Security are really complicated and use Spring MVC, as far as I can tell.
Now my idea was to create a HandlerFilterFunction looking like
class AuthenticationFilter : HandlerFilterFunction<ServerResponse, ServerResponse> {
override fun filter(request: ServerRequest, next: HandlerFunction<ServerResponse>): Mono<ServerResponse> {
val authHeader = request.headers().header("Authorization").firstOrNull()
// get user from database
request.attributes()["user"] = user
return next.handle(request)
}
}
and adding it to the router {...} bean.
Is this a good idea, or should I go another router? If so, can somebody point me towards a JWT tutorial for Spring Webflux.
The Spring Security docs point to a JWT-Based WebFlux Resource Server sample in the codebase.
It's not Kotlin-based, so I also posted a sample of my own just now; hopefully, it helps get you started.
As for your question, yes, you can create a filter of your own, though Spring Security ships with a BearerTokenAuthenticationFilter that already does what your filter would likely do. The first linked sample adds this filter manually while the second sample lets Spring Boot add it.

Spring Boot - Where in code can I find this Bean. Is it a Bean?

Hi I'm looking at a Spring Boot application and I'm trying to understand everything that it does. It uses Camel and I am not finding the documentation for Camel especially helpful. Basically I might have a fundamental misunderstanding that a Camel SME would really be able to help with. The piece of code I am looking at is ...
public class SBJobScheduler extends RouteBuilder {
from("direct:alertBatch")
.log(LoggingLevel.INFO, SB_LOGGER, "#The Scheduler is going to start ::sbJob:: batch.# ")
.to("spring-batch:sbJob")
.end();
So I am trying to find how in the heck can I know where "alertBatch" is. I don't see any beans by this name, but maybe I'm missing it. I just want to know what is this value and I'm using the debugger and it doesn't tell me.
alertBatch is the name that uniquely identifies this endpoint. From Camel documentation:
The direct: component provides direct, synchronous invocation of any consumers when a producer sends a message exchange. This endpoint can be used to connect existing routes in the same camel context.
URI format
direct:someName[?options]
Where someName can be any string that uniquely identifies the endpoint.
You can read more about this component here
I suggest that you create a public constant in the same class that creates the route, this way, when you need to call this route, you just refer the created constant. This way you turn your code clean, more readable and allows the call hierarchy functionality from IDEs.

How to keep following Endpoints as a property files in Spring Boot

I have a requirement. for accomplish that i want to keep this end points as a property files in application property files.
Create Endpoint,
http://35.240.228.219/services/create_common.php
{"activeStatus":200,"outputObject":{},"settingsObject":{},"connectToken":"","inputObject":{"filterCriteria":"news","sourceLink":"dtv"},"sessionId":815100,"userId":171}
Delete Endpoint,
http://35.240.228.219/services/delete_common.php
{"activeStatus":1,"outputObject":[],"settingsObject":[],"connectToken":"","inputObject":{"filterCriteria":"news","sourceLink":"dtv"},"sessionId":815100,"userId":171}
Can anyone suggest me how to keep these kind of web endpoints.
In application.properties you can have below properties:
endpoint.create=http://35.240.228.219/services/create_common.php
endpoint.delete=http://35.240.228.219/services/delete_common.php
and from anywhere in your controller/service/class you can call them like this:
#Value("${endpoint.create}")
private String createEndPoint;
//use it anywhere..

Spring Boot: Retrieve config via rest call upon application startup

I d like to make a REST call once on application startup to retrieve some configuration parameters.
For example, we need to retrieve an entity called FleetConfiguration from another server. I d like to do a GET once and save the keep the data in memory for the rest of the runtime.
What s the best way of doing this in Spring? using Bean, Config annotations ..?
I found this for example : https://stackoverflow.com/a/44923402/494659
I might as well use POJOs handle the lifecycle of it myself but I am sure there s a way to do it in Spring without re-inventing the wheel.
Thanks in advance.
The following method will run once the application starts, call the remote server and return a FleetConfiguration object which will be available throughout your app. The FleetConfiguration object will be a singleton and won't change.
#Bean
#EventListener(ApplicationReadyEvent.class)
public FleetConfiguration getFleetConfiguration(){
RestTemplate rest = new RestTemplate();
String url = "http://remoteserver/fleetConfiguration";
return rest.getForObject(url, FleetConfiguration.class);
}
The method should be declared in a #Configuration class or #Service class.
Ideally the call should test for the response code from the remote server and act accordingly.
Better approach is to use Spring Cloud Config to externalize every application's configuration here and it can be updated at runtime for any config change so no downtime either around same.

Available paths listing for Spring actions

I have an application which exposes RESTful actions using spring annotations and Spring MVC.
It looks like
#RequestMapping(value = "/example/{someId}",
method = RequestMethod.GET, consumes=MediaType.APPLICATION_JSON_VALUE,
produces=MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public void isRegisteredToThread(#PathVariable long someId, HttpServletResponse response) {
[something]
}
What I want is an automatically generated listing of all URL's, methods and available parameters - possibly within a WSDL. Is there a plugin or is it somehwere available?
WSDL is not done for rest, it's used for SOAP.
You might use WADL, but I really do not suggest it.
In my project I always use swagger (there is a release for spring). You may find more info here https://github.com/martypitt/swagger-springmvc and here http://blog.zenika.com/index.php?post/2013/07/11/Documenting-a-REST-API-with-Swagger-and-Spring-MVC
Give it a try.
As an alternative, if you don't need something web-based, you may try rest-shell (https://github.com/spring-projects/rest-shell)
You could take a look at the source code of RequestMappingEndpoint provided by the Spring Boot and see how Spring Boot reports the mappings.
Looking through that code one can see that the mappings (both handler and method mappings) can easily be obtained from the applicationContext
(using
applicationContext.getBeansOfType(AbstractUrlHandlerMapping.class)
and
applicationContext.getBeansOfType(AbstractHandlerMethodMapping.class)
respectively). After you have obtained the mapping you can process them anyway you like.
You might want to create a library that could include in all your projects that processes the mapping your organizations desired form

Resources