swagger not detected when i remove #configuration - maven

i try to integrate swagger into my spring boot project but i receive always an error :
"Error creating bean with name 'modelMapperImpl': Failed to introspect bean class [springfox.documentation.swagger2.mappers.ModelMapperImpl] " but when i remove #configuration from swaggerConfig swagger will not be detected ,here is my code :
WebConfig:
#Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE",
"PATCH");
}
}
SwaggerConfig
#EnableSwagger2
#Configuration
public class SwaggerConfig {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
Pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>

Try this approach.
#Configuration
#ConfigurationProperties(prefix = "mycompany.cors")
public class CorsSettings {
final private Logger log = LoggerFactory.getLogger(CorsSettings.class);
private List<String> origins = new ArrayList<>();
public CorsSettings() {
log.debug("construct CorsSettings");
}
public List<String> getOrigins() {
return this.origins;
}
#Bean
public WebMvcConfigurer corsConfigurer() {
if (origins != null) {
log.debug("corsOrgins=" + origins);
} else {
log.error("corsOrgins=null");
}
return new WebMvcConfigurerAdapter() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins(origins.toArray(new String[origins.size()]));
}
};
}
}
Next in Config
#Configuration
public class SwaggerConfig {
ApiInfo apiInfo() {
return new ApiInfoBuilder().title("My Swagger API").description("This is a my swagger server")
.license("").licenseUrl("https://opensource.org/licenses/MIT").termsOfServiceUrl("").version("1.0.0")
.contact(new Contact("My name", "://www.mycompany.com", "myemail#mycompany.com"))
.build();
}
#Bean
public Docket customImplementation() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("com.mycompany.path")).build()
.apiInfo(apiInfo());
}
}
Then in application.yml
mycompany:
cors:
origins:
- ${origin1:http://localhost:8080}
- ${origin2:http://localhost:8080}
- ${origin3:http://localhost:8080}
- ${origin4:http://localhost:8080}

Related

After deploy in jenkins, i can't find swagger

Actually, after i deployed my project on jenkins, i can't find swagger api docs.
what if our domain xxx.oooo.com, i've tried "xxx.oooo.com/swagger-ui/index.html", but can't still find. Also i tried ip4 address as well. but still doesn't work.
there is no problem about deploy, because there is no fail on jenkins.
i didnt work for front-end side, so i have no idea, but is it possible to be related with front-end about unable finding swagger api docs?..
i've also tried a lot of times through google, but still couldn't find answer yet. Plus, it works on local server really well!
here is my swaggerConfig.java file.
#Configuration
#EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurationSupport {
#Value("${swagger.info.title}")
private String title;
#Value("${swagger.info.desc}")
private String desc;
#Value("${swagger.info.version}")
private String version;
#Bean
public Docket api() {
return new Docket(DocumentationType.OAS_30)
.securityContexts(Arrays.asList(securityContext()))
.securitySchemes(Arrays.asList(apiKey()))
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.company.controller"))
.paths(PathSelectors.any())
.build();
}
public ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(title)
.description(desc)
.version(version)
.build();
}
public SecurityContext securityContext() {
return SecurityContext.builder()
.securityReferences(defaultAuth())
.build();
}
public List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accept all");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return Arrays.asList(new SecurityReference("Authorization", authorizationScopes));
}
public ApiKey apiKey() {
return new ApiKey("Authorization", "Authorization", "header");
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/swagger-ui/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
}
}
I am using
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
I also set up webConfig as well.
#Configuration
public class WebConfig implements WebMvcConfigurer {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*");
}
}

Spring Eureka LoadBalanced RestTemplate when not connected

Here are my dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
When my Spring Boot application is registered with Eureka, I can define a RestTemplate bean like this:
#Bean
#LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
And in my services I can make requests to other services using their registered spring.application.name:
restTemplate.getForEntity("http://application1/test", String.class);
How do I define where http://application1/ is located with Eureka disabled?
eureka.client.enabled=false
Current Implementation test:
#Configuration
public class RibbonConfig {
#Bean
public ServerList<Server> serverServerList() {
return new ConfigurationBasedServerList();
}
}
#Configuration
public class WebConfig {
#Bean
#LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
#Component
public class TestService implements CommandLineRunner {
#Autowired
private RestTemplate restTemplate;
#Override
public void run(String... args) throws Exception {
ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://application1/test", String.class);
System.out.println(responseEntity);
}
}
#RibbonClient(value = "application1", configuration = RibbonConfig.class)
#SpringBootApplication
public class Demo5Application {
public static void main(String[] args) {
SpringApplication.run(Demo5Application.class, args);
}
}
bootstrap.yml
eureka:
client:
enabled: false
application1:
ribbon:
list-of-servers: http://localhost:8081/
you can define a new RibbonClient configuration for your service this way:
#Configuration
#RibbonClient(name = "application1", configuration = Application1RibbonClientConfiguration.class)
public class Application {
...
}
class Application1RibbonClientConfiguration{
#Bean
public ServerList<Server> ribbonServerList() {
return new ConfigurationBasedServerList();
}
}
you can skip all the configuration above if you don't have eureka on classPath
next in your properties file you can list all the servers location like this:
application1.ribbon.listOfServers=..,..,..

Springfox swagger 2 not working with Spring Boot 1.5: HTTP 404 not found at /v2/api-docs

I have a Spring Boot project with springfox-swagger-2 as dependency.
Versions used:
Spring Boot: 1.5.9.RELEASE
springfox-swagger-2: 2.7.0
This is the configuration:
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket api() {
Docket api = new Docket(DocumentationType.SWAGGER_2);
api
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
api.apiInfo(apiInfo())
.globalOperationParameters(Lists.newArrayList(new ParameterBuilder()
.name("Example api info")
.description("description")
.modelRef(new ModelRef("string"))
.parameterType("parameter type example").build()))
;
return api;
}
#SuppressWarnings("rawtypes")
private ApiInfo apiInfo() {
Contact contact = new Contact("name", "url", "email");
Collection<VendorExtension> vendorExtensions = new ArrayList<>();
return new ApiInfo("title", "description", "version", "termsOfServiceUrl", contact, "license", "licenseUrl", vendorExtensions);
}
}
The application starts correctly, but the url /v2/api-docs gets an HTTP 404 Not Found
Even the /swagger-ui.html is not available adding the dependency for springfox-swagger-ui
The bootstrap log doesn't report any error.
I already tried to find the answer on other similar questions but any of them is working!
Any help would be appreciated.
SwaggerConfig.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket apiDocket() {
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.."))
.paths(PathSelectors.any())
.build();
return docket;
}
}
SecurityConfig.java
public class SecurityConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer{
#Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/v2/api-docs", "/configuration/**", "/swagger*/**", "/webjars/**")
}
#Override
protected void configure(HttpSecurity http) throws Exception{
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/v2/api-docs", "/configuration/**", "/swagger*/**", "/webjars/**")
.permitAll()
.anyRequest().authenticated();
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
pom.xml
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-core</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
try to add this to yourapplication.properties
spring.resources.add-mappings=true
Finally I have found the way to make it work.
The springfox-swagger-2 implementation has a #Controller within the class springfox.documentation.swagger2.web.Swagger2Controller.
This class implements the mapping for the url "/v2/api-docs" with this method:
#RequestMapping(
value = DEFAULT_URL,
method = RequestMethod.GET,
produces = { APPLICATION_JSON_VALUE, HAL_MEDIA_TYPE })
#PropertySourcedMapping(
value = "${springfox.documentation.swagger.v2.path}",
propertyKey = "springfox.documentation.swagger.v2.path")
#ResponseBody
public ResponseEntity<Json> getDocumentation(
#RequestParam(value = "group", required = false) String swaggerGroup,
HttpServletRequest servletRequest) {
String groupName = Optional.fromNullable(swaggerGroup).or(Docket.DEFAULT_GROUP_NAME);
Documentation documentation = documentationCache.documentationByGroup(groupName);
if (documentation == null) {
return new ResponseEntity<Json>(HttpStatus.NOT_FOUND);
}
Swagger swagger = mapper.mapDocumentation(documentation);
UriComponents uriComponents = componentsFrom(servletRequest, swagger.getBasePath());
swagger.basePath(Strings.isNullOrEmpty(uriComponents.getPath()) ? "/" : uriComponents.getPath());
if (isNullOrEmpty(swagger.getHost())) {
swagger.host(hostName(uriComponents));
}
return new ResponseEntity<Json>(jsonSerializer.toJson(swagger), HttpStatus.OK);
}
As you can see, the RequestMapping expects a parameter named "group".
So, if you call the "/v2/api-docs" url without the "group" parameter, the documentation obtained is null because there are no documentations in the cache for the key "" (empty String).
I solved adding a custom Filter implemented in this way:
#Component
public class SwaggerFilter implements Filter {
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String group = req.getParameter("group");
if (req.getServletPath().equals("/v2/api-docs") && group==null) {
res.sendRedirect("api-docs?group=default");
} else {
chain.doFilter(request, response);
}
}
#Override
public void destroy() {
}
}
The mechanism is simple: without the "group" parameter, there is a redirect with the "default" group parameter.
I also stumbled upon an HTTP 404 Not Found for /v2/api-docs (but during a unit test) as part of migrating Spring Boot from version 2.0.4.RELEASE to version 2.1.6.RELEASE. The unit test passed before the "upgrade".
The unit test class had the following annotations:
#Category(UnitIntegrationTest.class)
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#ContextConfiguration(classes = {SecurityConfiguration.class})
#ActiveProfiles("test")
and the test configuration was defined as an inner class:
#Configuration
#EnableWebMvc
#EnableSwagger2
#Import(value = BeanValidatorPluginsConfiguration.class)
public static class TestSwaggerConfiguration {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("the.package.we.want"))
.paths(PathSelectors.any())
.build();
}
}
The fix was to specify the TestSwaggerConfiguration in the #ContextConfiguration, e.g.:
#Category(UnitIntegrationTest.class)
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#ContextConfiguration(classes = {SecurityConfiguration.class, GenerateDocumentationTest.TestSwaggerConfiguration.class})
#ActiveProfiles("test")
As a side note, before hitting the HTTP 404 I also had to specify
spring.main.allow-bean-definition-overriding=true
in the application-test.properties as per the Spring Boot 2.1 Release Notes.
In case the person stuck is a noob like me, make sure you have run the Maven Install command after adding the dependencies in the pom.xml file.

springfox-data-rest configuration not work

I follow the link to config.
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-data-rest</artifactId>
<version>2.7.0</version>
</dependency>
#Configuration
#Import( {springfox.documentation.spring.data.rest.configuration.SpringDataRestConfiguration.class})
public class WebMvcConfig extends WebMvcConfigurerAdapter{
......
}
#RepositoryRestResource(collectionResourceRel = "mails", path = "mails")
public interface TMessageMailDao extends PagingAndSortingRepository<TMessageMail, Long>{
}
But when I open http://localhost:8080/swagger-ui.html, there is nothing.
I know springfox-data-rest is still in incubation. Is that the reason it's not work? Or anything wrong?
You are missing #EnableSwagger2 annotation.
Make sure to create a Docket bean as shown in the example below.
#Configuration
#Import({SpringDataRestConfiguration.class})
#EnableSwagger2
public class WebMvcConfig extends WebMvcConfigurerAdapter {
...
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("example")
.select()
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo("Example API", "Example API"));
}
private ApiInfo apiInfo(String title, String description) {
return new ApiInfoBuilder()
.title(title)
.description(description)
.build();
}
}
Make sure to add the following dependencies:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
Once it's working, your swagger-ui.html will look something like this:
I want to scan two packages. How to include two base packages and not one?
Just Controllers
If you are just interested in including REST controllers and not any repository, you can specify any number of packages within apis method of Docket with the help of a custom method.
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("book")
.select()
.apis(exactPackages("com.basaki.controller", "com.basaki.model"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo("Example Springfox API",
"Example Springfox API"));
}
private static Predicate<RequestHandler> exactPackages(
final String... pkgs) {
return input -> {
String currentPkg =
input.declaringClass().getPackage().getName();
for (String pkg : pkgs) {
if (pkg.equals(currentPkg)) {
return true;
}
}
return false;
};
}
Controllers and Repositories
If you are interested in including REST controllers and repositories, you have to take advantage of paths method in Docket with the help of a custom method. The custom method takes path regexes.
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("book")
.select()
.paths(matchPathRegex("/books(/|$).*",
"/booxs(/|$).*", "/tokens(/|$).*",
"/ping(/|$).*"))
.build()
.apiInfo(apiInfo("Example Springfox API",
"Example Springfox API"));
}
private static Predicate<String> matchPathRegex(final String... pathRegexs) {
return new Predicate<String>() {
#Override
public boolean apply(String input) {
for (String pathRegex : pathRegexs) {
if (input.matches(pathRegex)) {
return true;
}
}
return false;
}
};
}
Thank you for Indra Basak 's help.
My configuration just have one problem.
#Configuration
#EnableSwagger2
#Import({SpringDataRestConfiguration.class})
This three annotations have to use together. I config #EnableSwagger2 in another configuration file.

Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type:

I am trying to expose REST service, but while hitting it from POSTMAN i am getting below :
WARNING: Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type: class java.util.ArrayList
Where as i have also included below jar files which are required :
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.1</version>
</dependency>
Here is my REST controller Code :
#RestController
#RequestMapping("/MayankAPI")
public class TestRestAPI {
#RequestMapping(value="/sayHello" , method = RequestMethod.POST)
public TestPojo postData(#RequestBody String payload) {
System.out.println("Hello post"+payload);
TestPojo payload1=new TestPojo();
payload1.setStudentName("Jack");
return payload1;
}
#RequestMapping(value="/sayHello" , method = RequestMethod.GET)
public List<TestPojo> getData(String payload) {
System.out.println("Hello get"+payload);
List<TestPojo> payload1=new ArrayList<TestPojo>();
TestPojo tp = new TestPojo();
tp.setStudentName("Jack");
payload1.add(tp);
return payload1;
}
Here is my bean which i am trying to return :
public class TestPojo {
private String studentName;
private String studentId;
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
}
Please help me where i am doing wrong.
I know it too late but still
Alternate Solution:
you need to enable Spring project as Web MVC as follow:
#Configuration
#EnableWebMvc
#ComponentScan("basePackages = com.test")
public class MiBenefitConfiguration
{
}
This is happening because MappingJackson2HttpMessageConverter is not registered in my App config file as below.
#Configuration
#ComponentScan("basePackages = com.test")
public class MiBenefitConfiguration extends WebMvcConfigurationSupport{
#Bean
public ObjectMapper getObjectMapper() {
return new ObjectMapper();
}
#Bean
public MappingJackson2HttpMessageConverter messageConverter() {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(getObjectMapper());
return converter;
}
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(messageConverter());
addDefaultHttpMessageConverters(converters);
}
}

Resources