Skip to content

Commit

Permalink
Do not set contextPath for spring-boot (#104)
Browse files Browse the repository at this point in the history
  • Loading branch information
cbornet authored and wing328 committed May 28, 2018
1 parent 1a4e5a4 commit 71b5de3
Show file tree
Hide file tree
Showing 95 changed files with 457 additions and 57 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
package org.openapitools.codegen.languages;

import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
Expand All @@ -41,8 +40,6 @@
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
Expand Down Expand Up @@ -71,7 +68,7 @@ public class SpringCodegen extends AbstractJavaCodegen
public static final String SPRING_BOOT = "spring-boot";
public static final String SPRING_CLOUD_LIBRARY = "spring-cloud";
public static final String IMPLICIT_HEADERS = "implicitHeaders";
public static final String SWAGGER_DOCKET_CONFIG = "swaggerDocketConfig";
public static final String OPENAPI_DOCKET_CONFIG = "swaggerDocketConfig";

protected String title = "OpenAPI Spring";
protected String configPackage = "org.openapitools.configuration";
Expand All @@ -87,7 +84,7 @@ public class SpringCodegen extends AbstractJavaCodegen
protected boolean useTags = false;
protected boolean useBeanValidation = true;
protected boolean implicitHeaders = false;
protected boolean swaggerDocketConfig = false;
protected boolean openapiDocketConfig = false;
protected boolean useOptional = false;

public SpringCodegen() {
Expand Down Expand Up @@ -116,7 +113,7 @@ public SpringCodegen() {
cliOptions.add(CliOption.newBoolean(USE_TAGS, "use tags for creating interface and controller classnames"));
cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations"));
cliOptions.add(CliOption.newBoolean(IMPLICIT_HEADERS, "Use of @ApiImplicitParams for headers."));
cliOptions.add(CliOption.newBoolean(SWAGGER_DOCKET_CONFIG, "Generate Spring Swagger Docket configuration class."));
cliOptions.add(CliOption.newBoolean(OPENAPI_DOCKET_CONFIG, "Generate Spring OpenAPI Docket configuration class."));
cliOptions.add(CliOption.newBoolean(USE_OPTIONAL,
"Use Optional container for optional parameters"));

Expand Down Expand Up @@ -235,8 +232,8 @@ public void processOpts() {
this.setImplicitHeaders(Boolean.valueOf(additionalProperties.get(IMPLICIT_HEADERS).toString()));
}

if (additionalProperties.containsKey(SWAGGER_DOCKET_CONFIG)) {
this.setSwaggerDocketConfig(Boolean.valueOf(additionalProperties.get(SWAGGER_DOCKET_CONFIG).toString()));
if (additionalProperties.containsKey(OPENAPI_DOCKET_CONFIG)) {
this.setOpenapiDocketConfig(Boolean.valueOf(additionalProperties.get(OPENAPI_DOCKET_CONFIG).toString()));
}

typeMapping.put("file", "Resource");
Expand Down Expand Up @@ -283,7 +280,7 @@ public void processOpts() {
supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "RFC3339DateFormat.java"));
supportingFiles.add(new SupportingFile("application.properties",
("src.main.resources").replace(".", java.io.File.separator), "swagger.properties"));
("src.main.resources").replace(".", java.io.File.separator), "openapi.properties"));
}
if (library.equals(SPRING_CLOUD_LIBRARY)) {
supportingFiles.add(new SupportingFile("apiKeyRequestInterceptor.mustache",
Expand All @@ -310,7 +307,7 @@ public void processOpts() {
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "OpenAPIDocumentationConfig.java"));
}
}
} else if (this.swaggerDocketConfig && !library.equals(SPRING_CLOUD_LIBRARY) && !this.reactive) {
} else if (this.openapiDocketConfig && !library.equals(SPRING_CLOUD_LIBRARY) && !this.reactive) {
supportingFiles.add(new SupportingFile("openapiDocumentationConfig.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "OpenAPIDocumentationConfig.java"));
}
Expand Down Expand Up @@ -378,18 +375,10 @@ public void processOpts() {
}

// add lambda for mustache templates
additionalProperties.put("lambdaEscapeDoubleQuote", new Mustache.Lambda() {
@Override
public void execute(Template.Fragment fragment, Writer writer) throws IOException {
writer.write(fragment.execute().replaceAll("\"", Matcher.quoteReplacement("\\\"")));
}
});
additionalProperties.put("lambdaRemoveLineBreak", new Mustache.Lambda() {
@Override
public void execute(Template.Fragment fragment, Writer writer) throws IOException {
writer.write(fragment.execute().replaceAll("\\r|\\n", ""));
}
});
additionalProperties.put("lambdaEscapeDoubleQuote",
(Mustache.Lambda) (fragment, writer) -> writer.write(fragment.execute().replaceAll("\"", Matcher.quoteReplacement("\\\""))));
additionalProperties.put("lambdaRemoveLineBreak",
(Mustache.Lambda) (fragment, writer) -> writer.write(fragment.execute().replaceAll("\\r|\\n", "")));
}

@Override
Expand All @@ -409,11 +398,7 @@ public void addOperationToGroup(String tag, String resourcePath, Operation opera
} else {
co.subresourceOperation = !co.path.isEmpty();
}
List<CodegenOperation> opList = operations.get(basePath);
if (opList == null) {
opList = new ArrayList<CodegenOperation>();
operations.put(basePath, opList);
}
List<CodegenOperation> opList = operations.computeIfAbsent(basePath, k -> new ArrayList<>());
opList.add(co);
co.baseName = basePath;
} else {
Expand Down Expand Up @@ -674,8 +659,8 @@ public void setImplicitHeaders(boolean implicitHeaders) {
this.implicitHeaders = implicitHeaders;
}

public void setSwaggerDocketConfig(boolean swaggerDocketConfig) {
this.swaggerDocketConfig = swaggerDocketConfig;
public void setOpenapiDocketConfig(boolean openapiDocketConfig) {
this.openapiDocketConfig = openapiDocketConfig;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
{{/jdk8}}
import org.springframework.web.bind.annotation.RequestMapping;
{{^jdk8}}
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
{{/jdk8}}
Expand All @@ -39,6 +42,9 @@ import java.util.concurrent.Callable;
{{/jdk8}}
{{>generatedAnnotation}}
@Controller
{{=<% %>=}}
@RequestMapping("${openapi.<%title%>.base-path:<%>defaultBasePath%>}")
<%={{ }}=%>
{{#operations}}
public class {{classname}}Controller implements {{classname}} {
{{#isDelegate}}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
springfox.documentation.swagger.v2.path=/api-docs
server.{{#java8}}servlet.{{/java8}}context-path={{^contextPath}}/{{/contextPath}}{{#contextPath}}{{contextPath}}{{/contextPath}}
server.port={{serverPort}}
spring.jackson.date-format={{basePackage}}.RFC3339DateFormat
spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ The underlying library integrating OpenAPI to SpringBoot is [springfox](https://

Start your server as an simple java application

{{#reactive}}
{{^reactive}}
You can view the api documentation in swagger-ui by pointing to
http://localhost:8080/

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{{contextPath}}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import java.util.List;
@Configuration
@ComponentScan(basePackages = "{{apiPackage}}")
@EnableWebMvc
@PropertySource("classpath:swagger.properties")
@PropertySource("classpath:openapi.properties")
@Import(OpenAPIDocumentationConfig.class)
public class OpenAPIUiConfiguration extends WebMvcConfigurerAdapter {
private static final String[] SERVLET_RESOURCE_LOCATIONS = { "/" };
Expand Down
Original file line number Diff line number Diff line change
@@ -1,19 +1,24 @@
package {{configPackage}};

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.springframework.web.util.UriComponentsBuilder;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.paths.Paths;
import springfox.documentation.spring.web.paths.RelativePathProvider;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
{{#useOptional}}

{{#useOptional}}
import java.util.Optional;
{{/useOptional}}
import javax.servlet.ServletContext;

{{>generatedAnnotation}}
@Configuration
Expand All @@ -33,12 +38,15 @@ public class OpenAPIDocumentationConfig {
}

@Bean
public Docket customImplementation(){
{{=<% %>=}}
public Docket customImplementation(ServletContext servletContext, @Value("${openapi.<%title%>.base-path:<%>defaultBasePath%>}") String basePath) {
<%={{ }}=%>
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("{{apiPackage}}"))
.build()
{{#java8}}
.pathProvider(new BasePathAwareRelativePathProvider(servletContext, basePath))
.directModelSubstitute(java.time.LocalDate.class, java.sql.Date.class)
.directModelSubstitute(java.time.OffsetDateTime.class, java.util.Date.class)
{{/java8}}
Expand All @@ -56,4 +64,25 @@ public class OpenAPIDocumentationConfig {
.apiInfo(apiInfo());
}

class BasePathAwareRelativePathProvider extends RelativePathProvider {
private String basePath;
public BasePathAwareRelativePathProvider(ServletContext servletContext, String basePath) {
super(servletContext);
this.basePath = basePath;
}

@Override
protected String applicationPath() {
return Paths.removeAdjacentForwardSlashes(UriComponentsBuilder.fromPath(super.applicationPath()).path(basePath).build().toString());
}

@Override
public String getOperationPath(String operationPath) {
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromPath("/");
return Paths.removeAdjacentForwardSlashes(
uriComponentsBuilder.path(operationPath.replaceFirst("^" + basePath, "")).build().toString());
}
}

}
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package org.openapitools.api;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.NativeWebRequest;
import java.util.Optional;

@Controller
@RequestMapping("${openapi.openAPIPetstore.base-path:/}")
public class AnotherFakeApiController implements AnotherFakeApi {

private final NativeWebRequest request;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package org.openapitools.api;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.NativeWebRequest;
import java.util.Optional;

@Controller
@RequestMapping("${openapi.openAPIPetstore.base-path:/}")
public class FakeApiController implements FakeApi {

private final NativeWebRequest request;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package org.openapitools.api;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.NativeWebRequest;
import java.util.Optional;

@Controller
@RequestMapping("${openapi.openAPIPetstore.base-path:/}")
public class FakeClassnameTestApiController implements FakeClassnameTestApi {

private final NativeWebRequest request;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package org.openapitools.api;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.NativeWebRequest;
import java.util.Optional;

@Controller
@RequestMapping("${openapi.openAPIPetstore.base-path:/}")
public class PetApiController implements PetApi {

private final NativeWebRequest request;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package org.openapitools.api;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.NativeWebRequest;
import java.util.Optional;

@Controller
@RequestMapping("${openapi.openAPIPetstore.base-path:/}")
public class StoreApiController implements StoreApi {

private final NativeWebRequest request;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package org.openapitools.api;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.NativeWebRequest;
import java.util.Optional;

@Controller
@RequestMapping("${openapi.openAPIPetstore.base-path:/}")
public class UserApiController implements UserApi {

private final NativeWebRequest request;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
package org.openapitools.configuration;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.springframework.web.util.UriComponentsBuilder;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.paths.Paths;
import springfox.documentation.spring.web.paths.RelativePathProvider;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.servlet.ServletContext;


@Configuration
@EnableSwagger2
Expand All @@ -29,14 +35,36 @@ ApiInfo apiInfo() {
}

@Bean
public Docket customImplementation(){
public Docket customImplementation(ServletContext servletContext, @Value("${openapi.openAPIPetstore.base-path:/}") String basePath) {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("org.openapitools.api"))
.build()
.pathProvider(new BasePathAwareRelativePathProvider(servletContext, basePath))
.directModelSubstitute(java.time.LocalDate.class, java.sql.Date.class)
.directModelSubstitute(java.time.OffsetDateTime.class, java.util.Date.class)
.apiInfo(apiInfo());
}

class BasePathAwareRelativePathProvider extends RelativePathProvider {
private String basePath;

public BasePathAwareRelativePathProvider(ServletContext servletContext, String basePath) {
super(servletContext);
this.basePath = basePath;
}

@Override
protected String applicationPath() {
return Paths.removeAdjacentForwardSlashes(UriComponentsBuilder.fromPath(super.applicationPath()).path(basePath).build().toString());
}

@Override
public String getOperationPath(String operationPath) {
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromPath("/");
return Paths.removeAdjacentForwardSlashes(
uriComponentsBuilder.path(operationPath.replaceFirst("^" + basePath, "")).build().toString());
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
@Configuration
@ComponentScan(basePackages = "org.openapitools.api")
@EnableWebMvc
@PropertySource("classpath:swagger.properties")
@PropertySource("classpath:openapi.properties")
@Import(OpenAPIDocumentationConfig.class)
public class OpenAPIUiConfiguration extends WebMvcConfigurerAdapter {
private static final String[] SERVLET_RESOURCE_LOCATIONS = { "/" };
Expand Down
Loading

0 comments on commit 71b5de3

Please sign in to comment.