Conflict between Swagger2 and jackson-datatype-jsr310 in Spring Boot application - spring-boot

I am creating a REST API using Spring Boot and have issues serialising LocalDateTime when I use Swagger 2.
Without Swagger the JSON output is like this:
{
"id": 1,
...
"creationTimestamp": "2018-08-01T15:39:09.819"
}
And with Swagger it is like this:
{
"id": 1,
...
"creationTimestamp": [
2018,
8,
1,
15,
40,
59,
438000000
]
}
I have added this to the pom file so the dates are serialised correctly:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
This is the configuration of Jackson:
#Configuration
public class JacksonConfiguration {
#Bean
#Primary
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
return objectMapper;
}
}
And this is the configuration of Swagger:
#Configuration
#EnableSwagger2
public class SwaggerConfiguration extends WebMvcConfigurationSupport {
#Bean
public Docket messageApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.xxx.message.controller"))
.build()
.apiInfo(metaData());
}
private ApiInfo metaData() {
return new ApiInfoBuilder()
.title("Message service")
.version("1.0.0")
.build();
}
#Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
It works when I add add like this a deserialiser to the fields of the DTO. However it should work without having to add it.
#JsonFormat(pattern = "dd/MM/yyyy")
#JsonDeserialize(using = LocalDateTimeDeserializer.class)
#JsonSerialize(using = LocalDateTimeSerializer.class)
private LocalDateTime creationTimestamp;
I guess that the problem is that Swagger has its own object mapper that is overriding the other. Any idea of how to solve it?
Thanks in advance

As I see, the problem occurs when SwaggerConfiguration extends WebMvcConfigurationSupport. You can remove this extension if you don't need it.

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("*");
}
}

swagger not detected when i remove #configuration

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}

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.

Swagger doesn't display information about methods - SpringBoot

I have an API in Java SpringBoot and I want to document it in Swagger.
I have done the following (I only include classes that contain some code related to Swagger):
Main class
#EnableSwagger2
public class ProvisioningApiApplication {
public static void main(String[] args) {
if (AuthConfigFactory.getFactory() == null) {
AuthConfigFactory.setFactory(new AuthConfigFactoryImpl());
}
SpringApplication.run(ProvisioningApiApplication.class, args);
}
#Bean
public Docket swaggerSpringMvcPluggin() {
return new Docket(DocumentationType.SWAGGER_2)
.useDefaultResponseMessages(false)
.apiInfo(apiInfo())
.select()
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.build();
}
#Component
#Primary
public class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper() {
setSerializationInclusion(JsonInclude.Include.NON_NULL);
configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
enable(SerializationFeature.INDENT_OUTPUT);
}
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Provisioning API")
.version("0.0.1")
.build();
}
}
Controller
#RestController
#EnableAutoConfiguration
#CrossOrigin
public class RecursoController {
#Autowired
private Configuration configuration;
#Autowired
private TypeSpecService typeSpecService;
#Autowired
private IoTAgentService ioTAgentService;
#Autowired
private OrionService orionService;
#Autowired
private DeviceIdService deviceIdService;
#ApiOperation(value = "Put a device", nickname = "provisionDevice", tags = "Device")
#ApiResponses({
#ApiResponse(code = 200, message = "Ok", response = NewDeviceResponse.class)
})
#RequestMapping(method = RequestMethod.PUT, value = "/devices", consumes = "application/json", produces = "application/json")
public ResponseEntity<NewDeviceResponse> provisionDevice(#RequestBody NewDeviceRequest newDeviceRequest,
#RequestHeader("X-Auth-Token") String oAuthToken) {
// what my method does
}
The documentation results in the following swagger.json file:
{
swagger: "2.0",
info: {
version: "0.0.1",
title: "Provisioning API"
},
host: "localhost:8080",
basePath: "/"
}
As you can see, it only contains the name and the version of API but not the provisionDevice method.
I've tried everything but I can't figure it out what I'm doing bad. What am I missing?
Did you add #Api annotation in your class, where you have your main services?

Not able to get Swagger UI with spring boot

I am following the article at http://raibledesigns.com/rd/entry/documenting_your_spring_api_with.
Everything works fine but not able to integrate Swagger UI.
http://localhost:8080/docs/index.html
results in /error redirection.
I know this is an old question but maybe this will help someone with the similar problem in the future.
I followed similar tutorial to the one you mentioned and I made it work without a problem. I put my own document on how to setup a Swagger with UI in a Spring boot project couple of weeks ago. Maybe it will help you out since it is shorter and more up-to-date.
Add Maven dependencies
Stick these in your pom.xml:
<dependency>
<groupId>com.mangofactory</groupId>
<artifactId>swagger-springmvc</artifactId>
<version>1.0.2</version>
<type>jar</type>
</dependency>
Add Swagger UI
Download the Swagger UI from github. Copy the dist folder into your webapp directory and rename dist to swagger (or any name you like).
Open the index.html file inside the copied directory and change the url in the first javascript function so it points to the /api-docs endpoint:
var url = window.location.search.match(/url=([^&]+)/);
if (url && url.length > 1) {
url = decodeURIComponent(url[1]);
} else {
url = "/project-name/api-docs";
}
Configure Swagger
Create a SwaggerConfig.java class and configure swagger there:
#Configuration
#EnableSwagger
#EnableAutoConfiguration
public class SwaggerConfig {
private SpringSwaggerConfig springSwaggerConfig;
#Autowired
public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {
this.springSwaggerConfig = springSwaggerConfig;
}
#Bean
public SwaggerSpringMvcPlugin customImplementation() {
return new SwaggerSpringMvcPlugin(this.springSwaggerConfig)
// Root level documentation
.apiInfo(new ApiInfo("Swagger-demo JSON API", "This service provides a JSON representation the service API", null, null, null, null))
.useDefaultResponseMessages(false)
// Map the specific URL patterns into Swagger
.includePatterns("/greeting.*");
}
}
Your swagger should be up and running now. Try accessing /project-name/swagger/index.html.
I'm answering this with swagger2 configuration inside a gradle based spring boot application. Following are the configuration required for Swagger2.
Add Gradle Configuartion
Add Gradle dependencies inside build.gradle file
dependencies {
compile("io.springfox:springfox-swagger2:2.0.2")
compile("io.springfox:springfox-swagger-ui:2.0.2")
}
Swagger2 Confugration Class
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket userApi() {
return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any()).build().pathMapping("/")
.directModelSubstitute(LocalDate.class, String.class)
.genericModelSubstitutes(ResponseEntity.class)
.alternateTypeRules(newRule(
typeResolver.resolve(DeferredResult.class,
typeResolver.resolve(ResponseEntity.class, WildcardType.class)),
typeResolver.resolve(WildcardType.class)))
.useDefaultResponseMessages(false)
.globalResponseMessage(RequestMethod.GET,
newArrayList(new ResponseMessageBuilder().code(500).message("500 message")
.responseModel(new ModelRef("Error")).build()))
.securitySchemes(newArrayList(apiKey())).securityContexts(newArrayList(securityContext()))
.apiInfo(apiInfo());
}
#Autowired
private TypeResolver typeResolver;
private ApiKey apiKey() {
return new ApiKey("mykey", "api_key", "header");
}
private SecurityContext securityContext() {
return SecurityContext.builder().securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("/anyPath.*")).build();
}
List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return newArrayList(new SecurityReference("mykey", authorizationScopes));
}
#Bean
SecurityConfiguration security() {
return new SecurityConfiguration("123456", "test-app-realm", "clientapp", "apiKey");
}
#Bean
UiConfiguration uiConfig() {
return new UiConfiguration("validatorUrl");
}
private ApiInfo apiInfo() {
ApiInfo apiInfo = new ApiInfo("DSM API", "API for DSM", "1.0.0", "termsOfServiceUrl",
"nijo#ndimensionz.com", null, null);
return apiInfo;
}
}
Add Swagger UI
Download the Swagger UI from github. Copy the dist folder into your src/main/resources/static directory and rename dist to swagger
HomeController.class
#Api(basePath = "/", value = "/", description = "Home Controller")
#Controller
public class HomeController {
#RequestMapping("/")
public String home() {
return "redirect:swagger-ui.html";
}
}
MyApplication.class
#SpringBootApplication
#ComponentScan(basePackageClasses = SwaggerConfig.class)
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
Configure your spring boot application with dependencies and run to see the API.
the url will be http://localhost:8080/v2/swagger-ui.html
you can also customize this as above answer.
I too face same problem. I was able to see json but not swagger ui after adding dest folder aslo. In initialize class which extends SpringBootServletInitializer I added below method then it was working perfect
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SampleWebStaticApplication.class);
}
please refer link
Here is my working configuration incase it helps anyone else
#Configuration
#EnableSwagger2
#Profile({"!production"})
public class SwaggerConfiguration extends WebMvcConfigurerAdapter {
#Autowired
private ServletContext servletContext;
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.host("localhost")
.directModelSubstitute(LocalDate.class, Date.class)
.pathProvider(new RelativePathProvider(servletContext) {
#Override
public String getApplicationBasePath() {
return "/docs";
}
})
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
Since I am also using Spring security, I also had to add the following to my whitelist:
private String[] swaggerWhiteList = {"/v2/api-docs", "/swagger-resources/configuration/ui", "/swagger-resources", "/swagger-resources/configuration/security", "/swagger-ui.html", "/swagger.json", "/webjars/**"};
Then I could access it using the following url:
http://localhost:8080/docs/swagger-ui.html

Resources