Rest api filtering in spring boot - spring-boot

I have a project in spring boot, in my controller I have many methods with similar functionality.
Methods for searching post, popular, latest etc and the urls with slight variation like -
url 1 - search/{topicId}
url 2 - search/popular/{topicId}
url 3 - search/latest/{topicId}
What I want, is to have a single method with filter in url like search/{topicId}?filter=popular
How to achieve this in spring boot?

OOPs... it does not depend on SpringBoot. It is simply a URL mapping...You can accept the type as a request param and can process as per business.....
#Controller
public class BookController {
#GetMapping(value = "/search/{topicId}")
#ResponseBody
public List<Object> getBooksByType(#RequestParam String type) {
try{
if("popular".equalsIgnoreCase(type)){
//do your business stuffs
}else if ("latest".equalsIgnoreCase(type)){
//do your business stuffs
}
}catch(Exception e){
e.printStackTrace();
}
return new ArrayList<>();
}
}

Related

Spring webflux Multiple Exception handler in functional Endpoint

im working ins Spring web flux project and I used functional endpoints instead of controller annotation but I didn't find a solution to handle multiple exceptions for the same endpoint , this is my code :
#Override
protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
return RouterFunctions.route(RequestPredicates.GET("/router/users/{id}"),this::renderException);
}
private Mono<ServerResponse> renderException(ServerRequest request) {
Map<String, Object> error = this.getErrorAttributes(request, ErrorAttributeOptions.defaults());
error.remove("status");
error.remove("requestId");
return ServerResponse.status(HttpStatus.BAD_REQUEST).contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(error));
}
for the endpoint /router/users/{id} i trigger UserNotFoundException and UserException and I want to return 404 for UserNotFoundException and 500 for UserException but I don't know how to do that in the functional endpoint. anyone can guide me on how to do this in the correct way like we did in using #ExceptionHandler in rest controller?
If returning proper code is all you care about then adding #ResponseStatus for your custom exceptions might be the best solution.
#ResponseStatus(HttpStatus.NOT_FOUND)
public class UserNotFoundException extends RuntimeException {
// more methods...
public UserNotFoundException(final String message) {
super(message);
}
}
But if you want to build ServerResponse by yourself, make use of project reactor operators, like switchIfEmpty() or onErrorMap(), etc. which could be used as following
Mono<ServerResponse> response() {
return exampleService.getUser()
.flatMap(user -> ServerResponse.ok().body(user, User.class))
.switchIfEmpty(ServerResponse.notFound().build());
}
You might want to take a look at docs Which operator do I need? - handling errors

Resolving POST /** request URL to full request URL using micrometer

With the micro-service architecture I have written a generic POST request handler which is consumed by all the micro-services. The post mapping in spring look like this:
#RestController
#RequestMapping(value = "/v1/", consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE})
public class V1Controller {
#PostMapping(path = "/**")
public #ResponseBody Json post () {}
}
Now while I am consuming the metrics for this endpoint using micrometer I am only getting /v1/ as the endpoint in the metrics while I am sending the full URL like /v1/demo/foo from the calling service. I tried lot of the combination but it is not working. I have also added the WebMvcTagsProvider where I am listing to request and resolving the POST api calls.
#Bean
#SuppressWarnings("unchecked")
public WebMvcTagsProvider webMvcTagsProvider(ObjectMapper objectMapper) {
return new DefaultWebMvcTagsProvider() {
public Iterable<Tag> getTags(HttpServletRequest request, HttpServletResponse response, Object handler, Throwable exception) {
if ("POST".equals(request.getMethod())) {
Tag uriTag = Tag.of("uri", String.valueOf(request.getRequestURI()));
return Tags.of(WebMvcTags.method(request), uriTag, WebMvcTags.exception(exception), WebMvcTags.status(response));
}
return Tags.of(WebMvcTags.method(request), WebMvcTags.uri(request, response), WebMvcTags.exception(exception), WebMvcTags.status(response));
}
};
}
Still it is resolving to /v1/ URL in the metrics. I tried googling alot but didn't find any solution. Thanks in advance.
The build in Spring Boot RequestMapping based metrics match on the annotations and add those as tags.
This is to avoid a tag explosion. Imagine a #RequestMapping for a path like user/{userId}, you would want to group all those calls together (user/1, user/2, user/3).
You'll want to create your own Timer in your post method that set that url tags, etc there.
If you decide to reuse the same metric name as the built in Spring Boot metric, you'll want to disable that one as well, so you don't double count those requests.

Keep same URL but contract changes in Spring Boot REST Open API 3?

I am using Spring Boot and REST and Open API 3 implementation. In this example, v1 Group has List implementation - all data will get in List, in v2 Group has pagination implementation - all data will come in the form of pages.
For the consumer, we don't want to change endpoint url for them to be consume.
Endpoint which returns list.
#GetMapping(value = "/contacts", headers = {"Accept-version=v1"})
public ResponseEntity<List<Contact>> findAll() {
List<Contact> contacts = contactService.findContactList();
return new ResponseEntity<>(contacts, HttpStatus.OK);
}
Endpoint with Pagination
#GetMapping(value = "/contacts", headers = {"Accept-version=v2"})
public ResponseEntity<List<Contact>> findAll(Pageable pageable) {
Page<Contact> contactPages = contactService.findContactPageable(pageable);
return new ResponseEntity<>(contactPages, HttpStatus.OK);
}
I want V1 endpoint to be shown in GroupedOpenApi and v2 endpoint to be shown in the GroupedOpenApi2. Any suggestions ?
Lets assume you put the two endpoints in different packaged and then use the Following GroupedOpenApi definition:
#Bean
public GroupedOpenApi groupOpenApiV1() {
return GroupedOpenApi.builder()
.setGroup("v1")
.packagesToScan("test.org.springdoc.api.v1")
.build();
}
#Bean
public GroupedOpenApi groupOpenApiV2() {
return GroupedOpenApi.builder()
.setGroup("v2")
.packagesToScan("test.org.springdoc.api.v2")
.build();
}

How to implement Session Tracking in spring MVC?

I am very new to spring mvc, I have to develop a web application based on session tracking and my application is annotation based. In my web app I have route each page based on the username and role existence in session. Initially I have been using HttpSession as parameter to controller method, but it is very difficult to check each and every request. I know there are many application level security ways in spring, but I really couldn't understand how to use them. Please suggest me some solutions, For all help thanks in advance.
After updating with interceptors:
Controller class
// Method to showLogin page to user
#RequestMapping(value = "user")
public ModelAndView showLoginToUser(#ModelAttribute("VMFE") VmFeUser VMFE,HttpSession session) {
System.out.println("#C====>showLoginToUser()===> ");
ModelAndView view = new ModelAndView();
//session.setAttribute("user_name", "no_user");
try {
view.setViewName("login");
} catch (Exception e) {
e.printStackTrace();
}
return view;
}
Interceptor
public class HelloWorldInterceptor extends HandlerInterceptorAdapter {
#Override
public boolean preHandle (HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
RequestMapping rm = ((HandlerMethod) handler).getMethodAnnotation(
RequestMapping.class);
boolean alreadyLoggedIn = request.getSession()
.getAttribute("user_name") != null;
boolean loginPageRequested = rm != null && rm.value().length > 0
&& "login".equals(rm.value()[0]);
if (alreadyLoggedIn && loginPageRequested) {
//response.sendRedirect(request.getContextPath() + "/app/main-age");
return false;
} else if (!alreadyLoggedIn && !loginPageRequested) {
System.out.println("REDIRECTING===");
response.sendRedirect(request.getContextPath() + "/user");
return false;
}
return true;
}
}
Using spring security you can implement session tracking and apply filters to validate requests. Spring security is very easy to implement. Kindly follow spring security tutorial click here.
You can also check my git repo for implementation click here. It's a angular spring boot application and i have used spring security and JWT for authentication and authorization.
Hope it helps you thanks.

REST Calls from a Liferay Portlet

I'm trying to setup a simple Liferay + Maven portlet that can utilize REST services to fetch data from an external database. I believe I'm most of the way there but I'm stuck on the #RequestMapping within a Liferay portlet. I have a #Controller setup that runs fine on the View phase of the portlet
#Controller
#RequestMapping(value = "VIEW")
public class RiskController {
#ActionMapping
public void handleActionRequest(ActionRequest request, ActionResponse response)throws Exception {
return;
}
#RenderMapping
public ModelAndView handleRenderRequest(RenderRequest request, RenderResponse response, ModelMap model) {
model.addAttribute("helloWord", "123");
return new ModelAndView("index", model);
}
}
Now I'd like to write some service classes and fetch my data, but I'm not sure how to set this up as far as the Paths/URLs are concerned from a Liferay perspective (i.e., localhost:8080/myPortlet/myAjaxCall). I want to do something basic like return an Object via JSON like so
#RequestMapping(value = "/getMyData/123", method = RequestMethod.GET)
public #ResponseBody Data getData(#RequestParam long gcfId) {
Data data = dataRepo.getMyData(123);
return data;
}
Can anyone help get me in the right direction? Can provide more code if needed

Resources