Skip to content

Commit 9e1c9b4

Browse files
issue 444 - [Spring] process option useOas2 in spring templates as done in java ones
1 parent 52f95a9 commit 9e1c9b4

20 files changed

+172
-34
lines changed

src/main/java/io/swagger/codegen/v3/generators/java/SpringCodegen.java

Lines changed: 36 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -151,9 +151,6 @@ public String getHelp() {
151151

152152
@Override
153153
public void processOpts() {
154-
setUseOas2(true);
155-
additionalProperties.put(CodegenConstants.USE_OAS2, true);
156-
157154
// Process java8 option before common java ones to change the default dateLibrary to java8.
158155
if (additionalProperties.containsKey(JAVA8_MODE)) {
159156
this.setJava8(Boolean.valueOf(additionalProperties.get(JAVA8_MODE).toString()));
@@ -296,7 +293,7 @@ public void processOpts() {
296293

297294
if (!this.interfaceOnly) {
298295

299-
if (library.equals(DEFAULT_LIBRARY)) {
296+
if (isDefaultLibrary()) {
300297
apiTestTemplateFiles.clear();
301298
supportingFiles.add(new SupportingFile("homeController.mustache",
302299
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "HomeController.java"));
@@ -307,7 +304,8 @@ public void processOpts() {
307304
supportingFiles.add(new SupportingFile("application.mustache",
308305
("src.main.resources").replace(".", java.io.File.separator), "application.properties"));
309306
}
310-
if (library.equals(SPRING_MVC_LIBRARY)) {
307+
if (isSpringMvcLibrary()) {
308+
forceOas2();
311309
supportingFiles.add(new SupportingFile("webApplication.mustache",
312310
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "WebApplication.java"));
313311
supportingFiles.add(new SupportingFile("webMvcConfiguration.mustache",
@@ -319,7 +317,8 @@ public void processOpts() {
319317
supportingFiles.add(new SupportingFile("application.properties",
320318
("src.main.resources").replace(".", java.io.File.separator), "swagger.properties"));
321319
}
322-
if (library.equals(SPRING_CLOUD_LIBRARY)) {
320+
if (isSpringCloudLibrary()) {
321+
forceOas2();
323322
supportingFiles.add(new SupportingFile("apiKeyRequestInterceptor.mustache",
324323
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "ApiKeyRequestInterceptor.java"));
325324
supportingFiles.add(new SupportingFile("clientConfiguration.mustache",
@@ -355,7 +354,7 @@ public void processOpts() {
355354
supportingFiles.add(new SupportingFile("swaggerDocumentationConfig.mustache",
356355
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerDocumentationConfig.java"));
357356
}
358-
} else if ( this.swaggerDocketConfig && !library.equals(SPRING_CLOUD_LIBRARY)) {
357+
} else if ( this.swaggerDocketConfig && !isSpringCloudLibrary()) {
359358
supportingFiles.add(new SupportingFile("swaggerDocumentationConfig.mustache",
360359
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerDocumentationConfig.java"));
361360
}
@@ -366,7 +365,7 @@ public void processOpts() {
366365
if ("threetenbp".equals(dateLibrary)) {
367366
supportingFiles.add(new SupportingFile("customInstantDeserializer.mustache",
368367
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "CustomInstantDeserializer.java"));
369-
if (library.equals(DEFAULT_LIBRARY) || library.equals(SPRING_CLOUD_LIBRARY)) {
368+
if (isDefaultLibrary() || isSpringCloudLibrary()) {
370369
supportingFiles.add(new SupportingFile("jacksonConfiguration.mustache",
371370
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "JacksonConfiguration.java"));
372371
}
@@ -441,7 +440,7 @@ public void execute(Template.Fragment fragment, Writer writer) throws IOExceptio
441440

442441
@Override
443442
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
444-
if((library.equals(DEFAULT_LIBRARY) || library.equals(SPRING_MVC_LIBRARY)) && !useTags) {
443+
if((isDefaultLibrary() || isSpringMvcLibrary()) && !useTags) {
445444
String basePath = resourcePath;
446445
if (basePath.startsWith("/")) {
447446
basePath = basePath.substring(1);
@@ -470,7 +469,7 @@ public void addOperationToGroup(String tag, String resourcePath, Operation opera
470469

471470
@Override
472471
public String getArgumentsLocation() {
473-
return null;
472+
return "/arguments/spring.yaml";
474473
}
475474

476475
@Override
@@ -544,6 +543,10 @@ public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
544543
if ("0".equals(resp.code)) {
545544
resp.code = "200";
546545
}
546+
if (resp.baseType == null) {
547+
// set vendorExtensions.x-java-is-response-void to true as baseType is set to "Void"
548+
resp.vendorExtensions.put("x-java-is-response-void", true);
549+
}
547550
doDataTypeAssignment(resp.dataType, new DataTypeAssigner() {
548551
@Override
549552
public void setReturnType(final String returnType) {
@@ -671,9 +674,29 @@ private void removeHeadersFromContents(List<CodegenContent> contents) {
671674
}
672675
}
673676

677+
/**
678+
* Forces Oas2 specification, use it when Oas3 is not supported.
679+
*/
680+
private void forceOas2() {
681+
setUseOas2(true);
682+
additionalProperties.put(CodegenConstants.USE_OAS2, true);
683+
}
684+
685+
private boolean isSpringCloudLibrary() {
686+
return library.equals(SPRING_CLOUD_LIBRARY);
687+
}
688+
689+
private boolean isSpringMvcLibrary() {
690+
return library.equals(SPRING_MVC_LIBRARY);
691+
}
692+
693+
private boolean isDefaultLibrary() {
694+
return library.equals(DEFAULT_LIBRARY);
695+
}
696+
674697
@Override
675698
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
676-
if(library.equals(SPRING_CLOUD_LIBRARY)) {
699+
if (isSpringCloudLibrary()) {
677700
List<CodegenSecurity> authMethods = (List<CodegenSecurity>) objs.get("authMethods");
678701
if (authMethods != null) {
679702
for (CodegenSecurity authMethod : authMethods) {
@@ -695,10 +718,10 @@ public String toApiName(String name) {
695718

696719
@Override
697720
public String toApiTestFilename(String name) {
698-
if(library.equals(SPRING_MVC_LIBRARY)) {
721+
if (isSpringMvcLibrary()) {
699722
return toApiName(name) + "ControllerIT";
700723
}
701-
if(library.equals(SPRING_CLOUD_LIBRARY)) {
724+
if (isSpringCloudLibrary()) {
702725
return toApiName(name) + "Test";
703726
}
704727
return toApiName(name) + "ControllerIntegrationTest";
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
arguments:
2+
- option: "--use-oas2"
3+
description: "use OpenAPI v2.0 (Swagger 1.5.x) annotations (by default, OpenAPI v3.0 is used)."
4+
type: "boolean"
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{{#useOas2}}{{#allowableValues}}, allowableValues = "{{#values}}{{{.}}}{{^@last}}, {{/@last}}{{#@last}}{{/@last}}{{/values}}"{{/allowableValues}}{{#defaultValue}}, defaultValue = "{{{defaultValue}}}"{{/defaultValue}}{{/useOas2}}{{^useOas2}}, schema=@Schema({{#allowableValues}}allowableValues={ {{#values}}"{{{.}}}"{{^@last}}, {{/@last}}{{/values}}{{^values}}{{/values}} }{{#min}}, minimum="{{.}}"{{/min}}{{#max}}, maximum="{{.}}"{{/max}}{{/allowableValues}}{{#defaultValue}}{{#allowableValues}}, {{/allowableValues}}defaultValue="{{{defaultValue}}}"{{/defaultValue}}){{/useOas2}}

src/main/resources/handlebars/JavaSpring/api.mustache

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,19 @@ package {{package}};
1010
{{#jdk8-no-delegate}}
1111
import com.fasterxml.jackson.databind.ObjectMapper;
1212
{{/jdk8-no-delegate}}
13+
{{#useOas2}}
1314
import io.swagger.annotations.*;
15+
{{/useOas2}}
16+
{{^useOas2}}
17+
import io.swagger.v3.oas.annotations.Operation;
18+
import io.swagger.v3.oas.annotations.Parameter;
19+
import io.swagger.v3.oas.annotations.responses.ApiResponses;
20+
import io.swagger.v3.oas.annotations.responses.ApiResponse;
21+
import io.swagger.v3.oas.annotations.media.ArraySchema;
22+
import io.swagger.v3.oas.annotations.media.Content;
23+
import io.swagger.v3.oas.annotations.media.Schema;
24+
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
25+
{{/useOas2}}
1426
{{#jdk8-no-delegate}}
1527
import org.slf4j.Logger;
1628
import org.slf4j.LoggerFactory;
@@ -53,8 +65,11 @@ import java.util.Optional;
5365
{{#async}}
5466
import java.util.concurrent.{{^jdk8}}Callable{{/jdk8}}{{#jdk8}}CompletableFuture{{/jdk8}};
5567
{{/async}}
68+
5669
{{>generatedAnnotation}}
57-
@Api(value = "{{{baseName}}}", description = "the {{{baseName}}} API")
70+
{{#useOas2}}
71+
@Api(value = "{{{baseName}}}", description = "the {{{baseName}}} API")
72+
{{/useOas2}}
5873
{{#operations}}
5974
public interface {{classname}} {
6075
{{#jdk8}}
@@ -81,6 +96,7 @@ public interface {{classname}} {
8196
{{#operation}}
8297
{{#contents}}
8398

99+
{{#useOas2}}
84100
@ApiOperation(value = "{{{summary}}}", nickname = "{{{operationId}}}", notes = "{{{notes}}}"{{#returnBaseType}}, response = {{{returnBaseType}}}.class{{/returnBaseType}}{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}{{#hasAuthMethods}}, authorizations = {
85101
{{#authMethods}}@Authorization(value = "{{name}}"{{#isOAuth}}, scopes = { {{#each scopes}}
86102
@AuthorizationScope(scope = "{{@key}}", description = "{{this}}"){{^@last}},{{/@last}}{{/each}}
@@ -96,13 +112,22 @@ public interface {{classname}} {
96112
{{/headerParams}}
97113
})
98114
{{/implicitHeaders}}
115+
{{/useOas2}}
116+
{{^useOas2}}
117+
@Operation(summary = "{{{summary}}}", description = "{{{notes}}}"{{#hasAuthMethods}}, security = {
118+
{{#authMethods}}@SecurityRequirement(name = "{{name}}"{{#isOAuth}}, scopes = { {{#each scopes}}"{{@key}}"{{^@last}}, {{/@last}}{{/each}} }{{/isOAuth}}){{#hasMore}},
119+
{{/hasMore}}{{/authMethods}}
120+
}{{/hasAuthMethods}}, tags={ {{#vendorExtensions.x-tags}}"{{tag}}"{{#hasMore}}, {{/hasMore}}{{/vendorExtensions.x-tags}} })
121+
@ApiResponses(value = { {{#responses}}
122+
@ApiResponse(responseCode = "{{{code}}}", description = "{{{message}}}"{{^vendorExtensions.x-java-is-response-void}}, content = @Content({{^containerType}}schema = @Schema(implementation = {{{baseType}}}.class)){{/containerType}}{{#containerType}}array = @ArraySchema(schema = @Schema(implementation = {{{baseType}}}.class))){{/containerType}}{{/vendorExtensions.x-java-is-response-void}}){{#hasMore}},{{/hasMore}}{{/responses}} })
123+
{{/useOas2}}
99124
@RequestMapping(value = "{{{path}}}",{{#singleContentTypes}}{{#hasProduces}}
100125
produces = "{{{vendorExtensions.x-accepts}}}", {{/hasProduces}}{{#hasConsumes}}
101126
consumes = "{{{vendorExtensions.x-contentType}}}",{{/hasConsumes}}{{/singleContentTypes}}{{^singleContentTypes}}{{#hasProduces}}
102127
produces = { {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }, {{/hasProduces}}{{#hasConsumes}}
103-
consumes = { {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} },{{/hasConsumes}}{{/singleContentTypes}}
128+
consumes = { {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }, {{/hasConsumes}}{{/singleContentTypes}}
104129
method = RequestMethod.{{httpMethod}})
105-
{{#defaultInterfaces}}default {{/defaultInterfaces}}{{#responseWrapper}}{{.}}<{{/responseWrapper}}ResponseEntity<{{>returnTypes}}>{{#responseWrapper}}>{{/responseWrapper}} {{#delegate-method}}_{{/delegate-method}}{{operationId}}({{#parameters}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>cookieParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},{{/hasMore}}{{/parameters}}){{^defaultInterfaces}}{{#throwsException}} throws Exception{{/throwsException}};{{/defaultInterfaces}}{{#defaultInterfaces}}{{#throwsException}} throws Exception{{/throwsException}} {
130+
{{#defaultInterfaces}}default {{/defaultInterfaces}}{{#responseWrapper}}{{.}}<{{/responseWrapper}}ResponseEntity<{{>returnTypes}}>{{#responseWrapper}}>{{/responseWrapper}} {{#delegate-method}}_{{/delegate-method}}{{operationId}}({{#parameters}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>cookieParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/parameters}}){{^defaultInterfaces}}{{#throwsException}} throws Exception{{/throwsException}};{{/defaultInterfaces}}{{#defaultInterfaces}}{{#throwsException}} throws Exception{{/throwsException}} {
106131
{{#delegate-method}}
107132
return {{operationId}}({{#parameters}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/parameters}});
108133
}

src/main/resources/handlebars/JavaSpring/apiController.mustache

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,19 @@ package {{package}};
88
import com.fasterxml.jackson.databind.ObjectMapper;
99
{{/isDelegate}}
1010
{{#fullController}}
11+
{{#useOas2}}
1112
import io.swagger.annotations.*;
13+
{{/useOas2}}
14+
{{^useOas2}}
15+
import io.swagger.v3.oas.annotations.Operation;
16+
import io.swagger.v3.oas.annotations.Parameter;
17+
import io.swagger.v3.oas.annotations.responses.ApiResponses;
18+
import io.swagger.v3.oas.annotations.responses.ApiResponse;
19+
import io.swagger.v3.oas.annotations.media.ArraySchema;
20+
import io.swagger.v3.oas.annotations.media.Content;
21+
import io.swagger.v3.oas.annotations.media.Schema;
22+
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
23+
{{/useOas2}}
1224
import org.slf4j.Logger;
1325
import org.slf4j.LoggerFactory;
1426
import org.springframework.http.HttpStatus;
@@ -21,6 +33,9 @@ import org.springframework.web.bind.annotation.RequestBody;
2133
import org.springframework.web.bind.annotation.RequestHeader;
2234
import org.springframework.web.bind.annotation.RequestParam;
2335
import org.springframework.web.bind.annotation.RequestPart;
36+
{{^useOas2}}
37+
import org.springframework.web.bind.annotation.RestController;
38+
{{/useOas2}}
2439
import org.springframework.web.multipart.MultipartFile;
2540

2641
{{#useBeanValidation}}
@@ -49,8 +64,14 @@ import java.util.Map;
4964
import java.util.concurrent.Callable;
5065
{{/async}}
5166
{{/fullController}}
67+
5268
{{>generatedAnnotation}}
69+
{{#useOas2}}
5370
@Controller
71+
{{/useOas2}}
72+
{{^useOas2}}
73+
@RestController
74+
{{/useOas2}}
5475
{{#operations}}
5576
public class {{classname}}Controller implements {{classname}} {
5677
@@ -100,7 +121,7 @@ public class {{classname}}Controller implements {{classname}} {
100121
{{#fullController}}
101122
{{#operation}}
102123
{{#contents}}
103-
public {{#async}}Callable<{{/async}}ResponseEntity<{{>returnTypes}}>{{#async}}>{{/async}} {{operationId}}({{#parameters}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},{{/hasMore}}{{/parameters}}) {
124+
public {{#async}}Callable<{{/async}}ResponseEntity<{{>returnTypes}}>{{#async}}>{{/async}} {{operationId}}({{#parameters}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/parameters}}) {
104125
{{^isDelegate}}
105126
{{^async}}
106127
String accept = request.getHeader("Accept");

src/main/resources/handlebars/JavaSpring/apiDelegate.mustache

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,19 @@ package {{package}};
55
{{#jdk8}}
66
import com.fasterxml.jackson.databind.ObjectMapper;
77
{{/jdk8}}
8+
{{#useOas2}}
89
import io.swagger.annotations.*;
10+
{{/useOas2}}
11+
{{^useOas2}}
12+
import io.swagger.v3.oas.annotations.Operation;
13+
import io.swagger.v3.oas.annotations.Parameter;
14+
import io.swagger.v3.oas.annotations.responses.ApiResponses;
15+
import io.swagger.v3.oas.annotations.responses.ApiResponse;
16+
import io.swagger.v3.oas.annotations.media.ArraySchema;
17+
import io.swagger.v3.oas.annotations.media.Content;
18+
import io.swagger.v3.oas.annotations.media.Schema;
19+
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
20+
{{/useOas2}}
921
{{#jdk8}}
1022
import org.slf4j.Logger;
1123
import org.slf4j.LoggerFactory;

src/main/resources/handlebars/JavaSpring/apiException.mustache

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
package {{apiPackage}};
22

33
{{>generatedAnnotation}}
4-
public class ApiException extends Exception{
4+
public class ApiException extends Exception {
55
private int code;
66
public ApiException (int code, String msg) {
77
super(msg);
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
1+
{{#useOas2}}
12
springfox.documentation.swagger.v2.path=/api-docs
23
server.contextPath={{^contextPath}}/{{/contextPath}}{{#contextPath}}{{contextPath}}{{/contextPath}}
4+
{{/useOas2}}
35
server.port={{serverPort}}
46
spring.jackson.date-format={{basePackage}}.RFC3339DateFormat
57
spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
{{#isBodyParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{^isContainer}}{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{/isContainer}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{#useBeanValidation}}@Valid{{/useBeanValidation}} @RequestBody {{{dataType}}} {{paramName}}{{/isBodyParam}}
1+
{{#isBodyParam}}{{#useOas2}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{^isContainer}}{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{/isContainer}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}){{/useOas2}}{{^useOas2}}@Parameter(description = "{{{description}}}" {{#required}},required=true{{/required}}{{>allowableValuesAndDefaultValue}}){{/useOas2}}{{#useBeanValidation}}@Valid{{/useBeanValidation}} @RequestBody {{{dataType}}} {{paramName}}{{/isBodyParam}}
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
{{#isCookieParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}}{{#allowableValues}}, allowableValues="{{#values}}{{{.}}}{{^@last}}, {{/@last}}{{#@last}}{{/@last}}{{/values}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @CookieValue(value="{{baseName}}", required={{#required}}true{{/required}}{{^required}}false{{/required}}) {{>optionalDataType}} {{paramName}}{{/isCookieParam}}
1+
{{#isCookieParam}}{{#useOas2}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}}{{>allowableValuesAndDefaultValue}}){{/useOas2}}{{^useOas2}}@Parameter(description = "{{{description}}}" {{#required}},required=true{{/required}}{{>allowableValuesAndDefaultValue}}){{/useOas2}}@CookieValue(value="{{baseName}}", required={{#required}}true{{/required}}{{^required}}false{{/required}}) {{>optionalDataType}} {{paramName}}{{/isCookieParam}}

0 commit comments

Comments
 (0)