From 9dc0cb0a5a9843cebdcb2488c59a5d2fd3a9a1a9 Mon Sep 17 00:00:00 2001 From: Jachym Metlicka Date: Fri, 7 Aug 2026 14:08:53 +0200 Subject: [PATCH 1/4] feat(kotlin-spring): implement x-extra-imports support for models and operations --- docs/generators/kotlin-spring.md | 1 + .../openapitools/codegen/VendorExtension.java | 1 + .../languages/KotlinSpringServerCodegen.java | 97 +++++++++++++ .../main/resources/kotlin-spring/api.mustache | 2 + .../kotlin-spring/apiInterface.mustache | 2 + .../spring/KotlinSpringServerCodegenTest.java | 127 ++++++++++++++++++ .../kotlin/kotlin-spring-extra-imports.yaml | 64 +++++++++ 7 files changed, 294 insertions(+) create mode 100644 modules/openapi-generator/src/test/resources/3_0/kotlin/kotlin-spring-extra-imports.yaml diff --git a/docs/generators/kotlin-spring.md b/docs/generators/kotlin-spring.md index f42388d53000..1d98298707cd 100644 --- a/docs/generators/kotlin-spring.md +++ b/docs/generators/kotlin-spring.md @@ -87,6 +87,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |x-discriminator-value|Used with model inheritance to specify value for discriminator that identifies current model|MODEL| |x-field-extra-annotation|Custom annotation(s) to be added to property; accepts a string or list of strings|FIELD, OPERATION_PARAMETER|null |x-operation-extra-annotation|Custom annotation(s) to be added to operation; accepts a string or list of strings|OPERATION|null +|x-extra-imports|Custom import(s) to add to the generated file that declares the annotated model, property, operation, or parameter (e.g. so custom annotations can be referenced by their short name); accepts a string or list of strings. Values are emitted verbatim (Kotlin alias imports supported) and only exact duplicates are removed|MODEL, FIELD, OPERATION, OPERATION_PARAMETER|null |x-pattern-message|Add this property whenever you need to customize the invalidation error message for the regex pattern of a variable|FIELD, OPERATION_PARAMETER|null |x-size-message|Add this property whenever you need to customize the invalidation error message for the size or length of a variable|FIELD, OPERATION_PARAMETER|null |x-minimum-message|Add this property whenever you need to customize the invalidation error message for the minimum value of a variable|FIELD, OPERATION_PARAMETER|null diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/VendorExtension.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/VendorExtension.java index 288ca9d0fb99..92e34e47997e 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/VendorExtension.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/VendorExtension.java @@ -26,6 +26,7 @@ public enum VendorExtension { X_CLASS_EXTRA_ANNOTATION("x-class-extra-annotation", ExtensionLevel.MODEL, "Custom annotation(s) to be added to model; accepts a string or list of strings", null), X_FIELD_EXTRA_ANNOTATION("x-field-extra-annotation", Arrays.asList(ExtensionLevel.FIELD, ExtensionLevel.OPERATION_PARAMETER), "Custom annotation(s) to be added to property; accepts a string or list of strings", null), X_OPERATION_EXTRA_ANNOTATION("x-operation-extra-annotation", ExtensionLevel.OPERATION, "Custom annotation(s) to be added to operation; accepts a string or list of strings", null), + X_EXTRA_IMPORTS("x-extra-imports", Arrays.asList(ExtensionLevel.MODEL, ExtensionLevel.FIELD, ExtensionLevel.OPERATION, ExtensionLevel.OPERATION_PARAMETER), "Custom import(s) to add to the generated file that declares the annotated model, property, operation, or parameter (e.g. so custom annotations can be referenced by their short name); accepts a string or list of strings. Values are emitted verbatim (Kotlin alias imports supported) and only exact duplicates are removed", null), X_VERSION_PARAM("x-version-param", ExtensionLevel.OPERATION_PARAMETER, "Marker property that tells that this parameter would be used for endpoint versioning. Applicable for headers & query params. true/false", null), X_PATTERN_MESSAGE("x-pattern-message", Arrays.asList(ExtensionLevel.FIELD, ExtensionLevel.OPERATION_PARAMETER), "Add this property whenever you need to customize the invalidation error message for the regex pattern of a variable", null), X_SIZE_MESSAGE("x-size-message", Arrays.asList(ExtensionLevel.FIELD, ExtensionLevel.OPERATION_PARAMETER), "Add this property whenever you need to customize the invalidation error message for the size or length of a variable", null), diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinSpringServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinSpringServerCodegen.java index baaa203e60b4..b89b7b41060f 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinSpringServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinSpringServerCodegen.java @@ -1337,6 +1337,77 @@ public void addImportsToOneOfInterface(List> imports) { } } + /** + * Reads the {@code x-extra-imports} vendor extension from the given vendor-extension map and + * appends its values to {@code target}. The extension accepts either a single string or a list + * of strings; parsing is delegated to {@link #getObjectAsStringList(Object)} for consistency with + * how the sibling {@code x-*-extra-annotation} extensions are handled. Values are preserved + * verbatim (Kotlin alias imports are supported); no validation, trimming, or conflict detection is + * performed. Exact-duplicate handling is left to the caller's collection (typically a + * {@link LinkedHashSet} to keep insertion order while removing duplicates). + * + * @param vendorExtensions vendor extensions of a model, property, operation, or parameter (may be {@code null}) + * @param target collection to which extracted import directives are added + */ + private void collectExtraImports(Map vendorExtensions, Collection target) { + if (vendorExtensions == null) { + return; + } + target.addAll(getObjectAsStringList(vendorExtensions.get(VendorExtension.X_EXTRA_IMPORTS.getName()))); + } + + /** + * Appends the given import directives to an {@code imports}-style list (a list of maps each + * holding a single {@code "import"} entry, as rendered by the {@code {{#imports}}} template + * blocks), skipping directives whose exact text already appears in the list. + * + * @param imports existing import list to extend (must be mutable) + * @param extraImports import directives to add, in insertion order + */ + private void appendExtraImports(List> imports, Collection extraImports) { + Set existing = imports.stream() + .map(m -> m.get("import")) + .filter(Objects::nonNull) + .collect(Collectors.toCollection(HashSet::new)); + for (String imp : extraImports) { + if (existing.add(imp)) { + Map item = new HashMap<>(); + item.put("import", imp); + imports.add(item); + } + } + } + + @Override + public ModelsMap postProcessModels(ModelsMap objs) { + objs = super.postProcessModels(objs); + + // Collect x-extra-imports declared on each model and its properties, and add them to the + // model file's import list so custom class/field annotations can be referenced by short name. + // Each ModelsMap corresponds to a single generated model file, so this stays file-scoped. + Set extraImports = new LinkedHashSet<>(); + for (ModelMap mo : objs.getModels()) { + CodegenModel cm = mo.getModel(); + if (cm == null) { + continue; + } + collectExtraImports(cm.vendorExtensions, extraImports); + Stream.of(cm.vars, cm.allVars, cm.requiredVars, cm.optionalVars) + .filter(Objects::nonNull) + .flatMap(List::stream) + .forEach(p -> collectExtraImports(p.vendorExtensions, extraImports)); + } + if (!extraImports.isEmpty()) { + List> imports = objs.getImports(); + if (imports == null) { + imports = new ArrayList<>(); + objs.setImports(imports); + } + appendExtraImports(imports, extraImports); + } + return objs; + } + @Override public Map postProcessAllModels(Map objs) { objs = super.postProcessAllModels(objs); @@ -1689,6 +1760,31 @@ public void setReturnContainer(final String returnContainer) { handleImplicitHeaders(objs); + // Collect x-extra-imports declared on operations and their parameters for this API group. + // Grouping (by tag or by path segment, per useTags) is already reflected in this OperationsMap, + // so the imports are scoped to exactly the API file(s) that render these operations. They are + // exposed under a dedicated key (not the shared "imports" list) so that only templates which + // render the related annotations (api.mustache / apiInterface.mustache) emit them, while + // delegate, controller-wrapper, service and test templates do not. + if (operations != null) { + Set operationExtraImports = new LinkedHashSet<>(); + for (CodegenOperation operation : operations.getOperation()) { + collectExtraImports(operation.vendorExtensions, operationExtraImports); + if (operation.allParams != null) { + operation.allParams.forEach(param -> collectExtraImports(param.vendorExtensions, operationExtraImports)); + } + } + if (!operationExtraImports.isEmpty()) { + List> extraImportList = new ArrayList<>(); + for (String imp : operationExtraImports) { + Map item = new HashMap<>(); + item.put("import", imp); + extraImportList.add(item); + } + objs.put("operationExtraImports", extraImportList); + } + } + return objs; } @@ -1777,6 +1873,7 @@ public List getSupportedVendorExtensions() { extensions.add(VendorExtension.X_DISCRIMINATOR_VALUE); extensions.add(VendorExtension.X_FIELD_EXTRA_ANNOTATION); extensions.add(VendorExtension.X_OPERATION_EXTRA_ANNOTATION); + extensions.add(VendorExtension.X_EXTRA_IMPORTS); extensions.add(VendorExtension.X_PATTERN_MESSAGE); extensions.add(VendorExtension.X_SIZE_MESSAGE); extensions.add(VendorExtension.X_MINIMUM_MESSAGE); diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/api.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/api.mustache index 448cf0c8726e..7dc990aa6b82 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-spring/api.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/api.mustache @@ -2,6 +2,8 @@ package {{package}} {{#imports}}import {{import}} {{/imports}} +{{#operationExtraImports}}import {{{import}}} +{{/operationExtraImports}} {{#swagger2AnnotationLibrary}} import io.swagger.v3.oas.annotations.* import io.swagger.v3.oas.annotations.enums.* diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/apiInterface.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/apiInterface.mustache index 3da7f3319cc3..9ba8802785d7 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-spring/apiInterface.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/apiInterface.mustache @@ -7,6 +7,8 @@ package {{package}} {{#imports}}import {{import}} {{/imports}} +{{#operationExtraImports}}import {{{import}}} +{{/operationExtraImports}} {{#swagger2AnnotationLibrary}} import io.swagger.v3.oas.annotations.* import io.swagger.v3.oas.annotations.enums.* diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/spring/KotlinSpringServerCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/spring/KotlinSpringServerCodegenTest.java index e8d9e69d1468..bccb224f37f5 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/spring/KotlinSpringServerCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/spring/KotlinSpringServerCodegenTest.java @@ -7107,4 +7107,131 @@ public void testIssue24139NullableRefNoJsonSetterNullsFail() throws IOException "nestedNullable ($ref to nullable schema) must not have @JsonSetter(nulls = Nulls.FAIL)" ); } + + private static final String EXTRA_IMPORTS_SPEC = "src/test/resources/3_0/kotlin/kotlin-spring-extra-imports.yaml"; + + private String generateExtraImports(Consumer configure, boolean apisOnly) throws IOException { + File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); + output.deleteOnExit(); + String outputPath = output.getAbsolutePath().replace('\\', '/'); + + KotlinSpringServerCodegen codegen = new KotlinSpringServerCodegen(); + codegen.setOutputDir(output.getAbsolutePath()); + configure.accept(codegen); + + ClientOptInput input = new ClientOptInput() + .openAPI(TestUtils.parseSpec(EXTRA_IMPORTS_SPEC)) + .config(codegen); + DefaultGenerator generator = new DefaultGenerator(); + generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, apisOnly ? "false" : "true"); + generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_TESTS, "false"); + generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_DOCS, "false"); + generator.setGeneratorPropertyDefault(CodegenConstants.APIS, apisOnly ? "true" : "false"); + generator.setGeneratorPropertyDefault(CodegenConstants.API_TESTS, "false"); + generator.setGeneratorPropertyDefault(CodegenConstants.API_DOCS, "false"); + generator.setGeneratorPropertyDefault(CodegenConstants.SUPPORTING_FILES, "false"); + generator.opts(input).generate(); + + return outputPath; + } + + private static long countOccurrences(Path path, String needle) throws IOException { + String content = new String(Files.readAllBytes(path), StandardCharsets.UTF_8); + long count = 0; + int idx = 0; + while ((idx = content.indexOf(needle, idx)) != -1) { + count++; + idx += needle.length(); + } + return count; + } + + @Test(description = "x-extra-imports: model and property imports are added to the model file") + public void extraImportsOnModels() throws IOException { + String outputPath = generateExtraImports(codegen -> { }, false); + Path widget = Paths.get(outputPath + "/src/main/kotlin/org/openapitools/model/Widget.kt"); + + assertFileContains(widget, + "import com.example.model.MyClassAnn", + "import com.example.model.MyFieldAnn", + "import com.example.model.Dup", + "import com.example.other.Foo as Bar", + "@MyClassAnn", + "@MyFieldAnn"); + + // com.example.model.Dup is declared on the class and on a property but must be imported only once. + Assert.assertEquals(countOccurrences(widget, "import com.example.model.Dup"), 1L, + "Duplicate x-extra-imports directive must be emitted only once"); + } + + @Test(description = "x-extra-imports: operation/parameter imports are scoped per tag when useTags=true") + public void extraImportsOnApiWithTags() throws IOException { + String outputPath = generateExtraImports(codegen -> { + codegen.additionalProperties().put(INTERFACE_ONLY, true); + codegen.additionalProperties().put(USE_TAGS, true); + }, true); + + Path accounts = Paths.get(outputPath + "/src/main/kotlin/org/openapitools/api/AccountsApi.kt"); + Path orders = Paths.get(outputPath + "/src/main/kotlin/org/openapitools/api/OrdersApi.kt"); + + // Accounts file: its own operation import, its parameter import, and the multi-tag operation import. + assertFileContains(accounts, + "import com.example.security.Audited", + "import com.example.security.TenantId", + "import com.example.shared.Traced"); + // No leakage from the Orders group. + assertFileNotContains(accounts, "import com.example.security.RateLimited"); + + // Orders file: its own operation import plus the multi-tag operation import. + assertFileContains(orders, + "import com.example.security.RateLimited", + "import com.example.shared.Traced"); + assertFileNotContains(orders, + "import com.example.security.Audited", + "import com.example.security.TenantId"); + } + + @Test(description = "x-extra-imports: operation imports follow first-path-segment groups when useTags=false") + public void extraImportsOnApiWithoutTags() throws IOException { + String outputPath = generateExtraImports(codegen -> { + codegen.additionalProperties().put(INTERFACE_ONLY, true); + codegen.additionalProperties().put(USE_TAGS, false); + }, true); + + Path accounts = Paths.get(outputPath + "/src/main/kotlin/org/openapitools/api/AccountsApi.kt"); + Path orders = Paths.get(outputPath + "/src/main/kotlin/org/openapitools/api/OrdersApi.kt"); + Path shared = Paths.get(outputPath + "/src/main/kotlin/org/openapitools/api/SharedApi.kt"); + + // With path-segment grouping the shared operation is its own group, so Traced does not + // leak into the Accounts/Orders files. + assertFileContains(accounts, + "import com.example.security.Audited", + "import com.example.security.TenantId"); + assertFileNotContains(accounts, + "import com.example.security.RateLimited", + "import com.example.shared.Traced"); + + assertFileContains(orders, "import com.example.security.RateLimited"); + assertFileNotContains(orders, "import com.example.shared.Traced"); + + assertFileContains(shared, "import com.example.shared.Traced"); + } + + @Test(description = "x-extra-imports: only annotation-rendering files get imports (delegate/controller are excluded)") + public void extraImportsDelegateIsolation() throws IOException { + String outputPath = generateExtraImports(codegen -> { + codegen.additionalProperties().put(DELEGATE_PATTERN, true); + codegen.additionalProperties().put(USE_TAGS, true); + }, true); + + Path apiInterface = Paths.get(outputPath + "/src/main/kotlin/org/openapitools/api/AccountsApi.kt"); + Path controller = Paths.get(outputPath + "/src/main/kotlin/org/openapitools/api/AccountsApiController.kt"); + Path delegate = Paths.get(outputPath + "/src/main/kotlin/org/openapitools/api/AccountsApiDelegate.kt"); + + // The interface renders the operation annotation, so it must carry the import. + assertFileContains(apiInterface, "import com.example.security.Audited"); + // The delegate and controller wrapper do not render the annotation and must not carry the import. + assertFileNotContains(controller, "import com.example.security.Audited"); + assertFileNotContains(delegate, "import com.example.security.Audited"); + } } diff --git a/modules/openapi-generator/src/test/resources/3_0/kotlin/kotlin-spring-extra-imports.yaml b/modules/openapi-generator/src/test/resources/3_0/kotlin/kotlin-spring-extra-imports.yaml new file mode 100644 index 000000000000..ff766b2d8579 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/kotlin/kotlin-spring-extra-imports.yaml @@ -0,0 +1,64 @@ +openapi: "3.0.1" +info: + title: kotlin-spring x-extra-imports test + version: "1.0" + +paths: + /accounts/list: + get: + tags: [Accounts] + operationId: listAccounts + x-extra-imports: com.example.security.Audited + x-operation-extra-annotation: "@Audited" + parameters: + - name: tenant + in: query + required: false + schema: + type: string + x-extra-imports: com.example.security.TenantId + x-field-extra-annotation: "@TenantId" + responses: + "200": + description: OK + + /orders/list: + get: + tags: [Orders] + operationId: listOrders + x-extra-imports: + - com.example.security.RateLimited + x-operation-extra-annotation: "@RateLimited" + responses: + "200": + description: OK + + /shared/ping: + get: + tags: [Accounts, Orders] + operationId: sharedPing + x-extra-imports: com.example.shared.Traced + x-operation-extra-annotation: "@Traced" + responses: + "200": + description: OK + +components: + schemas: + Widget: + type: object + x-extra-imports: + - com.example.model.MyClassAnn + - com.example.model.Dup + x-class-extra-annotation: "@MyClassAnn" + properties: + name: + type: string + x-extra-imports: com.example.model.MyFieldAnn + x-field-extra-annotation: "@MyFieldAnn" + tag: + type: string + x-extra-imports: com.example.model.Dup + alias: + type: string + x-extra-imports: "com.example.other.Foo as Bar" From cb624be080ef0c12e1f330527c625c8a2be7ddee Mon Sep 17 00:00:00 2001 From: Jachym Metlicka Date: Fri, 7 Aug 2026 20:43:56 +0200 Subject: [PATCH 2/4] update samples --- .../petstore/java/resttemplate-springBoot4-jackson3/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/client/petstore/java/resttemplate-springBoot4-jackson3/pom.xml b/samples/client/petstore/java/resttemplate-springBoot4-jackson3/pom.xml index b5c5141bdd3d..859141904ec9 100644 --- a/samples/client/petstore/java/resttemplate-springBoot4-jackson3/pom.xml +++ b/samples/client/petstore/java/resttemplate-springBoot4-jackson3/pom.xml @@ -269,7 +269,7 @@ UTF-8 - 7.0.8 + 7.0.5 3.1.5 3.0.0 From b2468dec4396381e5745c6e9437f371799965aa6 Mon Sep 17 00:00:00 2001 From: Jachym Metlicka Date: Fri, 7 Aug 2026 21:10:38 +0200 Subject: [PATCH 3/4] add comment to template --- .../src/main/resources/kotlin-spring/api.mustache | 3 +++ .../src/main/resources/kotlin-spring/apiInterface.mustache | 3 +++ 2 files changed, 6 insertions(+) diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/api.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/api.mustache index 7dc990aa6b82..9ff4eb9308dc 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-spring/api.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/api.mustache @@ -4,6 +4,9 @@ package {{package}} {{/imports}} {{#operationExtraImports}}import {{{import}}} {{/operationExtraImports}} +{{! Dedicated key (not the shared imports list) so these x-extra-imports render only in files that + emit x-operation-extra-annotation. The OperationsMap imports list is shared with apiDelegate, + service, api_test, etc., which don't; keeping them here avoids leaking unused imports there. }} {{#swagger2AnnotationLibrary}} import io.swagger.v3.oas.annotations.* import io.swagger.v3.oas.annotations.enums.* diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/apiInterface.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/apiInterface.mustache index 9ba8802785d7..8059e27f83b6 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-spring/apiInterface.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/apiInterface.mustache @@ -9,6 +9,9 @@ package {{package}} {{/imports}} {{#operationExtraImports}}import {{{import}}} {{/operationExtraImports}} +{{! Dedicated key (not the shared imports list) so these x-extra-imports render only in files that + emit x-operation-extra-annotation. The OperationsMap imports list is shared with apiDelegate, + service, api_test, etc., which don't; keeping them here avoids leaking unused imports there. }} {{#swagger2AnnotationLibrary}} import io.swagger.v3.oas.annotations.* import io.swagger.v3.oas.annotations.enums.* From 916e47e3f6b7354fd9770d6536a79a450214df64 Mon Sep 17 00:00:00 2001 From: Jachym Metlicka Date: Fri, 7 Aug 2026 23:06:04 +0200 Subject: [PATCH 4/4] implement changes from CR feedback --- .../languages/KotlinSpringServerCodegen.java | 16 ++++++++- .../spring/KotlinSpringServerCodegenTest.java | 33 ++++++++++++++++++- .../kotlin/kotlin-spring-extra-imports.yaml | 31 +++++++++++++++++ 3 files changed, 78 insertions(+), 2 deletions(-) diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinSpringServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinSpringServerCodegen.java index b89b7b41060f..d71443a21b57 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinSpringServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinSpringServerCodegen.java @@ -1392,7 +1392,9 @@ public ModelsMap postProcessModels(ModelsMap objs) { continue; } collectExtraImports(cm.vendorExtensions, extraImports); - Stream.of(cm.vars, cm.allVars, cm.requiredVars, cm.optionalVars) + // allVars is the complete property set (own + inherited); vars is included for safety. + // The LinkedHashSet collapses any overlap between the two lists. + Stream.of(cm.vars, cm.allVars) .filter(Objects::nonNull) .flatMap(List::stream) .forEach(p -> collectExtraImports(p.vendorExtensions, extraImports)); @@ -1773,7 +1775,19 @@ public void setReturnContainer(final String returnContainer) { if (operation.allParams != null) { operation.allParams.forEach(param -> collectExtraImports(param.vendorExtensions, operationExtraImports)); } + // Implicit header params are moved out of allParams by handleImplicitHeaders above, + // so scan them separately to avoid dropping their declared imports. + if (operation.implicitHeadersParams != null) { + operation.implicitHeadersParams.forEach(param -> collectExtraImports(param.vendorExtensions, operationExtraImports)); + } } + // Drop any import already present in the shared imports list (e.g. produced from an + // operation's types) so the file keeps the documented once-per-file deduplication. + Set existingImports = objs.getImports().stream() + .map(m -> m.get("import")) + .filter(Objects::nonNull) + .collect(Collectors.toCollection(HashSet::new)); + operationExtraImports.removeAll(existingImports); if (!operationExtraImports.isEmpty()) { List> extraImportList = new ArrayList<>(); for (String imp : operationExtraImports) { diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/spring/KotlinSpringServerCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/spring/KotlinSpringServerCodegenTest.java index 61b227d26583..421e7226a0d8 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/spring/KotlinSpringServerCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/spring/KotlinSpringServerCodegenTest.java @@ -7156,7 +7156,7 @@ public void testIssue24139NullableRefNoJsonSetterNullsFail() throws IOException private String generateExtraImports(Consumer configure, boolean apisOnly) throws IOException { File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); - output.deleteOnExit(); + FileUtils.forceDeleteOnExit(output); String outputPath = output.getAbsolutePath().replace('\\', '/'); KotlinSpringServerCodegen codegen = new KotlinSpringServerCodegen(); @@ -7278,4 +7278,35 @@ public void extraImportsDelegateIsolation() throws IOException { assertFileNotContains(controller, "import com.example.security.Audited"); assertFileNotContains(delegate, "import com.example.security.Audited"); } + + @Test(description = "x-extra-imports: parameter imports on implicit header params are not lost") + public void extraImportsImplicitHeaderParams() throws IOException { + String outputPath = generateExtraImports(codegen -> { + codegen.additionalProperties().put(INTERFACE_ONLY, true); + codegen.additionalProperties().put(USE_TAGS, true); + codegen.additionalProperties().put(KotlinSpringServerCodegen.IMPLICIT_HEADERS, true); + }, true); + + Path audit = Paths.get(outputPath + "/src/main/kotlin/org/openapitools/api/AuditApi.kt"); + + // With implicitHeaders=true the header param is moved out of allParams into + // implicitHeadersParams, but its declared import must still be emitted. + assertFileContains(audit, "import com.example.security.TraceHeader"); + } + + @Test(description = "x-extra-imports: an import already generated from a type is not duplicated") + public void extraImportsDedupAgainstGeneratedImports() throws IOException { + String outputPath = generateExtraImports(codegen -> { + codegen.additionalProperties().put(INTERFACE_ONLY, true); + codegen.additionalProperties().put(USE_TAGS, true); + }, true); + + Path widgets = Paths.get(outputPath + "/src/main/kotlin/org/openapitools/api/WidgetsApi.kt"); + + // getWidget both returns Widget (generating an import) and declares the same value via + // x-extra-imports, so the file must keep the once-per-file deduplication. + assertFileContains(widgets, "import org.openapitools.model.Widget", "@WidgetChecked"); + Assert.assertEquals(countOccurrences(widgets, "import org.openapitools.model.Widget"), 1L, + "Extra import duplicating a generated type import must be emitted only once"); + } } diff --git a/modules/openapi-generator/src/test/resources/3_0/kotlin/kotlin-spring-extra-imports.yaml b/modules/openapi-generator/src/test/resources/3_0/kotlin/kotlin-spring-extra-imports.yaml index ff766b2d8579..65b63034645e 100644 --- a/modules/openapi-generator/src/test/resources/3_0/kotlin/kotlin-spring-extra-imports.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/kotlin/kotlin-spring-extra-imports.yaml @@ -43,6 +43,37 @@ paths: "200": description: OK + /audit/list: + get: + tags: [Audit] + operationId: listAudit + parameters: + - name: X-Trace-Id + in: header + required: false + schema: + type: string + x-extra-imports: com.example.security.TraceHeader + x-field-extra-annotation: "@TraceHeader" + responses: + "200": + description: OK + + /widgets/get: + get: + tags: [Widgets] + operationId: getWidget + x-extra-imports: + - org.openapitools.model.Widget + x-operation-extra-annotation: "@WidgetChecked" + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/Widget' + components: schemas: Widget: