Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/generators/kotlin-spring.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |null|
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |null|
|sourceFolder|source folder for generated code| |src/main/kotlin|
|springApiVersion|Default value for the 'version' attribute in @RequestMapping (spring-boot library, Spring Framework 7+). Override per operation with x-spring-api-version; an empty extension suppresses the default. Use useSpringBoot4=true for generated applications and configure a version resolver in the application. This option does not configure Spring's runtime default version.| |null|
|substituteGenericPagedModel|Detect schemas that represent paginated responses (an object with a 'content' array property and a 'page' pagination-metadata property) and replace their generated references with PagedModel<T>. By default this uses a generated type in the config package (default 'org.openapitools.configuration'), but `importMappings.PagedModel` can override it to a custom/FQCN-mapped type. The detected page schemas and the pagination metadata schema are suppressed from code generation.| |false|
|suspendFunctions|Whether to generate suspend functions for API operations. Useful for Spring MVC with Kotlin coroutines without requiring the full reactive stack.| |false|
|title|server title name or client service name| |OpenAPI Kotlin Spring|
Expand Down Expand Up @@ -107,6 +108,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|x-kotlin-implements|Ability to specify interfaces that model must implement|MODEL|empty array
|x-kotlin-implements-fields|Specify attributes that are implemented by the interface(s) added via `x-kotlin-implements`|MODEL|empty array
|x-spring-paginated|Add `org.springframework.data.domain.Pageable` to controller method. Can be used to handle `page`, `size` and `sort` query parameters. If these query parameters are also specified in the operation spec, they will be removed from the controller method as their values can be obtained from the `Pageable` object. Applies when `library=spring-boot` or `library=spring-cloud`; ignored for other (client) libraries.|OPERATION|false
|x-spring-api-version|Value for 'version' attribute in @RequestMapping (for Spring 7 and above).|OPERATION|null
|x-jackson-json-include-policy|Manually override the resolved Jackson `@JsonInclude` policy for this property. Must be one of `ALWAYS`, `NON_NULL`, `NON_ABSENT`, `NON_EMPTY`, `NON_DEFAULT`, `USE_DEFAULTS`, `CUSTOM`, or `NONE` to emit no annotation. Always wins over the automatic required/nullable matrix and the `optionalNonNullPropertyJsonInclude` option.|FIELD|resolved automatically per the required/nullable matrix
|x-jackson-json-setter-nulls|Manually override the resolved Jackson `@JsonSetter(nulls = ...)` deserialization null-handling for this property. Must be one of `SKIP` (ignore an explicit JSON null, keeping the default), `FAIL` (reject an explicit JSON null), or `NONE` to emit no annotation. Always wins over the automatic `openApiNullable` default and the `optionalNonNullPropertyJsonSetterNulls` option, and is honored regardless of `generateJsonSetterNullsAnnotations` or whether the property is required/nullable.|FIELD|resolved automatically per the openApiNullable default

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ public class KotlinSpringServerCodegen extends AbstractKotlinCodegen

public static final String USE_SPRING_BOOT3 = "useSpringBoot3";
public static final String USE_SPRING_BOOT4 = "useSpringBoot4";
public static final String SPRING_API_VERSION = "springApiVersion";
public static final String USE_SPRING_BUILT_IN_VALIDATION = "useSpringBuiltInValidation";
public static final String INCLUDE_HTTP_REQUEST_CONTEXT = "includeHttpRequestContext";
public static final String USE_FLOW_FOR_ARRAY_RETURN_TYPE = "useFlowForArrayReturnType";
Expand Down Expand Up @@ -312,6 +313,11 @@ public KotlinSpringServerCodegen() {
addOption(CONFIG_PACKAGE, "configuration package for generated code", this.getConfigPackage());
addOption(BASE_PACKAGE, "base package (invokerPackage) for generated code", basePackage);
addOption(SERVER_PORT, "configuration the port in which the sever is to run on", serverPort);
cliOptions.add(CliOption.newString(SPRING_API_VERSION,
"Default value for the 'version' attribute in @RequestMapping (spring-boot library, Spring Framework 7+). "
+ "Override per operation with x-spring-api-version; an empty extension suppresses the default. "
+ "Use useSpringBoot4=true for generated applications and configure a version resolver in the application. "
+ "This option does not configure Spring's runtime default version."));
addOption(CodegenConstants.MODEL_PACKAGE, "model package for generated code", modelPackage);
addOption(CodegenConstants.API_PACKAGE, "api package for generated code", apiPackage);
addSwitch(EXCEPTION_HANDLER, "generate default global exception handlers (not compatible with reactive. enabling reactive will disable exceptionHandler )", exceptionHandler);
Expand Down Expand Up @@ -975,6 +981,7 @@ public void processOpts() {
}
writePropertyBack(USE_SPRING_BOOT3, isUseSpringBoot3());
writePropertyBack(USE_SPRING_BOOT4, isUseSpringBoot4());
additionalProperties.put("springBootLibrary", SPRING_BOOT.equals(library));

modelTemplateFiles.put("model.mustache", ".kt");

Expand Down Expand Up @@ -2169,7 +2176,11 @@ public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List<Mo
OperationMap operations = objs.getOperations();
if (operations != null) {
List<CodegenOperation> ops = operations.getOperation();
Object apiVersion = additionalProperties.get(SPRING_API_VERSION);
ops.forEach(operation -> {
if (SPRING_BOOT.equals(library) && apiVersion != null) {
operation.vendorExtensions.putIfAbsent(VendorExtension.X_SPRING_API_VERSION.getName(), apiVersion);
}
List<CodegenResponse> responses = operation.responses;
if (responses != null) {
responses.forEach(resp -> {
Expand Down Expand Up @@ -2463,6 +2474,7 @@ public List<VendorExtension> getSupportedVendorExtensions() {
extensions.add(VendorExtension.X_KOTLIN_IMPLEMENTS);
extensions.add(VendorExtension.X_KOTLIN_IMPLEMENTS_FIELDS);
extensions.add(VendorExtension.X_SPRING_PAGINATED);
extensions.add(VendorExtension.X_SPRING_API_VERSION);
extensions.add(VendorExtension.X_JACKSON_JSON_INCLUDE_POLICY);
extensions.add(VendorExtension.X_JACKSON_JSON_SETTER_NULLS);
return extensions;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,8 @@ class {{classname}}Controller({{#serviceInterface}}@Autowired(required = true) v
produces = [{{/-first}}"{{#lambdaEscapeInNormalString}}{{{.}}}{{/lambdaEscapeInNormalString}}"{{^-last}}, {{/-last}}{{#-last}}]{{/-last}}{{/vendorExtensions.x-accepts}}{{^vendorExtensions.x-accepts}}{{#hasProduces}},
produces = [{{#produces}}"{{#lambdaEscapeInNormalString}}{{{rawMediaType}}}{{/lambdaEscapeInNormalString}}"{{^-last}}, {{/-last}}{{/produces}}]{{/hasProduces}}{{/vendorExtensions.x-accepts}}{{#vendorExtensions.x-content-type}},
consumes = ["{{#lambdaEscapeInNormalString}}{{{vendorExtensions.x-content-type}}}{{/lambdaEscapeInNormalString}}"]{{/vendorExtensions.x-content-type}}{{^vendorExtensions.x-content-type}}{{#hasConsumes}},
consumes = [{{#consumes}}"{{#lambdaEscapeInNormalString}}{{{rawMediaType}}}{{/lambdaEscapeInNormalString}}"{{^-last}}, {{/-last}}{{/consumes}}]{{/hasConsumes}}{{/vendorExtensions.x-content-type}}
consumes = [{{#consumes}}"{{#lambdaEscapeInNormalString}}{{{rawMediaType}}}{{/lambdaEscapeInNormalString}}"{{^-last}}, {{/-last}}{{/consumes}}]{{/hasConsumes}}{{/vendorExtensions.x-content-type}}{{#springBootLibrary}}{{#vendorExtensions.x-spring-api-version}}{{^empty}},
version = "{{#lambdaEscapeInNormalString}}{{{vendorExtensions.x-spring-api-version}}}{{/lambdaEscapeInNormalString}}"{{/empty}}{{/vendorExtensions.x-spring-api-version}}{{/springBootLibrary}}
)
{{#suspendFunctions}}suspend {{/suspendFunctions}}{{^suspendFunctions}}{{#reactive}}{{^isArray}}suspend {{/isArray}}{{#isArray}}{{#vendorExtensions.x-reactive-array-string-return}}suspend {{/vendorExtensions.x-reactive-array-string-return}}{{^vendorExtensions.x-reactive-array-string-return}}{{^useFlowForArrayReturnType}}suspend {{/useFlowForArrayReturnType}}{{/vendorExtensions.x-reactive-array-string-return}}{{/isArray}}{{/reactive}}{{/suspendFunctions}}fun {{operationId}}({{#allParams}}
{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>cookieParams}}{{>bodyParams}}{{>formParams}}{{^-last}},{{/-last}}{{/allParams}}{{#includeHttpRequestContext}}{{#hasParams}},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,8 @@ interface {{classname}} {
produces = [{{/-first}}"{{#lambdaEscapeInNormalString}}{{{.}}}{{/lambdaEscapeInNormalString}}"{{^-last}}, {{/-last}}{{#-last}}]{{/-last}}{{/vendorExtensions.x-accepts}}{{^vendorExtensions.x-accepts}}{{#hasProduces}},
produces = [{{#produces}}"{{#lambdaEscapeInNormalString}}{{{rawMediaType}}}{{/lambdaEscapeInNormalString}}"{{^-last}}, {{/-last}}{{/produces}}]{{/hasProduces}}{{/vendorExtensions.x-accepts}}{{#vendorExtensions.x-content-type}},
consumes = ["{{#lambdaEscapeInNormalString}}{{{vendorExtensions.x-content-type}}}{{/lambdaEscapeInNormalString}}"]{{/vendorExtensions.x-content-type}}{{^vendorExtensions.x-content-type}}{{#hasConsumes}},
consumes = [{{#consumes}}"{{#lambdaEscapeInNormalString}}{{{rawMediaType}}}{{/lambdaEscapeInNormalString}}"{{^-last}}, {{/-last}}{{/consumes}}]{{/hasConsumes}}{{/vendorExtensions.x-content-type}}
consumes = [{{#consumes}}"{{#lambdaEscapeInNormalString}}{{{rawMediaType}}}{{/lambdaEscapeInNormalString}}"{{^-last}}, {{/-last}}{{/consumes}}]{{/hasConsumes}}{{/vendorExtensions.x-content-type}}{{#springBootLibrary}}{{#vendorExtensions.x-spring-api-version}}{{^empty}},
version = "{{#lambdaEscapeInNormalString}}{{{vendorExtensions.x-spring-api-version}}}{{/lambdaEscapeInNormalString}}"{{/empty}}{{/vendorExtensions.x-spring-api-version}}{{/springBootLibrary}}
)
{{#suspendFunctions}}suspend {{/suspendFunctions}}{{^suspendFunctions}}{{#reactive}}{{^isArray}}suspend {{/isArray}}{{#isArray}}{{#vendorExtensions.x-reactive-array-string-return}}suspend {{/vendorExtensions.x-reactive-array-string-return}}{{^vendorExtensions.x-reactive-array-string-return}}{{^useFlowForArrayReturnType}}suspend {{/useFlowForArrayReturnType}}{{/vendorExtensions.x-reactive-array-string-return}}{{/isArray}}{{/reactive}}{{/suspendFunctions}}fun {{operationId}}({{#allParams}}
{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>cookieParams}}{{>bodyParams}}{{>formParams}}{{^-last}},{{/-last}}{{/allParams}}{{#includeHttpRequestContext}}{{#hasParams}},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4889,6 +4889,78 @@ public void springBootEscapesQuotedMediaTypes() throws IOException {
"ApiUtil.setExampleResponse(request, \"application/json; profile=\\\"x\\$y\\\"\", ");
}

@DataProvider
public Object[][] apiVersionModes() {
return new Object[][]{
{false, false, false}, {true, false, false}, {false, true, false},
{false, false, true}, {true, false, true}, {false, true, true}
};
}

@Test(dataProvider = "apiVersionModes")
public void testSpringApiVersion(boolean interfaceOnly, boolean delegatePattern, boolean reactive) throws IOException {
for (String defaultVersion : new String[]{null, "1.0", ""}) {
Map<String, Object> properties = new HashMap<>(Map.of(
USE_SPRING_BOOT4, true, USE_TAGS, true,
INTERFACE_ONLY, interfaceOnly, DELEGATE_PATTERN, delegatePattern, REACTIVE, reactive));
if (defaultVersion != null) {
properties.put(SPRING_API_VERSION, defaultVersion);
}
Map<String, File> files = generateFromContract("src/test/resources/3_0/spring/apiVersion.yaml", properties);
File api = files.get(interfaceOnly || delegatePattern ? "TestApi.kt" : "TestApiController.kt");
String defaultMapping = requestMappingForOperation(api, "getVersions");
if (defaultVersion == null || defaultVersion.isEmpty()) {
assertThat(defaultMapping).doesNotContain("version =");
} else {
assertThat(defaultMapping).contains("version = \"1.0\"");
}
assertThat(requestMappingForOperation(api, "getOverrides")).contains("version = \"2+\"");
assertThat(requestMappingForOperation(api, "getNones")).doesNotContain("version =");
if (delegatePattern) {
assertFileNotContains(files.get("TestApiDelegate.kt").toPath(), "@RequestMapping");
}
}
}

@Test(dataProvider = "apiVersionModes")
public void testSpringApiVersionEscapesKotlinStrings(boolean interfaceOnly, boolean delegatePattern, boolean reactive) throws IOException {
String version = "v\"quoted\"\\path$version";
Map<String, File> files = generateFromContract("src/test/resources/3_0/spring/apiVersion.yaml",
new HashMap<>(Map.of(USE_SPRING_BOOT4, true, USE_TAGS, true, SPRING_API_VERSION, version,
INTERFACE_ONLY, interfaceOnly, DELEGATE_PATTERN, delegatePattern, REACTIVE, reactive)));
File api = files.get(interfaceOnly || delegatePattern ? "TestApi.kt" : "TestApiController.kt");
assertThat(requestMappingForOperation(api, "getVersions"))
.contains("version = \"v\\\"quoted\\\"\\\\path\\$version\"");
}

@Test
public void testSpringApiVersionIsNotAppliedToClients() throws IOException {
for (String library : List.of(SPRING_CLOUD_LIBRARY, SPRING_DECLARATIVE_HTTP_INTERFACE_LIBRARY)) {
Map<String, File> files = generateFromContract("src/test/resources/3_0/spring/apiVersion.yaml",
new HashMap<>(Map.of(USE_SPRING_BOOT4, true, USE_TAGS, true, INTERFACE_ONLY, true,
SPRING_API_VERSION, "1.0")), new HashMap<>(), config -> config.setLibrary(library));
assertFileNotContains(files.get("TestApi.kt").toPath(), "version =");
}
}

@Test
public void testSpringApiVersionIsOptInForOlderSpring() throws IOException {
for (boolean springBoot3 : new boolean[]{false, true}) {
Map<String, File> files = generateFromContract("src/test/resources/3_0/petstore.yaml",
new HashMap<>(Map.of(USE_SPRING_BOOT3, springBoot3, USE_TAGS, true, INTERFACE_ONLY, true)));
assertFileNotContains(files.get("PetApi.kt").toPath(), "version =");
}
}

private static String requestMappingForOperation(File api, String operationId) throws IOException {
String content = Files.readString(api.toPath());
int method = content.indexOf("fun " + operationId + "(");
assertThat(method).as("operation %s in %s", operationId, api).isGreaterThanOrEqualTo(0);
int mapping = content.lastIndexOf("@RequestMapping(", method);
assertThat(mapping).as("mapping for %s", operationId).isGreaterThanOrEqualTo(0);
return content.substring(mapping, method);
}

private Map<String, File> generateFromContract(String url) throws IOException {
return generateFromContract(url, new HashMap<>(), new HashMap<>());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,25 @@ paths:
tags:
- Test
operationId: getVersions
responses:
'200':
description: OK
/overrides:
get:
tags:
- Test
operationId: getOverrides
x-spring-api-version: '2+'
responses:
'200':
description: OK
/nones:
get:
tags:
- Test
operationId: getNones
x-spring-api-version: ''
responses:
'200':
description: OK