Swagger UI does not show Params - spring

I've got a Spring-Application (2.1.0.RELEASE) and added Swagger and Swagger-UI (2.9.2).
I have a SwaggerConfig class, that I copied from the Baeldung tutorial
Then, there is the App class:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
#EnableAutoConfiguration
public class App
{
public static void main(String[] args) throws Exception {
SpringApplication.run(App.class, args);
}
}
And there is the actual REST controller:
#RestController
public class TweetRating {
#GetMapping("/{userid}/tweet")
public static void getTweet(#PathVariable String userid){
System.out.println("UserID: "+ userid);
}
#GetMapping("/")
public static void isWorking(#RequestParam String id){
System.out.println("ID: "+ id);
}
}
The Swagger-UI just won't show the params of the methods. Neither the PathVariable not the RequestParam. Therefore, the "Try it out" function does not make any sense, of course. It looks like this:
Screenshot1
Screenshot2
Why is that and how can I solve it?

Try to apply enableUrlTemplating(true) in you SwaggerConfig :
#Configuration
#EnableSwagger2
public class SwaggerConfig {                                   
    #Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2) 
          .select()                                 
          .apis(RequestHandlerSelectors.any())             
          .paths(PathSelectors.any())  
.enableUrlTemplating(true)                       
          .build();                                          
    }
Also try this one :
#ApiOperation(value = "Dexcription of endpoint")
#RequestMapping
public String doSomething(#ApiParam(value = "Description of path vaiable")#PathVariable("/{code}")

Related

Spring boot controller not being detected

Good day. I'm having issues with my Springboot app. The controller isn't being detected.The Component scan is used but it won't detect the controllers.
Folder structure
Application
#EntityScan(basePackages = "com.jokedata.models")
#EnableJpaRepositories(basePackages = "com.jokedata.repositories")
//#ComponentScan(basePackages = {"com.jokeweb.project.controllers"})
#SpringBootApplication(scanBasePackages = "com.jokeweb.project.controllers")
public class JokeApplication {
public static void main(String[] args) {
SpringApplication.run(JokeDataApplication.class, args);
}
}
Controller
#RestController
public class UserController {
#GetMapping("/home")
public String home() {
return "home";
}
}
Check if request URL or application port is correct or not.

Spring Boot - #RestController annotation gets picked up, but when replaced with #Controller annotation, it stops working

Here is a dummy project for the same :-
BlogApplication.java
#SpringBootApplication
#RestController
public class BlogApplication {
public static void main(String[] args) {
SpringApplication.run(BlogApplication.class, args);
}
#GetMapping("/hello")
public String hello(#RequestParam(value = "name", defaultValue = "World") String name) {
return String.format("Hello %s!", name);
}
}
HtmlController.java
#Controller //does not work
OR
#RestController //works
public class HtmlController {
#GetMapping("/getHtmlFile")
public String getHtmlFile() {
return "Bit Torrent Brief";
}
}
Why is it that #RestController is able to map getHtmlFile but #Controller returns 404 when /getHtmlFile is hit?
#RestController is the combination of #Controller and #ResponseBody.
when you use #Controller, you should write #ResponseBody before your method return type
#Controller
public class HtmlController {
#GetMapping("/getHtmlFile")
public #ResponseBody String getHtmlFile() {
return "Bit Torrent Brief";
}
}
This works.

Spring data with postgress and r2dbc does not work

I am trying to run simple spring boot application with spring data and r2dbc but when i run select query it does return any record.
Configuration
#Configuration
#EnableR2dbcRepositories("com.ns.repository")
public class R2DBCConfiguration extends AbstractR2dbcConfiguration {
#Bean
#Override
public PostgresqlConnectionFactory connectionFactory() {
return new PostgresqlConnectionFactory(PostgresqlConnectionConfiguration
.builder()
.host("localhost")
.database("employee")
.username("postgres")
.password("nssdw")
.port(5432)
.build());
}
#Bean
public DatabaseClient databaseClient(ConnectionFactory connectionFactory) {
return DatabaseClient.builder().connectionFactory(connectionFactory).build();
}
#Bean
R2dbcRepositoryFactory repositoryFactory(DatabaseClient client) {
RelationalMappingContext context = new RelationalMappingContext();
context.afterPropertiesSet();
return new R2dbcRepositoryFactory(client, context, new DefaultReactiveDataAccessStrategy(new PostgresDialect()));
}
}
Controller which is just simple get request I am not even passing the request paramter just hard coding the id as 1 for the name_id
package com.ns.controller;
import com.ns.entities.Name;
import com.ns.repository.NameRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
#RestController
public class EventDrivenController {
#Autowired
private NameRepository repositoryEvent;
#GetMapping(value = "/pools" )
public Mono<Name> getEmployee() {
Mono<Name> mono = repositoryEvent.findById(1);
repositoryEvent.findById(1).doOnEach(System.out::println);
return mono;
}
}
Reactive repository which is simple get by id request
#Repository
public interface NameRepository extends ReactiveCrudRepository<Name,Integer> {
#Query( "SELECT name_id, last_name, first_name FROM name WHERE name_id = $1")
Mono<Name> findById(Integer id);
}
webclient which is just invoking the get call
public void callwebclient() {
WebClient client = WebClient.create("http://localhost:8080");
Mono<Name> nameMono = client.get()
.uri("/pools")
.retrieve()
.bodyToMono(Name.class);
nameMono.subscribe(System.out::println);
}
main class for spring boot
#SpringBootApplication
public class EventDrivenSystemApplication implements CommandLineRunner {
#Autowired
NameRepository nameRepository;
public static void main(String[] args) {
SpringApplication.run(EventDrivenSystemApplication.class, args);
NameWebClient nameWebClient = new NameWebClient();
nameWebClient.callwebclient();
}
}
Main class which is calling webclient . print statment in the webclient does not print anything
#ComponentScan(basePackages ={"com.ns"})
#SpringBootApplication
#EnableR2dbcRepositories
public class EventDrivenSystemApplication {
public static void main(String[] args) {
SpringApplication.run(EventDrivenSystemApplication.class, args);
NameWebClient nameWebClient = new NameWebClient();
nameWebClient.callwebclient();
}
}

Multiple forward slashes in request mapping in spring

#RestController
#RequestMapping("/api")
public class AbcController {
#RequestMapping(value = "/abc", method = RequestMethod.GET)
public String abc(){
return "Hello";
}
}
Valid URL: http://localhost:8080/api/abc
Invalid URls:
http://localhost:8080////api/abc
http://localhost:8080/////api////abc
http://localhost:8080/////////api/////abc
Problem: My controller is accepting all above urls. I want to restrict it and accept only valid url and throw error on invalid urls.
Note: I'm not using any custom routing. It's default spring has.
The simplest way is to add custom handler interceptor to validate the url.
public class ValidateURLInterceptor extends HandlerInterceptorAdapter {
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (isValidUrl(request.getRequestURI())) {
return true;
}
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid URL");
return false;
}
private static boolean isValidUrl(String url) {
return !url.contains("//");
}
}
And then update the MVC configuration
#Configuration
public class AppConfig implements WebMvcConfigurer {
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new ValidateURLInterceptor());
}
}
Add maven dependency for spring security and use below code to allow access to all the paths without logging in.
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
#EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter
{
#Override
public void configure(WebSecurity web) throws Exception
{
web
.ignoring()
.antMatchers("/**");
}
}

access to property in external file works in controller but not in domain class

I have a property set in an external application.properties file and find that I can access it in the controller but not in the domain class. I'm using SpringBoot 1.1.9 and groovy and code snippets listed below.
Can someone please explain what I'm missing here?
Thanks!
--john
//Application class used to startup
#Configuration
#ComponentScan
#EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
//Controller - property is injected
#RestController
class CityController {
#Value( '${sample.property}' )
String stringTemplate
#RequestMapping(value = "/", method = RequestMethod.GET)
public String index(HttpServletResponse response) {
return String.format(stringTemplate, 'world')
}
}
//Domain class - property does not seem to be injected
#Component
public class City {
#Value( '${sample.property}' )
String stringTemplate
String toString() {
return String.format(stringTemplate, 'world')
}
}

Resources