diff --git a/.github/workflows/samples-kotlin-server-jdk17.yaml b/.github/workflows/samples-kotlin-server-jdk17.yaml index 8ecbb33a02f3..df76323362eb 100644 --- a/.github/workflows/samples-kotlin-server-jdk17.yaml +++ b/.github/workflows/samples-kotlin-server-jdk17.yaml @@ -46,6 +46,7 @@ jobs: matrix: sample: # server + - samples/server/others/kotlin-springboot/allOf-multilevel - samples/server/others/kotlin-springboot/oneOf-discriminator - samples/server/others/kotlin-springboot/oneOf-discriminator-const - samples/server/others/kotlin-springboot/oneOf-enum-discriminator diff --git a/.github/workflows/samples-kotlin-server-jdk21.yaml b/.github/workflows/samples-kotlin-server-jdk21.yaml index b4691689bb70..8db627f2fcdf 100644 --- a/.github/workflows/samples-kotlin-server-jdk21.yaml +++ b/.github/workflows/samples-kotlin-server-jdk21.yaml @@ -25,6 +25,7 @@ jobs: fail-fast: false matrix: sample: + - samples/server/others/kotlin-springboot/allOf-multilevel - samples/server/others/kotlin-springboot/oneOf-discriminator - samples/server/others/kotlin-springboot/oneOf-discriminator-const - samples/server/others/kotlin-springboot/oneOf-enum-discriminator diff --git a/bin/configs/kotlin-spring-boot-allof-multilevel.yaml b/bin/configs/kotlin-spring-boot-allof-multilevel.yaml new file mode 100644 index 000000000000..1a1962a72833 --- /dev/null +++ b/bin/configs/kotlin-spring-boot-allof-multilevel.yaml @@ -0,0 +1,11 @@ +generatorName: kotlin-spring +outputDir: samples/server/others/kotlin-springboot/allOf-multilevel +library: spring-boot +inputSpec: modules/openapi-generator/src/test/resources/3_1/allof-multilevel-inheritance.yaml +templateDir: modules/openapi-generator/src/main/resources/kotlin-spring +additionalProperties: + documentationProvider: none + annotationLibrary: none + useSwaggerUI: "false" + interfaceOnly: "true" + useSpringBoot3: "true" diff --git a/docs/generators/kotlin-spring.md b/docs/generators/kotlin-spring.md index 5eaa5ffc9cfa..65cb259a08c3 100644 --- a/docs/generators/kotlin-spring.md +++ b/docs/generators/kotlin-spring.md @@ -68,6 +68,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |useFlowForArrayReturnType|Whether to use Flow for array/collection return types when reactive is enabled. If false, will use List instead.| |true| |useJackson3|Use Jackson 3 dependencies (tools.jackson package). Only available with `useSpringBoot4`. Defaults to true when `useSpringBoot4` is enabled.| |false| |useResponseEntity|Whether (when false) to return actual type (e.g. List<Fruit>) and handle non-happy path responses via exceptions flow or (when true) return entire ResponseEntity (e.g. ResponseEntity<List<Fruit>>). If disabled, method are annotated using a @ResponseStatus annotation, which has the status of the first response declared in the Api definition| |true| +|useSealedDiscriminatorInterfaces|Generate sealed interfaces instead of plain interfaces for allOf discriminator parent models. When true (default), discriminator parents rendered as `sealed interface`, enabling exhaustive `when` matching and preventing external implementors (which cannot know all subtypes). Set to false to restore the legacy plain `interface` behavior, e.g. when you implement the generated interface from a module outside the generated package.| |true| |useSealedResponseInterfaces|Generate sealed interfaces for endpoint responses that all possible response types implement. Allows controllers to return any valid response type in a type-safe manner (e.g., sealed interface CreateUserResponse implemented by User, ConflictResponse, ErrorResponse)| |false| |useSpringBoot3|Generate code and provide dependencies for use with Spring Boot ≥ 3 (use jakarta instead of javax in imports). Enabling this option will also enable `useJakartaEe`.| |false| |useSpringBoot4|Generate code and provide dependencies for use with Spring Boot 4.x. Enabling this option will also enable `useJakartaEe`.| |false| @@ -314,7 +315,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |Composite|✓|OAS2,OAS3 |Polymorphism|✓|OAS2,OAS3 |Union|✗|OAS3 -|allOf|✗|OAS2,OAS3 +|allOf|✓|OAS2,OAS3 |anyOf|✗|OAS3 |oneOf|✓|OAS3 |not|✗|OAS3 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 dba07bae883e..01f33de0c758 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 @@ -108,6 +108,7 @@ public class KotlinSpringServerCodegen extends AbstractKotlinCodegen public static final String GENERATE_PAGEABLE_CONSTRAINT_VALIDATION = "generatePageableConstraintValidation"; public static final String SUBSTITUTE_GENERIC_PAGED_MODEL = "substituteGenericPagedModel"; public static final String USE_SEALED_RESPONSE_INTERFACES = "useSealedResponseInterfaces"; + public static final String USE_SEALED_DISCRIMINATOR_INTERFACES = "useSealedDiscriminatorInterfaces"; public static final String COMPANION_OBJECT = "companionObject"; public static final String SUSPEND_FUNCTIONS = "suspendFunctions"; @@ -178,6 +179,7 @@ public String getDescription() { @Setter private boolean generatePageableConstraintValidation = false; @Setter private boolean substituteGenericPagedModel = false; @Setter private boolean useSealedResponseInterfaces = false; + @Setter private boolean useSealedDiscriminatorInterfaces = true; @Setter private boolean companionObject = false; @Setter private boolean useEnumValueInterface = false; private String valuedEnumClassName = "ValuedEnum"; @@ -229,7 +231,8 @@ public KotlinSpringServerCodegen() { ) .includeSchemaSupportFeatures( SchemaSupportFeature.Polymorphism, - SchemaSupportFeature.oneOf + SchemaSupportFeature.oneOf, + SchemaSupportFeature.allOf ) .includeParameterFeatures( ParameterFeature.Cookie @@ -295,6 +298,13 @@ public KotlinSpringServerCodegen() { addSwitch(USE_SEALED_RESPONSE_INTERFACES, "Generate sealed interfaces for endpoint responses that all possible response types implement. Allows controllers to return any valid response type in a type-safe manner (e.g., sealed interface CreateUserResponse implemented by User, ConflictResponse, ErrorResponse)", useSealedResponseInterfaces); + addSwitch(USE_SEALED_DISCRIMINATOR_INTERFACES, + "Generate sealed interfaces instead of plain interfaces for allOf discriminator parent models. " + + "When true (default), discriminator parents rendered as `sealed interface`, enabling exhaustive " + + "`when` matching and preventing external implementors (which cannot know all subtypes). " + + "Set to false to restore the legacy plain `interface` behavior, e.g. when you implement " + + "the generated interface from a module outside the generated package.", + useSealedDiscriminatorInterfaces); addOption(X_KOTLIN_IMPLEMENTS_SKIP, "A list of fully qualified interfaces that should NOT be implemented despite their presence in vendor extension `x-kotlin-implements`. Example: yaml `xKotlinImplementsSkip: [com.some.pack.WithPhotoUrls]` skips implementing the interface in any schema", "empty list"); addOption(X_KOTLIN_IMPLEMENTS_FIELDS_SKIP, "A list of fields per schema name that should NOT be created with `override` keyword despite their presence in vendor extension `x-kotlin-implements-fields` for the schema. Example: yaml `xKotlinImplementsFieldsSkip: Pet: [photoUrls]` skips `override` for `photoUrls` in schema `Pet`", "empty map"); addOption(SCHEMA_IMPLEMENTS, "A map of single interface or a list of interfaces per schema name that should be implemented (serves similar purpose as `x-kotlin-implements`, but is fully decoupled from the api spec). Example: yaml `schemaImplements: {Pet: com.some.pack.WithId, Category: [com.some.pack.CategoryInterface], Dog: [com.some.pack.Canine, com.some.pack.OtherInterface]}` implements interfaces in schemas `Pet` (interface `com.some.pack.WithId`), `Category` (interface `com.some.pack.CategoryInterface`), `Dog`(interfaces `com.some.pack.Canine`, `com.some.pack.OtherInterface`)", "empty map"); @@ -577,6 +587,12 @@ public void processOpts() { } writePropertyBack(USE_SEALED_RESPONSE_INTERFACES, useSealedResponseInterfaces); + if (additionalProperties.containsKey(USE_SEALED_DISCRIMINATOR_INTERFACES)) { + this.setUseSealedDiscriminatorInterfaces( + Boolean.parseBoolean(additionalProperties.get(USE_SEALED_DISCRIMINATOR_INTERFACES).toString())); + } + writePropertyBack(USE_SEALED_DISCRIMINATOR_INTERFACES, useSealedDiscriminatorInterfaces); + if (additionalProperties.containsKey(COMPANION_OBJECT)) { this.setCompanionObject(convertPropertyToBooleanAndWriteBack(COMPANION_OBJECT)); } else { @@ -1319,26 +1335,65 @@ public Map postProcessAllModels(Map objs) Map allModelsMap = getAllModels(objs); - // For each oneOf interface with a discriminator, mark the discriminator property - // as inherited in each subtype and set its default value from the discriminator mapping + // For each discriminator parent (oneOf interfaces and allOf parents alike), mark the + // discriminator property as inherited in each child and set its default value. for (CodegenModel cm : allModelsMap.values()) { - if (Boolean.TRUE.equals(cm.vendorExtensions.get(CodegenConstants.X_IS_ONE_OF_INTERFACE)) - && cm.discriminator != null) { - String discrimBaseName = cm.discriminator.getPropertyBaseName(); - String discrimType = cm.discriminator.getPropertyType(); - boolean isEnumDiscriminator = cm.discriminator.getIsEnum(); - - // Build child name -> mapping name lookup from discriminator mappings - Map childToMappingName = new HashMap<>(); - for (CodegenDiscriminator.MappedModel mm : cm.discriminator.getMappedModels()) { - childToMappingName.put(mm.getModelName(), mm.getMappingName()); + if (cm.discriminator == null + || cm.discriminator.getMappedModels() == null + || cm.discriminator.getMappedModels().isEmpty()) continue; + String discrimBaseName = cm.discriminator.getPropertyBaseName(); + String discrimType = cm.discriminator.getPropertyType(); + boolean isEnumDiscriminator = cm.discriminator.getIsEnum(); + for (CodegenDiscriminator.MappedModel mm : cm.discriminator.getMappedModels()) { + CodegenModel child = allModelsMap.get(mm.getModelName()); + if (child != null && child != cm) { + markPropertyAsInherited(child, discrimBaseName, discrimType, + mm.getMappingName(), isEnumDiscriminator); } + } + } - for (String childName : cm.oneOf) { - CodegenModel child = allModelsMap.get(childName); - if (child != null) { - String mappingName = childToMappingName.get(childName); - markPropertyAsInherited(child, discrimBaseName, discrimType, mappingName, isEnumDiscriminator); + // Multi-level allOf inheritance: detect "mid-level" models — models that (a) have at least + // one child via allOf and (b) are themselves a child (have a parent) but are NOT a + // discriminator root. These must become `open class` so their own subclasses can extend them. + // Example: Animal (sealed interface) ← Dog (open class, has child BigDog) ← BigDog (data class) + for (CodegenModel cm : allModelsMap.values()) { + boolean isMidLevel = cm.hasChildren + && cm.discriminator == null + && cm.parent != null + && !Boolean.TRUE.equals(cm.vendorExtensions.get(CodegenConstants.X_IS_ONE_OF_INTERFACE)); + if (isMidLevel) { + // Mark for `open class` rendering in the template + cm.vendorExtensions.put("x-is-open-class", true); + // Mark every *own* (non-inherited) property as `open` so subclasses can override it. + // Inherited properties (override) are implicitly open in an open class. + Stream.of(cm.vars, cm.requiredVars, cm.optionalVars, cm.allVars) + .flatMap(List::stream) + .filter(p -> !p.isInherited) + .forEach(p -> p.vendorExtensions.put("x-model-is-open", true)); + } + } + + // For children of open (non-interface) parent classes, build a parent constructor call + // so the template can emit `: Dog(className = className, ...)`. + // x-parent-is-class tells the template the parent requires `()` (even when arg list is empty); + // x-parent-ctor-args holds the argument string. Kept separate so a parent with no properties + // still generates `: ParentClass()` rather than the compile-error `: ParentClass` (no parens). + for (CodegenModel cm : allModelsMap.values()) { + if (cm.parent != null) { + CodegenModel parentModel = allModelsMap.get(cm.parent); + if (parentModel != null + && Boolean.TRUE.equals(parentModel.vendorExtensions.get("x-is-open-class"))) { + cm.vendorExtensions.put("x-parent-is-class", true); + List ctorArgs = new ArrayList<>(); + for (CodegenProperty prop : parentModel.getRequiredVars()) { + ctorArgs.add(prop.getName() + " = " + prop.getName()); + } + for (CodegenProperty prop : parentModel.getOptionalVars()) { + ctorArgs.add(prop.getName() + " = " + prop.getName()); + } + if (!ctorArgs.isEmpty()) { + cm.vendorExtensions.put("x-parent-ctor-args", String.join(", ", ctorArgs)); } } } diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/dataClass.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/dataClass.mustache index 3eeb19e70bcd..5bb5b044dbc3 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-spring/dataClass.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/dataClass.mustache @@ -14,14 +14,14 @@ {{#vendorExtensions.x-class-extra-annotation}} {{{.}}} {{/vendorExtensions.x-class-extra-annotation}} -{{#discriminator}}interface {{classname}}{{/discriminator}}{{^discriminator}}{{#hasVars}}data {{/hasVars}}class {{classname}}( +{{#discriminator}}{{#useSealedDiscriminatorInterfaces}}sealed {{/useSealedDiscriminatorInterfaces}}interface {{classname}}{{/discriminator}}{{^discriminator}}{{#vendorExtensions.x-is-open-class}}open {{/vendorExtensions.x-is-open-class}}{{^vendorExtensions.x-is-open-class}}{{#hasVars}}data {{/hasVars}}{{/vendorExtensions.x-is-open-class}}class {{classname}}( {{#requiredVars}} {{>dataClassReqVar}}{{^-last}}, {{/-last}}{{/requiredVars}}{{#hasRequired}}{{#hasOptional}}, {{/hasOptional}}{{/hasRequired}}{{#optionalVars}}{{>dataClassOptVar}}{{^-last}}, {{/-last}}{{/optionalVars}} ){{/discriminator}}{{! no newline -}}{{#parent}} : {{{.}}}{{#isMap}}(){{/isMap}}{{! no newline +}}{{#parent}} : {{{.}}}{{#vendorExtensions.x-parent-is-class}}({{{vendorExtensions.x-parent-ctor-args}}}){{/vendorExtensions.x-parent-is-class}}{{^vendorExtensions.x-parent-is-class}}{{#isMap}}(){{/isMap}}{{/vendorExtensions.x-parent-is-class}}{{! no newline }}{{#vendorExtensions.x-kotlin-implements}}, {{{.}}}{{/vendorExtensions.x-kotlin-implements}}{{! <- serializableModel is also handled via x-kotlin-implements }}{{#vendorExtensions.x-implements-sealed-interfaces}}{{#.}}, {{{.}}}{{/.}}{{/vendorExtensions.x-implements-sealed-interfaces}}{{! <- add sealed interface implementations }}{{/parent}}{{! no newline @@ -43,6 +43,29 @@ {{>interfaceOptVar}}{{! prevent indent}} {{/optionalVars}} {{/discriminator}} +{{#vendorExtensions.x-is-open-class}} + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other?.javaClass != javaClass) return false + other as {{classname}} + return {{#allVars}}{{name}} == other.{{name}}{{^-last}} + && {{/-last}}{{/allVars}}{{^allVars}}true{{/allVars}} + } + + override fun hashCode(): Int { + return Objects.hash({{#allVars}}{{name}}{{^-last}}, {{/-last}}{{/allVars}}) + } + + override fun toString(): String { + return "{{classname}}({{#allVars}}{{name}}=${{name}}{{^-last}}, {{/-last}}{{/allVars}})" + } + + fun copy( +{{#allVars}} + {{name}}: {{{dataType}}}{{^required}}?{{/required}} = this.{{name}}{{^-last}},{{/-last}} +{{/allVars}} + ): {{classname}} = {{classname}}({{#allVars}}{{name}} = {{name}}{{^-last}}, {{/-last}}{{/allVars}}) +{{/vendorExtensions.x-is-open-class}} {{#hasEnums}}{{#vars}}{{#isEnum}} /** * {{{description}}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassOptVar.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassOptVar.mustache index 404692bece79..dab7f1cc39df 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassOptVar.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassOptVar.mustache @@ -4,4 +4,4 @@ @Deprecated(message = ""){{/deprecated}}{{#vendorExtensions.x-field-extra-annotation}} {{{.}}}{{/vendorExtensions.x-field-extra-annotation}}{{#vendorExtensions.x-has-json-setter-nulls-fail}} @field:JsonSetter(nulls = Nulls.FAIL){{/vendorExtensions.x-has-json-setter-nulls-fail}} - @get:JsonProperty("{{{baseName}}}"){{#isInherited}} override{{/isInherited}} {{>modelMutable}} {{{name}}}: {{#vendorExtensions.x-is-jackson-optional-nullable}}JsonNullable<{{#isEnum}}{{#isArray}}{{baseType}}<{{/isArray}}{{classname}}.{{{nameInPascalCase}}}{{#isArray}}>{{/isArray}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}>{{/vendorExtensions.x-is-jackson-optional-nullable}}{{^vendorExtensions.x-is-jackson-optional-nullable}}{{#isEnum}}{{#isArray}}{{baseType}}<{{/isArray}}{{classname}}.{{{nameInPascalCase}}}{{#isArray}}>{{/isArray}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}?{{/vendorExtensions.x-is-jackson-optional-nullable}} = {{#vendorExtensions.x-is-jackson-optional-nullable}}JsonNullable.undefined(){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^vendorExtensions.x-is-jackson-optional-nullable}}{{^defaultValue}}null{{/defaultValue}}{{#defaultValue}}{{^isNumber}}{{{defaultValue}}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{/vendorExtensions.x-is-jackson-optional-nullable}} \ No newline at end of file + @get:JsonProperty("{{{baseName}}}"){{#isInherited}} override{{/isInherited}}{{^isInherited}}{{#vendorExtensions.x-model-is-open}} open{{/vendorExtensions.x-model-is-open}}{{/isInherited}} {{>modelMutable}} {{{name}}}: {{#vendorExtensions.x-is-jackson-optional-nullable}}JsonNullable<{{#isEnum}}{{#isArray}}{{baseType}}<{{/isArray}}{{classname}}.{{{nameInPascalCase}}}{{#isArray}}>{{/isArray}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}>{{/vendorExtensions.x-is-jackson-optional-nullable}}{{^vendorExtensions.x-is-jackson-optional-nullable}}{{#isEnum}}{{#isArray}}{{baseType}}<{{/isArray}}{{classname}}.{{{nameInPascalCase}}}{{#isArray}}>{{/isArray}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}?{{/vendorExtensions.x-is-jackson-optional-nullable}} = {{#vendorExtensions.x-is-jackson-optional-nullable}}JsonNullable.undefined(){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^vendorExtensions.x-is-jackson-optional-nullable}}{{^defaultValue}}null{{/defaultValue}}{{#defaultValue}}{{^isNumber}}{{{defaultValue}}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{/vendorExtensions.x-is-jackson-optional-nullable}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassReqVar.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassReqVar.mustache index 92e2875ac08a..02f70ea7431c 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassReqVar.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassReqVar.mustache @@ -2,4 +2,4 @@ @Schema({{#example}}example = "{{#lambdaRemoveLineBreak}}{{#lambdaEscapeInNormalString}}{{{.}}}{{/lambdaEscapeInNormalString}}{{/lambdaRemoveLineBreak}}", {{/example}}required = true, {{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}description = "{{{description}}}"){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}} @ApiModelProperty({{#example}}example = "{{#lambdaRemoveLineBreak}}{{#lambdaEscapeInNormalString}}{{{.}}}{{/lambdaEscapeInNormalString}}{{/lambdaRemoveLineBreak}}", {{/example}}required = true, {{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}value = "{{{description}}}"){{/swagger1AnnotationLibrary}}{{#vendorExtensions.x-field-extra-annotation}} {{{.}}}{{/vendorExtensions.x-field-extra-annotation}} - @get:JsonProperty("{{{baseName}}}", required = true){{#isInherited}} override{{/isInherited}} {{>modelMutable}} {{{name}}}: {{#isEnum}}{{#isArray}}{{baseType}}<{{/isArray}}{{classname}}.{{{nameInPascalCase}}}{{#isArray}}>{{/isArray}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{#isNullable}}?{{/isNullable}}{{#defaultValue}} = {{^isNumber}}{{{defaultValue}}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}} \ No newline at end of file + @get:JsonProperty("{{{baseName}}}", required = true){{#isInherited}} override{{/isInherited}}{{^isInherited}}{{#vendorExtensions.x-model-is-open}} open{{/vendorExtensions.x-model-is-open}}{{/isInherited}} {{>modelMutable}} {{{name}}}: {{#isEnum}}{{#isArray}}{{baseType}}<{{/isArray}}{{classname}}.{{{nameInPascalCase}}}{{#isArray}}>{{/isArray}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{#isNullable}}?{{/isNullable}}{{#defaultValue}} = {{^isNumber}}{{{defaultValue}}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}} \ No newline at end of file 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 4ac2f195bb74..712ae51f2620 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 @@ -1176,7 +1176,7 @@ public void generateSerializableModelWithSchemaImplements() throws Exception { "@get:JsonProperty(\"likesFetch\", required = true) override val likesFetch: kotlin.Boolean,", "@get:JsonProperty(\"name\", required = true) override val name: kotlin.String,", "@get:JsonProperty(\"photoUrls\", required = true) override val photoUrls: kotlin.collections.List,", - "@get:JsonProperty(\"petType\", required = true) override val petType: kotlin.String,", + "@get:JsonProperty(\"petType\", required = true) override val petType: kotlin.String = \"Dog\",", "@get:JsonProperty(\"id\") override val id: kotlin.Long? = null,", "@get:JsonProperty(\"category\") override val category: Category? = null,", "@get:JsonProperty(\"tags\") override val tags: kotlin.collections.List? = null,", @@ -6678,4 +6678,214 @@ public void schemaMappingWithNullableAllOfRendersNullableKotlinProperty() throws String content = Files.readString(myObjectFile.toPath()); assertThat(content).contains("com.example.ExternalModel?"); } + + // ==================== allOf discriminator default value tests ==================== + + @Test(description = "allOf discriminator children get a default value from the schema name when no explicit mapping") + public void testAllOfDiscriminatorChildrenGetDefaultValue() throws IOException { + File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); + output.deleteOnExit(); + + new DefaultGenerator().opts(new ClientOptInput() + .openAPI(new OpenAPIParser().readLocation("src/test/resources/3_1/polymorphism-allof-and-discriminator.yaml", null, new ParseOptions()).getOpenAPI()) + .config(new KotlinSpringServerCodegen() {{ + setOutputDir(output.getAbsolutePath()); + }})) + .generate(); + + String outputPath = output.getAbsolutePath() + "/src/main/kotlin/org/openapitools/model"; + + // Cat and Dog are allOf children of Pet; no explicit mapping → schema name is the discriminating value + assertFileContains(Paths.get(outputPath + "/Cat.kt"), + "data class Cat", + "override val petType: kotlin.String = \"Cat\"" + ); + assertFileContains(Paths.get(outputPath + "/Dog.kt"), + "data class Dog", + "override val petType: kotlin.String = \"Dog\"" + ); + // Pet parent is a plain interface when useSealedDiscriminatorInterfaces is at its default + assertFileContains(Paths.get(outputPath + "/Pet.kt"), + "interface Pet" + ); + assertFileNotContains(Paths.get(outputPath + "/Cat.kt"), + "petType: kotlin.String?", "petType: kotlin.Any" + ); + assertFileNotContains(Paths.get(outputPath + "/Dog.kt"), + "petType: kotlin.String?", "petType: kotlin.Any" + ); + } + + @Test(description = "allOf discriminator children get default value matching the explicit mapping key") + public void testAllOfDiscriminatorWithExplicitMappingDefaultValue() throws IOException { + File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); + output.deleteOnExit(); + + new DefaultGenerator().opts(new ClientOptInput() + .openAPI(new OpenAPIParser().readLocation("src/test/resources/3_0/kotlin/petstore-with-x-kotlin-implements.yaml", null, new ParseOptions()).getOpenAPI()) + .config(new KotlinSpringServerCodegen() {{ + setOutputDir(output.getAbsolutePath()); + }})) + .generate(); + + String outputPath = output.getAbsolutePath() + "/src/main/kotlin/org/openapitools/model"; + + // Pet has discriminator petType with explicit mapping: Dog → "Dog", Cat → "Cat" + assertFileContains(Paths.get(outputPath + "/Dog.kt"), + "data class Dog", + "override val petType: kotlin.String = \"Dog\"" + ); + assertFileContains(Paths.get(outputPath + "/Cat.kt"), + "data class Cat", + "override val petType: kotlin.String = \"Cat\"" + ); + } + + // ==================== allOf sealed interface tests ==================== + + @Test(description = "allOf discriminator parent generates sealed interface by default") + public void testAllOfDiscriminatorParentIsSealedInterfaceByDefault() throws IOException { + File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); + output.deleteOnExit(); + + new DefaultGenerator().opts(new ClientOptInput() + .openAPI(new OpenAPIParser().readLocation("src/test/resources/3_1/polymorphism-allof-and-discriminator.yaml", null, new ParseOptions()).getOpenAPI()) + .config(new KotlinSpringServerCodegen() {{ + setOutputDir(output.getAbsolutePath()); + }})) + .generate(); + + String outputPath = output.getAbsolutePath() + "/src/main/kotlin/org/openapitools/model"; + + // Pet should be a sealed interface with Jackson annotations + assertFileContains(Paths.get(outputPath + "/Pet.kt"), + "sealed interface Pet", + "@JsonTypeInfo", "property = \"petType\"", "visible = true", + "@JsonSubTypes" + ); + // Children must remain data classes — sealing only applies to the discriminator parent + assertFileContains(Paths.get(outputPath + "/Dog.kt"), "data class Dog"); + assertFileContains(Paths.get(outputPath + "/Cat.kt"), "data class Cat"); + assertFileNotContains(Paths.get(outputPath + "/Dog.kt"), "sealed"); + assertFileNotContains(Paths.get(outputPath + "/Cat.kt"), "sealed"); + } + + @Test(description = "allOf discriminator parent generates plain interface when useSealedDiscriminatorInterfaces=false") + public void testAllOfDiscriminatorOptOutPlainInterface() throws IOException { + File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); + output.deleteOnExit(); + + new DefaultGenerator().opts(new ClientOptInput() + .openAPI(new OpenAPIParser().readLocation("src/test/resources/3_1/polymorphism-allof-and-discriminator.yaml", null, new ParseOptions()).getOpenAPI()) + .config(new KotlinSpringServerCodegen() {{ + setOutputDir(output.getAbsolutePath()); + additionalProperties().put(USE_SEALED_DISCRIMINATOR_INTERFACES, "false"); + }})) + .generate(); + + String outputPath = output.getAbsolutePath() + "/src/main/kotlin/org/openapitools/model"; + + // Opt-out: plain interface, not sealed + assertFileContains(Paths.get(outputPath + "/Pet.kt"), "interface Pet"); + assertFileNotContains(Paths.get(outputPath + "/Pet.kt"), "sealed interface Pet"); + } + + @Test(description = "allOf sealed interface correctly composes external x-kotlin-implements supertypes") + public void testSealedInterfaceWithExternalSupertypes() throws IOException { + File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); + output.deleteOnExit(); + + new DefaultGenerator().opts(new ClientOptInput() + .openAPI(new OpenAPIParser().readLocation("src/test/resources/3_0/kotlin/petstore-with-x-kotlin-implements.yaml", null, new ParseOptions()).getOpenAPI()) + .config(new KotlinSpringServerCodegen() {{ + setOutputDir(output.getAbsolutePath()); + }})) + .generate(); + + String outputPath = output.getAbsolutePath() + "/src/main/kotlin/org/openapitools/model"; + + // Pet has x-kotlin-implements external supertypes; sealed should come before those + assertFileContains(Paths.get(outputPath + "/Pet.kt"), + "sealed interface Pet : com.some.pack.Named" + ); + } + + @Test(description = "oneOf sealed interface stays sealed when useSealedDiscriminatorInterfaces=false (different template path)") + public void testOneOfInterfaceStillSealedWhenAllOfFlagOff() throws IOException { + File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); + output.deleteOnExit(); + + new DefaultGenerator().opts(new ClientOptInput() + .openAPI(new OpenAPIParser().readLocation("src/test/resources/3_0/kotlin/polymorphism-oneof-discriminator.yaml", null, new ParseOptions()).getOpenAPI()) + .config(new KotlinSpringServerCodegen() {{ + setOutputDir(output.getAbsolutePath()); + additionalProperties().put(USE_SEALED_DISCRIMINATOR_INTERFACES, "false"); + }})) + .generate(); + + String outputPath = output.getAbsolutePath() + "/src/main/kotlin/org/openapitools/model"; + + // oneOf parent uses oneof_interface.mustache, not dataClass.mustache — flag has no effect on it + assertFileContains(Paths.get(outputPath + "/Animal.kt"), "sealed interface Animal"); + } + + // ==================== multi-level allOf inheritance tests (fixes #18206) ==================== + + @Test(description = "multi-level allOf: mid-level model becomes open class, leaf stays data class with parent ctor call") + public void testMultiLevelAllOfInheritance() throws IOException { + File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); + output.deleteOnExit(); + + new DefaultGenerator().opts(new ClientOptInput() + .openAPI(new OpenAPIParser().readLocation("src/test/resources/3_1/allof-multilevel-inheritance.yaml", null, new ParseOptions()).getOpenAPI()) + .config(new KotlinSpringServerCodegen() {{ + setOutputDir(output.getAbsolutePath()); + }})) + .generate(); + + String outputPath = output.getAbsolutePath() + "/src/main/kotlin/org/openapitools/model"; + + // Animal: sealed interface with Jackson annotations listing ALL descendants + assertFileContains(Paths.get(outputPath + "/Animal.kt"), + "sealed interface Animal", + "@JsonTypeInfo", "property = \"className\"", "visible = true", + "BigDog::class", + "Dog::class", + "Cat::class" + ); + + // Dog: open class (not data class) so BigDog can extend it; no ctor call to Animal (interface parent) + assertFileContains(Paths.get(outputPath + "/Dog.kt"), + "open class Dog(", + ") : Animal {", + "override val className: kotlin.String = \"Dog\"", + "open val breed: kotlin.String?" + ); + assertFileNotContains(Paths.get(outputPath + "/Dog.kt"), "data class Dog"); + assertFileNotContains(Paths.get(outputPath + "/Dog.kt"), ": Animal("); + // open class generates equals/hashCode/toString/copy since data class would normally provide these + assertFileContains(Paths.get(outputPath + "/Dog.kt"), + "override fun equals(other: Any?): Boolean", + "if (other?.javaClass != javaClass) return false", + "override fun hashCode(): Int", + "Objects.hash(", + "override fun toString(): String", + "fun copy(", + "): Dog = Dog(" + ); + + // Cat: leaf (no children) — stays a data class, unaffected + assertFileContains(Paths.get(outputPath + "/Cat.kt"), "data class Cat"); + + // BigDog: data class extending open class Dog with constructor call passing all parent ctor args + assertFileContains(Paths.get(outputPath + "/BigDog.kt"), + "data class BigDog(", + "override val className: kotlin.String = \"BigDog\"", + "override val breed", + "override val color" + ); + // Must call Dog's constructor (not bare `: Dog`) + assertFileContains(Paths.get(outputPath + "/BigDog.kt"), ") : Dog("); + assertFileNotContains(Paths.get(outputPath + "/BigDog.kt"), ") : Dog {"); + } } diff --git a/modules/openapi-generator/src/test/resources/3_1/allof-multilevel-inheritance.yaml b/modules/openapi-generator/src/test/resources/3_1/allof-multilevel-inheritance.yaml new file mode 100644 index 000000000000..c1b89b75b8e3 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_1/allof-multilevel-inheritance.yaml @@ -0,0 +1,59 @@ +openapi: 3.1.0 +info: + title: Multi-level allOf inheritance test + description: > + Reproduces the kotlin-spring multi-level inheritance bug (issue #18206). + Animal ← Dog ← BigDog: Dog is both a child of Animal and a parent of BigDog, + so it must become an `open class` rather than a `final data class` to allow + BigDog to extend it. + version: "1.0" +paths: + /animals: + get: + operationId: getAnimal + responses: + 200: + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/Animal' +components: + schemas: + Animal: + type: object + discriminator: + propertyName: className + required: + - className + properties: + className: + type: string + color: + type: string + default: red + Dog: + allOf: + - $ref: '#/components/schemas/Animal' + - type: object + properties: + breed: + type: string + Cat: + allOf: + - $ref: '#/components/schemas/Animal' + - type: object + properties: + breed: + type: string + BigDog: + allOf: + - $ref: '#/components/schemas/Dog' + - type: object + required: + - dogType + properties: + dogType: + type: string + declawed: + type: boolean diff --git a/samples/server/others/kotlin-springboot/allOf-multilevel/.openapi-generator-ignore b/samples/server/others/kotlin-springboot/allOf-multilevel/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/server/others/kotlin-springboot/allOf-multilevel/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/others/kotlin-springboot/allOf-multilevel/.openapi-generator/FILES b/samples/server/others/kotlin-springboot/allOf-multilevel/.openapi-generator/FILES new file mode 100644 index 000000000000..9d852e0330df --- /dev/null +++ b/samples/server/others/kotlin-springboot/allOf-multilevel/.openapi-generator/FILES @@ -0,0 +1,15 @@ +README.md +build.gradle.kts +gradle/wrapper/gradle-wrapper.jar +gradle/wrapper/gradle-wrapper.properties +gradlew +gradlew.bat +pom.xml +settings.gradle +src/main/kotlin/org/openapitools/api/AnimalsApi.kt +src/main/kotlin/org/openapitools/api/ApiUtil.kt +src/main/kotlin/org/openapitools/api/Exceptions.kt +src/main/kotlin/org/openapitools/model/Animal.kt +src/main/kotlin/org/openapitools/model/BigDog.kt +src/main/kotlin/org/openapitools/model/Cat.kt +src/main/kotlin/org/openapitools/model/Dog.kt diff --git a/samples/server/others/kotlin-springboot/allOf-multilevel/.openapi-generator/VERSION b/samples/server/others/kotlin-springboot/allOf-multilevel/.openapi-generator/VERSION new file mode 100644 index 000000000000..ca7bf6e46889 --- /dev/null +++ b/samples/server/others/kotlin-springboot/allOf-multilevel/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.23.0-SNAPSHOT diff --git a/samples/server/others/kotlin-springboot/allOf-multilevel/README.md b/samples/server/others/kotlin-springboot/allOf-multilevel/README.md new file mode 100644 index 000000000000..b35f47a7fae6 --- /dev/null +++ b/samples/server/others/kotlin-springboot/allOf-multilevel/README.md @@ -0,0 +1,21 @@ +# multiLevelAllOfInheritanceTest + +This Kotlin based [Spring Boot](https://spring.io/projects/spring-boot) application has been generated using the [OpenAPI Generator](https://github.com/OpenAPITools/openapi-generator). + +## Getting Started + +This document assumes you have either maven or gradle available, either via the wrapper or otherwise. This does not come with a gradle / maven wrapper checked in. + +By default a [`pom.xml`](pom.xml) file will be generated. If you specified `gradleBuildFile=true` when generating this project, a `build.gradle.kts` will also be generated. Note this uses [Gradle Kotlin DSL](https://github.com/gradle/kotlin-dsl). + +To build the project using maven, run: +```bash +mvn package && java -jar target/openapi-spring-1.0.0.jar +``` + +To build the project using gradle, run: +```bash +gradle build && java -jar build/libs/openapi-spring-1.0.0.jar +``` + +If all builds successfully, the server should run on [http://localhost:8080/](http://localhost:8080/) diff --git a/samples/server/others/kotlin-springboot/allOf-multilevel/build.gradle.kts b/samples/server/others/kotlin-springboot/allOf-multilevel/build.gradle.kts new file mode 100644 index 000000000000..30b6a49c9bf6 --- /dev/null +++ b/samples/server/others/kotlin-springboot/allOf-multilevel/build.gradle.kts @@ -0,0 +1,49 @@ +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile + +group = "org.openapitools" +version = "1.0.0" +java.sourceCompatibility = JavaVersion.VERSION_17 + +repositories { + mavenCentral() + maven { url = uri("https://repo.spring.io/milestone") } +} + +tasks.withType { + kotlinOptions.jvmTarget = "17" +} + +tasks.bootJar { + enabled = false +} + +plugins { + val kotlinVersion = "1.9.25" + id("org.jetbrains.kotlin.jvm") version kotlinVersion + id("org.jetbrains.kotlin.plugin.jpa") version kotlinVersion + id("org.jetbrains.kotlin.plugin.spring") version kotlinVersion + id("org.springframework.boot") version "3.3.13" + id("io.spring.dependency-management") version "1.1.7" +} + +dependencies { + implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") + implementation("org.jetbrains.kotlin:kotlin-reflect") + implementation("org.springframework.boot:spring-boot-starter-web") + + implementation("com.google.code.findbugs:jsr305:3.0.2") + implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml") + implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-xml") + implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310") + implementation("com.fasterxml.jackson.module:jackson-module-kotlin") + implementation("org.springframework.data:spring-data-commons") + implementation("org.springframework.boot:spring-boot-starter-validation") + implementation("jakarta.validation:jakarta.validation-api") + + implementation("jakarta.annotation:jakarta.annotation-api:2.1.0") + + testImplementation("org.jetbrains.kotlin:kotlin-test-junit5") + testImplementation("org.springframework.boot:spring-boot-starter-test") { + exclude(module = "junit") + } +} diff --git a/samples/server/others/kotlin-springboot/allOf-multilevel/gradle/wrapper/gradle-wrapper.jar b/samples/server/others/kotlin-springboot/allOf-multilevel/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000000..e6441136f3d4 Binary files /dev/null and b/samples/server/others/kotlin-springboot/allOf-multilevel/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/server/others/kotlin-springboot/allOf-multilevel/gradle/wrapper/gradle-wrapper.properties b/samples/server/others/kotlin-springboot/allOf-multilevel/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000000..80187ac30432 --- /dev/null +++ b/samples/server/others/kotlin-springboot/allOf-multilevel/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/samples/server/others/kotlin-springboot/allOf-multilevel/gradlew b/samples/server/others/kotlin-springboot/allOf-multilevel/gradlew new file mode 100644 index 000000000000..9d0ce634cb11 --- /dev/null +++ b/samples/server/others/kotlin-springboot/allOf-multilevel/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while +APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path +[ -h "$app_path" ] +do +ls=$( ls -ld "$app_path" ) +link=${ls#*' -> '} +case $link in #( +/*) app_path=$link ;; #( +*) app_path=$APP_HOME$link ;; +esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { +echo "$*" +} >&2 + +die () { +echo +echo "$*" +echo +exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( +CYGWIN* ) cygwin=true ;; #( +Darwin* ) darwin=true ;; #( +MSYS* | MINGW* ) msys=true ;; #( +NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then +if [ -x "$JAVA_HOME/jre/sh/java" ] ; then +# IBM's JDK on AIX uses strange locations for the executables +JAVACMD=$JAVA_HOME/jre/sh/java +else +JAVACMD=$JAVA_HOME/bin/java +fi +if [ ! -x "$JAVACMD" ] ; then +die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi +else +JAVACMD=java +if ! command -v java >/dev/null 2>&1 +then +die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then +case $MAX_FD in #( +max*) +# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. +# shellcheck disable=SC2039,SC3045 +MAX_FD=$( ulimit -H -n ) || +warn "Could not query maximum file descriptor limit" +esac +case $MAX_FD in #( +'' | soft) :;; #( +*) +# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. +# shellcheck disable=SC2039,SC3045 +ulimit -n "$MAX_FD" || +warn "Could not set maximum file descriptor limit to $MAX_FD" +esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then +APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) +CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + +JAVACMD=$( cygpath --unix "$JAVACMD" ) + +# Now convert the arguments - kludge to limit ourselves to /bin/sh +for arg do +if +case $arg in #( +-*) false ;; # don't mess with options #( +/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath +[ -e "$t" ] ;; #( +*) false ;; +esac +then +arg=$( cygpath --path --ignore --mixed "$arg" ) +fi +# Roll the args list around exactly as many times as the number of +# args, so each arg winds up back in the position where it started, but +# possibly modified. +# +# NB: a `for` loop captures its iteration list before it begins, so +# changing the positional parameters here affects neither the number of +# iterations, nor the values presented in `arg`. +shift # remove old arg +set -- "$@" "$arg" # push replacement arg +done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ +"-Dorg.gradle.appname=$APP_BASE_NAME" \ +-classpath "$CLASSPATH" \ +org.gradle.wrapper.GradleWrapperMain \ +"$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then +die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( +printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | +xargs -n1 | +sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | +tr '\n' ' ' +)" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/samples/server/others/kotlin-springboot/allOf-multilevel/gradlew.bat b/samples/server/others/kotlin-springboot/allOf-multilevel/gradlew.bat new file mode 100644 index 000000000000..25da30dbdeee --- /dev/null +++ b/samples/server/others/kotlin-springboot/allOf-multilevel/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/server/others/kotlin-springboot/allOf-multilevel/pom.xml b/samples/server/others/kotlin-springboot/allOf-multilevel/pom.xml new file mode 100644 index 000000000000..c83b8a04b7ef --- /dev/null +++ b/samples/server/others/kotlin-springboot/allOf-multilevel/pom.xml @@ -0,0 +1,158 @@ + + 4.0.0 + org.openapitools + openapi-spring + jar + openapi-spring + 1.0.0 + + 3.0.2 + 2.1.0 + 1.9.25 + + 1.9.25 + UTF-8 + + + org.springframework.boot + spring-boot-starter-parent + 3.3.13 + + + + repository.spring.milestone + Spring Milestone Repository + https://repo.spring.io/milestone + + + + + spring-milestones + https://repo.spring.io/milestone + + + + ${project.basedir}/src/main/kotlin + ${project.basedir}/src/test/kotlin + + + org.apache.maven.plugins + maven-source-plugin + + + attach-sources + + jar + + + + + + kotlin-maven-plugin + org.jetbrains.kotlin + ${kotlin.version} + + + spring + + 17 + + + + compile + compile + + compile + + + + test-compile + test-compile + + test-compile + + + + + + org.jetbrains.kotlin + kotlin-maven-allopen + ${kotlin.version} + + + + + + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + ${kotlin.version} + + + org.jetbrains.kotlin + kotlin-reflect + ${kotlin.version} + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.data + spring-data-commons + + + + + + + com.google.code.findbugs + jsr305 + ${findbugs-jsr305.version} + + + com.fasterxml.jackson.dataformat + jackson-dataformat-yaml + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + + com.fasterxml.jackson.module + jackson-module-kotlin + + + + jakarta.validation + jakarta.validation-api + + + org.springframework.boot + spring-boot-starter-validation + + + + jakarta.annotation + jakarta.annotation-api + ${jakarta-annotation.version} + provided + + + org.springframework.boot + spring-boot-starter-test + test + + + org.jetbrains.kotlin + kotlin-test-junit5 + ${kotlin-test-junit5.version} + test + + + diff --git a/samples/server/others/kotlin-springboot/allOf-multilevel/settings.gradle b/samples/server/others/kotlin-springboot/allOf-multilevel/settings.gradle new file mode 100644 index 000000000000..14844905cd40 --- /dev/null +++ b/samples/server/others/kotlin-springboot/allOf-multilevel/settings.gradle @@ -0,0 +1,15 @@ +pluginManagement { + repositories { + maven { url = uri("https://repo.spring.io/snapshot") } + maven { url = uri("https://repo.spring.io/milestone") } + gradlePluginPortal() + } + resolutionStrategy { + eachPlugin { + if (requested.id.id == "org.springframework.boot") { + useModule("org.springframework.boot:spring-boot-gradle-plugin:${requested.version}") + } + } + } +} +rootProject.name = "openapi-spring" diff --git a/samples/server/others/kotlin-springboot/allOf-multilevel/src/main/kotlin/org/openapitools/api/AnimalsApi.kt b/samples/server/others/kotlin-springboot/allOf-multilevel/src/main/kotlin/org/openapitools/api/AnimalsApi.kt new file mode 100644 index 000000000000..785214cfdfdc --- /dev/null +++ b/samples/server/others/kotlin-springboot/allOf-multilevel/src/main/kotlin/org/openapitools/api/AnimalsApi.kt @@ -0,0 +1,50 @@ +/** + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.23.0-SNAPSHOT). + * https://openapi-generator.tech + * Do not edit the class manually. +*/ +package org.openapitools.api + +import org.openapitools.model.Animal +import org.springframework.http.HttpStatus +import org.springframework.http.MediaType +import org.springframework.http.ResponseEntity + +import org.springframework.web.bind.annotation.* +import org.springframework.validation.annotation.Validated +import org.springframework.web.context.request.NativeWebRequest +import org.springframework.beans.factory.annotation.Autowired + +import jakarta.validation.constraints.DecimalMax +import jakarta.validation.constraints.DecimalMin +import jakarta.validation.constraints.Email +import jakarta.validation.constraints.Max +import jakarta.validation.constraints.Min +import jakarta.validation.constraints.NotNull +import jakarta.validation.constraints.Pattern +import jakarta.validation.constraints.Size +import jakarta.validation.Valid + +import kotlin.collections.List +import kotlin.collections.Map + +@RestController +@Validated +interface AnimalsApi { + + + @RequestMapping( + method = [RequestMethod.GET], + // "/animals" + value = [PATH_GET_ANIMAL], + produces = ["application/json"] + ) + fun getAnimal(): ResponseEntity { + return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) + } + + companion object { + //for your own safety never directly reuse these path definitions in tests + const val PATH_GET_ANIMAL: String = "/animals" + } +} diff --git a/samples/server/others/kotlin-springboot/allOf-multilevel/src/main/kotlin/org/openapitools/api/ApiUtil.kt b/samples/server/others/kotlin-springboot/allOf-multilevel/src/main/kotlin/org/openapitools/api/ApiUtil.kt new file mode 100644 index 000000000000..03344e13b474 --- /dev/null +++ b/samples/server/others/kotlin-springboot/allOf-multilevel/src/main/kotlin/org/openapitools/api/ApiUtil.kt @@ -0,0 +1,19 @@ +package org.openapitools.api + +import org.springframework.web.context.request.NativeWebRequest + +import jakarta.servlet.http.HttpServletResponse +import java.io.IOException + +object ApiUtil { + fun setExampleResponse(req: NativeWebRequest, contentType: String, example: String) { + try { + val res = req.getNativeResponse(HttpServletResponse::class.java) + res?.characterEncoding = "UTF-8" + res?.addHeader("Content-Type", contentType) + res?.writer?.print(example) + } catch (e: IOException) { + throw RuntimeException(e) + } + } +} diff --git a/samples/server/others/kotlin-springboot/allOf-multilevel/src/main/kotlin/org/openapitools/api/Exceptions.kt b/samples/server/others/kotlin-springboot/allOf-multilevel/src/main/kotlin/org/openapitools/api/Exceptions.kt new file mode 100644 index 000000000000..1bd78f54576a --- /dev/null +++ b/samples/server/others/kotlin-springboot/allOf-multilevel/src/main/kotlin/org/openapitools/api/Exceptions.kt @@ -0,0 +1,30 @@ +package org.openapitools.api + +import org.springframework.context.annotation.Configuration +import org.springframework.http.HttpStatus +import org.springframework.web.bind.annotation.ControllerAdvice +import org.springframework.web.bind.annotation.ExceptionHandler +import jakarta.servlet.http.HttpServletResponse +import jakarta.validation.ConstraintViolationException + +// TODO Extend ApiException for custom exception handling, e.g. the below NotFound exception +sealed class ApiException(msg: String, val code: Int) : Exception(msg) + +class NotFoundException(msg: String, code: Int = HttpStatus.NOT_FOUND.value()) : ApiException(msg, code) + +@Configuration("org.openapitools.api.DefaultExceptionHandler") +@ControllerAdvice +class DefaultExceptionHandler { + + @ExceptionHandler(value = [ApiException::class]) + fun onApiException(ex: ApiException, response: HttpServletResponse): Unit = + response.sendError(ex.code, ex.message) + + @ExceptionHandler(value = [NotImplementedError::class]) + fun onNotImplemented(ex: NotImplementedError, response: HttpServletResponse): Unit = + response.sendError(HttpStatus.NOT_IMPLEMENTED.value()) + + @ExceptionHandler(value = [ConstraintViolationException::class]) + fun onConstraintViolation(ex: ConstraintViolationException, response: HttpServletResponse): Unit = + response.sendError(HttpStatus.BAD_REQUEST.value(), ex.constraintViolations.joinToString(", ") { it.message }) +} diff --git a/samples/server/others/kotlin-springboot/allOf-multilevel/src/main/kotlin/org/openapitools/model/Animal.kt b/samples/server/others/kotlin-springboot/allOf-multilevel/src/main/kotlin/org/openapitools/model/Animal.kt new file mode 100644 index 000000000000..2b9567af22c2 --- /dev/null +++ b/samples/server/others/kotlin-springboot/allOf-multilevel/src/main/kotlin/org/openapitools/model/Animal.kt @@ -0,0 +1,45 @@ +package org.openapitools.model + +import java.util.Objects +import com.fasterxml.jackson.annotation.JsonIgnoreProperties +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.annotation.JsonSetter +import com.fasterxml.jackson.annotation.JsonSubTypes +import com.fasterxml.jackson.annotation.JsonTypeInfo +import com.fasterxml.jackson.annotation.Nulls +import jakarta.validation.constraints.DecimalMax +import jakarta.validation.constraints.DecimalMin +import jakarta.validation.constraints.Email +import jakarta.validation.constraints.Max +import jakarta.validation.constraints.Min +import jakarta.validation.constraints.NotNull +import jakarta.validation.constraints.Pattern +import jakarta.validation.constraints.Size +import jakarta.validation.Valid + +/** + * + * @param className + * @param color + */ +@JsonIgnoreProperties( + value = ["className"], // ignore manually set className, it will be automatically generated by Jackson during serialization + allowSetters = true // allows the className to be set during deserialization +) +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "className", visible = true) +@JsonSubTypes( + JsonSubTypes.Type(value = BigDog::class, name = "BigDog"), + JsonSubTypes.Type(value = Cat::class, name = "Cat"), + JsonSubTypes.Type(value = Dog::class, name = "Dog") +) + +sealed interface Animal { + + val className: kotlin.String + + + val color: kotlin.String? + + +} + diff --git a/samples/server/others/kotlin-springboot/allOf-multilevel/src/main/kotlin/org/openapitools/model/BigDog.kt b/samples/server/others/kotlin-springboot/allOf-multilevel/src/main/kotlin/org/openapitools/model/BigDog.kt new file mode 100644 index 000000000000..2ecba5d1f95d --- /dev/null +++ b/samples/server/others/kotlin-springboot/allOf-multilevel/src/main/kotlin/org/openapitools/model/BigDog.kt @@ -0,0 +1,43 @@ +package org.openapitools.model + +import java.util.Objects +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.annotation.JsonSetter +import com.fasterxml.jackson.annotation.Nulls +import org.openapitools.model.Dog +import jakarta.validation.constraints.DecimalMax +import jakarta.validation.constraints.DecimalMin +import jakarta.validation.constraints.Email +import jakarta.validation.constraints.Max +import jakarta.validation.constraints.Min +import jakarta.validation.constraints.NotNull +import jakarta.validation.constraints.Pattern +import jakarta.validation.constraints.Size +import jakarta.validation.Valid + +/** + * + * @param dogType + * @param className + * @param declawed + * @param color + * @param breed + */ +data class BigDog( + + @get:JsonProperty("dogType", required = true) val dogType: kotlin.String, + + @get:JsonProperty("className", required = true) override val className: kotlin.String = "BigDog", + + @field:JsonSetter(nulls = Nulls.FAIL) + @get:JsonProperty("declawed") val declawed: kotlin.Boolean? = null, + + @field:JsonSetter(nulls = Nulls.FAIL) + @get:JsonProperty("color") override val color: kotlin.String? = "red", + + @field:JsonSetter(nulls = Nulls.FAIL) + @get:JsonProperty("breed") override val breed: kotlin.String? = null +) : Dog { + +} + diff --git a/samples/server/others/kotlin-springboot/allOf-multilevel/src/main/kotlin/org/openapitools/model/Cat.kt b/samples/server/others/kotlin-springboot/allOf-multilevel/src/main/kotlin/org/openapitools/model/Cat.kt new file mode 100644 index 000000000000..e7dba4bbc6db --- /dev/null +++ b/samples/server/others/kotlin-springboot/allOf-multilevel/src/main/kotlin/org/openapitools/model/Cat.kt @@ -0,0 +1,36 @@ +package org.openapitools.model + +import java.util.Objects +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.annotation.JsonSetter +import com.fasterxml.jackson.annotation.Nulls +import org.openapitools.model.Animal +import jakarta.validation.constraints.DecimalMax +import jakarta.validation.constraints.DecimalMin +import jakarta.validation.constraints.Email +import jakarta.validation.constraints.Max +import jakarta.validation.constraints.Min +import jakarta.validation.constraints.NotNull +import jakarta.validation.constraints.Pattern +import jakarta.validation.constraints.Size +import jakarta.validation.Valid + +/** + * + * @param className + * @param breed + * @param color + */ +data class Cat( + + @get:JsonProperty("className", required = true) override val className: kotlin.String = "Cat", + + @field:JsonSetter(nulls = Nulls.FAIL) + @get:JsonProperty("breed") val breed: kotlin.String? = null, + + @field:JsonSetter(nulls = Nulls.FAIL) + @get:JsonProperty("color") override val color: kotlin.String? = "red" +) : Animal { + +} + diff --git a/samples/server/others/kotlin-springboot/allOf-multilevel/src/main/kotlin/org/openapitools/model/Dog.kt b/samples/server/others/kotlin-springboot/allOf-multilevel/src/main/kotlin/org/openapitools/model/Dog.kt new file mode 100644 index 000000000000..f3ff2819b0de --- /dev/null +++ b/samples/server/others/kotlin-springboot/allOf-multilevel/src/main/kotlin/org/openapitools/model/Dog.kt @@ -0,0 +1,58 @@ +package org.openapitools.model + +import java.util.Objects +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.annotation.JsonSetter +import com.fasterxml.jackson.annotation.Nulls +import org.openapitools.model.Animal +import jakarta.validation.constraints.DecimalMax +import jakarta.validation.constraints.DecimalMin +import jakarta.validation.constraints.Email +import jakarta.validation.constraints.Max +import jakarta.validation.constraints.Min +import jakarta.validation.constraints.NotNull +import jakarta.validation.constraints.Pattern +import jakarta.validation.constraints.Size +import jakarta.validation.Valid + +/** + * + * @param className + * @param breed + * @param color + */ +open class Dog( + + @get:JsonProperty("className", required = true) override val className: kotlin.String = "Dog", + + @field:JsonSetter(nulls = Nulls.FAIL) + @get:JsonProperty("breed") open val breed: kotlin.String? = null, + + @field:JsonSetter(nulls = Nulls.FAIL) + @get:JsonProperty("color") override val color: kotlin.String? = "red" +) : Animal { + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other?.javaClass != javaClass) return false + other as Dog + return className == other.className + && color == other.color + && breed == other.breed + } + + override fun hashCode(): Int { + return Objects.hash(className, color, breed) + } + + override fun toString(): String { + return "Dog(className=$className, color=$color, breed=$breed)" + } + + fun copy( + className: kotlin.String = this.className, + color: kotlin.String? = this.color, + breed: kotlin.String? = this.breed + ): Dog = Dog(className = className, color = color, breed = breed) + +} + diff --git a/samples/server/petstore/kotlin-springboot-include-http-request-context-delegate/src/main/kotlin/org/openapitools/model/Cat.kt b/samples/server/petstore/kotlin-springboot-include-http-request-context-delegate/src/main/kotlin/org/openapitools/model/Cat.kt index 9c4d77f6a75e..deaa14834ead 100644 --- a/samples/server/petstore/kotlin-springboot-include-http-request-context-delegate/src/main/kotlin/org/openapitools/model/Cat.kt +++ b/samples/server/petstore/kotlin-springboot-include-http-request-context-delegate/src/main/kotlin/org/openapitools/model/Cat.kt @@ -42,7 +42,7 @@ data class Cat( @get:JsonProperty("photoUrls", required = true) override val photoUrls: kotlin.collections.List, @ApiModelProperty(example = "null", required = true, value = "") - @get:JsonProperty("petType", required = true) override val petType: kotlin.String, + @get:JsonProperty("petType", required = true) override val petType: kotlin.String = "Cat", @ApiModelProperty(example = "null", value = "") @field:JsonSetter(nulls = Nulls.FAIL) diff --git a/samples/server/petstore/kotlin-springboot-include-http-request-context-delegate/src/main/kotlin/org/openapitools/model/Dog.kt b/samples/server/petstore/kotlin-springboot-include-http-request-context-delegate/src/main/kotlin/org/openapitools/model/Dog.kt index 302fa2eff7d4..ae6c42110f0b 100644 --- a/samples/server/petstore/kotlin-springboot-include-http-request-context-delegate/src/main/kotlin/org/openapitools/model/Dog.kt +++ b/samples/server/petstore/kotlin-springboot-include-http-request-context-delegate/src/main/kotlin/org/openapitools/model/Dog.kt @@ -52,7 +52,7 @@ data class Dog( @get:JsonProperty("photoUrls", required = true) override val photoUrls: kotlin.collections.List, @ApiModelProperty(example = "null", required = true, value = "") - @get:JsonProperty("petType", required = true) override val petType: kotlin.String, + @get:JsonProperty("petType", required = true) override val petType: kotlin.String = "Dog", @ApiModelProperty(example = "null", value = "") @field:JsonSetter(nulls = Nulls.FAIL) diff --git a/samples/server/petstore/kotlin-springboot-include-http-request-context-delegate/src/main/kotlin/org/openapitools/model/Pet.kt b/samples/server/petstore/kotlin-springboot-include-http-request-context-delegate/src/main/kotlin/org/openapitools/model/Pet.kt index bad6273edeec..5d923749553e 100644 --- a/samples/server/petstore/kotlin-springboot-include-http-request-context-delegate/src/main/kotlin/org/openapitools/model/Pet.kt +++ b/samples/server/petstore/kotlin-springboot-include-http-request-context-delegate/src/main/kotlin/org/openapitools/model/Pet.kt @@ -43,7 +43,7 @@ import io.swagger.annotations.ApiModelProperty JsonSubTypes.Type(value = Dog::class, name = "Dog") ) -interface Pet : com.some.pack.Named, com.some.pack.WithCategory, com.some.pack.WithDefaultMethods, com.some.pack.WithPhotoUrls, java.io.Serializable { +sealed interface Pet : com.some.pack.Named, com.some.pack.WithCategory, com.some.pack.WithDefaultMethods, com.some.pack.WithPhotoUrls, java.io.Serializable { @get:ApiModelProperty(example = "null", required = true, value = "") override val name: kotlin.String diff --git a/samples/server/petstore/kotlin-springboot-x-kotlin-implements/src/main/kotlin/org/openapitools/model/Cat.kt b/samples/server/petstore/kotlin-springboot-x-kotlin-implements/src/main/kotlin/org/openapitools/model/Cat.kt index 9c4d77f6a75e..deaa14834ead 100644 --- a/samples/server/petstore/kotlin-springboot-x-kotlin-implements/src/main/kotlin/org/openapitools/model/Cat.kt +++ b/samples/server/petstore/kotlin-springboot-x-kotlin-implements/src/main/kotlin/org/openapitools/model/Cat.kt @@ -42,7 +42,7 @@ data class Cat( @get:JsonProperty("photoUrls", required = true) override val photoUrls: kotlin.collections.List, @ApiModelProperty(example = "null", required = true, value = "") - @get:JsonProperty("petType", required = true) override val petType: kotlin.String, + @get:JsonProperty("petType", required = true) override val petType: kotlin.String = "Cat", @ApiModelProperty(example = "null", value = "") @field:JsonSetter(nulls = Nulls.FAIL) diff --git a/samples/server/petstore/kotlin-springboot-x-kotlin-implements/src/main/kotlin/org/openapitools/model/Dog.kt b/samples/server/petstore/kotlin-springboot-x-kotlin-implements/src/main/kotlin/org/openapitools/model/Dog.kt index 3227118e8756..33ecfe0648f9 100644 --- a/samples/server/petstore/kotlin-springboot-x-kotlin-implements/src/main/kotlin/org/openapitools/model/Dog.kt +++ b/samples/server/petstore/kotlin-springboot-x-kotlin-implements/src/main/kotlin/org/openapitools/model/Dog.kt @@ -52,7 +52,7 @@ data class Dog( @get:JsonProperty("photoUrls", required = true) override val photoUrls: kotlin.collections.List, @ApiModelProperty(example = "null", required = true, value = "") - @get:JsonProperty("petType", required = true) override val petType: kotlin.String, + @get:JsonProperty("petType", required = true) override val petType: kotlin.String = "Dog", @ApiModelProperty(example = "null", value = "") @field:JsonSetter(nulls = Nulls.FAIL) diff --git a/samples/server/petstore/kotlin-springboot-x-kotlin-implements/src/main/kotlin/org/openapitools/model/Pet.kt b/samples/server/petstore/kotlin-springboot-x-kotlin-implements/src/main/kotlin/org/openapitools/model/Pet.kt index df7bfc8367c9..05a19d715420 100644 --- a/samples/server/petstore/kotlin-springboot-x-kotlin-implements/src/main/kotlin/org/openapitools/model/Pet.kt +++ b/samples/server/petstore/kotlin-springboot-x-kotlin-implements/src/main/kotlin/org/openapitools/model/Pet.kt @@ -43,7 +43,7 @@ import io.swagger.annotations.ApiModelProperty JsonSubTypes.Type(value = Dog::class, name = "Dog") ) -interface Pet : com.some.pack.Named, com.some.pack.WithCategory, com.some.pack.WithDefaultMethods, com.some.pack.WithId, java.io.Serializable { +sealed interface Pet : com.some.pack.Named, com.some.pack.WithCategory, com.some.pack.WithDefaultMethods, com.some.pack.WithId, java.io.Serializable { @get:ApiModelProperty(example = "null", required = true, value = "") override val name: kotlin.String