From 4602f18ca810b9c91e9e6a9afb8bbe5dad1b2a14 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Wed, 2 Aug 2023 10:06:11 +0800 Subject: [PATCH 001/292] Add model name mapping feature to C# codegen (#16209) * add model name mapping feature to C# codegen * rename file * update samples * update doc --- ...sharp-restsharp-net6.0-name-mappings.yaml} | 3 + docs/customization.md | 11 +- .../openapitools/codegen/cmd/ConfigHelp.java | 15 ++ .../openapitools/codegen/cmd/Generate.java | 8 ++ .../codegen/config/GeneratorSettings.java | 45 ++++++ .../OpenApiGeneratorGenerateExtension.kt | 5 + .../gradle/plugin/tasks/GenerateTask.kt | 13 ++ .../codegen/plugin/CodeGenMojo.java | 11 ++ .../openapitools/codegen/CodegenConfig.java | 2 + .../openapitools/codegen/DefaultCodegen.java | 12 ++ .../codegen/config/CodegenConfigurator.java | 17 +++ .../config/CodegenConfiguratorUtils.java | 13 ++ .../languages/AbstractCSharpCodegen.java | 47 ++++--- .../3_0/name-parameter-mappings.yaml | 8 ++ .../.openapi-generator/FILES | 2 + .../README.md | 4 +- .../api/openapi.yaml | 10 ++ .../docs/Env.md | 10 ++ .../docs/FakeApi.md | 14 +- .../Org.OpenAPITools.Test/Model/EnvTests.cs | 66 +++++++++ .../Org.OpenAPITools.Test.csproj | 2 +- .../src/Org.OpenAPITools/Api/FakeApi.cs | 45 +++--- .../src/Org.OpenAPITools/Model/Env.cs | 128 ++++++++++++++++++ .../Org.OpenAPITools/Org.OpenAPITools.csproj | 2 +- .../.openapi-generator/FILES | 2 + .../kotlin-name-parameter-mappings/README.md | 1 + .../docs/Environment.md | 10 ++ .../docs/FakeApi.md | 9 +- .../org/openapitools/client/apis/FakeApi.kt | 18 ++- .../openapitools/client/models/Environment.kt | 35 +++++ 30 files changed, 509 insertions(+), 59 deletions(-) rename bin/configs/{csharp-restsharp-name-mappings.yaml => csharp-restsharp-net6.0-name-mappings.yaml} (90%) create mode 100644 samples/client/petstore/csharp-restsharp-name-parameter-mappings/docs/Env.md create mode 100644 samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools.Test/Model/EnvTests.cs create mode 100644 samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools/Model/Env.cs create mode 100644 samples/client/petstore/kotlin-name-parameter-mappings/docs/Environment.md create mode 100644 samples/client/petstore/kotlin-name-parameter-mappings/src/main/kotlin/org/openapitools/client/models/Environment.kt diff --git a/bin/configs/csharp-restsharp-name-mappings.yaml b/bin/configs/csharp-restsharp-net6.0-name-mappings.yaml similarity index 90% rename from bin/configs/csharp-restsharp-name-mappings.yaml rename to bin/configs/csharp-restsharp-net6.0-name-mappings.yaml index 6e87c97a2e05..56af6a800cb7 100644 --- a/bin/configs/csharp-restsharp-name-mappings.yaml +++ b/bin/configs/csharp-restsharp-net6.0-name-mappings.yaml @@ -10,6 +10,9 @@ parameterNameMappings: _type: UnderscoreType type_: TypeWithUnderscore http_debug_operation: HttpDebugOperation +modelNameMappings: + Environment: Env additionalProperties: packageGuid: '{321C8C3F-0156-40C1-AE42-D59761FB9B6C}' hideGenerationTimestamp: "true" + targetFramework: net6.0 diff --git a/docs/customization.md b/docs/customization.md index 72522ee48bf4..ea91e18c4bc3 100644 --- a/docs/customization.md +++ b/docs/customization.md @@ -416,7 +416,16 @@ Here is an example to use `nameMappings` and `parameterNameMapping` in CLI: java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generate -g java -i modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-okhttp-gson.yaml -o /tmp/java2/ --name-mappings _type=underscoreType, type_=typeWithUnderscore, --parameter-name-mappings _type=paramType, type_=typeParam ``` -(Not all generators support this feature yet. Please give it a try to confirm the behaviour and open an issue (ticket) to let us know which generators you would like to have this feature enabled and we'll prioritize accordingly.) +To map model names, use `modelNameMappings` option, e.g. +```sh +java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generate -g csharp -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -o /tmp/csharp/ --model-name-mappings Tag=Label +``` +will rename the Tag schema to Label instead. + + +(Not all generators support thess features yet. Please give it a try to confirm the behaviour and open an issue (ticket) to let us know which generators you would like to have this feature enabled and we'll prioritize accordingly.) + +Related PRs: #16209 (modelNameMappings), #16194, #16206 (nameMappings, parameterNameMappings) ## Schema Mapping diff --git a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/ConfigHelp.java b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/ConfigHelp.java index 2871642347ad..fd379374fba5 100644 --- a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/ConfigHelp.java +++ b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/ConfigHelp.java @@ -86,6 +86,9 @@ public class ConfigHelp extends OpenApiGeneratorCommand { @Option(name = {"--parameter-name-mappings"}, title = "parameter name mappings", description = "displays the parameter name mappings (none)") private Boolean parameterNameMappings; + @Option(name = {"--model-name-mappings"}, title = "model name mappings", description = "displays the model name mappings (none)") + private Boolean modelNameMappings; + @Option(name = {"--openapi-normalizer"}, title = "openapi normalizer rules", description = "displays the OpenAPI normalizer rules (none)") private Boolean openapiNormalizer; @@ -527,6 +530,18 @@ private void generatePlainTextHelp(StringBuilder sb, CodegenConfig config) { sb.append(newline); } + if (Boolean.TRUE.equals(modelNameMappings)) { + sb.append(newline).append("MODEL NAME MAPPING").append(newline).append(newline); + Map map = config.modelNameMapping() + .entrySet() + .stream() + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> { + throw new IllegalStateException(String.format(Locale.ROOT, "Duplicated options! %s and %s", a, b)); + }, TreeMap::new)); + writePlainTextFromMap(sb, map, optIndent, optNestedIndent, "model name", "Mapped to"); + sb.append(newline); + } + if (Boolean.TRUE.equals(openapiNormalizer)) { sb.append(newline).append("OPENAPI NORMALIZER RULES").append(newline).append(newline); Map map = config.openapiNormalizer() diff --git a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Generate.java b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Generate.java index c64e44757c4b..7d4ed09e27b1 100644 --- a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Generate.java +++ b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Generate.java @@ -202,6 +202,13 @@ public class Generate extends OpenApiGeneratorCommand { + " You can also have multiple occurrences of this option.") private List parameterNameMappings = new ArrayList<>(); + @Option( + name = {"--model-name-mappings"}, + title = "model name mappings", + description = "specifies mappings between the model name and the new name in the format of model_name=AnotherName,model_name2=OtherName2." + + " You can also have multiple occurrences of this option.") + private List modelNameMappings = new ArrayList<>(); + @Option( name = {"--openapi-normalizer"}, title = "OpenAPI normalizer rules", @@ -484,6 +491,7 @@ public void execute() { applyInlineSchemaOptionsKvpList(inlineSchemaOptions, configurator); applyNameMappingsKvpList(nameMappings, configurator); applyParameterNameMappingsKvpList(parameterNameMappings, configurator); + applyModelNameMappingsKvpList(modelNameMappings, configurator); applyOpenAPINormalizerKvpList(openapiNormalizer, configurator); applyTypeMappingsKvpList(typeMappings, configurator); applyAdditionalPropertiesKvpList(additionalProperties, configurator); diff --git a/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/config/GeneratorSettings.java b/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/config/GeneratorSettings.java index 4b5b41dd1bee..3aaaccf16339 100644 --- a/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/config/GeneratorSettings.java +++ b/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/config/GeneratorSettings.java @@ -55,6 +55,7 @@ public final class GeneratorSettings implements Serializable { private final Map inlineSchemaOptions; private final Map nameMappings; private final Map parameterNameMappings; + private final Map modelNameMappings; private final Map openapiNormalizer; private final Set languageSpecificPrimitives; private final Map reservedWordsMappings; @@ -285,6 +286,15 @@ public Map getParameterNameMappings() { return parameterNameMappings; } + /** + * Gets model name mappings between a model name and the new name. + * + * @return the model name mappings + */ + public Map getModelNameMappings() { + return modelNameMappings; + } + /** * Gets OpenAPI normalizer rules * @@ -414,6 +424,7 @@ private GeneratorSettings(Builder builder) { inlineSchemaOptions = Collections.unmodifiableMap(builder.inlineSchemaOptions); nameMappings = Collections.unmodifiableMap(builder.nameMappings); parameterNameMappings = Collections.unmodifiableMap(builder.parameterNameMappings); + modelNameMappings = Collections.unmodifiableMap(builder.modelNameMappings); openapiNormalizer = Collections.unmodifiableMap(builder.openapiNormalizer); languageSpecificPrimitives = Collections.unmodifiableSet(builder.languageSpecificPrimitives); reservedWordsMappings = Collections.unmodifiableMap(builder.reservedWordsMappings); @@ -490,6 +501,7 @@ public GeneratorSettings() { inlineSchemaOptions = Collections.unmodifiableMap(new HashMap<>(0)); nameMappings = Collections.unmodifiableMap(new HashMap<>(0)); parameterNameMappings = Collections.unmodifiableMap(new HashMap<>(0)); + modelNameMappings = Collections.unmodifiableMap(new HashMap<>(0)); openapiNormalizer = Collections.unmodifiableMap(new HashMap<>(0)); languageSpecificPrimitives = Collections.unmodifiableSet(new HashSet<>(0)); reservedWordsMappings = Collections.unmodifiableMap(new HashMap<>(0)); @@ -557,6 +569,9 @@ public static Builder newBuilder(GeneratorSettings copy) { if (copy.getParameterNameMappings() != null) { builder.parameterNameMappings.putAll(copy.getParameterNameMappings()); } + if (copy.getModelNameMappings() != null) { + builder.modelNameMappings.putAll(copy.getModelNameMappings()); + } if (copy.getOpenAPINormalizer() != null) { builder.openapiNormalizer.putAll(copy.getOpenAPINormalizer()); } @@ -604,6 +619,7 @@ public static final class Builder { private Map inlineSchemaOptions; private Map nameMappings; private Map parameterNameMappings; + private Map modelNameMappings; private Map openapiNormalizer; private Set languageSpecificPrimitives; private Map reservedWordsMappings; @@ -627,6 +643,7 @@ public Builder() { inlineSchemaOptions = new HashMap<>(); nameMappings = new HashMap<>(); parameterNameMappings = new HashMap<>(); + modelNameMappings = new HashMap<>(); openapiNormalizer = new HashMap<>(); languageSpecificPrimitives = new HashSet<>(); reservedWordsMappings = new HashMap<>(); @@ -1000,6 +1017,32 @@ public Builder withParameterNameMapping(String key, String value) { return this; } + /** + * Sets the {@code modelNameMappings} and returns a reference to this Builder so that the methods can be chained together. + * + * @param modelNameMappings the {@code modelNameMappings} to set + * @return a reference to this Builder + */ + public Builder withModelNameMappings(Map modelNameMappings) { + this.modelNameMappings = modelNameMappings; + return this; + } + + /** + * Sets a single {@code modelNameMappings} and returns a reference to this Builder so that the methods can be chained together. + * + * @param key A key for the name mapping + * @param value The value of name mapping + * @return a reference to this Builder + */ + public Builder withModelNameMapping(String key, String value) { + if (this.modelNameMappings == null) { + this.modelNameMappings = new HashMap<>(); + } + this.modelNameMappings.put(key, value); + return this; + } + /** * Sets the {@code openapiNormalizer} and returns a reference to this Builder so that the methods can be chained together. * @@ -1216,6 +1259,7 @@ public boolean equals(Object o) { Objects.equals(getInlineSchemaOptions(), that.getInlineSchemaOptions()) && Objects.equals(getNameMappings(), that.getNameMappings()) && Objects.equals(getParameterNameMappings(), that.getParameterNameMappings()) && + Objects.equals(getModelNameMappings(), that.getModelNameMappings()) && Objects.equals(getOpenAPINormalizer(), that.getOpenAPINormalizer()) && Objects.equals(getLanguageSpecificPrimitives(), that.getLanguageSpecificPrimitives()) && Objects.equals(getReservedWordsMappings(), that.getReservedWordsMappings()) && @@ -1250,6 +1294,7 @@ public int hashCode() { getInlineSchemaOptions(), getNameMappings(), getParameterNameMappings(), + getModelNameMappings(), getOpenAPINormalizer(), getLanguageSpecificPrimitives(), getReservedWordsMappings(), diff --git a/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/extensions/OpenApiGeneratorGenerateExtension.kt b/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/extensions/OpenApiGeneratorGenerateExtension.kt index 76c89b263e14..04e654942b6d 100644 --- a/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/extensions/OpenApiGeneratorGenerateExtension.kt +++ b/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/extensions/OpenApiGeneratorGenerateExtension.kt @@ -177,6 +177,11 @@ open class OpenApiGeneratorGenerateExtension(project: Project) { */ val parameterNameMappings = project.objects.mapProperty() + /** + * Specifies mappings between a model name and the new name + */ + val modelNameMappings = project.objects.mapProperty() + /** * Specifies mappings (rules) in OpenAPI normalizer */ diff --git a/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/GenerateTask.kt b/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/GenerateTask.kt index a4fa91b375f6..bb2380d0a613 100644 --- a/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/GenerateTask.kt +++ b/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/GenerateTask.kt @@ -286,6 +286,13 @@ open class GenerateTask @Inject constructor(private val objectFactory: ObjectFac @Input val parameterNameMappings = project.objects.mapProperty() + /** + * Specifies mappings between the model name and the new name + */ + @Optional + @Input + val modelNameMappings = project.objects.mapProperty() + /** * Specifies mappings (rules) in OpenAPI normalizer */ @@ -833,6 +840,12 @@ open class GenerateTask @Inject constructor(private val objectFactory: ObjectFac } } + if (modelNameMappings.isPresent) { + modelNameMappings.get().forEach { entry -> + configurator.addModelNameMapping(entry.key, entry.value) + } + } + if (openapiNormalizer.isPresent) { openapiNormalizer.get().forEach { entry -> configurator.addOpenAPINormalizer(entry.key, entry.value) diff --git a/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java b/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java index d887357349f1..b45318b9f853 100644 --- a/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java +++ b/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java @@ -344,6 +344,12 @@ public class CodeGenMojo extends AbstractMojo { @Parameter(name = "parameterNameMappings", property = "openapi.generator.maven.plugin.parameterNameMappings") private List parameterNameMappings; + /** + * A map of model names and the new names + */ + @Parameter(name = "modelNameMappings", property = "openapi.generator.maven.plugin.modelNameMappings") + private List modelNameMappings; + /** * A set of rules for OpenAPI normalizer */ @@ -823,6 +829,11 @@ public void execute() throws MojoExecutionException { applyParameterNameMappingsKvpList(parameterNameMappings, configurator); } + // Apply Model Name Mappings + if (modelNameMappings != null && (configOptions == null || !configOptions.containsKey("model-name-mappings"))) { + applyModelNameMappingsKvpList(modelNameMappings, configurator); + } + // Apply OpenAPI normalizer rules if (openapiNormalizer != null && (configOptions == null || !configOptions.containsKey("openapi-normalizer"))) { applyOpenAPINormalizerKvpList(openapiNormalizer, configurator); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java index 5bcd76b73754..0b0b3b8a8872 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java @@ -151,6 +151,8 @@ public interface CodegenConfig { Map parameterNameMapping(); + Map modelNameMapping(); + Map openapiNormalizer(); Map apiTemplateFiles(); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java index a412b96eb70c..082f378c695b 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java @@ -168,6 +168,8 @@ public class DefaultCodegen implements CodegenConfig { protected Map nameMapping = new HashMap<>(); // a map to store the mapping between parameter name and the name provided by the user protected Map parameterNameMapping = new HashMap<>(); + // a map to store the mapping between model name and the name provided by the user + protected Map modelNameMapping = new HashMap<>(); // a map to store the rules in OpenAPI Normalizer protected Map openapiNormalizer = new HashMap<>(); protected String modelPackage = "", apiPackage = "", fileSuffix; @@ -1213,6 +1215,11 @@ public Map parameterNameMapping() { return parameterNameMapping; } + @Override + public Map modelNameMapping() { + return modelNameMapping; + } + @Override public Map openapiNormalizer() { return openapiNormalizer; @@ -2616,6 +2623,11 @@ public String toApiName(String name) { */ @Override public String toModelName(final String name) { + // obtain the name from modelNameMapping directly if provided + if (modelNameMapping.containsKey(name)) { + return modelNameMapping.get(name); + } + if (schemaKeyToModelNameCache.containsKey(name)) { return schemaKeyToModelNameCache.get(name); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java index c2268ab79eb5..f494204a184c 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java @@ -73,6 +73,7 @@ public class CodegenConfigurator { private Map inlineSchemaOptions = new HashMap<>(); private Map nameMappings = new HashMap<>(); private Map parameterNameMappings = new HashMap<>(); + private Map modelNameMappings = new HashMap<>(); private Map openapiNormalizer = new HashMap<>(); private Set languageSpecificPrimitives = new HashSet<>(); private Map reservedWordsMappings = new HashMap<>(); @@ -132,6 +133,9 @@ public static CodegenConfigurator fromFile(String configFile, Module... modules) if(generatorSettings.getParameterNameMappings() != null) { configurator.parameterNameMappings.putAll(generatorSettings.getParameterNameMappings()); } + if(generatorSettings.getModelNameMappings() != null) { + configurator.modelNameMappings.putAll(generatorSettings.getModelNameMappings()); + } if(generatorSettings.getOpenAPINormalizer() != null) { configurator.openapiNormalizer.putAll(generatorSettings.getOpenAPINormalizer()); } @@ -234,6 +238,12 @@ public CodegenConfigurator addParameterNameMapping(String key, String value) { return this; } + public CodegenConfigurator addModelNameMapping(String key, String value) { + this.modelNameMappings.put(key, value); + generatorSettingsBuilder.withModelNameMapping(key, value); + return this; + } + public CodegenConfigurator addOpenAPINormalizer(String key, String value) { this.openapiNormalizer.put(key, value); generatorSettingsBuilder.withOpenAPINormalizer(key, value); @@ -424,6 +434,12 @@ public CodegenConfigurator setParameterNameMappings(Map paramete return this; } + public CodegenConfigurator setModelNameMappings(Map modelNameMappings) { + this.modelNameMappings = modelNameMappings; + generatorSettingsBuilder.withModelNameMappings(modelNameMappings); + return this; + } + public CodegenConfigurator setOpenAPINormalizer(Map openapiNormalizer) { this.openapiNormalizer = openapiNormalizer; generatorSettingsBuilder.withOpenAPINormalizer(openapiNormalizer); @@ -711,6 +727,7 @@ public ClientOptInput toClientOptInput() { config.inlineSchemaOption().putAll(generatorSettings.getInlineSchemaOptions()); config.nameMapping().putAll(generatorSettings.getNameMappings()); config.parameterNameMapping().putAll(generatorSettings.getParameterNameMappings()); + config.modelNameMapping().putAll(generatorSettings.getModelNameMappings()); config.openapiNormalizer().putAll(generatorSettings.getOpenAPINormalizer()); config.languageSpecificPrimitives().addAll(generatorSettings.getLanguageSpecificPrimitives()); config.reservedWordsMappings().putAll(generatorSettings.getReservedWordsMappings()); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfiguratorUtils.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfiguratorUtils.java index 32c921c7f7c3..c6a871b7c42e 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfiguratorUtils.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfiguratorUtils.java @@ -146,6 +146,19 @@ public static void applyParameterNameMappingsKvp(String parameterNameMappings, C } } + public static void applyModelNameMappingsKvpList(List modelNameMappings, CodegenConfigurator configurator) { + for (String propString : modelNameMappings) { + applyModelNameMappingsKvp(propString, configurator); + } + } + + public static void applyModelNameMappingsKvp(String modelNameMappings, CodegenConfigurator configurator) { + final Map map = createMapFromKeyValuePairs(modelNameMappings); + for (Map.Entry entry : map.entrySet()) { + configurator.addModelNameMapping(entry.getKey().trim(), entry.getValue().trim()); + } + } + public static void applyOpenAPINormalizerKvpList(List openapiNormalizer, CodegenConfigurator configurator) { for (String propString : openapiNormalizer) { applyOpenAPINormalizerKvp(propString, configurator); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCSharpCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCSharpCodegen.java index a37f70e7b343..fac84740841c 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCSharpCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCSharpCodegen.java @@ -521,10 +521,10 @@ public Map postProcessAllModels(Map objs) // GrandparentAnimal has a discriminator, but no oneOf nor anyOf // modules\openapi-generator\src\test\resources\3_0\csharp\petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml model.setHasDiscriminatorWithNonEmptyMapping( - ((model.anyOf != null && model.anyOf.size() > 0) || (model.anyOf != null &&model.oneOf.size() > 0)) && - model.discriminator != null && - model.discriminator.getMappedModels() != null && - model.discriminator.getMappedModels().size() > 0); + ((model.anyOf != null && model.anyOf.size() > 0) || (model.anyOf != null && model.oneOf.size() > 0)) && + model.discriminator != null && + model.discriminator.getMappedModels() != null && + model.discriminator.getMappedModels().size() > 0); if (model.isEnum) { enumRefs.put(model.getClassname(), model); @@ -539,7 +539,7 @@ public Map postProcessAllModels(Map objs) if (composedSchemas != null) { List allOf = composedSchemas.getAllOf(); if (allOf != null) { - for(CodegenProperty property : allOf) { + for (CodegenProperty property : allOf) { property.name = patchPropertyName(model, property.baseType); patchPropertyVendorExtensinos(property); } @@ -548,7 +548,7 @@ public Map postProcessAllModels(Map objs) List anyOf = composedSchemas.getAnyOf(); if (anyOf != null) { removePropertiesDeclaredInComposedTypes(objs, model, anyOf); - for(CodegenProperty property : anyOf) { + for (CodegenProperty property : anyOf) { property.name = patchPropertyName(model, property.baseType); property.isNullable = true; patchPropertyVendorExtensinos(property); @@ -558,7 +558,7 @@ public Map postProcessAllModels(Map objs) List oneOf = composedSchemas.getOneOf(); if (oneOf != null) { removePropertiesDeclaredInComposedTypes(objs, model, oneOf); - for(CodegenProperty property : oneOf) { + for (CodegenProperty property : oneOf) { property.name = patchPropertyName(model, property.baseType); property.isNullable = true; patchPropertyVendorExtensinos(property); @@ -598,10 +598,10 @@ public Map postProcessAllModels(Map objs) } /** - * Returns true if the model contains any properties with a public setter - * If true, the model's constructor accessor should be made public to ensure end users - * can instantiate the object. If false, then the model is only ever given - * to us by the server, so we do not need a public constructor + * Returns true if the model contains any properties with a public setter + * If true, the model's constructor accessor should be made public to ensure end users + * can instantiate the object. If false, then the model is only ever given + * to us by the server, so we do not need a public constructor */ private boolean modelIsMutatable(CodegenModel model, Set processed) { if (processed == null) { @@ -850,14 +850,18 @@ protected void patchVendorExtensionNullableValueType(CodegenParameter parameter) } } - /** Returns the model related to the given parameter */ + /** + * Returns the model related to the given parameter + */ private CodegenModel getModelFromParameter(List allModels, CodegenParameter parameter) { return parameter.isModel - ? allModels.stream().map(m -> m.getModel()).filter(m -> m.getClassname().equals(parameter.dataType)).findFirst().orElse(null) - : null; + ? allModels.stream().map(m -> m.getModel()).filter(m -> m.getClassname().equals(parameter.dataType)).findFirst().orElse(null) + : null; } - /** This is the same as patchVendorExtensionNullableValueType except it uses the deprecated getNullableTypes property */ + /** + * This is the same as patchVendorExtensionNullableValueType except it uses the deprecated getNullableTypes property + */ protected void patchVendorExtensionNullableValueTypeLegacy(CodegenParameter parameter) { if (parameter.isNullable && !parameter.isContainer && (this.getNullableTypes().contains(parameter.dataType) || parameter.isEnum)) { parameter.vendorExtensions.put("x-nullable-value-type", true); @@ -1021,8 +1025,8 @@ public String escapeReservedWord(CodegenModel model, String name) { name = this.escapeReservedWord(name); return name.equalsIgnoreCase(model.getClassname()) - ? this.invalidNamePrefix + camelize(name) - : name; + ? this.invalidNamePrefix + camelize(name) + : name; } @Override @@ -1046,8 +1050,8 @@ public String escapeReservedWord(String name) { @Override public String toExampleValue(Schema p) { return p.getExample() == null - ? null - : p.getExample().toString(); + ? null + : p.getExample().toString(); } /** @@ -1176,6 +1180,11 @@ public String getTypeDeclaration(Schema p) { @Override public String toModelName(String name) { + // obtain the name from modelNameMapping directly if provided + if (modelNameMapping.containsKey(name)) { + return modelNameMapping.get(name); + } + // We need to check if schema-mapping has a different model for this class, so we use it // instead of the auto-generated one. if (schemaMapping.containsKey(name)) { diff --git a/modules/openapi-generator/src/test/resources/3_0/name-parameter-mappings.yaml b/modules/openapi-generator/src/test/resources/3_0/name-parameter-mappings.yaml index 35830d7824fa..bcbe90b2dfe5 100644 --- a/modules/openapi-generator/src/test/resources/3_0/name-parameter-mappings.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/name-parameter-mappings.yaml @@ -42,8 +42,16 @@ paths: responses: 200: description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/Environment' components: schemas: + Environment: + properties: + dummy: + type: string PropertyNameMapping: properties: http_debug_operation: diff --git a/samples/client/petstore/csharp-restsharp-name-parameter-mappings/.openapi-generator/FILES b/samples/client/petstore/csharp-restsharp-name-parameter-mappings/.openapi-generator/FILES index 6c5ad7b08bd3..7ba297eae0fc 100644 --- a/samples/client/petstore/csharp-restsharp-name-parameter-mappings/.openapi-generator/FILES +++ b/samples/client/petstore/csharp-restsharp-name-parameter-mappings/.openapi-generator/FILES @@ -3,6 +3,7 @@ Org.OpenAPITools.sln README.md api/openapi.yaml appveyor.yml +docs/Env.md docs/FakeApi.md docs/PropertyNameMapping.md git_push.sh @@ -25,5 +26,6 @@ src/Org.OpenAPITools/Client/OpenAPIDateConverter.cs src/Org.OpenAPITools/Client/RequestOptions.cs src/Org.OpenAPITools/Client/RetryConfiguration.cs src/Org.OpenAPITools/Model/AbstractOpenAPISchema.cs +src/Org.OpenAPITools/Model/Env.cs src/Org.OpenAPITools/Model/PropertyNameMapping.cs src/Org.OpenAPITools/Org.OpenAPITools.csproj diff --git a/samples/client/petstore/csharp-restsharp-name-parameter-mappings/README.md b/samples/client/petstore/csharp-restsharp-name-parameter-mappings/README.md index d9c2ce3ca203..5cc4dbc8109c 100644 --- a/samples/client/petstore/csharp-restsharp-name-parameter-mappings/README.md +++ b/samples/client/petstore/csharp-restsharp-name-parameter-mappings/README.md @@ -94,7 +94,8 @@ namespace Example try { // parameter name mapping test - apiInstance.GetParameterNameMapping(UnderscoreType, type, TypeWithUnderscore, httpDebugOption); + Env result = apiInstance.GetParameterNameMapping(UnderscoreType, type, TypeWithUnderscore, httpDebugOption); + Debug.WriteLine(result); } catch (ApiException e) { @@ -121,6 +122,7 @@ Class | Method | HTTP request | Description ## Documentation for Models + - [Model.Env](docs/Env.md) - [Model.PropertyNameMapping](docs/PropertyNameMapping.md) diff --git a/samples/client/petstore/csharp-restsharp-name-parameter-mappings/api/openapi.yaml b/samples/client/petstore/csharp-restsharp-name-parameter-mappings/api/openapi.yaml index 68780421d1f6..fbb5fb24974c 100644 --- a/samples/client/petstore/csharp-restsharp-name-parameter-mappings/api/openapi.yaml +++ b/samples/client/petstore/csharp-restsharp-name-parameter-mappings/api/openapi.yaml @@ -48,12 +48,22 @@ paths: style: form responses: "200": + content: + application/json: + schema: + $ref: '#/components/schemas/Environment' description: OK summary: parameter name mapping test tags: - fake components: schemas: + Environment: + example: + dummy: dummy + properties: + dummy: + type: string PropertyNameMapping: properties: http_debug_operation: diff --git a/samples/client/petstore/csharp-restsharp-name-parameter-mappings/docs/Env.md b/samples/client/petstore/csharp-restsharp-name-parameter-mappings/docs/Env.md new file mode 100644 index 000000000000..c9c69c0f23a2 --- /dev/null +++ b/samples/client/petstore/csharp-restsharp-name-parameter-mappings/docs/Env.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.Env + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Dummy** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-restsharp-name-parameter-mappings/docs/FakeApi.md b/samples/client/petstore/csharp-restsharp-name-parameter-mappings/docs/FakeApi.md index 2aa6ced4c785..38edc53dab9a 100644 --- a/samples/client/petstore/csharp-restsharp-name-parameter-mappings/docs/FakeApi.md +++ b/samples/client/petstore/csharp-restsharp-name-parameter-mappings/docs/FakeApi.md @@ -8,7 +8,7 @@ All URIs are relative to *http://localhost* # **GetParameterNameMapping** -> void GetParameterNameMapping (long UnderscoreType, string type, string TypeWithUnderscore, string httpDebugOption) +> Env GetParameterNameMapping (long UnderscoreType, string type, string TypeWithUnderscore, string httpDebugOption) parameter name mapping test @@ -37,7 +37,8 @@ namespace Example try { // parameter name mapping test - apiInstance.GetParameterNameMapping(UnderscoreType, type, TypeWithUnderscore, httpDebugOption); + Env result = apiInstance.GetParameterNameMapping(UnderscoreType, type, TypeWithUnderscore, httpDebugOption); + Debug.WriteLine(result); } catch (ApiException e) { @@ -57,7 +58,10 @@ This returns an ApiResponse object which contains the response data, status code try { // parameter name mapping test - apiInstance.GetParameterNameMappingWithHttpInfo(UnderscoreType, type, TypeWithUnderscore, httpDebugOption); + ApiResponse response = apiInstance.GetParameterNameMappingWithHttpInfo(UnderscoreType, type, TypeWithUnderscore, httpDebugOption); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); } catch (ApiException e) { @@ -78,7 +82,7 @@ catch (ApiException e) ### Return type -void (empty response body) +[**Env**](Env.md) ### Authorization @@ -87,7 +91,7 @@ No authorization required ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: Not defined + - **Accept**: application/json ### HTTP response details diff --git a/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools.Test/Model/EnvTests.cs b/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools.Test/Model/EnvTests.cs new file mode 100644 index 000000000000..9da726a22bc4 --- /dev/null +++ b/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools.Test/Model/EnvTests.cs @@ -0,0 +1,66 @@ +/* + * Dummy + * + * To test name, parameter mapping options + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Env + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class EnvTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Env + //private Env instance; + + public EnvTests() + { + // TODO uncomment below to create an instance of Env + //instance = new Env(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Env + /// + [Fact] + public void EnvInstanceTest() + { + // TODO uncomment below to test "IsType" Env + //Assert.IsType(instance); + } + + /// + /// Test the property 'Dummy' + /// + [Fact] + public void DummyTest() + { + // TODO unit test for the property 'Dummy' + } + } +} diff --git a/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index ca4153189a50..ebda386b94da 100644 --- a/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -3,7 +3,7 @@ Org.OpenAPITools.Test Org.OpenAPITools.Test - net7.0 + net6.0 false annotations diff --git a/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools/Api/FakeApi.cs index 0ea7552d84a7..f61afa1411b3 100644 --- a/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools/Api/FakeApi.cs @@ -15,6 +15,7 @@ using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api { @@ -34,8 +35,8 @@ public interface IFakeApiSync : IApiAccessor /// type_ /// http debug option (to test parameter naming option) /// Index associated with the operation. - /// - void GetParameterNameMapping(long UnderscoreType, string type, string TypeWithUnderscore, string httpDebugOption, int operationIndex = 0); + /// Env + Env GetParameterNameMapping(long UnderscoreType, string type, string TypeWithUnderscore, string httpDebugOption, int operationIndex = 0); /// /// parameter name mapping test @@ -49,8 +50,8 @@ public interface IFakeApiSync : IApiAccessor /// type_ /// http debug option (to test parameter naming option) /// Index associated with the operation. - /// ApiResponse of Object(void) - ApiResponse GetParameterNameMappingWithHttpInfo(long UnderscoreType, string type, string TypeWithUnderscore, string httpDebugOption, int operationIndex = 0); + /// ApiResponse of Env + ApiResponse GetParameterNameMappingWithHttpInfo(long UnderscoreType, string type, string TypeWithUnderscore, string httpDebugOption, int operationIndex = 0); #endregion Synchronous Operations } @@ -73,8 +74,8 @@ public interface IFakeApiAsync : IApiAccessor /// http debug option (to test parameter naming option) /// Index associated with the operation. /// Cancellation Token to cancel the request. - /// Task of void - System.Threading.Tasks.Task GetParameterNameMappingAsync(long UnderscoreType, string type, string TypeWithUnderscore, string httpDebugOption, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// Task of Env + System.Threading.Tasks.Task GetParameterNameMappingAsync(long UnderscoreType, string type, string TypeWithUnderscore, string httpDebugOption, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// /// parameter name mapping test @@ -89,8 +90,8 @@ public interface IFakeApiAsync : IApiAccessor /// http debug option (to test parameter naming option) /// Index associated with the operation. /// Cancellation Token to cancel the request. - /// Task of ApiResponse - System.Threading.Tasks.Task> GetParameterNameMappingWithHttpInfoAsync(long UnderscoreType, string type, string TypeWithUnderscore, string httpDebugOption, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// Task of ApiResponse (Env) + System.Threading.Tasks.Task> GetParameterNameMappingWithHttpInfoAsync(long UnderscoreType, string type, string TypeWithUnderscore, string httpDebugOption, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); #endregion Asynchronous Operations } @@ -220,10 +221,11 @@ public Org.OpenAPITools.Client.ExceptionFactory ExceptionFactory /// type_ /// http debug option (to test parameter naming option) /// Index associated with the operation. - /// - public void GetParameterNameMapping(long UnderscoreType, string type, string TypeWithUnderscore, string httpDebugOption, int operationIndex = 0) + /// Env + public Env GetParameterNameMapping(long UnderscoreType, string type, string TypeWithUnderscore, string httpDebugOption, int operationIndex = 0) { - GetParameterNameMappingWithHttpInfo(UnderscoreType, type, TypeWithUnderscore, httpDebugOption); + Org.OpenAPITools.Client.ApiResponse localVarResponse = GetParameterNameMappingWithHttpInfo(UnderscoreType, type, TypeWithUnderscore, httpDebugOption); + return localVarResponse.Data; } /// @@ -235,8 +237,8 @@ public void GetParameterNameMapping(long UnderscoreType, string type, string Typ /// type_ /// http debug option (to test parameter naming option) /// Index associated with the operation. - /// ApiResponse of Object(void) - public Org.OpenAPITools.Client.ApiResponse GetParameterNameMappingWithHttpInfo(long UnderscoreType, string type, string TypeWithUnderscore, string httpDebugOption, int operationIndex = 0) + /// ApiResponse of Env + public Org.OpenAPITools.Client.ApiResponse GetParameterNameMappingWithHttpInfo(long UnderscoreType, string type, string TypeWithUnderscore, string httpDebugOption, int operationIndex = 0) { // verify the required parameter 'type' is set if (type == null) @@ -263,6 +265,7 @@ public Org.OpenAPITools.Client.ApiResponse GetParameterNameMappingWithHt // to determine the Accept header string[] _accepts = new string[] { + "application/json" }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -287,7 +290,7 @@ public Org.OpenAPITools.Client.ApiResponse GetParameterNameMappingWithHt // make the HTTP request - var localVarResponse = this.Client.Get("/fake/parameter-name-mapping", localVarRequestOptions, this.Configuration); + var localVarResponse = this.Client.Get("/fake/parameter-name-mapping", localVarRequestOptions, this.Configuration); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetParameterNameMapping", localVarResponse); @@ -310,10 +313,11 @@ public Org.OpenAPITools.Client.ApiResponse GetParameterNameMappingWithHt /// http debug option (to test parameter naming option) /// Index associated with the operation. /// Cancellation Token to cancel the request. - /// Task of void - public async System.Threading.Tasks.Task GetParameterNameMappingAsync(long UnderscoreType, string type, string TypeWithUnderscore, string httpDebugOption, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + /// Task of Env + public async System.Threading.Tasks.Task GetParameterNameMappingAsync(long UnderscoreType, string type, string TypeWithUnderscore, string httpDebugOption, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { - await GetParameterNameMappingWithHttpInfoAsync(UnderscoreType, type, TypeWithUnderscore, httpDebugOption, operationIndex, cancellationToken).ConfigureAwait(false); + Org.OpenAPITools.Client.ApiResponse localVarResponse = await GetParameterNameMappingWithHttpInfoAsync(UnderscoreType, type, TypeWithUnderscore, httpDebugOption, operationIndex, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; } /// @@ -326,8 +330,8 @@ public Org.OpenAPITools.Client.ApiResponse GetParameterNameMappingWithHt /// http debug option (to test parameter naming option) /// Index associated with the operation. /// Cancellation Token to cancel the request. - /// Task of ApiResponse - public async System.Threading.Tasks.Task> GetParameterNameMappingWithHttpInfoAsync(long UnderscoreType, string type, string TypeWithUnderscore, string httpDebugOption, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + /// Task of ApiResponse (Env) + public async System.Threading.Tasks.Task> GetParameterNameMappingWithHttpInfoAsync(long UnderscoreType, string type, string TypeWithUnderscore, string httpDebugOption, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // verify the required parameter 'type' is set if (type == null) @@ -355,6 +359,7 @@ public Org.OpenAPITools.Client.ApiResponse GetParameterNameMappingWithHt // to determine the Accept header string[] _accepts = new string[] { + "application/json" }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -379,7 +384,7 @@ public Org.OpenAPITools.Client.ApiResponse GetParameterNameMappingWithHt // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/fake/parameter-name-mapping", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + var localVarResponse = await this.AsynchronousClient.GetAsync("/fake/parameter-name-mapping", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { diff --git a/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools/Model/Env.cs b/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools/Model/Env.cs new file mode 100644 index 000000000000..f540de64f58f --- /dev/null +++ b/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools/Model/Env.cs @@ -0,0 +1,128 @@ +/* + * Dummy + * + * To test name, parameter mapping options + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; + +namespace Org.OpenAPITools.Model +{ + /// + /// Env + /// + [DataContract(Name = "Environment")] + public partial class Env : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// dummy. + public Env(string dummy = default(string)) + { + this.Dummy = dummy; + } + + /// + /// Gets or Sets Dummy + /// + [DataMember(Name = "dummy", EmitDefaultValue = false)] + public string Dummy { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Env {\n"); + sb.Append(" Dummy: ").Append(Dummy).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return this.Equals(input as Env); + } + + /// + /// Returns true if Env instances are equal + /// + /// Instance of Env to be compared + /// Boolean + public bool Equals(Env input) + { + if (input == null) + { + return false; + } + return + ( + this.Dummy == input.Dummy || + (this.Dummy != null && + this.Dummy.Equals(input.Dummy)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Dummy != null) + { + hashCode = (hashCode * 59) + this.Dummy.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 04d24edbf5d8..89948381e2ee 100644 --- a/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -2,7 +2,7 @@ false - net7.0 + net6.0 Org.OpenAPITools Org.OpenAPITools Library diff --git a/samples/client/petstore/kotlin-name-parameter-mappings/.openapi-generator/FILES b/samples/client/petstore/kotlin-name-parameter-mappings/.openapi-generator/FILES index 3e52f58af4b3..c23198de3c83 100644 --- a/samples/client/petstore/kotlin-name-parameter-mappings/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-name-parameter-mappings/.openapi-generator/FILES @@ -1,5 +1,6 @@ README.md build.gradle +docs/Environment.md docs/FakeApi.md docs/PropertyNameMapping.md gradle/wrapper/gradle-wrapper.jar @@ -25,4 +26,5 @@ src/main/kotlin/org/openapitools/client/infrastructure/ResponseExtensions.kt src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt +src/main/kotlin/org/openapitools/client/models/Environment.kt src/main/kotlin/org/openapitools/client/models/PropertyNameMapping.kt diff --git a/samples/client/petstore/kotlin-name-parameter-mappings/README.md b/samples/client/petstore/kotlin-name-parameter-mappings/README.md index 7873db5b81db..d67b16fd2f76 100644 --- a/samples/client/petstore/kotlin-name-parameter-mappings/README.md +++ b/samples/client/petstore/kotlin-name-parameter-mappings/README.md @@ -50,6 +50,7 @@ Class | Method | HTTP request | Description ## Documentation for Models + - [org.openapitools.client.models.Environment](docs/Environment.md) - [org.openapitools.client.models.PropertyNameMapping](docs/PropertyNameMapping.md) diff --git a/samples/client/petstore/kotlin-name-parameter-mappings/docs/Environment.md b/samples/client/petstore/kotlin-name-parameter-mappings/docs/Environment.md new file mode 100644 index 000000000000..90250da0b675 --- /dev/null +++ b/samples/client/petstore/kotlin-name-parameter-mappings/docs/Environment.md @@ -0,0 +1,10 @@ + +# Environment + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**dummy** | **kotlin.String** | | [optional] + + + diff --git a/samples/client/petstore/kotlin-name-parameter-mappings/docs/FakeApi.md b/samples/client/petstore/kotlin-name-parameter-mappings/docs/FakeApi.md index 10a34e9f9eac..46c7a5435fc6 100644 --- a/samples/client/petstore/kotlin-name-parameter-mappings/docs/FakeApi.md +++ b/samples/client/petstore/kotlin-name-parameter-mappings/docs/FakeApi.md @@ -9,7 +9,7 @@ Method | HTTP request | Description # **getParameterNameMapping** -> getParameterNameMapping(underscoreType, type, typeWithUnderscore, httpDebugOption) +> Environment getParameterNameMapping(underscoreType, type, typeWithUnderscore, httpDebugOption) parameter name mapping test @@ -25,7 +25,8 @@ val type : kotlin.String = type_example // kotlin.String | type val typeWithUnderscore : kotlin.String = typeWithUnderscore_example // kotlin.String | type_ val httpDebugOption : kotlin.String = httpDebugOption_example // kotlin.String | http debug option (to test parameter naming option) try { - apiInstance.getParameterNameMapping(underscoreType, type, typeWithUnderscore, httpDebugOption) + val result : Environment = apiInstance.getParameterNameMapping(underscoreType, type, typeWithUnderscore, httpDebugOption) + println(result) } catch (e: ClientException) { println("4xx response calling FakeApi#getParameterNameMapping") e.printStackTrace() @@ -46,7 +47,7 @@ Name | Type | Description | Notes ### Return type -null (empty response body) +[**Environment**](Environment.md) ### Authorization @@ -55,5 +56,5 @@ No authorization required ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: Not defined + - **Accept**: application/json diff --git a/samples/client/petstore/kotlin-name-parameter-mappings/src/main/kotlin/org/openapitools/client/apis/FakeApi.kt b/samples/client/petstore/kotlin-name-parameter-mappings/src/main/kotlin/org/openapitools/client/apis/FakeApi.kt index 49c61653a51c..294e6db2e141 100644 --- a/samples/client/petstore/kotlin-name-parameter-mappings/src/main/kotlin/org/openapitools/client/apis/FakeApi.kt +++ b/samples/client/petstore/kotlin-name-parameter-mappings/src/main/kotlin/org/openapitools/client/apis/FakeApi.kt @@ -19,6 +19,7 @@ import java.io.IOException import okhttp3.OkHttpClient import okhttp3.HttpUrl +import org.openapitools.client.models.Environment import com.squareup.moshi.Json @@ -51,19 +52,20 @@ class FakeApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = * @param type type * @param typeWithUnderscore type_ * @param httpDebugOption http debug option (to test parameter naming option) - * @return void + * @return Environment * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception * @throws UnsupportedOperationException If the API returns an informational or redirection response * @throws ClientException If the API returns a client error response * @throws ServerException If the API returns a server error response */ + @Suppress("UNCHECKED_CAST") @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) - fun getParameterNameMapping(underscoreType: kotlin.Long, type: kotlin.String, typeWithUnderscore: kotlin.String, httpDebugOption: kotlin.String) : Unit { + fun getParameterNameMapping(underscoreType: kotlin.Long, type: kotlin.String, typeWithUnderscore: kotlin.String, httpDebugOption: kotlin.String) : Environment { val localVarResponse = getParameterNameMappingWithHttpInfo(underscoreType = underscoreType, type = type, typeWithUnderscore = typeWithUnderscore, httpDebugOption = httpDebugOption) return when (localVarResponse.responseType) { - ResponseType.Success -> Unit + ResponseType.Success -> (localVarResponse as Success<*>).data as Environment ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") ResponseType.ClientError -> { @@ -84,15 +86,16 @@ class FakeApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = * @param type type * @param typeWithUnderscore type_ * @param httpDebugOption http debug option (to test parameter naming option) - * @return ApiResponse + * @return ApiResponse * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception */ + @Suppress("UNCHECKED_CAST") @Throws(IllegalStateException::class, IOException::class) - fun getParameterNameMappingWithHttpInfo(underscoreType: kotlin.Long, type: kotlin.String, typeWithUnderscore: kotlin.String, httpDebugOption: kotlin.String) : ApiResponse { + fun getParameterNameMappingWithHttpInfo(underscoreType: kotlin.Long, type: kotlin.String, typeWithUnderscore: kotlin.String, httpDebugOption: kotlin.String) : ApiResponse { val localVariableConfig = getParameterNameMappingRequestConfig(underscoreType = underscoreType, type = type, typeWithUnderscore = typeWithUnderscore, httpDebugOption = httpDebugOption) - return request( + return request( localVariableConfig ) } @@ -116,7 +119,8 @@ class FakeApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = val localVariableHeaders: MutableMap = mutableMapOf() underscoreType.apply { localVariableHeaders["_type"] = this.toString() } typeWithUnderscore.apply { localVariableHeaders["type_"] = this.toString() } - + localVariableHeaders["Accept"] = "application/json" + return RequestConfig( method = RequestMethod.GET, path = "/fake/parameter-name-mapping", diff --git a/samples/client/petstore/kotlin-name-parameter-mappings/src/main/kotlin/org/openapitools/client/models/Environment.kt b/samples/client/petstore/kotlin-name-parameter-mappings/src/main/kotlin/org/openapitools/client/models/Environment.kt new file mode 100644 index 000000000000..7a4c656b0a3e --- /dev/null +++ b/samples/client/petstore/kotlin-name-parameter-mappings/src/main/kotlin/org/openapitools/client/models/Environment.kt @@ -0,0 +1,35 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + + +import com.squareup.moshi.Json +import com.squareup.moshi.JsonClass + +/** + * + * + * @param dummy + */ + + +data class Environment ( + + @Json(name = "dummy") + val dummy: kotlin.String? = null + +) + From 0ce1fef01675e20afe221d79d9f36a8a19ed5470 Mon Sep 17 00:00:00 2001 From: martin-mfg <2026226+martin-mfg@users.noreply.github.com> Date: Wed, 2 Aug 2023 08:27:27 +0200 Subject: [PATCH 002/292] fix 2 sonar-reported bugs (#16229) --- .../org/openapitools/codegen/languages/AbstractAdaCodegen.java | 2 +- .../org/openapitools/codegen/languages/ZapierClientCodegen.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractAdaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractAdaCodegen.java index a470c8ec5fdd..3c4a5ced5567 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractAdaCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractAdaCodegen.java @@ -831,7 +831,7 @@ public int compareTo(ModelDepend second) { //LOGGER.debug("Compare " + name + " with " + second.name + "=-1"); return -1; } - if (depend != null && (depend == null ? 0 : depend.size()) != (second.depend == null ? 0 : second.depend.size())) { + if (depend != null && depend.size() != (second.depend == null ? 0 : second.depend.size())) { //LOGGER.debug("Compare " + name + " with " + second.name + "=D" // + (depend.size() - second.depend.size())); return depend.size() - second.depend.size(); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ZapierClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ZapierClientCodegen.java index 822add48ddf2..d730606104bb 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ZapierClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ZapierClientCodegen.java @@ -183,7 +183,7 @@ public CodegenResponse fromResponse(String responseCode, ApiResponse response) { CodegenResponse r = super.fromResponse(responseCode, response); try { Map>> map = Json.mapper().readerFor(Map.class).readValue(Json.pretty(response.getContent())); - Map.Entry>> entry = map.entrySet().stream().findFirst().get(); + Map.Entry>> entry = map.entrySet().stream().findFirst().orElseThrow(()-> new IllegalStateException("no response object available")); Map> example = entry.getValue(); r.examples = toExamples(example.get("examples")); } catch (Exception e) { From d67f5ddeffb65d55faa4cc47343cebf21a907ef3 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Wed, 2 Aug 2023 15:13:13 +0800 Subject: [PATCH 003/292] Fix circleci node 4 failure (#16236) * fix circleci failure * remove debug * fix --- .circleci/config.yml | 6 +++--- CI/circle_parallel.sh | 9 --------- 2 files changed, 3 insertions(+), 12 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index bcf8db2b1586..2f05fb9a72ed 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -204,8 +204,8 @@ jobs: - command_build_and_test: nodeNo: "3" node4: - docker: - - image: fkrull/multi-python + machine: + image: ubuntu-2004:202201-02 working_directory: ~/OpenAPITools/openapi-generator shell: /bin/bash --login environment: @@ -215,7 +215,7 @@ jobs: DOCKER_CODEGEN_CLI_IMAGE_NAME: openapitools/openapi-generator-cli steps: - checkout - - command_docker_build_and_test: + - command_build_and_test: nodeNo: "4" workflows: version: 2 diff --git a/CI/circle_parallel.sh b/CI/circle_parallel.sh index 4ccb585afed5..b5baa82c9604 100755 --- a/CI/circle_parallel.sh +++ b/CI/circle_parallel.sh @@ -9,15 +9,6 @@ set -e export NODE_ENV=test -function cleanup { - # Show logs of 'petstore.swagger' container to troubleshoot Unit Test failures, if any. - if [ "$NODE_INDEX" != "4" ]; then - docker logs petstore.swagger # container name specified in circle.yml - fi -} - -trap cleanup EXIT - if [ "$NODE_INDEX" = "1" ]; then echo "Running node $NODE_INDEX to test 'samples.circleci' defined in pom.xml ..." java -version From 1d39902930e7e95cfb9e8489671b60fd340cce24 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Wed, 2 Aug 2023 17:26:23 +0800 Subject: [PATCH 004/292] Add name mappings support to JS client (#16234) * add name mappings support to JS client * update doc * udpate doc * update doc --- bin/configs/javascript-es6.yaml | 7 +++++ docs/customization.md | 9 +++--- .../languages/JavascriptClientCodegen.java | 15 ++++++++++ .../javascript-es6/.openapi-generator/FILES | 4 +-- .../client/petstore/javascript-es6/README.md | 2 +- .../petstore/javascript-es6/docs/FakeApi.md | 8 +++--- ...lthCheckResult.md => HealthCheckStatus.md} | 4 +-- .../javascript-es6/src/api/FakeApi.js | 12 ++++---- .../petstore/javascript-es6/src/index.js | 8 +++--- ...lthCheckResult.js => HealthCheckStatus.js} | 28 +++++++++---------- ...sult.spec.js => HealthCheckStatus.spec.js} | 18 ++++++------ 11 files changed, 68 insertions(+), 47 deletions(-) rename samples/client/petstore/javascript-es6/docs/{HealthCheckResult.md => HealthCheckStatus.md} (56%) rename samples/client/petstore/javascript-es6/src/model/{HealthCheckResult.js => HealthCheckStatus.js} (75%) rename samples/client/petstore/javascript-es6/test/model/{HealthCheckResult.spec.js => HealthCheckStatus.spec.js} (77%) diff --git a/bin/configs/javascript-es6.yaml b/bin/configs/javascript-es6.yaml index 67f013b0c513..bc9562f93e76 100644 --- a/bin/configs/javascript-es6.yaml +++ b/bin/configs/javascript-es6.yaml @@ -5,3 +5,10 @@ inputSpec: modules/openapi-generator/src/test/resources/3_0/javascript/petstore- templateDir: modules/openapi-generator/src/main/resources/Javascript additionalProperties: appName: PetstoreClient +modelNameMappings: + HealthCheckResult: HealthCheckStatus +parameterNameMappings: + query_1: queryOne +# the following has no effect as js client gen use baseName directly +nameMappings: + NullableMessage: nullable_field diff --git a/docs/customization.md b/docs/customization.md index ea91e18c4bc3..29834b7f3bde 100644 --- a/docs/customization.md +++ b/docs/customization.md @@ -413,19 +413,18 @@ One can map the property name using `nameMappings` option and parameter name usi Here is an example to use `nameMappings` and `parameterNameMapping` in CLI: ```sh -java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generate -g java -i modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-okhttp-gson.yaml -o /tmp/java2/ --name-mappings _type=underscoreType, type_=typeWithUnderscore, --parameter-name-mappings _type=paramType, type_=typeParam +java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generate -g java -i modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-okhttp-gson.yaml -o /tmp/java2/ --name-mappings _type=underscoreType,type_=typeWithUnderscore, --parameter-name-mappings _type=paramType,type_=typeParam ``` To map model names, use `modelNameMappings` option, e.g. ```sh java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generate -g csharp -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -o /tmp/csharp/ --model-name-mappings Tag=Label ``` -will rename the Tag schema to Label instead. +will rename the `Tag` schema to `Label` instead. +Not all generators support thess features yet. Please give it a try to confirm the behaviour and open an issue (ticket) to let us know which generators you would like to have this feature enabled and we'll prioritize accordingly. We also welcome PRs to add these features to generators. Related PRs for reference: #16209, #16234 (modelNameMappings), #16194, #16206 (nameMappings, parameterNameMappings). -(Not all generators support thess features yet. Please give it a try to confirm the behaviour and open an issue (ticket) to let us know which generators you would like to have this feature enabled and we'll prioritize accordingly.) - -Related PRs: #16209 (modelNameMappings), #16194, #16206 (nameMappings, parameterNameMappings) +NOTE: some generators use `baseName` (original name obtained direclty from OpenAPI spec, e.g. `shipping-date`) mustache tag in the templates so the mapping feature won't work. ## Schema Mapping diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClientCodegen.java index c0ae1f4e8b76..0aef3f2ae27b 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClientCodegen.java @@ -507,6 +507,11 @@ private String getNameUsingModelPropertyNaming(String name) { @Override public String toVarName(String name) { + // obtain the name from nameMapping directly if provided + if (nameMapping.containsKey(name)) { + return nameMapping.get(name); + } + // sanitize name name = sanitizeName(name); // FIXME parameter should not be assigned. Also declare it as "final" @@ -538,12 +543,22 @@ protected boolean isReservedWord(String word) { @Override public String toParamName(String name) { + // obtain the name from parameterNameMapping directly if provided + if (parameterNameMapping.containsKey(name)) { + return parameterNameMapping.get(name); + } + // should be the same as variable name return toVarName(name); } @Override public String toModelName(String name) { + // obtain the name from modelNameMapping directly if provided + if (modelNameMapping.containsKey(name)) { + return modelNameMapping.get(name); + } + name = sanitizeName(name); // FIXME parameter should not be assigned. Also declare it as "final" if (!StringUtils.isEmpty(modelNamePrefix)) { diff --git a/samples/client/petstore/javascript-es6/.openapi-generator/FILES b/samples/client/petstore/javascript-es6/.openapi-generator/FILES index 9011fa6ed434..65b22f216a72 100644 --- a/samples/client/petstore/javascript-es6/.openapi-generator/FILES +++ b/samples/client/petstore/javascript-es6/.openapi-generator/FILES @@ -31,7 +31,7 @@ docs/Foo.md docs/FooGetDefaultResponse.md docs/FormatTest.md docs/HasOnlyReadOnly.md -docs/HealthCheckResult.md +docs/HealthCheckStatus.md docs/List.md docs/MapTest.md docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -97,7 +97,7 @@ src/model/Foo.js src/model/FooGetDefaultResponse.js src/model/FormatTest.js src/model/HasOnlyReadOnly.js -src/model/HealthCheckResult.js +src/model/HealthCheckStatus.js src/model/List.js src/model/MapTest.js src/model/MixedPropertiesAndAdditionalPropertiesClass.js diff --git a/samples/client/petstore/javascript-es6/README.md b/samples/client/petstore/javascript-es6/README.md index db2c6ef4a403..1f574fb0f355 100644 --- a/samples/client/petstore/javascript-es6/README.md +++ b/samples/client/petstore/javascript-es6/README.md @@ -190,7 +190,7 @@ Class | Method | HTTP request | Description - [OpenApiPetstore.FooGetDefaultResponse](docs/FooGetDefaultResponse.md) - [OpenApiPetstore.FormatTest](docs/FormatTest.md) - [OpenApiPetstore.HasOnlyReadOnly](docs/HasOnlyReadOnly.md) - - [OpenApiPetstore.HealthCheckResult](docs/HealthCheckResult.md) + - [OpenApiPetstore.HealthCheckStatus](docs/HealthCheckStatus.md) - [OpenApiPetstore.List](docs/List.md) - [OpenApiPetstore.MapTest](docs/MapTest.md) - [OpenApiPetstore.MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) diff --git a/samples/client/petstore/javascript-es6/docs/FakeApi.md b/samples/client/petstore/javascript-es6/docs/FakeApi.md index 5b76c0a7f503..a63ae962532a 100644 --- a/samples/client/petstore/javascript-es6/docs/FakeApi.md +++ b/samples/client/petstore/javascript-es6/docs/FakeApi.md @@ -26,7 +26,7 @@ Method | HTTP request | Description ## fakeHealthGet -> HealthCheckResult fakeHealthGet() +> HealthCheckStatus fakeHealthGet() Health check endpoint @@ -51,7 +51,7 @@ This endpoint does not need any parameter. ### Return type -[**HealthCheckResult**](HealthCheckResult.md) +[**HealthCheckStatus**](HealthCheckStatus.md) ### Authorization @@ -78,7 +78,7 @@ let defaultClient = OpenApiPetstore.ApiClient.instance; let apiInstance = new OpenApiPetstore.FakeApi(); let pet = new OpenApiPetstore.Pet(); // Pet | Pet object that needs to be added to the store let opts = { - 'query1': "query1_example", // String | query parameter + 'queryOne': "queryOne_example", // String | query parameter 'header1': "header1_example" // String | header parameter }; apiInstance.fakeHttpSignatureTest(pet, opts, (error, data, response) => { @@ -96,7 +96,7 @@ apiInstance.fakeHttpSignatureTest(pet, opts, (error, data, response) => { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | - **query1** | **String**| query parameter | [optional] + **queryOne** | **String**| query parameter | [optional] **header1** | **String**| header parameter | [optional] ### Return type diff --git a/samples/client/petstore/javascript-es6/docs/HealthCheckResult.md b/samples/client/petstore/javascript-es6/docs/HealthCheckStatus.md similarity index 56% rename from samples/client/petstore/javascript-es6/docs/HealthCheckResult.md rename to samples/client/petstore/javascript-es6/docs/HealthCheckStatus.md index bbb74ac6a0ae..1311bc15006e 100644 --- a/samples/client/petstore/javascript-es6/docs/HealthCheckResult.md +++ b/samples/client/petstore/javascript-es6/docs/HealthCheckStatus.md @@ -1,9 +1,9 @@ -# OpenApiPetstore.HealthCheckResult +# OpenApiPetstore.HealthCheckStatus ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**nullableMessage** | **String** | | [optional] +**nullable_field** | **String** | | [optional] diff --git a/samples/client/petstore/javascript-es6/src/api/FakeApi.js b/samples/client/petstore/javascript-es6/src/api/FakeApi.js index b80b6c6e81fd..151b1fc60ef9 100644 --- a/samples/client/petstore/javascript-es6/src/api/FakeApi.js +++ b/samples/client/petstore/javascript-es6/src/api/FakeApi.js @@ -16,7 +16,7 @@ import ApiClient from "../ApiClient"; import Client from '../model/Client'; import EnumClass from '../model/EnumClass'; import FileSchemaTestClass from '../model/FileSchemaTestClass'; -import HealthCheckResult from '../model/HealthCheckResult'; +import HealthCheckStatus from '../model/HealthCheckStatus'; import OuterComposite from '../model/OuterComposite'; import OuterObjectWithEnumProperty from '../model/OuterObjectWithEnumProperty'; import Pet from '../model/Pet'; @@ -45,14 +45,14 @@ export default class FakeApi { * Callback function to receive the result of the fakeHealthGet operation. * @callback module:api/FakeApi~fakeHealthGetCallback * @param {String} error Error message, if any. - * @param {module:model/HealthCheckResult} data The data returned by the service call. + * @param {module:model/HealthCheckStatus} data The data returned by the service call. * @param {String} response The complete HTTP response. */ /** * Health check endpoint * @param {module:api/FakeApi~fakeHealthGetCallback} callback The callback function, accepting three arguments: error, data, response - * data is of type: {@link module:model/HealthCheckResult} + * data is of type: {@link module:model/HealthCheckStatus} */ fakeHealthGet(callback) { let postBody = null; @@ -69,7 +69,7 @@ export default class FakeApi { let authNames = []; let contentTypes = []; let accepts = ['application/json']; - let returnType = HealthCheckResult; + let returnType = HealthCheckStatus; return this.apiClient.callApi( '/fake/health', 'GET', pathParams, queryParams, headerParams, formParams, postBody, @@ -89,7 +89,7 @@ export default class FakeApi { * test http signature authentication * @param {module:model/Pet} pet Pet object that needs to be added to the store * @param {Object} opts Optional parameters - * @param {String} [query1] query parameter + * @param {String} [queryOne] query parameter * @param {String} [header1] header parameter * @param {module:api/FakeApi~fakeHttpSignatureTestCallback} callback The callback function, accepting three arguments: error, data, response */ @@ -104,7 +104,7 @@ export default class FakeApi { let pathParams = { }; let queryParams = { - 'query_1': opts['query1'] + 'query_1': opts['queryOne'] }; let headerParams = { 'header_1': opts['header1'] diff --git a/samples/client/petstore/javascript-es6/src/index.js b/samples/client/petstore/javascript-es6/src/index.js index 2783bffde761..2466b0ebdabf 100644 --- a/samples/client/petstore/javascript-es6/src/index.js +++ b/samples/client/petstore/javascript-es6/src/index.js @@ -38,7 +38,7 @@ import Foo from './model/Foo'; import FooGetDefaultResponse from './model/FooGetDefaultResponse'; import FormatTest from './model/FormatTest'; import HasOnlyReadOnly from './model/HasOnlyReadOnly'; -import HealthCheckResult from './model/HealthCheckResult'; +import HealthCheckStatus from './model/HealthCheckStatus'; import List from './model/List'; import MapTest from './model/MapTest'; import MixedPropertiesAndAdditionalPropertiesClass from './model/MixedPropertiesAndAdditionalPropertiesClass'; @@ -262,10 +262,10 @@ export { HasOnlyReadOnly, /** - * The HealthCheckResult model constructor. - * @property {module:model/HealthCheckResult} + * The HealthCheckStatus model constructor. + * @property {module:model/HealthCheckStatus} */ - HealthCheckResult, + HealthCheckStatus, /** * The List model constructor. diff --git a/samples/client/petstore/javascript-es6/src/model/HealthCheckResult.js b/samples/client/petstore/javascript-es6/src/model/HealthCheckStatus.js similarity index 75% rename from samples/client/petstore/javascript-es6/src/model/HealthCheckResult.js rename to samples/client/petstore/javascript-es6/src/model/HealthCheckStatus.js index 112fd7784265..6299516cbbd8 100644 --- a/samples/client/petstore/javascript-es6/src/model/HealthCheckResult.js +++ b/samples/client/petstore/javascript-es6/src/model/HealthCheckStatus.js @@ -14,19 +14,19 @@ import ApiClient from '../ApiClient'; /** - * The HealthCheckResult model module. - * @module model/HealthCheckResult + * The HealthCheckStatus model module. + * @module model/HealthCheckStatus * @version 1.0.0 */ -class HealthCheckResult { +class HealthCheckStatus { /** - * Constructs a new HealthCheckResult. + * Constructs a new HealthCheckStatus. * Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. - * @alias module:model/HealthCheckResult + * @alias module:model/HealthCheckStatus */ constructor() { - HealthCheckResult.initialize(this); + HealthCheckStatus.initialize(this); } /** @@ -38,15 +38,15 @@ class HealthCheckResult { } /** - * Constructs a HealthCheckResult from a plain JavaScript object, optionally creating a new instance. + * Constructs a HealthCheckStatus from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from data to obj if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/HealthCheckResult} obj Optional instance to populate. - * @return {module:model/HealthCheckResult} The populated HealthCheckResult instance. + * @param {module:model/HealthCheckStatus} obj Optional instance to populate. + * @return {module:model/HealthCheckStatus} The populated HealthCheckStatus instance. */ static constructFromObject(data, obj) { if (data) { - obj = obj || new HealthCheckResult(); + obj = obj || new HealthCheckStatus(); if (data.hasOwnProperty('NullableMessage')) { obj['NullableMessage'] = ApiClient.convertToType(data['NullableMessage'], 'String'); @@ -56,9 +56,9 @@ class HealthCheckResult { } /** - * Validates the JSON data with respect to HealthCheckResult. + * Validates the JSON data with respect to HealthCheckStatus. * @param {Object} data The plain JavaScript object bearing properties of interest. - * @return {boolean} to indicate whether the JSON data is valid with respect to HealthCheckResult. + * @return {boolean} to indicate whether the JSON data is valid with respect to HealthCheckStatus. */ static validateJSON(data) { // ensure the json data is a string @@ -77,12 +77,12 @@ class HealthCheckResult { /** * @member {String} NullableMessage */ -HealthCheckResult.prototype['NullableMessage'] = undefined; +HealthCheckStatus.prototype['NullableMessage'] = undefined; -export default HealthCheckResult; +export default HealthCheckStatus; diff --git a/samples/client/petstore/javascript-es6/test/model/HealthCheckResult.spec.js b/samples/client/petstore/javascript-es6/test/model/HealthCheckStatus.spec.js similarity index 77% rename from samples/client/petstore/javascript-es6/test/model/HealthCheckResult.spec.js rename to samples/client/petstore/javascript-es6/test/model/HealthCheckStatus.spec.js index 25d9ecd929f0..6eb9dccd9bee 100644 --- a/samples/client/petstore/javascript-es6/test/model/HealthCheckResult.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/HealthCheckStatus.spec.js @@ -28,7 +28,7 @@ var instance; beforeEach(function() { - instance = new OpenApiPetstore.HealthCheckResult(); + instance = new OpenApiPetstore.HealthCheckStatus(); }); var getProperty = function(object, getter, property) { @@ -47,16 +47,16 @@ object[property] = value; } - describe('HealthCheckResult', function() { - it('should create an instance of HealthCheckResult', function() { - // uncomment below and update the code to test HealthCheckResult - //var instance = new OpenApiPetstore.HealthCheckResult(); - //expect(instance).to.be.a(OpenApiPetstore.HealthCheckResult); + describe('HealthCheckStatus', function() { + it('should create an instance of HealthCheckStatus', function() { + // uncomment below and update the code to test HealthCheckStatus + //var instance = new OpenApiPetstore.HealthCheckStatus(); + //expect(instance).to.be.a(OpenApiPetstore.HealthCheckStatus); }); - it('should have the property nullableMessage (base name: "NullableMessage")', function() { - // uncomment below and update the code to test the property nullableMessage - //var instance = new OpenApiPetstore.HealthCheckResult(); + it('should have the property nullable_field (base name: "NullableMessage")', function() { + // uncomment below and update the code to test the property nullable_field + //var instance = new OpenApiPetstore.HealthCheckStatus(); //expect(instance).to.be(); }); From 81c398e5304f411eb57814349841827c13b2a54e Mon Sep 17 00:00:00 2001 From: William Cheng Date: Wed, 2 Aug 2023 17:26:52 +0800 Subject: [PATCH 005/292] add model name mappings support to the elixir client generator (#16233) --- bin/configs/elixir.yaml | 7 +++++++ .../codegen/languages/ElixirClientCodegen.java | 12 ++++++++++++ .../client/petstore/elixir/.openapi-generator/FILES | 2 +- .../{deprecated_object.ex => deprecated_model.ex} | 2 +- .../model/object_with_deprecated_fields.ex | 4 ++-- 5 files changed, 23 insertions(+), 4 deletions(-) rename samples/client/petstore/elixir/lib/openapi_petstore/model/{deprecated_object.ex => deprecated_model.ex} (86%) diff --git a/bin/configs/elixir.yaml b/bin/configs/elixir.yaml index a287f44705b0..917661865ddb 100644 --- a/bin/configs/elixir.yaml +++ b/bin/configs/elixir.yaml @@ -4,3 +4,10 @@ inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-e templateDir: modules/openapi-generator/src/main/resources/elixir additionalProperties: invokerPackage: OpenapiPetstore +modelNameMappings: + DeprecatedObject: DeprecatedModel +# the following options have no effect on elixir client gen which uses baseName +nameMappings: + deprecatedRef: deprecatedReference +parameterNameMapping: + ioutils: ioutils_parameter diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElixirClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElixirClientCodegen.java index 8bf83f7362c4..c43b67f58691 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElixirClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElixirClientCodegen.java @@ -482,6 +482,11 @@ public String toApiFilename(String name) { @Override public String toModelName(String name) { + // obtain the name from modelNameMapping directly if provided + if (modelNameMapping.containsKey(name)) { + return modelNameMapping.get(name); + } + // camelize the model name // phone_number => PhoneNumber return camelize(toModelFilename(name)); @@ -489,6 +494,12 @@ public String toModelName(String name) { @Override public String toModelFilename(String name) { + // obtain the name from modelNameMapping directly if provided + // and convert it to snake case + if (modelNameMapping.containsKey(name)) { + return underscore(modelNameMapping.get(name)); + } + if (!StringUtils.isEmpty(modelNamePrefix)) { name = modelNamePrefix + "_" + name; } @@ -991,4 +1002,5 @@ public void setModuleName(String moduleName) { @Override public GeneratorLanguage generatorLanguage() { return GeneratorLanguage.ELIXIR; } + } diff --git a/samples/client/petstore/elixir/.openapi-generator/FILES b/samples/client/petstore/elixir/.openapi-generator/FILES index cce73801e7c9..cf3fc36a0ab8 100644 --- a/samples/client/petstore/elixir/.openapi-generator/FILES +++ b/samples/client/petstore/elixir/.openapi-generator/FILES @@ -26,7 +26,7 @@ lib/openapi_petstore/model/cat.ex lib/openapi_petstore/model/category.ex lib/openapi_petstore/model/class_model.ex lib/openapi_petstore/model/client.ex -lib/openapi_petstore/model/deprecated_object.ex +lib/openapi_petstore/model/deprecated_model.ex lib/openapi_petstore/model/dog.ex lib/openapi_petstore/model/enum_arrays.ex lib/openapi_petstore/model/enum_class.ex diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/deprecated_object.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/deprecated_model.ex similarity index 86% rename from samples/client/petstore/elixir/lib/openapi_petstore/model/deprecated_object.ex rename to samples/client/petstore/elixir/lib/openapi_petstore/model/deprecated_model.ex index efbb7eacea89..99e6f8b69e07 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/deprecated_object.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/deprecated_model.ex @@ -1,7 +1,7 @@ # NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. -defmodule OpenapiPetstore.Model.DeprecatedObject do +defmodule OpenapiPetstore.Model.DeprecatedModel do @moduledoc """ """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/object_with_deprecated_fields.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/object_with_deprecated_fields.ex index 67b403e60afc..fea09465054a 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/object_with_deprecated_fields.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/object_with_deprecated_fields.ex @@ -17,7 +17,7 @@ defmodule OpenapiPetstore.Model.ObjectWithDeprecatedFields do @type t :: %__MODULE__{ :uuid => String.t | nil, :id => float() | nil, - :deprecatedRef => OpenapiPetstore.Model.DeprecatedObject.t | nil, + :deprecatedRef => OpenapiPetstore.Model.DeprecatedModel.t | nil, :bars => [String.t] | nil } @@ -25,7 +25,7 @@ defmodule OpenapiPetstore.Model.ObjectWithDeprecatedFields do def decode(value) do value - |> Deserializer.deserialize(:deprecatedRef, :struct, OpenapiPetstore.Model.DeprecatedObject) + |> Deserializer.deserialize(:deprecatedRef, :struct, OpenapiPetstore.Model.DeprecatedModel) end end From 45d8027bb4dbf924eb5af7bdae2e625ee29e256f Mon Sep 17 00:00:00 2001 From: Masahiro Sakai Date: Thu, 3 Aug 2023 14:29:33 +0900 Subject: [PATCH 006/292] [haskell-servant][haskell-yesod] Use table-based conversion for field name conversion (#16232) * [haskell-servant][haskell-yesod] use table-based conversion for field name conversion Current fieldLabelModifier implementation always produces uncapitalize name, but it is inappropriate if the original JSON field name begins with a capital letter. * [haskell-servant][haskell-yesod] regenerate samples --- .../languages/HaskellServantCodegen.java | 3 +- .../languages/HaskellYesodServerCodegen.java | 3 +- .../resources/haskell-servant/Types.mustache | 41 ++--- .../haskell-yesod/src/API/Types.mustache | 38 ++-- .../lib/OpenAPIPetstore/Types.hs | 171 +++++++++++------- .../src/OpenAPIPetstore/Types.hs | 158 +++++++++------- 6 files changed, 229 insertions(+), 185 deletions(-) diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellServantCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellServantCodegen.java index dbc1b25ff187..7b0e72f39990 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellServantCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellServantCodegen.java @@ -658,6 +658,7 @@ public CodegenModel fromModel(String name, Schema mod) { String prefix = camelize(model.classname, LOWERCASE_FIRST_LETTER); for (CodegenProperty prop : model.vars) { prop.name = toVarName(prefix + camelize(prop.name)); + prop.vendorExtensions.put("x-base-name-string-literal", "\"" + escapeText(prop.getBaseName()) + "\""); } // Create newtypes for things with non-object types @@ -668,8 +669,6 @@ public CodegenModel fromModel(String name, Schema mod) { model.vendorExtensions.put("x-custom-newtype", newtype); } - // Provide the prefix as a vendor extension, so that it can be used in the ToJSON and FromJSON instances. - model.vendorExtensions.put("x-prefix", prefix); model.vendorExtensions.put("x-data", dataOrNewtype); return model; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellYesodServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellYesodServerCodegen.java index dd1bffb2a0ec..b49846d51d3e 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellYesodServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellYesodServerCodegen.java @@ -552,6 +552,7 @@ public CodegenModel fromModel(String name, Schema mod) { String prefix = camelize(model.classname, LOWERCASE_FIRST_LETTER); for (CodegenProperty prop : model.vars) { prop.name = toVarName(prefix + camelize(prop.name)); + prop.vendorExtensions.put("x-base-name-string-literal", "\"" + escapeText(prop.getBaseName()) + "\""); } // Create newtypes for things with non-object types @@ -562,8 +563,6 @@ public CodegenModel fromModel(String name, Schema mod) { model.vendorExtensions.put("x-custom-newtype", newtype); } - // Provide the prefix as a vendor extension, so that it can be used in the ToJSON and FromJSON instances. - model.vendorExtensions.put("x-prefix", prefix); model.vendorExtensions.put("x-data", dataOrNewtype); return model; diff --git a/modules/openapi-generator/src/main/resources/haskell-servant/Types.mustache b/modules/openapi-generator/src/main/resources/haskell-servant/Types.mustache index 15a1b9305bdb..a8f444d35853 100644 --- a/modules/openapi-generator/src/main/resources/haskell-servant/Types.mustache +++ b/modules/openapi-generator/src/main/resources/haskell-servant/Types.mustache @@ -13,7 +13,7 @@ module {{title}}.Types ( import Data.Data (Data) import Data.UUID (UUID) -import Data.List (stripPrefix) +import Data.List (lookup) import Data.Maybe (fromMaybe) import Data.Aeson (Value, FromJSON(..), ToJSON(..), genericToJSON, genericParseJSON) import Data.Aeson.Types (Options(..), defaultOptions) @@ -26,7 +26,6 @@ import qualified Data.Char as Char import qualified Data.Text as T import qualified Data.Map as Map import GHC.Generics (Generic) -import Data.Function ((&)) {{#imports}}import {{import}} {{/imports}} @@ -42,16 +41,28 @@ import Data.Function ((&)) } deriving (Show, Eq, Generic, Data) instance FromJSON {{classname}} where - parseJSON = genericParseJSON (removeFieldLabelPrefix "{{vendorExtensions.x-prefix}}") + parseJSON = genericParseJSON options{{classname}} instance ToJSON {{classname}} where - toJSON = genericToJSON (removeFieldLabelPrefix "{{vendorExtensions.x-prefix}}") + toJSON = genericToJSON options{{classname}} {{#generateToSchema}} instance ToSchema {{classname}} where declareNamedSchema = Swagger.genericDeclareNamedSchema $ Swagger.fromAesonOptions - $ removeFieldLabelPrefix "{{vendorExtensions.x-prefix}}" + $ options{{classname}} {{/generateToSchema}} +options{{classname}} :: Options +options{{classname}} = + defaultOptions + { omitNothingFields = True + , fieldLabelModifier = \s -> fromMaybe ("did not find JSON field name for " ++ show s) $ lookup s table + } + where + table = + [ {{#vars}}("{{& name}}", {{& vendorExtensions.x-base-name-string-literal}}){{^-last}} + , {{/-last}}{{/vars}} + ] + {{/parent}} {{#parent}} newtype {{classname}} = {{classname}} { un{{classname}} :: {{parent}} } @@ -63,23 +74,3 @@ newtype {{classname}} = {{classname}} {{vendorExtensions.x-custom-newtype}} deri {{/vendorExtensions.x-custom-newtype}} {{/model}} {{/models}} - -uncapitalize :: String -> String -uncapitalize (first:rest) = Char.toLower first : rest -uncapitalize [] = [] - --- | Remove a field label prefix during JSON parsing. --- Also perform any replacements for special characters. -removeFieldLabelPrefix :: String -> Options -removeFieldLabelPrefix prefix = - defaultOptions - { omitNothingFields = True - , fieldLabelModifier = uncapitalize . replaceSpecialChars . fromMaybe (error ("did not find prefix " ++ prefix)) . stripPrefix prefix - } - where - replaceSpecialChars field = foldl (&) field (map mkCharReplacement specialChars) - specialChars = - [ {{#specialCharReplacements}}("{{&char}}", "{{&replacement}}"){{^-last}} - , {{/-last}}{{/specialCharReplacements}} - ] - mkCharReplacement (replaceStr, searchStr) = T.unpack . T.replace (T.pack searchStr) (T.pack replaceStr) . T.pack diff --git a/modules/openapi-generator/src/main/resources/haskell-yesod/src/API/Types.mustache b/modules/openapi-generator/src/main/resources/haskell-yesod/src/API/Types.mustache index e60798054e8a..e9e22668d0ff 100644 --- a/modules/openapi-generator/src/main/resources/haskell-yesod/src/API/Types.mustache +++ b/modules/openapi-generator/src/main/resources/haskell-yesod/src/API/Types.mustache @@ -13,6 +13,7 @@ module {{apiModuleName}}.Types ( import ClassyPrelude.Yesod import Data.Foldable (foldl) +import qualified Data.List as List import Data.Maybe (fromMaybe) import Data.Aeson (Value, FromJSON(..), ToJSON(..), genericToJSON, genericParseJSON) import Data.Aeson.Types (Options(..), defaultOptions) @@ -20,7 +21,6 @@ import qualified Data.Char as Char import qualified Data.Text as T import qualified Data.Map as Map import GHC.Generics (Generic) -import Data.Function ((&)) {{#imports}}import {{import}} {{/imports}} @@ -36,9 +36,21 @@ import Data.Function ((&)) } deriving (Show, Eq, Generic) instance FromJSON {{classname}} where - parseJSON = genericParseJSON (removeFieldLabelPrefix "{{vendorExtensions.x-prefix}}") + parseJSON = genericParseJSON options{{classname}} instance ToJSON {{classname}} where - toJSON = genericToJSON (removeFieldLabelPrefix "{{vendorExtensions.x-prefix}}") + toJSON = genericToJSON options{{classname}} + +options{{classname}} :: Options +options{{classname}} = + defaultOptions + { omitNothingFields = True + , fieldLabelModifier = \s -> fromMaybe ("did not find JSON field name for " ++ show s) $ List.lookup s table + } + where + table = + [ {{#vars}}("{{& name}}", {{& vendorExtensions.x-base-name-string-literal}}){{^-last}} + , {{/-last}}{{/vars}} + ] {{/parent}} {{#parent}} @@ -51,23 +63,3 @@ newtype {{classname}} = {{classname}} {{vendorExtensions.x-custom-newtype}} deri {{/vendorExtensions.x-custom-newtype}} {{/model}} {{/models}} - -uncapitalize :: String -> String -uncapitalize (c : cs) = Char.toLower c : cs -uncapitalize [] = [] - --- | Remove a field label prefix during JSON parsing. --- Also perform any replacements for special characters. -removeFieldLabelPrefix :: String -> Options -removeFieldLabelPrefix prefix = - defaultOptions - { omitNothingFields = True - , fieldLabelModifier = uncapitalize . replaceSpecialChars . fromMaybe (error ("did not find prefix " ++ prefix)) . stripPrefix prefix - } - where - replaceSpecialChars field = foldl (&) field (map mkCharReplacement specialChars) - specialChars = - [ {{#specialCharReplacements}}("{{&char}}", "{{&replacement}}"){{^-last}} - , {{/-last}}{{/specialCharReplacements}} - ] - mkCharReplacement (replaceStr, searchStr) = T.unpack . T.replace (T.pack searchStr) (T.pack replaceStr) . T.pack diff --git a/samples/server/petstore/haskell-servant/lib/OpenAPIPetstore/Types.hs b/samples/server/petstore/haskell-servant/lib/OpenAPIPetstore/Types.hs index 6f1dd6e54c88..5b34009d2ff5 100644 --- a/samples/server/petstore/haskell-servant/lib/OpenAPIPetstore/Types.hs +++ b/samples/server/petstore/haskell-servant/lib/OpenAPIPetstore/Types.hs @@ -14,7 +14,7 @@ module OpenAPIPetstore.Types ( import Data.Data (Data) import Data.UUID (UUID) -import Data.List (stripPrefix) +import Data.List (lookup) import Data.Maybe (fromMaybe) import Data.Aeson (Value, FromJSON(..), ToJSON(..), genericToJSON, genericParseJSON) import Data.Aeson.Types (Options(..), defaultOptions) @@ -27,7 +27,6 @@ import qualified Data.Char as Char import qualified Data.Text as T import qualified Data.Map as Map import GHC.Generics (Generic) -import Data.Function ((&)) -- | Describes the result of uploading an image resource @@ -38,13 +37,26 @@ data ApiResponse = ApiResponse } deriving (Show, Eq, Generic, Data) instance FromJSON ApiResponse where - parseJSON = genericParseJSON (removeFieldLabelPrefix "apiResponse") + parseJSON = genericParseJSON optionsApiResponse instance ToJSON ApiResponse where - toJSON = genericToJSON (removeFieldLabelPrefix "apiResponse") + toJSON = genericToJSON optionsApiResponse instance ToSchema ApiResponse where declareNamedSchema = Swagger.genericDeclareNamedSchema $ Swagger.fromAesonOptions - $ removeFieldLabelPrefix "apiResponse" + $ optionsApiResponse + +optionsApiResponse :: Options +optionsApiResponse = + defaultOptions + { omitNothingFields = True + , fieldLabelModifier = \s -> fromMaybe ("did not find JSON field name for " ++ show s) $ lookup s table + } + where + table = + [ ("apiResponseCode", "code") + , ("apiResponseType", "type") + , ("apiResponseMessage", "message") + ] -- | A category for a pet @@ -54,13 +66,25 @@ data Category = Category } deriving (Show, Eq, Generic, Data) instance FromJSON Category where - parseJSON = genericParseJSON (removeFieldLabelPrefix "category") + parseJSON = genericParseJSON optionsCategory instance ToJSON Category where - toJSON = genericToJSON (removeFieldLabelPrefix "category") + toJSON = genericToJSON optionsCategory instance ToSchema Category where declareNamedSchema = Swagger.genericDeclareNamedSchema $ Swagger.fromAesonOptions - $ removeFieldLabelPrefix "category" + $ optionsCategory + +optionsCategory :: Options +optionsCategory = + defaultOptions + { omitNothingFields = True + , fieldLabelModifier = \s -> fromMaybe ("did not find JSON field name for " ++ show s) $ lookup s table + } + where + table = + [ ("categoryId", "id") + , ("categoryName", "name") + ] -- | An order for a pets from the pet store @@ -74,13 +98,29 @@ data Order = Order } deriving (Show, Eq, Generic, Data) instance FromJSON Order where - parseJSON = genericParseJSON (removeFieldLabelPrefix "order") + parseJSON = genericParseJSON optionsOrder instance ToJSON Order where - toJSON = genericToJSON (removeFieldLabelPrefix "order") + toJSON = genericToJSON optionsOrder instance ToSchema Order where declareNamedSchema = Swagger.genericDeclareNamedSchema $ Swagger.fromAesonOptions - $ removeFieldLabelPrefix "order" + $ optionsOrder + +optionsOrder :: Options +optionsOrder = + defaultOptions + { omitNothingFields = True + , fieldLabelModifier = \s -> fromMaybe ("did not find JSON field name for " ++ show s) $ lookup s table + } + where + table = + [ ("orderId", "id") + , ("orderPetId", "petId") + , ("orderQuantity", "quantity") + , ("orderShipDate", "shipDate") + , ("orderStatus", "status") + , ("orderComplete", "complete") + ] -- | A pet for sale in the pet store @@ -94,13 +134,29 @@ data Pet = Pet } deriving (Show, Eq, Generic, Data) instance FromJSON Pet where - parseJSON = genericParseJSON (removeFieldLabelPrefix "pet") + parseJSON = genericParseJSON optionsPet instance ToJSON Pet where - toJSON = genericToJSON (removeFieldLabelPrefix "pet") + toJSON = genericToJSON optionsPet instance ToSchema Pet where declareNamedSchema = Swagger.genericDeclareNamedSchema $ Swagger.fromAesonOptions - $ removeFieldLabelPrefix "pet" + $ optionsPet + +optionsPet :: Options +optionsPet = + defaultOptions + { omitNothingFields = True + , fieldLabelModifier = \s -> fromMaybe ("did not find JSON field name for " ++ show s) $ lookup s table + } + where + table = + [ ("petId", "id") + , ("petCategory", "category") + , ("petName", "name") + , ("petPhotoUrls", "photoUrls") + , ("petTags", "tags") + , ("petStatus", "status") + ] -- | A tag for a pet @@ -110,13 +166,25 @@ data Tag = Tag } deriving (Show, Eq, Generic, Data) instance FromJSON Tag where - parseJSON = genericParseJSON (removeFieldLabelPrefix "tag") + parseJSON = genericParseJSON optionsTag instance ToJSON Tag where - toJSON = genericToJSON (removeFieldLabelPrefix "tag") + toJSON = genericToJSON optionsTag instance ToSchema Tag where declareNamedSchema = Swagger.genericDeclareNamedSchema $ Swagger.fromAesonOptions - $ removeFieldLabelPrefix "tag" + $ optionsTag + +optionsTag :: Options +optionsTag = + defaultOptions + { omitNothingFields = True + , fieldLabelModifier = \s -> fromMaybe ("did not find JSON field name for " ++ show s) $ lookup s table + } + where + table = + [ ("tagId", "id") + , ("tagName", "name") + ] -- | A User who is purchasing from the pet store @@ -132,66 +200,29 @@ data User = User } deriving (Show, Eq, Generic, Data) instance FromJSON User where - parseJSON = genericParseJSON (removeFieldLabelPrefix "user") + parseJSON = genericParseJSON optionsUser instance ToJSON User where - toJSON = genericToJSON (removeFieldLabelPrefix "user") + toJSON = genericToJSON optionsUser instance ToSchema User where declareNamedSchema = Swagger.genericDeclareNamedSchema $ Swagger.fromAesonOptions - $ removeFieldLabelPrefix "user" - + $ optionsUser -uncapitalize :: String -> String -uncapitalize (first:rest) = Char.toLower first : rest -uncapitalize [] = [] - --- | Remove a field label prefix during JSON parsing. --- Also perform any replacements for special characters. -removeFieldLabelPrefix :: String -> Options -removeFieldLabelPrefix prefix = +optionsUser :: Options +optionsUser = defaultOptions { omitNothingFields = True - , fieldLabelModifier = uncapitalize . replaceSpecialChars . fromMaybe (error ("did not find prefix " ++ prefix)) . stripPrefix prefix + , fieldLabelModifier = \s -> fromMaybe ("did not find JSON field name for " ++ show s) $ lookup s table } where - replaceSpecialChars field = foldl (&) field (map mkCharReplacement specialChars) - specialChars = - [ ("$", "Dollar") - , ("^", "Caret") - , ("|", "Pipe") - , ("=", "Equal") - , ("*", "Star") - , ("-", "Dash") - , ("&", "Ampersand") - , ("%", "Percent") - , ("#", "Hash") - , ("@", "At") - , ("!", "Exclamation") - , ("+", "Plus") - , (":", "Colon") - , (";", "Semicolon") - , (">", "GreaterThan") - , ("<", "LessThan") - , (".", "Period") - , ("_", "Underscore") - , ("?", "Question_Mark") - , (",", "Comma") - , ("'", "Quote") - , ("/", "Slash") - , ("(", "Left_Parenthesis") - , (")", "Right_Parenthesis") - , ("{", "Left_Curly_Bracket") - , ("}", "Right_Curly_Bracket") - , ("[", "Left_Square_Bracket") - , ("]", "Right_Square_Bracket") - , ("~", "Tilde") - , ("`", "Backtick") - , ("<=", "Less_Than_Or_Equal_To") - , (">=", "Greater_Than_Or_Equal_To") - , ("!=", "Not_Equal") - , ("<>", "Not_Equal") - , ("~=", "Tilde_Equal") - , ("\\", "Back_Slash") - , ("\"", "Double_Quote") + table = + [ ("userId", "id") + , ("userUsername", "username") + , ("userFirstName", "firstName") + , ("userLastName", "lastName") + , ("userEmail", "email") + , ("userPassword", "password") + , ("userPhone", "phone") + , ("userUserStatus", "userStatus") ] - mkCharReplacement (replaceStr, searchStr) = T.unpack . T.replace (T.pack searchStr) (T.pack replaceStr) . T.pack + diff --git a/samples/server/petstore/haskell-yesod/src/OpenAPIPetstore/Types.hs b/samples/server/petstore/haskell-yesod/src/OpenAPIPetstore/Types.hs index b8077fc0427c..54ba54fd7686 100644 --- a/samples/server/petstore/haskell-yesod/src/OpenAPIPetstore/Types.hs +++ b/samples/server/petstore/haskell-yesod/src/OpenAPIPetstore/Types.hs @@ -14,6 +14,7 @@ module OpenAPIPetstore.Types ( import ClassyPrelude.Yesod import Data.Foldable (foldl) +import qualified Data.List as List import Data.Maybe (fromMaybe) import Data.Aeson (Value, FromJSON(..), ToJSON(..), genericToJSON, genericParseJSON) import Data.Aeson.Types (Options(..), defaultOptions) @@ -21,7 +22,6 @@ import qualified Data.Char as Char import qualified Data.Text as T import qualified Data.Map as Map import GHC.Generics (Generic) -import Data.Function ((&)) -- | Describes the result of uploading an image resource @@ -32,9 +32,22 @@ data ApiResponse = ApiResponse } deriving (Show, Eq, Generic) instance FromJSON ApiResponse where - parseJSON = genericParseJSON (removeFieldLabelPrefix "apiResponse") + parseJSON = genericParseJSON optionsApiResponse instance ToJSON ApiResponse where - toJSON = genericToJSON (removeFieldLabelPrefix "apiResponse") + toJSON = genericToJSON optionsApiResponse + +optionsApiResponse :: Options +optionsApiResponse = + defaultOptions + { omitNothingFields = True + , fieldLabelModifier = \s -> fromMaybe ("did not find JSON field name for " ++ show s) $ List.lookup s table + } + where + table = + [ ("apiResponseCode", "code") + , ("apiResponseType", "type") + , ("apiResponseMessage", "message") + ] -- | A category for a pet @@ -44,9 +57,21 @@ data Category = Category } deriving (Show, Eq, Generic) instance FromJSON Category where - parseJSON = genericParseJSON (removeFieldLabelPrefix "category") + parseJSON = genericParseJSON optionsCategory instance ToJSON Category where - toJSON = genericToJSON (removeFieldLabelPrefix "category") + toJSON = genericToJSON optionsCategory + +optionsCategory :: Options +optionsCategory = + defaultOptions + { omitNothingFields = True + , fieldLabelModifier = \s -> fromMaybe ("did not find JSON field name for " ++ show s) $ List.lookup s table + } + where + table = + [ ("categoryId", "id") + , ("categoryName", "name") + ] -- | An order for a pets from the pet store @@ -60,9 +85,25 @@ data Order = Order } deriving (Show, Eq, Generic) instance FromJSON Order where - parseJSON = genericParseJSON (removeFieldLabelPrefix "order") + parseJSON = genericParseJSON optionsOrder instance ToJSON Order where - toJSON = genericToJSON (removeFieldLabelPrefix "order") + toJSON = genericToJSON optionsOrder + +optionsOrder :: Options +optionsOrder = + defaultOptions + { omitNothingFields = True + , fieldLabelModifier = \s -> fromMaybe ("did not find JSON field name for " ++ show s) $ List.lookup s table + } + where + table = + [ ("orderId", "id") + , ("orderPetId", "petId") + , ("orderQuantity", "quantity") + , ("orderShipDate", "shipDate") + , ("orderStatus", "status") + , ("orderComplete", "complete") + ] -- | A pet for sale in the pet store @@ -76,9 +117,25 @@ data Pet = Pet } deriving (Show, Eq, Generic) instance FromJSON Pet where - parseJSON = genericParseJSON (removeFieldLabelPrefix "pet") + parseJSON = genericParseJSON optionsPet instance ToJSON Pet where - toJSON = genericToJSON (removeFieldLabelPrefix "pet") + toJSON = genericToJSON optionsPet + +optionsPet :: Options +optionsPet = + defaultOptions + { omitNothingFields = True + , fieldLabelModifier = \s -> fromMaybe ("did not find JSON field name for " ++ show s) $ List.lookup s table + } + where + table = + [ ("petId", "id") + , ("petCategory", "category") + , ("petName", "name") + , ("petPhotoUrls", "photoUrls") + , ("petTags", "tags") + , ("petStatus", "status") + ] -- | A tag for a pet @@ -88,9 +145,21 @@ data Tag = Tag } deriving (Show, Eq, Generic) instance FromJSON Tag where - parseJSON = genericParseJSON (removeFieldLabelPrefix "tag") + parseJSON = genericParseJSON optionsTag instance ToJSON Tag where - toJSON = genericToJSON (removeFieldLabelPrefix "tag") + toJSON = genericToJSON optionsTag + +optionsTag :: Options +optionsTag = + defaultOptions + { omitNothingFields = True + , fieldLabelModifier = \s -> fromMaybe ("did not find JSON field name for " ++ show s) $ List.lookup s table + } + where + table = + [ ("tagId", "id") + , ("tagName", "name") + ] -- | A User who is purchasing from the pet store @@ -106,62 +175,25 @@ data User = User } deriving (Show, Eq, Generic) instance FromJSON User where - parseJSON = genericParseJSON (removeFieldLabelPrefix "user") + parseJSON = genericParseJSON optionsUser instance ToJSON User where - toJSON = genericToJSON (removeFieldLabelPrefix "user") - + toJSON = genericToJSON optionsUser -uncapitalize :: String -> String -uncapitalize (c : cs) = Char.toLower c : cs -uncapitalize [] = [] - --- | Remove a field label prefix during JSON parsing. --- Also perform any replacements for special characters. -removeFieldLabelPrefix :: String -> Options -removeFieldLabelPrefix prefix = +optionsUser :: Options +optionsUser = defaultOptions { omitNothingFields = True - , fieldLabelModifier = uncapitalize . replaceSpecialChars . fromMaybe (error ("did not find prefix " ++ prefix)) . stripPrefix prefix + , fieldLabelModifier = \s -> fromMaybe ("did not find JSON field name for " ++ show s) $ List.lookup s table } where - replaceSpecialChars field = foldl (&) field (map mkCharReplacement specialChars) - specialChars = - [ ("$", "Dollar") - , ("^", "Caret") - , ("|", "Pipe") - , ("=", "Equal") - , ("*", "Star") - , ("-", "Dash") - , ("&", "Ampersand") - , ("%", "Percent") - , ("#", "Hash") - , ("@", "At") - , ("!", "Exclamation") - , ("+", "Plus") - , (":", "Colon") - , (";", "Semicolon") - , (">", "GreaterThan") - , ("<", "LessThan") - , (".", "Period") - , ("_", "Underscore") - , ("?", "Question_Mark") - , (",", "Comma") - , ("'", "Quote") - , ("/", "Slash") - , ("(", "Left_Parenthesis") - , (")", "Right_Parenthesis") - , ("{", "Left_Curly_Bracket") - , ("}", "Right_Curly_Bracket") - , ("[", "Left_Square_Bracket") - , ("]", "Right_Square_Bracket") - , ("~", "Tilde") - , ("`", "Backtick") - , ("<=", "Less_Than_Or_Equal_To") - , (">=", "Greater_Than_Or_Equal_To") - , ("!=", "Not_Equal") - , ("<>", "Not_Equal") - , ("~=", "Tilde_Equal") - , ("\\", "Back_Slash") - , ("\"", "Double_Quote") + table = + [ ("userId", "id") + , ("userUsername", "username") + , ("userFirstName", "firstName") + , ("userLastName", "lastName") + , ("userEmail", "email") + , ("userPassword", "password") + , ("userPhone", "phone") + , ("userUserStatus", "userStatus") ] - mkCharReplacement (replaceStr, searchStr) = T.unpack . T.replace (T.pack searchStr) (T.pack replaceStr) . T.pack + From cb56e50e0c9ef894368a8c0cdb07f35909182f5f Mon Sep 17 00:00:00 2001 From: hai22yu23 Date: Thu, 3 Aug 2023 18:13:42 +0800 Subject: [PATCH 007/292] support 32bit in postdata (#16238) --- .../src/main/resources/C-libcurl/apiClient.c.mustache | 2 +- samples/client/petstore/c/src/apiClient.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/C-libcurl/apiClient.c.mustache b/modules/openapi-generator/src/main/resources/C-libcurl/apiClient.c.mustache index e5912de027a9..0d1bf5b06593 100644 --- a/modules/openapi-generator/src/main/resources/C-libcurl/apiClient.c.mustache +++ b/modules/openapi-generator/src/main/resources/C-libcurl/apiClient.c.mustache @@ -236,7 +236,7 @@ char *assembleHeaderField(char *key, char *value) { void postData(CURL *handle, const char *bodyParameters) { curl_easy_setopt(handle, CURLOPT_POSTFIELDS, bodyParameters); curl_easy_setopt(handle, CURLOPT_POSTFIELDSIZE_LARGE, - strlen(bodyParameters)); + (curl_off_t)strlen(bodyParameters)); } int lengthOfKeyPair(keyValuePair_t *keyPair) { diff --git a/samples/client/petstore/c/src/apiClient.c b/samples/client/petstore/c/src/apiClient.c index 89d6301a98d4..4f8cc3ca0561 100644 --- a/samples/client/petstore/c/src/apiClient.c +++ b/samples/client/petstore/c/src/apiClient.c @@ -190,7 +190,7 @@ char *assembleHeaderField(char *key, char *value) { void postData(CURL *handle, const char *bodyParameters) { curl_easy_setopt(handle, CURLOPT_POSTFIELDS, bodyParameters); curl_easy_setopt(handle, CURLOPT_POSTFIELDSIZE_LARGE, - strlen(bodyParameters)); + (curl_off_t)strlen(bodyParameters)); } int lengthOfKeyPair(keyValuePair_t *keyPair) { From 82516c75d26fe7d41a5faf2680df1fceb4b264ac Mon Sep 17 00:00:00 2001 From: William Cheng Date: Thu, 3 Aug 2023 21:09:00 +0800 Subject: [PATCH 008/292] Fix implements in oneof, anyof templates in java okhttp client generator (#16241) * fix implements in oneof, anyof templates in java okhttp * add tests * update samples --- bin/configs/java-okhttp-gson-streaming.yaml | 1 + .../okhttp-gson/anyof_model.mustache | 2 +- .../okhttp-gson/oneof_model.mustache | 2 +- .../src/test/resources/3_0/streaming.yaml | 4 + .../.openapi-generator/FILES | 2 + .../java/okhttp-gson-streaming/README.md | 1 + .../okhttp-gson-streaming/api/openapi.yaml | 4 + .../okhttp-gson-streaming/docs/SimpleOneOf.md | 16 + .../okhttp-gson-streaming/docs/SomeObj.md | 4 + .../java/org/openapitools/client/JSON.java | 1 + .../client/model/SimpleOneOf.java | 280 ++++++++++++++++++ .../openapitools/client/model/SomeObj.java | 5 +- .../client/model/SimpleOneOfTest.java | 33 +++ 13 files changed, 352 insertions(+), 3 deletions(-) create mode 100644 samples/client/others/java/okhttp-gson-streaming/docs/SimpleOneOf.md create mode 100644 samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/model/SimpleOneOf.java create mode 100644 samples/client/others/java/okhttp-gson-streaming/src/test/java/org/openapitools/client/model/SimpleOneOfTest.java diff --git a/bin/configs/java-okhttp-gson-streaming.yaml b/bin/configs/java-okhttp-gson-streaming.yaml index 34da56581a74..9e75c93bac4c 100644 --- a/bin/configs/java-okhttp-gson-streaming.yaml +++ b/bin/configs/java-okhttp-gson-streaming.yaml @@ -7,3 +7,4 @@ additionalProperties: artifactId: petstore-okhttp-gson hideGenerationTimestamp: "true" supportStreaming: true + serializableModel: true diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/anyof_model.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/anyof_model.mustache index 333dfbd81cf2..39a942e04a32 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/anyof_model.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/anyof_model.mustache @@ -32,7 +32,7 @@ import com.google.gson.JsonParseException; import {{invokerPackage}}.JSON; {{>additionalModelTypeAnnotations}}{{>generatedAnnotation}}{{>xmlAnnotation}} -public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-implements}}, {{{.}}}{{/vendorExtensions.x-implements}} { +public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-implements}} implements {{{.}}}{{^-last}}, {{/-last}}{{/vendorExtensions.x-implements}} { private static final Logger log = Logger.getLogger({{classname}}.class.getName()); public static class CustomTypeAdapterFactory implements TypeAdapterFactory { diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/oneof_model.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/oneof_model.mustache index fc817fbbf0d2..6ab9ac9d396d 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/oneof_model.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/oneof_model.mustache @@ -34,7 +34,7 @@ import com.google.gson.JsonParseException; import {{invokerPackage}}.JSON; {{>additionalModelTypeAnnotations}}{{>generatedAnnotation}}{{>xmlAnnotation}} -public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-implements}}, {{{.}}}{{/vendorExtensions.x-implements}} { +public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-implements}} implements {{{.}}}{{^-last}}, {{/-last}}{{/vendorExtensions.x-implements}} { private static final Logger log = Logger.getLogger({{classname}}.class.getName()); public static class CustomTypeAdapterFactory implements TypeAdapterFactory { diff --git a/modules/openapi-generator/src/test/resources/3_0/streaming.yaml b/modules/openapi-generator/src/test/resources/3_0/streaming.yaml index 28c7114f1d5a..79ecef76a0e8 100644 --- a/modules/openapi-generator/src/test/resources/3_0/streaming.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/streaming.yaml @@ -77,3 +77,7 @@ components: type: boolean type: type: string + SimpleOneOf: + oneOf: + - type: string + - type: integer diff --git a/samples/client/others/java/okhttp-gson-streaming/.openapi-generator/FILES b/samples/client/others/java/okhttp-gson-streaming/.openapi-generator/FILES index 1f0129a4d8c9..e86711088b66 100644 --- a/samples/client/others/java/okhttp-gson-streaming/.openapi-generator/FILES +++ b/samples/client/others/java/okhttp-gson-streaming/.openapi-generator/FILES @@ -6,6 +6,7 @@ api/openapi.yaml build.gradle build.sbt docs/PingApi.md +docs/SimpleOneOf.md docs/SomeObj.md git_push.sh gradle.properties @@ -35,4 +36,5 @@ src/main/java/org/openapitools/client/auth/Authentication.java src/main/java/org/openapitools/client/auth/HttpBasicAuth.java src/main/java/org/openapitools/client/auth/HttpBearerAuth.java src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java +src/main/java/org/openapitools/client/model/SimpleOneOf.java src/main/java/org/openapitools/client/model/SomeObj.java diff --git a/samples/client/others/java/okhttp-gson-streaming/README.md b/samples/client/others/java/okhttp-gson-streaming/README.md index bed7f7484a49..5308de7dee17 100644 --- a/samples/client/others/java/okhttp-gson-streaming/README.md +++ b/samples/client/others/java/okhttp-gson-streaming/README.md @@ -124,6 +124,7 @@ Class | Method | HTTP request | Description ## Documentation for Models + - [SimpleOneOf](docs/SimpleOneOf.md) - [SomeObj](docs/SomeObj.md) diff --git a/samples/client/others/java/okhttp-gson-streaming/api/openapi.yaml b/samples/client/others/java/okhttp-gson-streaming/api/openapi.yaml index 50bf4ce1ec89..b2d364cc6ad5 100644 --- a/samples/client/others/java/okhttp-gson-streaming/api/openapi.yaml +++ b/samples/client/others/java/okhttp-gson-streaming/api/openapi.yaml @@ -80,6 +80,10 @@ components: type: type: string type: object + SimpleOneOf: + oneOf: + - type: string + - type: integer getPing_request: properties: name: diff --git a/samples/client/others/java/okhttp-gson-streaming/docs/SimpleOneOf.md b/samples/client/others/java/okhttp-gson-streaming/docs/SimpleOneOf.md new file mode 100644 index 000000000000..aa7149fde93a --- /dev/null +++ b/samples/client/others/java/okhttp-gson-streaming/docs/SimpleOneOf.md @@ -0,0 +1,16 @@ + + +# SimpleOneOf + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| + + +## Implemented Interfaces + +* Serializable + + diff --git a/samples/client/others/java/okhttp-gson-streaming/docs/SomeObj.md b/samples/client/others/java/okhttp-gson-streaming/docs/SomeObj.md index 49a0726b5a38..70bf3335f7be 100644 --- a/samples/client/others/java/okhttp-gson-streaming/docs/SomeObj.md +++ b/samples/client/others/java/okhttp-gson-streaming/docs/SomeObj.md @@ -22,4 +22,8 @@ | SOMEOBJIDENTIFIER | "SomeObjIdentifier" | +## Implemented Interfaces + +* Serializable + diff --git a/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/JSON.java b/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/JSON.java index 1e547ada4313..417a0011024a 100644 --- a/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/JSON.java +++ b/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/JSON.java @@ -93,6 +93,7 @@ private static Class getClassByDiscriminator(Map classByDiscriminatorValue, Stri gsonBuilder.registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter); gsonBuilder.registerTypeAdapter(LocalDate.class, localDateTypeAdapter); gsonBuilder.registerTypeAdapter(byte[].class, byteArrayAdapter); + gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.SimpleOneOf.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.SomeObj.CustomTypeAdapterFactory()); gson = gsonBuilder.create(); } diff --git a/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/model/SimpleOneOf.java b/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/model/SimpleOneOf.java new file mode 100644 index 000000000000..36de4fc0b025 --- /dev/null +++ b/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/model/SimpleOneOf.java @@ -0,0 +1,280 @@ +/* + * ping some object + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import java.io.Serializable; + + + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonArray; +import com.google.gson.JsonParseException; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class SimpleOneOf extends AbstractOpenApiSchema implements Serializable { + private static final Logger log = Logger.getLogger(SimpleOneOf.class.getName()); + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!SimpleOneOf.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'SimpleOneOf' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterString = gson.getDelegateAdapter(this, TypeToken.get(String.class)); + final TypeAdapter adapterInteger = gson.getDelegateAdapter(this, TypeToken.get(Integer.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, SimpleOneOf value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + // check if the actual instance is of the type `String` + if (value.getActualInstance() instanceof String) { + JsonPrimitive primitive = adapterString.toJsonTree((String)value.getActualInstance()).getAsJsonPrimitive(); + elementAdapter.write(out, primitive); + return; + } + // check if the actual instance is of the type `Integer` + if (value.getActualInstance() instanceof Integer) { + JsonPrimitive primitive = adapterInteger.toJsonTree((Integer)value.getActualInstance()).getAsJsonPrimitive(); + elementAdapter.write(out, primitive); + return; + } + throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: Integer, String"); + } + + @Override + public SimpleOneOf read(JsonReader in) throws IOException { + Object deserialized = null; + JsonElement jsonElement = elementAdapter.read(in); + + int match = 0; + ArrayList errorMessages = new ArrayList<>(); + TypeAdapter actualAdapter = elementAdapter; + + // deserialize String + try { + // validate the JSON object to see if any exception is thrown + if(!jsonElement.getAsJsonPrimitive().isString()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type String in the JSON string but got `%s`", jsonElement.toString())); + } + actualAdapter = adapterString; + match++; + log.log(Level.FINER, "Input data matches schema 'String'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for String failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'String'", e); + } + // deserialize Integer + try { + // validate the JSON object to see if any exception is thrown + if(!jsonElement.getAsJsonPrimitive().isNumber()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString())); + } + actualAdapter = adapterInteger; + match++; + log.log(Level.FINER, "Input data matches schema 'Integer'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Integer failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'Integer'", e); + } + + if (match == 1) { + SimpleOneOf ret = new SimpleOneOf(); + ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); + return ret; + } + + throw new IOException(String.format("Failed deserialization for SimpleOneOf: %d classes match result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", match, errorMessages, jsonElement.toString())); + } + }.nullSafe(); + } + } + + // store a list of schema names defined in oneOf + public static final Map> schemas = new HashMap>(); + + public SimpleOneOf() { + super("oneOf", Boolean.FALSE); + } + + public SimpleOneOf(Integer o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public SimpleOneOf(String o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("String", String.class); + schemas.put("Integer", Integer.class); + } + + @Override + public Map> getSchemas() { + return SimpleOneOf.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * Integer, String + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (instance instanceof String) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof Integer) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be Integer, String"); + } + + /** + * Get the actual instance, which can be the following: + * Integer, String + * + * @return The actual instance (Integer, String) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `String`. If the actual instance is not `String`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `String` + * @throws ClassCastException if the instance is not `String` + */ + public String getString() throws ClassCastException { + return (String)super.getActualInstance(); + } + /** + * Get the actual instance of `Integer`. If the actual instance is not `Integer`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Integer` + * @throws ClassCastException if the instance is not `Integer` + */ + public Integer getInteger() throws ClassCastException { + return (Integer)super.getActualInstance(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to SimpleOneOf + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + // validate oneOf schemas one by one + int validCount = 0; + ArrayList errorMessages = new ArrayList<>(); + // validate the json string with String + try { + if(!jsonElement.getAsJsonPrimitive().isString()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type String in the JSON string but got `%s`", jsonElement.toString())); + } + validCount++; + } catch (Exception e) { + errorMessages.add(String.format("Deserialization for String failed with `%s`.", e.getMessage())); + // continue to the next one + } + // validate the json string with Integer + try { + if(!jsonElement.getAsJsonPrimitive().isNumber()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString())); + } + validCount++; + } catch (Exception e) { + errorMessages.add(String.format("Deserialization for Integer failed with `%s`.", e.getMessage())); + // continue to the next one + } + if (validCount != 1) { + throw new IOException(String.format("The JSON string is invalid for SimpleOneOf with oneOf schemas: Integer, String. %d class(es) match the result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", validCount, errorMessages, jsonElement.toString())); + } + } + + /** + * Create an instance of SimpleOneOf given an JSON string + * + * @param jsonString JSON string + * @return An instance of SimpleOneOf + * @throws IOException if the JSON string is invalid with respect to SimpleOneOf + */ + public static SimpleOneOf fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, SimpleOneOf.class); + } + + /** + * Convert an instance of SimpleOneOf to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/model/SomeObj.java b/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/model/SomeObj.java index d52b087d3e9a..b55567f3d79a 100644 --- a/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/model/SomeObj.java +++ b/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/model/SomeObj.java @@ -21,6 +21,7 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; +import java.io.Serializable; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -51,7 +52,9 @@ * SomeObj */ @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class SomeObj { +public class SomeObj implements Serializable { + private static final long serialVersionUID = 1L; + /** * Gets or Sets $type */ diff --git a/samples/client/others/java/okhttp-gson-streaming/src/test/java/org/openapitools/client/model/SimpleOneOfTest.java b/samples/client/others/java/okhttp-gson-streaming/src/test/java/org/openapitools/client/model/SimpleOneOfTest.java new file mode 100644 index 000000000000..b1d2d8042a4f --- /dev/null +++ b/samples/client/others/java/okhttp-gson-streaming/src/test/java/org/openapitools/client/model/SimpleOneOfTest.java @@ -0,0 +1,33 @@ +/* + * ping some object + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for SimpleOneOf + */ +public class SimpleOneOfTest { + private final SimpleOneOf model = new SimpleOneOf(); + + /** + * Model tests for SimpleOneOf + */ + @Test + public void testSimpleOneOf() { + // TODO: test SimpleOneOf + } + +} From c080660cc15e4c34a1871df84c49a067ac8bf442 Mon Sep 17 00:00:00 2001 From: Ken Kaizu Date: Sat, 5 Aug 2023 14:32:02 +0900 Subject: [PATCH 009/292] [Scala] scala-akka-http-server support pekko-http using useApachePekko flag (#16255) * introduce useApachePekko flag into scala-akka-http-server * useApachePekko flag in scala-akka-http-server templates * introduce scala-pekko-http-server samples --- .github/workflows/samples-scala.yaml | 1 + bin/configs/scala-pekko-http-server.yaml | 7 + docs/generators/scala-akka-http-server.md | 1 + .../languages/ScalaAkkaHttpServerCodegen.java | 39 +++- .../scala-akka-http-server/api.mustache | 20 +- .../scala-akka-http-server/build.sbt.mustache | 6 +- .../controller.mustache | 10 +- .../scala-akka-http-server/helper.mustache | 4 +- .../multipartDirectives.mustache | 20 +- .../stringDirectives.mustache | 20 +- .../.openapi-generator-ignore | 23 ++ .../.openapi-generator/FILES | 15 ++ .../.openapi-generator/VERSION | 1 + .../scala-pekko-http-server/README.md | 54 +++++ .../scala-pekko-http-server/build.sbt | 9 + .../openapitools/server/AkkaHttpHelper.scala | 34 +++ .../org/openapitools/server/Controller.scala | 18 ++ .../server/MultipartDirectives.scala | 89 ++++++++ .../server/StringDirectives.scala | 126 +++++++++++ .../org/openapitools/server/api/PetApi.scala | 198 ++++++++++++++++++ .../openapitools/server/api/StoreApi.scala | 101 +++++++++ .../org/openapitools/server/api/UserApi.scala | 162 ++++++++++++++ .../server/model/ApiResponse.scala | 18 ++ .../openapitools/server/model/Category.scala | 16 ++ .../org/openapitools/server/model/Order.scala | 25 +++ .../org/openapitools/server/model/Pet.scala | 24 +++ .../org/openapitools/server/model/Tag.scala | 16 ++ .../org/openapitools/server/model/User.scala | 28 +++ 28 files changed, 1038 insertions(+), 47 deletions(-) create mode 100644 bin/configs/scala-pekko-http-server.yaml create mode 100644 samples/server/petstore/scala-pekko-http-server/.openapi-generator-ignore create mode 100644 samples/server/petstore/scala-pekko-http-server/.openapi-generator/FILES create mode 100644 samples/server/petstore/scala-pekko-http-server/.openapi-generator/VERSION create mode 100644 samples/server/petstore/scala-pekko-http-server/README.md create mode 100644 samples/server/petstore/scala-pekko-http-server/build.sbt create mode 100644 samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/AkkaHttpHelper.scala create mode 100644 samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/Controller.scala create mode 100644 samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/MultipartDirectives.scala create mode 100644 samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/StringDirectives.scala create mode 100644 samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/api/PetApi.scala create mode 100644 samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/api/StoreApi.scala create mode 100644 samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/api/UserApi.scala create mode 100644 samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/model/ApiResponse.scala create mode 100644 samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/model/Category.scala create mode 100644 samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/model/Order.scala create mode 100644 samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/model/Pet.scala create mode 100644 samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/model/Tag.scala create mode 100644 samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/model/User.scala diff --git a/.github/workflows/samples-scala.yaml b/.github/workflows/samples-scala.yaml index 0d71f743d67b..dfb11048bd36 100644 --- a/.github/workflows/samples-scala.yaml +++ b/.github/workflows/samples-scala.yaml @@ -27,6 +27,7 @@ jobs: - samples/server/petstore/scala-lagom-server - samples/server/petstore/scala-play-server - samples/server/petstore/scala-akka-http-server + - samples/server/petstore/scala-pekko-http-server - samples/server/petstore/scalatra - samples/server/petstore/scala-finch # cannot be tested with jdk11 steps: diff --git a/bin/configs/scala-pekko-http-server.yaml b/bin/configs/scala-pekko-http-server.yaml new file mode 100644 index 000000000000..1758feaf615f --- /dev/null +++ b/bin/configs/scala-pekko-http-server.yaml @@ -0,0 +1,7 @@ +generatorName: scala-akka-http-server +outputDir: samples/server/petstore/scala-pekko-http-server +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/scala-akka-http-server +additionalProperties: + artifactId: openapi-scala-pekko-http-server + useApachePekko: true diff --git a/docs/generators/scala-akka-http-server.md b/docs/generators/scala-akka-http-server.md index df3cef97920e..8419c093758b 100644 --- a/docs/generators/scala-akka-http-server.md +++ b/docs/generators/scala-akka-http-server.md @@ -37,6 +37,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| |sourceFolder|source folder for generated code| |null| +|useApachePekko|Use apache pekko-http instead of akka-http.| |false| ## IMPORT MAPPING diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaAkkaHttpServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaAkkaHttpServerCodegen.java index dd50aec48895..7ec9dd1c6945 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaAkkaHttpServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaAkkaHttpServerCodegen.java @@ -44,15 +44,27 @@ public class ScalaAkkaHttpServerCodegen extends AbstractScalaCodegen implements protected String akkaHttpVersion; protected boolean generateAsManagedSources; + protected boolean useApachePekko; public static final String AKKA_HTTP_VERSION = "akkaHttpVersion"; public static final String AKKA_HTTP_VERSION_DESC = "The version of akka-http"; public static final String DEFAULT_AKKA_HTTP_VERSION = "10.1.10"; + public static final String DEFAULT_PEKKO_HTTP_VERSION = "1.0.0"; public static final String GENERATE_AS_MANAGED_SOURCES = "asManagedSources"; public static final String GENERATE_AS_MANAGED_SOURCES_DESC = "Resulting files cab be used as managed resources. No build files or default controllers will be generated"; public static final boolean DEFAULT_GENERATE_AS_MANAGED_SOURCES = false; + public static final String USE_APACHE_PEKKO = "useApachePekko"; + public static final String USE_APACHE_PEKKO_DESC = "Use apache pekko-http instead of akka-http."; + public static final boolean DEFAULT_USE_APACHE_PEKKO = false; + + // scala-akka-http-server specific properties + private static final String IS_10_1_10_PLUS = "akkaHttp10_1_10_plus"; + private static final String AKKA_IMPORT_GROUP_ID = "akkaImportGroupId"; + + private static final Pattern akkaVersionPattern = Pattern.compile("([0-9]+)(\\.([0-9]+))?(\\.([0-9]+))?(.\\+)?"); + final Logger LOGGER = LoggerFactory.getLogger(ScalaAkkaHttpServerCodegen.class); public CodegenType getTag() { @@ -108,6 +120,7 @@ public ScalaAkkaHttpServerCodegen() { invokerPackage = "org.openapitools.server"; akkaHttpVersion = DEFAULT_AKKA_HTTP_VERSION; generateAsManagedSources = DEFAULT_GENERATE_AS_MANAGED_SOURCES; + useApachePekko = DEFAULT_USE_APACHE_PEKKO; setReservedWordsLowerCase( Arrays.asList( @@ -124,6 +137,7 @@ public ScalaAkkaHttpServerCodegen() { cliOptions.add(CliOption.newString(CodegenConstants.ARTIFACT_VERSION, CodegenConstants.ARTIFACT_VERSION_DESC).defaultValue(artifactVersion)); cliOptions.add(CliOption.newString(AKKA_HTTP_VERSION, AKKA_HTTP_VERSION_DESC).defaultValue(akkaHttpVersion)); cliOptions.add(CliOption.newBoolean(GENERATE_AS_MANAGED_SOURCES, GENERATE_AS_MANAGED_SOURCES_DESC).defaultValue(Boolean.valueOf(DEFAULT_GENERATE_AS_MANAGED_SOURCES).toString())); + cliOptions.add(CliOption.newBoolean(USE_APACHE_PEKKO, USE_APACHE_PEKKO_DESC).defaultValue(Boolean.valueOf(DEFAULT_USE_APACHE_PEKKO).toString())); importMapping.remove("Seq"); importMapping.remove("List"); @@ -181,14 +195,27 @@ public void processOpts() { additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); } + if (additionalProperties.containsKey(USE_APACHE_PEKKO)) { + useApachePekko = Boolean.parseBoolean(additionalProperties.get(USE_APACHE_PEKKO).toString()); + } else { + additionalProperties.put(USE_APACHE_PEKKO, useApachePekko); + } + if (additionalProperties.containsKey(AKKA_HTTP_VERSION)) { akkaHttpVersion = (String) additionalProperties.get(AKKA_HTTP_VERSION); } else { - additionalProperties.put(AKKA_HTTP_VERSION, akkaHttpVersion); + String version = useApachePekko ? DEFAULT_PEKKO_HTTP_VERSION : DEFAULT_AKKA_HTTP_VERSION; + additionalProperties.put(AKKA_HTTP_VERSION, version); } - parseAkkaHttpVersion(); - + if (useApachePekko) { + additionalProperties.put(IS_10_1_10_PLUS, true); // Pekko HTTP is a fork of Akka HTTP 10.2.x + additionalProperties.put(USE_APACHE_PEKKO, true); + additionalProperties.put(AKKA_IMPORT_GROUP_ID, "org.apache.pekko"); + } else { + additionalProperties.put(AKKA_IMPORT_GROUP_ID, "akka"); + parseAkkaHttpVersion(); + } if (additionalProperties.containsKey(GENERATE_AS_MANAGED_SOURCES)) { generateAsManagedSources = Boolean.parseBoolean(additionalProperties.get(GENERATE_AS_MANAGED_SOURCES).toString()); @@ -210,12 +237,8 @@ public void processOpts() { (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "MultipartDirectives.scala")); } - private static final String IS_10_1_10_PLUS = "akkaHttp10_1_10_plus"; - private boolean is10_1_10AndAbove = false; - - private static final Pattern akkaVersionPattern = Pattern.compile("([0-9]+)(\\.([0-9]+))?(\\.([0-9]+))?(.\\+)?"); - private void parseAkkaHttpVersion() { + boolean is10_1_10AndAbove = false; Matcher matcher = akkaVersionPattern.matcher(akkaHttpVersion); if (matcher.matches()) { String majorS = matcher.group(1); diff --git a/modules/openapi-generator/src/main/resources/scala-akka-http-server/api.mustache b/modules/openapi-generator/src/main/resources/scala-akka-http-server/api.mustache index 27cb2cb8d4fb..57a72c7387e7 100644 --- a/modules/openapi-generator/src/main/resources/scala-akka-http-server/api.mustache +++ b/modules/openapi-generator/src/main/resources/scala-akka-http-server/api.mustache @@ -1,15 +1,15 @@ package {{package}} -import akka.http.scaladsl.server.Directives._ -import akka.http.scaladsl.server.Route -import akka.http.scaladsl.model.StatusCodes -{{^pathMatcherPatterns.isEmpty}}import akka.http.scaladsl.server.{PathMatcher, PathMatcher1} +import {{akkaImportGroupId}}.http.scaladsl.server.Directives._ +import {{akkaImportGroupId}}.http.scaladsl.server.Route +import {{akkaImportGroupId}}.http.scaladsl.model.StatusCodes +{{^pathMatcherPatterns.isEmpty}}import {{akkaImportGroupId}}.http.scaladsl.server.{PathMatcher, PathMatcher1} {{/pathMatcherPatterns.isEmpty}} -{{#hasMarshalling}}import akka.http.scaladsl.marshalling.ToEntityMarshaller -import akka.http.scaladsl.unmarshalling.FromEntityUnmarshaller -import akka.http.scaladsl.unmarshalling.FromStringUnmarshaller +{{#hasMarshalling}}import {{akkaImportGroupId}}.http.scaladsl.marshalling.ToEntityMarshaller +import {{akkaImportGroupId}}.http.scaladsl.unmarshalling.FromEntityUnmarshaller +import {{akkaImportGroupId}}.http.scaladsl.unmarshalling.FromStringUnmarshaller {{/hasMarshalling}} -{{#hasCookieParams}}import akka.http.scaladsl.model.headers.HttpCookiePair +{{#hasCookieParams}}import {{akkaImportGroupId}}.http.scaladsl.model.headers.HttpCookiePair {{/hasCookieParams}} import {{invokerPackage}}.AkkaHttpHelper._ {{#hasMultipart}}import {{invokerPackage}}.StringDirectives @@ -20,8 +20,8 @@ import {{invokerPackage}}.PartsAndFiles {{#imports}}import {{import}} {{/imports}} {{#hasMultipart}}import scala.util.Try -import akka.http.scaladsl.server.MalformedRequestContentRejection -import akka.http.scaladsl.server.directives.FileInfo +import {{akkaImportGroupId}}.http.scaladsl.server.MalformedRequestContentRejection +import {{akkaImportGroupId}}.http.scaladsl.server.directives.FileInfo {{/hasMultipart}} diff --git a/modules/openapi-generator/src/main/resources/scala-akka-http-server/build.sbt.mustache b/modules/openapi-generator/src/main/resources/scala-akka-http-server/build.sbt.mustache index d4b57b676140..f2f036b613f7 100644 --- a/modules/openapi-generator/src/main/resources/scala-akka-http-server/build.sbt.mustache +++ b/modules/openapi-generator/src/main/resources/scala-akka-http-server/build.sbt.mustache @@ -3,7 +3,9 @@ name := "{{artifactId}}" organization := "{{groupId}}" scalaVersion := "2.12.8" -libraryDependencies ++= Seq( +libraryDependencies ++= Seq({{#useApachePekko}} + "org.apache.pekko" %% "pekko-stream" % "{{akkaHttpVersion}}", + "org.apache.pekko" %% "pekko-http" % "{{akkaHttpVersion}}"{{/useApachePekko}}{{^useApachePekko}} "com.typesafe.akka" %% "akka-stream" % "2.5.21", - "com.typesafe.akka" %% "akka-http" % "{{akkaHttpVersion}}" + "com.typesafe.akka" %% "akka-http" % "{{akkaHttpVersion}}"{{/useApachePekko}} ) diff --git a/modules/openapi-generator/src/main/resources/scala-akka-http-server/controller.mustache b/modules/openapi-generator/src/main/resources/scala-akka-http-server/controller.mustache index 7aa237fa6e62..b67a75b83c12 100644 --- a/modules/openapi-generator/src/main/resources/scala-akka-http-server/controller.mustache +++ b/modules/openapi-generator/src/main/resources/scala-akka-http-server/controller.mustache @@ -1,12 +1,12 @@ package {{invokerPackage}} -import akka.http.scaladsl.Http -import akka.http.scaladsl.server.Route +import {{akkaImportGroupId}}.http.scaladsl.Http +import {{akkaImportGroupId}}.http.scaladsl.server.Route {{#apiInfo}}{{#apis}}{{#operations}}import {{package}}.{{classname}} {{/operations}}{{/apis}}{{/apiInfo}} -import akka.http.scaladsl.server.Directives._ -import akka.actor.ActorSystem -import akka.stream.ActorMaterializer +import {{akkaImportGroupId}}.http.scaladsl.server.Directives._ +import {{akkaImportGroupId}}.actor.ActorSystem +import {{akkaImportGroupId}}.stream.ActorMaterializer class Controller({{#apiInfo}}{{#apis}}{{#operations}}{{classVarName}}: {{classname}}{{^-last}}, {{/-last}}{{/operations}}{{/apis}}{{/apiInfo}})(implicit system: ActorSystem, materializer: ActorMaterializer) { diff --git a/modules/openapi-generator/src/main/resources/scala-akka-http-server/helper.mustache b/modules/openapi-generator/src/main/resources/scala-akka-http-server/helper.mustache index 8aa3c0f8c269..ffd7090e2d44 100644 --- a/modules/openapi-generator/src/main/resources/scala-akka-http-server/helper.mustache +++ b/modules/openapi-generator/src/main/resources/scala-akka-http-server/helper.mustache @@ -1,7 +1,7 @@ package {{invokerPackage}} -import akka.http.scaladsl.server.Directives._ -import akka.http.scaladsl.server.{PathMatcher, PathMatcher1} +import {{akkaImportGroupId}}.http.scaladsl.server.Directives._ +import {{akkaImportGroupId}}.http.scaladsl.server.{PathMatcher, PathMatcher1} import scala.util.{Failure, Success, Try} import scala.util.control.NoStackTrace diff --git a/modules/openapi-generator/src/main/resources/scala-akka-http-server/multipartDirectives.mustache b/modules/openapi-generator/src/main/resources/scala-akka-http-server/multipartDirectives.mustache index 6e802204c57d..97427179ff21 100644 --- a/modules/openapi-generator/src/main/resources/scala-akka-http-server/multipartDirectives.mustache +++ b/modules/openapi-generator/src/main/resources/scala-akka-http-server/multipartDirectives.mustache @@ -3,22 +3,22 @@ package {{invokerPackage}} import java.io.File import java.nio.file.Files -import akka.annotation.ApiMayChange -import akka.http.scaladsl.model.Multipart.FormData -import akka.http.scaladsl.model.{ContentType, HttpEntity, Multipart} -import akka.http.scaladsl.server.Directive1 -import akka.http.scaladsl.server.directives._ -import akka.stream.Materializer -import akka.stream.scaladsl._ +import {{akkaImportGroupId}}.annotation.ApiMayChange +import {{akkaImportGroupId}}.http.scaladsl.model.Multipart.FormData +import {{akkaImportGroupId}}.http.scaladsl.model.{ContentType, HttpEntity, Multipart} +import {{akkaImportGroupId}}.http.scaladsl.server.Directive1 +import {{akkaImportGroupId}}.http.scaladsl.server.directives._ +import {{akkaImportGroupId}}.stream.Materializer +import {{akkaImportGroupId}}.stream.scaladsl._ import scala.collection.immutable import scala.concurrent.{ExecutionContextExecutor, Future} trait MultipartDirectives { - import akka.http.scaladsl.server.directives.BasicDirectives._ - import akka.http.scaladsl.server.directives.FutureDirectives._ - import akka.http.scaladsl.server.directives.MarshallingDirectives._ + import {{akkaImportGroupId}}.http.scaladsl.server.directives.BasicDirectives._ + import {{akkaImportGroupId}}.http.scaladsl.server.directives.FutureDirectives._ + import {{akkaImportGroupId}}.http.scaladsl.server.directives.MarshallingDirectives._ @ApiMayChange def formAndFiles(fileFields: FileField*): Directive1[PartsAndFiles] = diff --git a/modules/openapi-generator/src/main/resources/scala-akka-http-server/stringDirectives.mustache b/modules/openapi-generator/src/main/resources/scala-akka-http-server/stringDirectives.mustache index 5640a9d45490..5ee2f6035f97 100644 --- a/modules/openapi-generator/src/main/resources/scala-akka-http-server/stringDirectives.mustache +++ b/modules/openapi-generator/src/main/resources/scala-akka-http-server/stringDirectives.mustache @@ -1,9 +1,9 @@ package {{invokerPackage}} -import akka.http.scaladsl.common._ -import akka.http.scaladsl.server.{Directive, Directive0, Directive1, InvalidRequiredValueForQueryParamRejection, MalformedFormFieldRejection, MissingFormFieldRejection, MissingQueryParamRejection, UnsupportedRequestContentTypeRejection} -import akka.http.scaladsl.server.directives.BasicDirectives -import akka.http.scaladsl.unmarshalling.Unmarshaller.UnsupportedContentTypeException +import {{akkaImportGroupId}}.http.scaladsl.common._ +import {{akkaImportGroupId}}.http.scaladsl.server.{Directive, Directive0, Directive1, InvalidRequiredValueForQueryParamRejection, MalformedFormFieldRejection, MissingFormFieldRejection, MissingQueryParamRejection, UnsupportedRequestContentTypeRejection} +import {{akkaImportGroupId}}.http.scaladsl.server.directives.BasicDirectives +import {{akkaImportGroupId}}.http.scaladsl.unmarshalling.Unmarshaller.UnsupportedContentTypeException import scala.concurrent.Future import scala.util.{Failure, Success} @@ -48,10 +48,10 @@ object StringDirectives extends StringDirectives { def apply(value: A): B = f(value) } - import akka.http.scaladsl.server.directives.BasicDirectives._ - import akka.http.scaladsl.server.directives.FutureDirectives._ - import akka.http.scaladsl.server.directives.RouteDirectives._ - import akka.http.scaladsl.unmarshalling._ + import {{akkaImportGroupId}}.http.scaladsl.server.directives.BasicDirectives._ + import {{akkaImportGroupId}}.http.scaladsl.server.directives.FutureDirectives._ + import {{akkaImportGroupId}}.http.scaladsl.server.directives.RouteDirectives._ + import {{akkaImportGroupId}}.http.scaladsl.unmarshalling._ type FSU[T] = FromStringUnmarshaller[T] type FSOU[T] = Unmarshaller[Option[String], T] @@ -112,8 +112,8 @@ object StringDirectives extends StringDirectives { //////////////////// tuple support //////////////////// - import akka.http.scaladsl.server.util.BinaryPolyFunc - import akka.http.scaladsl.server.util.TupleOps._ + import {{akkaImportGroupId}}.http.scaladsl.server.util.BinaryPolyFunc + import {{akkaImportGroupId}}.http.scaladsl.server.util.TupleOps._ implicit def forTuple[T](implicit fold: FoldLeft[Directive0, T, ConvertStringDefAndConcatenate.type]): StringDefAux[T, fold.Out] = stringDef[T, fold.Out](fold(BasicDirectives.pass, _)) diff --git a/samples/server/petstore/scala-pekko-http-server/.openapi-generator-ignore b/samples/server/petstore/scala-pekko-http-server/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/server/petstore/scala-pekko-http-server/.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/petstore/scala-pekko-http-server/.openapi-generator/FILES b/samples/server/petstore/scala-pekko-http-server/.openapi-generator/FILES new file mode 100644 index 000000000000..cfcbab175e5d --- /dev/null +++ b/samples/server/petstore/scala-pekko-http-server/.openapi-generator/FILES @@ -0,0 +1,15 @@ +README.md +build.sbt +src/main/scala/org/openapitools/server/AkkaHttpHelper.scala +src/main/scala/org/openapitools/server/Controller.scala +src/main/scala/org/openapitools/server/MultipartDirectives.scala +src/main/scala/org/openapitools/server/StringDirectives.scala +src/main/scala/org/openapitools/server/api/PetApi.scala +src/main/scala/org/openapitools/server/api/StoreApi.scala +src/main/scala/org/openapitools/server/api/UserApi.scala +src/main/scala/org/openapitools/server/model/ApiResponse.scala +src/main/scala/org/openapitools/server/model/Category.scala +src/main/scala/org/openapitools/server/model/Order.scala +src/main/scala/org/openapitools/server/model/Pet.scala +src/main/scala/org/openapitools/server/model/Tag.scala +src/main/scala/org/openapitools/server/model/User.scala diff --git a/samples/server/petstore/scala-pekko-http-server/.openapi-generator/VERSION b/samples/server/petstore/scala-pekko-http-server/.openapi-generator/VERSION new file mode 100644 index 000000000000..757e67400401 --- /dev/null +++ b/samples/server/petstore/scala-pekko-http-server/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/scala-pekko-http-server/README.md b/samples/server/petstore/scala-pekko-http-server/README.md new file mode 100644 index 000000000000..a1c3b50c09b2 --- /dev/null +++ b/samples/server/petstore/scala-pekko-http-server/README.md @@ -0,0 +1,54 @@ +# OpenAPI Petstore + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + + + ## API + + ### Pet + + |Name|Role| + |----|----| + |`org.openapitools.server.api.PetController`|akka-http API controller| + |`org.openapitools.server.api.PetApi`|Representing trait| + |`org.openapitools.server.api.PetApiImpl`|Default implementation| + + * `POST /v2/pet` - Add a new pet to the store + * `DELETE /v2/pet/{petId}` - Deletes a pet + * `GET /v2/pet/findByStatus?status=[value]` - Finds Pets by status + * `GET /v2/pet/findByTags?tags=[value]` - Finds Pets by tags + * `GET /v2/pet/{petId}` - Find pet by ID + * `PUT /v2/pet` - Update an existing pet + * `POST /v2/pet/{petId}` - Updates a pet in the store with form data + * `POST /v2/pet/{petId}/uploadImage` - uploads an image + + ### Store + + |Name|Role| + |----|----| + |`org.openapitools.server.api.StoreController`|akka-http API controller| + |`org.openapitools.server.api.StoreApi`|Representing trait| + |`org.openapitools.server.api.StoreApiImpl`|Default implementation| + + * `DELETE /v2/store/order/{orderId}` - Delete purchase order by ID + * `GET /v2/store/inventory` - Returns pet inventories by status + * `GET /v2/store/order/{orderId}` - Find purchase order by ID + * `POST /v2/store/order` - Place an order for a pet + + ### User + + |Name|Role| + |----|----| + |`org.openapitools.server.api.UserController`|akka-http API controller| + |`org.openapitools.server.api.UserApi`|Representing trait| + |`org.openapitools.server.api.UserApiImpl`|Default implementation| + + * `POST /v2/user` - Create user + * `POST /v2/user/createWithArray` - Creates list of users with given input array + * `POST /v2/user/createWithList` - Creates list of users with given input array + * `DELETE /v2/user/{username}` - Delete user + * `GET /v2/user/{username}` - Get user by user name + * `GET /v2/user/login?username=[value]&password=[value]` - Logs user into the system + * `GET /v2/user/logout` - Logs out current logged in user session + * `PUT /v2/user/{username}` - Updated user + diff --git a/samples/server/petstore/scala-pekko-http-server/build.sbt b/samples/server/petstore/scala-pekko-http-server/build.sbt new file mode 100644 index 000000000000..8e54aeb598ff --- /dev/null +++ b/samples/server/petstore/scala-pekko-http-server/build.sbt @@ -0,0 +1,9 @@ +version := "1.0.0" +name := "openapi-scala-pekko-http-server" +organization := "org.openapitools" +scalaVersion := "2.12.8" + +libraryDependencies ++= Seq( + "org.apache.pekko" %% "pekko-stream" % "1.0.0", + "org.apache.pekko" %% "pekko-http" % "1.0.0" +) diff --git a/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/AkkaHttpHelper.scala b/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/AkkaHttpHelper.scala new file mode 100644 index 000000000000..ba240dedd8a6 --- /dev/null +++ b/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/AkkaHttpHelper.scala @@ -0,0 +1,34 @@ +package org.openapitools.server + +import org.apache.pekko.http.scaladsl.server.Directives._ +import org.apache.pekko.http.scaladsl.server.{PathMatcher, PathMatcher1} +import scala.util.{Failure, Success, Try} +import scala.util.control.NoStackTrace + +object AkkaHttpHelper { + def optToTry[T](opt: Option[T], err: => String): Try[T] = + opt.map[Try[T]](Success(_)) getOrElse Failure(new RuntimeException(err) with NoStackTrace) + + /** + * A PathMatcher that matches and extracts a Float value. The matched string representation is the pure decimal, + * optionally signed form of a float value, i.e. without exponent. + * + * @group pathmatcher + */ + val FloatNumber: PathMatcher1[Float] = + PathMatcher("""[+-]?\d*\.?\d*""".r) flatMap { string => + try Some(java.lang.Float.parseFloat(string)) + catch { case _: NumberFormatException => None } + } + + /** + * A PathMatcher that matches and extracts a Boolean value. + * + * @group pathmatcher + */ + val Boolean: PathMatcher1[Boolean] = + Segment.flatMap { string => + try Some(string.toBoolean) + catch { case _: IllegalArgumentException => None } + } +} diff --git a/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/Controller.scala b/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/Controller.scala new file mode 100644 index 000000000000..58b99cbe0ee5 --- /dev/null +++ b/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/Controller.scala @@ -0,0 +1,18 @@ +package org.openapitools.server + +import org.apache.pekko.http.scaladsl.Http +import org.apache.pekko.http.scaladsl.server.Route +import org.openapitools.server.api.PetApi +import org.openapitools.server.api.StoreApi +import org.openapitools.server.api.UserApi + +import org.apache.pekko.http.scaladsl.server.Directives._ +import org.apache.pekko.actor.ActorSystem +import org.apache.pekko.stream.ActorMaterializer + +class Controller(pet: PetApi, store: StoreApi, user: UserApi)(implicit system: ActorSystem, materializer: ActorMaterializer) { + + lazy val routes: Route = pet.route ~ store.route ~ user.route + + Http().bindAndHandle(routes, "0.0.0.0", 9000) +} \ No newline at end of file diff --git a/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/MultipartDirectives.scala b/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/MultipartDirectives.scala new file mode 100644 index 000000000000..87c1ef2c852f --- /dev/null +++ b/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/MultipartDirectives.scala @@ -0,0 +1,89 @@ +package org.openapitools.server + +import java.io.File +import java.nio.file.Files + +import org.apache.pekko.annotation.ApiMayChange +import org.apache.pekko.http.scaladsl.model.Multipart.FormData +import org.apache.pekko.http.scaladsl.model.{ContentType, HttpEntity, Multipart} +import org.apache.pekko.http.scaladsl.server.Directive1 +import org.apache.pekko.http.scaladsl.server.directives._ +import org.apache.pekko.stream.Materializer +import org.apache.pekko.stream.scaladsl._ + +import scala.collection.immutable +import scala.concurrent.{ExecutionContextExecutor, Future} + +trait MultipartDirectives { + + import org.apache.pekko.http.scaladsl.server.directives.BasicDirectives._ + import org.apache.pekko.http.scaladsl.server.directives.FutureDirectives._ + import org.apache.pekko.http.scaladsl.server.directives.MarshallingDirectives._ + + @ApiMayChange + def formAndFiles(fileFields: FileField*): Directive1[PartsAndFiles] = + entity(as[Multipart.FormData]).flatMap { + formData => + extractRequestContext.flatMap { ctx => + implicit val mat: Materializer = ctx.materializer + implicit val ec: ExecutionContextExecutor = ctx.executionContext + + val uploadingSink: Sink[FormData.BodyPart, Future[PartsAndFiles]] = + Sink.foldAsync[PartsAndFiles, Multipart.FormData.BodyPart](PartsAndFiles.Empty) { + (acc, part) => + def discard(p: Multipart.FormData.BodyPart): Future[PartsAndFiles] = { + p.entity.discardBytes() + Future.successful(acc) + } + + part.filename.map { + fileName => + fileFields.find(_.fieldName == part.name) + .map { + case FileField(_, destFn) => + val fileInfo = FileInfo(part.name, fileName, part.entity.contentType) + val dest = destFn(fileInfo) + + part.entity.dataBytes.runWith(FileIO.toPath(dest.toPath)).map { _ => + acc.addFile(fileInfo, dest) + } + }.getOrElse(discard(part)) + } getOrElse { + part.entity match { + case HttpEntity.Strict(ct: ContentType.NonBinary, data) => + val charsetName = ct.charset.nioCharset.name + val partContent = data.decodeString(charsetName) + + Future.successful(acc.addForm(part.name, partContent)) + case _ => + discard(part) + } + } + } + + val uploadedF = formData.parts.runWith(uploadingSink) + + onSuccess(uploadedF) + } + } +} + +object MultipartDirectives extends MultipartDirectives with FileUploadDirectives { + val tempFileFromFileInfo: FileInfo => File = { + file: FileInfo => Files.createTempFile(file.fileName, ".tmp").toFile() + } +} + +final case class FileField(fieldName: String, fileNameF: FileInfo => File = MultipartDirectives.tempFileFromFileInfo) + +final case class PartsAndFiles(form: immutable.Map[String, String], files: Map[String, (FileInfo, File)]) { + def addForm(fieldName: String, content: String): PartsAndFiles = this.copy(form.updated(fieldName, content)) + + def addFile(info: FileInfo, file: File): PartsAndFiles = this.copy( + files = files.updated(info.fieldName, (info, file)) + ) +} + +object PartsAndFiles { + val Empty: PartsAndFiles = PartsAndFiles(immutable.Map.empty, immutable.Map.empty) +} \ No newline at end of file diff --git a/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/StringDirectives.scala b/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/StringDirectives.scala new file mode 100644 index 000000000000..6e83b56aa6fd --- /dev/null +++ b/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/StringDirectives.scala @@ -0,0 +1,126 @@ +package org.openapitools.server + +import org.apache.pekko.http.scaladsl.common._ +import org.apache.pekko.http.scaladsl.server.{Directive, Directive0, Directive1, InvalidRequiredValueForQueryParamRejection, MalformedFormFieldRejection, MissingFormFieldRejection, MissingQueryParamRejection, UnsupportedRequestContentTypeRejection} +import org.apache.pekko.http.scaladsl.server.directives.BasicDirectives +import org.apache.pekko.http.scaladsl.unmarshalling.Unmarshaller.UnsupportedContentTypeException + +import scala.concurrent.Future +import scala.util.{Failure, Success} + +trait StringDirectives { + implicit def _symbol2NR(symbol: Symbol): NameReceptacle[String] = new NameReceptacle[String](symbol.name) + implicit def _string2NR(string: String): NameReceptacle[String] = new NameReceptacle[String](string) + + import StringDirectives._ + type StringValueProvider = Map[String, String] + + def stringField(pdm: StringMagnet): pdm.Out = pdm() + + def stringFields(pdm: StringMagnet): pdm.Out = pdm() + +} + +object StringDirectives extends StringDirectives { + + sealed trait StringMagnet { + type Out + def apply(): Out + } + object StringMagnet { + implicit def apply[T](value: T)(implicit sdef: StringDef[T]): StringMagnet { type Out = sdef.Out } = + new StringMagnet { + type Out = sdef.Out + def apply(): sdef.Out = sdef(value) + } + } + + type StringDefAux[A, B] = StringDef[A] { type Out = B } + sealed trait StringDef[T] { + type Out + def apply(value: T): Out + } + object StringDef { + protected def stringDef[A, B](f: A => B): StringDefAux[A, B] = + new StringDef[A] { + type Out = B + + def apply(value: A): B = f(value) + } + + import org.apache.pekko.http.scaladsl.server.directives.BasicDirectives._ + import org.apache.pekko.http.scaladsl.server.directives.FutureDirectives._ + import org.apache.pekko.http.scaladsl.server.directives.RouteDirectives._ + import org.apache.pekko.http.scaladsl.unmarshalling._ + + type FSU[T] = FromStringUnmarshaller[T] + type FSOU[T] = Unmarshaller[Option[String], T] + type SFVP = StringValueProvider + + protected def extractField[A, B](f: A => Directive1[B]): StringDefAux[A, Directive1[B]] = stringDef(f) + + protected def handleFieldResult[T](fieldName: String, result: Future[T]): Directive1[T] = onComplete(result).flatMap { + case Success(x) => provide(x) + case Failure(Unmarshaller.NoContentException) => reject(MissingFormFieldRejection(fieldName)) + case Failure(x: UnsupportedContentTypeException) => reject(UnsupportedRequestContentTypeRejection(x.supported, x.actualContentType)) + case Failure(x) => reject(MalformedFormFieldRejection(fieldName, if (x.getMessage == null) "" else x.getMessage, Option(x.getCause))) + } + + private def filter[T](paramName: String, fsou: FSOU[T])(implicit vp: SFVP): Directive1[T] = { + extract { ctx => + import ctx.{executionContext, materializer} + handleFieldResult(paramName, fsou(vp.get(paramName))) + }.flatMap(identity) + } + + implicit def forString(implicit fsu: FSU[String], vp: SFVP): StringDefAux[String, Directive1[String]] = + extractField[String, String] { string => filter(string, fsu) } + implicit def forSymbol(implicit fsu: FSU[String], vp: SFVP): StringDefAux[Symbol, Directive1[String]] = + extractField[Symbol, String] { symbol => filter(symbol.name, fsu) } + implicit def forNR[T](implicit fsu: FSU[T], vp: SFVP): StringDefAux[NameReceptacle[T], Directive1[T]] = + extractField[NameReceptacle[T], T] { nr => filter(nr.name, fsu) } + implicit def forNUR[T](implicit vp: SFVP): StringDefAux[NameUnmarshallerReceptacle[T], Directive1[T]] = + extractField[NameUnmarshallerReceptacle[T], T] { nr => filter(nr.name, nr.um) } + implicit def forNOR[T](implicit fsou: FSOU[T], vp: SFVP): StringDefAux[NameOptionReceptacle[T], Directive1[Option[T]]] = + extractField[NameOptionReceptacle[T], Option[T]] { nr => filter[Option[T]](nr.name, fsou) } + implicit def forNDR[T](implicit fsou: FSOU[T], vp: SFVP): StringDefAux[NameDefaultReceptacle[T], Directive1[T]] = + extractField[NameDefaultReceptacle[T], T] { nr => filter[T](nr.name, fsou withDefaultValue nr.default) } + implicit def forNOUR[T](implicit vp: SFVP): StringDefAux[NameOptionUnmarshallerReceptacle[T], Directive1[Option[T]]] = + extractField[NameOptionUnmarshallerReceptacle[T], Option[T]] { nr => filter(nr.name, nr.um: FSOU[T]) } + implicit def forNDUR[T](implicit vp: SFVP): StringDefAux[NameDefaultUnmarshallerReceptacle[T], Directive1[T]] = + extractField[NameDefaultUnmarshallerReceptacle[T], T] { nr => filter[T](nr.name, (nr.um: FSOU[T]) withDefaultValue nr.default) } + + //////////////////// required parameter support //////////////////// + + private def requiredFilter[T](paramName: String, fsou: FSOU[T], requiredValue: Any)(implicit vp: SFVP): Directive0 = { + extract { ctx => + import ctx.{executionContext, materializer} + onComplete(fsou(vp.get(paramName))) flatMap { + case Success(value) if value == requiredValue => pass + case Success(value) => reject(InvalidRequiredValueForQueryParamRejection(paramName, requiredValue.toString, value.toString)).toDirective[Unit] + case _ => reject(MissingQueryParamRejection(paramName)).toDirective[Unit] + } + }.flatMap(identity) + } + + implicit def forRVR[T](implicit fsu: FSU[T], vp: SFVP): StringDefAux[RequiredValueReceptacle[T], Directive0] = + stringDef[RequiredValueReceptacle[T], Directive0] { rvr => requiredFilter(rvr.name, fsu, rvr.requiredValue) } + + implicit def forRVDR[T](implicit vp: SFVP): StringDefAux[RequiredValueUnmarshallerReceptacle[T], Directive0] = + stringDef[RequiredValueUnmarshallerReceptacle[T], Directive0] { rvr => requiredFilter(rvr.name, rvr.um, rvr.requiredValue) } + + //////////////////// tuple support //////////////////// + + import org.apache.pekko.http.scaladsl.server.util.BinaryPolyFunc + import org.apache.pekko.http.scaladsl.server.util.TupleOps._ + + implicit def forTuple[T](implicit fold: FoldLeft[Directive0, T, ConvertStringDefAndConcatenate.type]): StringDefAux[T, fold.Out] = + stringDef[T, fold.Out](fold(BasicDirectives.pass, _)) + + object ConvertStringDefAndConcatenate extends BinaryPolyFunc { + implicit def from[P, TA, TB](implicit sdef: StringDef[P] {type Out = Directive[TB]}, ev: Join[TA, TB]): BinaryPolyFunc.Case[Directive[TA], P, ConvertStringDefAndConcatenate.type] {type Out = Directive[ev.Out]} = + at[Directive[TA], P] { (a, t) => a & sdef(t) } + } + + } +} diff --git a/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/api/PetApi.scala b/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/api/PetApi.scala new file mode 100644 index 000000000000..23f7b88abcec --- /dev/null +++ b/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/api/PetApi.scala @@ -0,0 +1,198 @@ +package org.openapitools.server.api + +import org.apache.pekko.http.scaladsl.server.Directives._ +import org.apache.pekko.http.scaladsl.server.Route +import org.apache.pekko.http.scaladsl.model.StatusCodes +import org.apache.pekko.http.scaladsl.marshalling.ToEntityMarshaller +import org.apache.pekko.http.scaladsl.unmarshalling.FromEntityUnmarshaller +import org.apache.pekko.http.scaladsl.unmarshalling.FromStringUnmarshaller +import org.openapitools.server.AkkaHttpHelper._ +import org.openapitools.server.StringDirectives +import org.openapitools.server.MultipartDirectives +import org.openapitools.server.FileField +import org.openapitools.server.PartsAndFiles +import org.openapitools.server.model.ApiResponse +import java.io.File +import org.openapitools.server.model.Pet +import scala.util.Try +import org.apache.pekko.http.scaladsl.server.MalformedRequestContentRejection +import org.apache.pekko.http.scaladsl.server.directives.FileInfo + + +class PetApi( + petService: PetApiService, + petMarshaller: PetApiMarshaller +) extends MultipartDirectives with StringDirectives { + + + import petMarshaller._ + + lazy val route: Route = + path("pet") { + post { + entity(as[Pet]){ pet => + petService.addPet(pet = pet) + } + } + } ~ + path("pet" / LongNumber) { (petId) => + delete { + optionalHeaderValueByName("api_key") { apiKey => + petService.deletePet(petId = petId, apiKey = apiKey) + } + } + } ~ + path("pet" / "findByStatus") { + get { + parameters("status".as[String]) { (status) => + petService.findPetsByStatus(status = status) + } + } + } ~ + path("pet" / "findByTags") { + get { + parameters("tags".as[String]) { (tags) => + petService.findPetsByTags(tags = tags) + } + } + } ~ + path("pet" / LongNumber) { (petId) => + get { + petService.getPetById(petId = petId) + } + } ~ + path("pet") { + put { + entity(as[Pet]){ pet => + petService.updatePet(pet = pet) + } + } + } ~ + path("pet" / LongNumber) { (petId) => + post { + formFields("name".as[String].?, "status".as[String].?) { (name, status) => + petService.updatePetWithForm(petId = petId, name = name, status = status) + } + } + } ~ + path("pet" / LongNumber / "uploadImage") { (petId) => + post { + formAndFiles(FileField("file")) { partsAndFiles => + val _____ : Try[Route] = for { + file <- optToTry(partsAndFiles.files.get("file"), s"File file missing") + } yield { + implicit val vp: StringValueProvider = partsAndFiles.form + stringFields("additionalMetadata".as[String].?) { (additionalMetadata) => + petService.uploadFile(petId = petId, additionalMetadata = additionalMetadata, file = file) + } + } + _____.fold[Route](t => reject(MalformedRequestContentRejection("Missing file.", t)), identity) + } + } + } +} + + +trait PetApiService { + + def addPet200(responsePet: Pet)(implicit toEntityMarshallerPet: ToEntityMarshaller[Pet]): Route = + complete((200, responsePet)) + def addPet405: Route = + complete((405, "Invalid input")) + /** + * Code: 200, Message: successful operation, DataType: Pet + * Code: 405, Message: Invalid input + */ + def addPet(pet: Pet) + (implicit toEntityMarshallerPet: ToEntityMarshaller[Pet]): Route + + def deletePet400: Route = + complete((400, "Invalid pet value")) + /** + * Code: 400, Message: Invalid pet value + */ + def deletePet(petId: Long, apiKey: Option[String]): Route + + def findPetsByStatus200(responsePetarray: Seq[Pet])(implicit toEntityMarshallerPetarray: ToEntityMarshaller[Seq[Pet]]): Route = + complete((200, responsePetarray)) + def findPetsByStatus400: Route = + complete((400, "Invalid status value")) + /** + * Code: 200, Message: successful operation, DataType: Seq[Pet] + * Code: 400, Message: Invalid status value + */ + def findPetsByStatus(status: String) + (implicit toEntityMarshallerPetarray: ToEntityMarshaller[Seq[Pet]]): Route + + def findPetsByTags200(responsePetarray: Seq[Pet])(implicit toEntityMarshallerPetarray: ToEntityMarshaller[Seq[Pet]]): Route = + complete((200, responsePetarray)) + def findPetsByTags400: Route = + complete((400, "Invalid tag value")) + /** + * Code: 200, Message: successful operation, DataType: Seq[Pet] + * Code: 400, Message: Invalid tag value + */ + def findPetsByTags(tags: String) + (implicit toEntityMarshallerPetarray: ToEntityMarshaller[Seq[Pet]]): Route + + def getPetById200(responsePet: Pet)(implicit toEntityMarshallerPet: ToEntityMarshaller[Pet]): Route = + complete((200, responsePet)) + def getPetById400: Route = + complete((400, "Invalid ID supplied")) + def getPetById404: Route = + complete((404, "Pet not found")) + /** + * Code: 200, Message: successful operation, DataType: Pet + * Code: 400, Message: Invalid ID supplied + * Code: 404, Message: Pet not found + */ + def getPetById(petId: Long) + (implicit toEntityMarshallerPet: ToEntityMarshaller[Pet]): Route + + def updatePet200(responsePet: Pet)(implicit toEntityMarshallerPet: ToEntityMarshaller[Pet]): Route = + complete((200, responsePet)) + def updatePet400: Route = + complete((400, "Invalid ID supplied")) + def updatePet404: Route = + complete((404, "Pet not found")) + def updatePet405: Route = + complete((405, "Validation exception")) + /** + * Code: 200, Message: successful operation, DataType: Pet + * Code: 400, Message: Invalid ID supplied + * Code: 404, Message: Pet not found + * Code: 405, Message: Validation exception + */ + def updatePet(pet: Pet) + (implicit toEntityMarshallerPet: ToEntityMarshaller[Pet]): Route + + def updatePetWithForm405: Route = + complete((405, "Invalid input")) + /** + * Code: 405, Message: Invalid input + */ + def updatePetWithForm(petId: Long, name: Option[String], status: Option[String]): Route + + def uploadFile200(responseApiResponse: ApiResponse)(implicit toEntityMarshallerApiResponse: ToEntityMarshaller[ApiResponse]): Route = + complete((200, responseApiResponse)) + /** + * Code: 200, Message: successful operation, DataType: ApiResponse + */ + def uploadFile(petId: Long, additionalMetadata: Option[String], file: (FileInfo, File)) + (implicit toEntityMarshallerApiResponse: ToEntityMarshaller[ApiResponse]): Route + +} + +trait PetApiMarshaller { + implicit def fromEntityUnmarshallerPet: FromEntityUnmarshaller[Pet] + + + + implicit def toEntityMarshallerPetarray: ToEntityMarshaller[Seq[Pet]] + + implicit def toEntityMarshallerPet: ToEntityMarshaller[Pet] + + implicit def toEntityMarshallerApiResponse: ToEntityMarshaller[ApiResponse] + +} + diff --git a/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/api/StoreApi.scala b/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/api/StoreApi.scala new file mode 100644 index 000000000000..300d018d3948 --- /dev/null +++ b/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/api/StoreApi.scala @@ -0,0 +1,101 @@ +package org.openapitools.server.api + +import org.apache.pekko.http.scaladsl.server.Directives._ +import org.apache.pekko.http.scaladsl.server.Route +import org.apache.pekko.http.scaladsl.model.StatusCodes +import org.apache.pekko.http.scaladsl.marshalling.ToEntityMarshaller +import org.apache.pekko.http.scaladsl.unmarshalling.FromEntityUnmarshaller +import org.apache.pekko.http.scaladsl.unmarshalling.FromStringUnmarshaller +import org.openapitools.server.AkkaHttpHelper._ +import org.openapitools.server.model.Order + + +class StoreApi( + storeService: StoreApiService, + storeMarshaller: StoreApiMarshaller +) { + + + import storeMarshaller._ + + lazy val route: Route = + path("store" / "order" / Segment) { (orderId) => + delete { + storeService.deleteOrder(orderId = orderId) + } + } ~ + path("store" / "inventory") { + get { + storeService.getInventory() + } + } ~ + path("store" / "order" / LongNumber) { (orderId) => + get { + storeService.getOrderById(orderId = orderId) + } + } ~ + path("store" / "order") { + post { + entity(as[Order]){ order => + storeService.placeOrder(order = order) + } + } + } +} + + +trait StoreApiService { + + def deleteOrder400: Route = + complete((400, "Invalid ID supplied")) + def deleteOrder404: Route = + complete((404, "Order not found")) + /** + * Code: 400, Message: Invalid ID supplied + * Code: 404, Message: Order not found + */ + def deleteOrder(orderId: String): Route + + def getInventory200(responseMapmap: Map[String, Int])(implicit toEntityMarshallerMapmap: ToEntityMarshaller[Map[String, Int]]): Route = + complete((200, responseMapmap)) + /** + * Code: 200, Message: successful operation, DataType: Map[String, Int] + */ + def getInventory(): Route + + def getOrderById200(responseOrder: Order)(implicit toEntityMarshallerOrder: ToEntityMarshaller[Order]): Route = + complete((200, responseOrder)) + def getOrderById400: Route = + complete((400, "Invalid ID supplied")) + def getOrderById404: Route = + complete((404, "Order not found")) + /** + * Code: 200, Message: successful operation, DataType: Order + * Code: 400, Message: Invalid ID supplied + * Code: 404, Message: Order not found + */ + def getOrderById(orderId: Long) + (implicit toEntityMarshallerOrder: ToEntityMarshaller[Order]): Route + + def placeOrder200(responseOrder: Order)(implicit toEntityMarshallerOrder: ToEntityMarshaller[Order]): Route = + complete((200, responseOrder)) + def placeOrder400: Route = + complete((400, "Invalid Order")) + /** + * Code: 200, Message: successful operation, DataType: Order + * Code: 400, Message: Invalid Order + */ + def placeOrder(order: Order) + (implicit toEntityMarshallerOrder: ToEntityMarshaller[Order]): Route + +} + +trait StoreApiMarshaller { + implicit def fromEntityUnmarshallerOrder: FromEntityUnmarshaller[Order] + + + + implicit def toEntityMarshallerOrder: ToEntityMarshaller[Order] + +} + diff --git a/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/api/UserApi.scala b/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/api/UserApi.scala new file mode 100644 index 000000000000..e1e39d96471a --- /dev/null +++ b/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/api/UserApi.scala @@ -0,0 +1,162 @@ +package org.openapitools.server.api + +import org.apache.pekko.http.scaladsl.server.Directives._ +import org.apache.pekko.http.scaladsl.server.Route +import org.apache.pekko.http.scaladsl.model.StatusCodes +import org.apache.pekko.http.scaladsl.marshalling.ToEntityMarshaller +import org.apache.pekko.http.scaladsl.unmarshalling.FromEntityUnmarshaller +import org.apache.pekko.http.scaladsl.unmarshalling.FromStringUnmarshaller +import org.openapitools.server.AkkaHttpHelper._ +import java.time.OffsetDateTime +import org.openapitools.server.model.User + + +class UserApi( + userService: UserApiService, + userMarshaller: UserApiMarshaller +) { + + + import userMarshaller._ + + lazy val route: Route = + path("user") { + post { + entity(as[User]){ user => + userService.createUser(user = user) + } + } + } ~ + path("user" / "createWithArray") { + post { + entity(as[Seq[User]]){ user => + userService.createUsersWithArrayInput(user = user) + } + } + } ~ + path("user" / "createWithList") { + post { + entity(as[Seq[User]]){ user => + userService.createUsersWithListInput(user = user) + } + } + } ~ + path("user" / Segment) { (username) => + delete { + userService.deleteUser(username = username) + } + } ~ + path("user" / Segment) { (username) => + get { + userService.getUserByName(username = username) + } + } ~ + path("user" / "login") { + get { + parameters("username".as[String], "password".as[String]) { (username, password) => + userService.loginUser(username = username, password = password) + } + } + } ~ + path("user" / "logout") { + get { + userService.logoutUser() + } + } ~ + path("user" / Segment) { (username) => + put { + entity(as[User]){ user => + userService.updateUser(username = username, user = user) + } + } + } +} + + +trait UserApiService { + + def createUserDefault(statusCode: Int): Route = + complete((statusCode, "successful operation")) + /** + * Code: 0, Message: successful operation + */ + def createUser(user: User): Route + + def createUsersWithArrayInputDefault(statusCode: Int): Route = + complete((statusCode, "successful operation")) + /** + * Code: 0, Message: successful operation + */ + def createUsersWithArrayInput(user: Seq[User]): Route + + def createUsersWithListInputDefault(statusCode: Int): Route = + complete((statusCode, "successful operation")) + /** + * Code: 0, Message: successful operation + */ + def createUsersWithListInput(user: Seq[User]): Route + + def deleteUser400: Route = + complete((400, "Invalid username supplied")) + def deleteUser404: Route = + complete((404, "User not found")) + /** + * Code: 400, Message: Invalid username supplied + * Code: 404, Message: User not found + */ + def deleteUser(username: String): Route + + def getUserByName200(responseUser: User)(implicit toEntityMarshallerUser: ToEntityMarshaller[User]): Route = + complete((200, responseUser)) + def getUserByName400: Route = + complete((400, "Invalid username supplied")) + def getUserByName404: Route = + complete((404, "User not found")) + /** + * Code: 200, Message: successful operation, DataType: User + * Code: 400, Message: Invalid username supplied + * Code: 404, Message: User not found + */ + def getUserByName(username: String) + (implicit toEntityMarshallerUser: ToEntityMarshaller[User]): Route + + def loginUser200(responseString: String)(implicit toEntityMarshallerString: ToEntityMarshaller[String]): Route = + complete((200, responseString)) + def loginUser400: Route = + complete((400, "Invalid username/password supplied")) + /** + * Code: 200, Message: successful operation, DataType: String + * Code: 400, Message: Invalid username/password supplied + */ + def loginUser(username: String, password: String): Route + + def logoutUserDefault(statusCode: Int): Route = + complete((statusCode, "successful operation")) + /** + * Code: 0, Message: successful operation + */ + def logoutUser(): Route + + def updateUser400: Route = + complete((400, "Invalid user supplied")) + def updateUser404: Route = + complete((404, "User not found")) + /** + * Code: 400, Message: Invalid user supplied + * Code: 404, Message: User not found + */ + def updateUser(username: String, user: User): Route + +} + +trait UserApiMarshaller { + implicit def fromEntityUnmarshallerUser: FromEntityUnmarshaller[User] + + implicit def fromEntityUnmarshallerUserList: FromEntityUnmarshaller[Seq[User]] + + + + implicit def toEntityMarshallerUser: ToEntityMarshaller[User] + +} + diff --git a/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/model/ApiResponse.scala b/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/model/ApiResponse.scala new file mode 100644 index 000000000000..abe04c18183d --- /dev/null +++ b/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/model/ApiResponse.scala @@ -0,0 +1,18 @@ +package org.openapitools.server.model + + +/** + * = An uploaded response = + * + * Describes the result of uploading an image resource + * + * @param code for example: ''null'' + * @param `type` for example: ''null'' + * @param message for example: ''null'' +*/ +final case class ApiResponse ( + code: Option[Int] = None, + `type`: Option[String] = None, + message: Option[String] = None +) + diff --git a/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/model/Category.scala b/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/model/Category.scala new file mode 100644 index 000000000000..f01b8adf6e06 --- /dev/null +++ b/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/model/Category.scala @@ -0,0 +1,16 @@ +package org.openapitools.server.model + + +/** + * = Pet category = + * + * A category for a pet + * + * @param id for example: ''null'' + * @param name for example: ''null'' +*/ +final case class Category ( + id: Option[Long] = None, + name: Option[String] = None +) + diff --git a/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/model/Order.scala b/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/model/Order.scala new file mode 100644 index 000000000000..e79e2c15cf6e --- /dev/null +++ b/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/model/Order.scala @@ -0,0 +1,25 @@ +package org.openapitools.server.model + +import java.time.OffsetDateTime + +/** + * = Pet Order = + * + * An order for a pets from the pet store + * + * @param id for example: ''null'' + * @param petId for example: ''null'' + * @param quantity for example: ''null'' + * @param shipDate for example: ''null'' + * @param status Order Status for example: ''null'' + * @param complete for example: ''null'' +*/ +final case class Order ( + id: Option[Long] = None, + petId: Option[Long] = None, + quantity: Option[Int] = None, + shipDate: Option[OffsetDateTime] = None, + status: Option[String] = None, + complete: Option[Boolean] = None +) + diff --git a/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/model/Pet.scala b/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/model/Pet.scala new file mode 100644 index 000000000000..0f58bcee1da7 --- /dev/null +++ b/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/model/Pet.scala @@ -0,0 +1,24 @@ +package org.openapitools.server.model + + +/** + * = a Pet = + * + * A pet for sale in the pet store + * + * @param id for example: ''null'' + * @param category for example: ''null'' + * @param name for example: ''doggie'' + * @param photoUrls for example: ''null'' + * @param tags for example: ''null'' + * @param status pet status in the store for example: ''null'' +*/ +final case class Pet ( + id: Option[Long] = None, + category: Option[Category] = None, + name: String, + photoUrls: Seq[String], + tags: Option[Seq[Tag]] = None, + status: Option[String] = None +) + diff --git a/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/model/Tag.scala b/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/model/Tag.scala new file mode 100644 index 000000000000..9daae0f44fff --- /dev/null +++ b/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/model/Tag.scala @@ -0,0 +1,16 @@ +package org.openapitools.server.model + + +/** + * = Pet Tag = + * + * A tag for a pet + * + * @param id for example: ''null'' + * @param name for example: ''null'' +*/ +final case class Tag ( + id: Option[Long] = None, + name: Option[String] = None +) + diff --git a/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/model/User.scala b/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/model/User.scala new file mode 100644 index 000000000000..18e1772ba4d4 --- /dev/null +++ b/samples/server/petstore/scala-pekko-http-server/src/main/scala/org/openapitools/server/model/User.scala @@ -0,0 +1,28 @@ +package org.openapitools.server.model + + +/** + * = a User = + * + * A User who is purchasing from the pet store + * + * @param id for example: ''null'' + * @param username for example: ''null'' + * @param firstName for example: ''null'' + * @param lastName for example: ''null'' + * @param email for example: ''null'' + * @param password for example: ''null'' + * @param phone for example: ''null'' + * @param userStatus User Status for example: ''null'' +*/ +final case class User ( + id: Option[Long] = None, + username: Option[String] = None, + firstName: Option[String] = None, + lastName: Option[String] = None, + email: Option[String] = None, + password: Option[String] = None, + phone: Option[String] = None, + userStatus: Option[Int] = None +) + From f6fb83878bccf3fd61379943f6611c99d9bfe819 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Sat, 5 Aug 2023 13:32:43 +0800 Subject: [PATCH 010/292] [Default] update isAdditionalPropertiesTrue tag to cover more types (#16227) * enhance additional properties support * update samples * update tests * add more tests * update samples * fix samples --- .../openapitools/codegen/CodegenModel.java | 7 +- .../openapitools/codegen/DefaultCodegen.java | 10 +- .../codegen/DefaultCodegenTest.java | 14 +-- ...ith-fake-endpoints-models-for-testing.yaml | 21 +++- .../src/Org.OpenAPITools/Model/Drawing.cs | 12 +++ .../Org.OpenAPITools/Model/NullableClass.cs | 12 +++ .../src/Org.OpenAPITools/Model/Drawing.cs | 7 ++ .../Org.OpenAPITools/Model/NullableClass.cs | 7 ++ .../src/Org.OpenAPITools/Model/Drawing.cs | 7 ++ .../Org.OpenAPITools/Model/NullableClass.cs | 7 ++ .../src/Org.OpenAPITools/Model/Drawing.cs | 7 ++ .../Org.OpenAPITools/Model/NullableClass.cs | 7 ++ .../src/Org.OpenAPITools/Model/Drawing.cs | 12 +++ .../Org.OpenAPITools/Model/NullableClass.cs | 12 +++ .../src/Org.OpenAPITools/Model/Drawing.cs | 12 +++ .../Org.OpenAPITools/Model/NullableClass.cs | 12 +++ .../src/Org.OpenAPITools/Model/Drawing.cs | 12 +++ .../Org.OpenAPITools/Model/NullableClass.cs | 12 +++ .../src/Org.OpenAPITools/Model/Drawing.cs | 12 +++ .../Org.OpenAPITools/Model/NullableClass.cs | 12 +++ .../src/Org.OpenAPITools/Model/Drawing.cs | 15 ++- .../Org.OpenAPITools/Model/NullableClass.cs | 15 ++- .../src/Org.OpenAPITools/Model/Drawing.cs | 12 +++ .../Org.OpenAPITools/Model/NullableClass.cs | 12 +++ .../src/Org.OpenAPITools/Model/Drawing.cs | 12 +++ .../Org.OpenAPITools/Model/NullableClass.cs | 12 +++ .../model_additional_properties_any_type.go | 25 +++++ .../model_additional_properties_array.go | 25 +++++ .../model_additional_properties_boolean.go | 25 +++++ .../model_additional_properties_integer.go | 25 +++++ .../model_additional_properties_number.go | 25 +++++ .../model_additional_properties_object.go | 25 +++++ .../model_additional_properties_string.go | 25 +++++ .../model/AdditionalPropertiesAnyType.java | 98 ++++++++++++++++--- .../model/AdditionalPropertiesArray.java | 98 ++++++++++++++++--- .../model/AdditionalPropertiesBoolean.java | 98 ++++++++++++++++--- .../model/AdditionalPropertiesInteger.java | 98 ++++++++++++++++--- .../model/AdditionalPropertiesNumber.java | 98 ++++++++++++++++--- .../model/AdditionalPropertiesObject.java | 98 ++++++++++++++++--- .../model/AdditionalPropertiesString.java | 98 ++++++++++++++++--- .../model/AdditionalPropertiesAnyType.java | 98 ++++++++++++++++--- .../model/AdditionalPropertiesArray.java | 98 ++++++++++++++++--- .../model/AdditionalPropertiesBoolean.java | 98 ++++++++++++++++--- .../model/AdditionalPropertiesInteger.java | 98 ++++++++++++++++--- .../model/AdditionalPropertiesNumber.java | 98 ++++++++++++++++--- .../model/AdditionalPropertiesObject.java | 98 ++++++++++++++++--- .../model/AdditionalPropertiesString.java | 98 ++++++++++++++++--- .../openapitools/client/model/Drawing.java | 98 ++++++++++++++++--- .../client/model/NullableClass.java | 98 ++++++++++++++++--- .../src/PSPetstore/Model/Drawing.ps1 | 5 +- .../src/PSPetstore/Model/NullableClass.ps1 | 5 +- .../builds/test-petstore/api.ts | 4 +- .../api.ts | 2 +- .../go/go-petstore/model_nullable_class.go | 36 +++++++ .../python-aiohttp/.openapi-generator/FILES | 6 ++ .../client/petstore/python-aiohttp/README.md | 3 + .../docs/AdditionalPropertiesAnyType.md | 28 ++++++ .../docs/AdditionalPropertiesObject.md | 28 ++++++ ...AdditionalPropertiesWithDescriptionOnly.md | 28 ++++++ .../python-aiohttp/petstore_api/__init__.py | 3 + .../petstore_api/models/__init__.py | 3 + .../models/additional_properties_any_type.py | 83 ++++++++++++++++ .../models/additional_properties_object.py | 83 ++++++++++++++++ ...tional_properties_with_description_only.py | 83 ++++++++++++++++ .../petstore_api/models/nullable_class.py | 12 +++ .../test_additional_properties_any_type.py | 54 ++++++++++ .../test/test_additional_properties_class.py | 11 ++- .../test/test_additional_properties_object.py | 54 ++++++++++ ...tional_properties_with_description_only.py | 54 ++++++++++ .../petstore/python/.openapi-generator/FILES | 6 ++ .../openapi3/client/petstore/python/README.md | 3 + .../docs/AdditionalPropertiesAnyType.md | 28 ++++++ .../python/docs/AdditionalPropertiesClass.md | 0 .../python/docs/AdditionalPropertiesObject.md | 28 ++++++ ...AdditionalPropertiesWithDescriptionOnly.md | 28 ++++++ .../client/petstore/python/docs/Animal.md | 0 .../petstore/python/docs/AnotherFakeApi.md | 0 .../petstore/python/docs/ApiResponse.md | 0 .../python/docs/ArrayOfArrayOfNumberOnly.md | 0 .../petstore/python/docs/ArrayOfNumberOnly.md | 0 .../client/petstore/python/docs/ArrayTest.md | 0 .../petstore/python/docs/Capitalization.md | 0 .../client/petstore/python/docs/Cat.md | 0 .../client/petstore/python/docs/Category.md | 0 .../client/petstore/python/docs/ClassModel.md | 0 .../client/petstore/python/docs/Client.md | 0 .../client/petstore/python/docs/DefaultApi.md | 0 .../client/petstore/python/docs/Dog.md | 0 .../client/petstore/python/docs/EnumArrays.md | 0 .../client/petstore/python/docs/EnumClass.md | 0 .../client/petstore/python/docs/EnumTest.md | 0 .../client/petstore/python/docs/FakeApi.md | 0 .../python/docs/FakeClassnameTags123Api.md | 0 .../client/petstore/python/docs/File.md | 0 .../python/docs/FileSchemaTestClass.md | 0 .../client/petstore/python/docs/Foo.md | 0 .../client/petstore/python/docs/FormatTest.md | 0 .../petstore/python/docs/HasOnlyReadOnly.md | 0 .../petstore/python/docs/HealthCheckResult.md | 0 .../petstore/python/docs/InlineObject.md | 11 --- .../petstore/python/docs/InlineObject1.md | 11 --- .../petstore/python/docs/InlineObject2.md | 11 --- .../petstore/python/docs/InlineObject3.md | 23 ----- .../petstore/python/docs/InlineObject4.md | 11 --- .../petstore/python/docs/InlineObject5.md | 11 --- .../python/docs/InlineResponseDefault.md | 11 --- .../client/petstore/python/docs/List.md | 0 .../client/petstore/python/docs/MapTest.md | 0 ...dPropertiesAndAdditionalPropertiesClass.md | 0 .../petstore/python/docs/Model200Response.md | 0 .../petstore/python/docs/ModelReturn.md | 0 .../petstore/python/docs/Model_200Response.md | 13 --- .../petstore/python/docs/Model_Return.md | 12 --- .../client/petstore/python/docs/Name.md | 0 .../petstore/python/docs/NestedOneOf.md | 12 --- .../petstore/python/docs/NullableClass.md | 0 .../client/petstore/python/docs/NumberOnly.md | 0 .../client/petstore/python/docs/Order.md | 0 .../petstore/python/docs/OuterComposite.md | 0 .../client/petstore/python/docs/OuterEnum.md | 0 .../python/docs/OuterEnumDefaultValue.md | 0 .../petstore/python/docs/OuterEnumInteger.md | 0 .../docs/OuterEnumIntegerDefaultValue.md | 0 .../client/petstore/python/docs/Pet.md | 0 .../client/petstore/python/docs/PetApi.md | 0 .../petstore/python/docs/ReadOnlyFirst.md | 0 .../petstore/python/docs/SpecialModelName.md | 0 .../client/petstore/python/docs/StoreApi.md | 0 .../client/petstore/python/docs/Tag.md | 0 .../client/petstore/python/docs/User.md | 0 .../client/petstore/python/docs/UserApi.md | 0 .../petstore/python/petstore_api/__init__.py | 3 + .../python/petstore_api/models/__init__.py | 3 + .../models/additional_properties_any_type.py | 83 ++++++++++++++++ .../models/additional_properties_object.py | 83 ++++++++++++++++ ...tional_properties_with_description_only.py | 83 ++++++++++++++++ .../petstore_api/models/nullable_class.py | 12 +++ .../test_additional_properties_any_type.py | 54 ++++++++++ .../test/test_additional_properties_class.py | 15 +-- .../test/test_additional_properties_object.py | 54 ++++++++++ ...tional_properties_with_description_only.py | 54 ++++++++++ .../petstore/python/tests/test_model.py | 16 ++- 142 files changed, 2966 insertions(+), 333 deletions(-) create mode 100644 samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesAnyType.md create mode 100644 samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesObject.md create mode 100644 samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesWithDescriptionOnly.md create mode 100644 samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_any_type.py create mode 100644 samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_object.py create mode 100644 samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_with_description_only.py create mode 100644 samples/openapi3/client/petstore/python-aiohttp/test/test_additional_properties_any_type.py create mode 100644 samples/openapi3/client/petstore/python-aiohttp/test/test_additional_properties_object.py create mode 100644 samples/openapi3/client/petstore/python-aiohttp/test/test_additional_properties_with_description_only.py create mode 100644 samples/openapi3/client/petstore/python/docs/AdditionalPropertiesAnyType.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/AdditionalPropertiesClass.md create mode 100644 samples/openapi3/client/petstore/python/docs/AdditionalPropertiesObject.md create mode 100644 samples/openapi3/client/petstore/python/docs/AdditionalPropertiesWithDescriptionOnly.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/Animal.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/AnotherFakeApi.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/ApiResponse.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/ArrayOfArrayOfNumberOnly.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/ArrayOfNumberOnly.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/ArrayTest.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/Capitalization.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/Cat.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/Category.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/ClassModel.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/Client.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/DefaultApi.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/Dog.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/EnumArrays.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/EnumClass.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/EnumTest.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/FakeApi.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/FakeClassnameTags123Api.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/File.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/FileSchemaTestClass.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/Foo.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/FormatTest.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/HasOnlyReadOnly.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/HealthCheckResult.md delete mode 100755 samples/openapi3/client/petstore/python/docs/InlineObject.md delete mode 100755 samples/openapi3/client/petstore/python/docs/InlineObject1.md delete mode 100755 samples/openapi3/client/petstore/python/docs/InlineObject2.md delete mode 100755 samples/openapi3/client/petstore/python/docs/InlineObject3.md delete mode 100755 samples/openapi3/client/petstore/python/docs/InlineObject4.md delete mode 100755 samples/openapi3/client/petstore/python/docs/InlineObject5.md delete mode 100755 samples/openapi3/client/petstore/python/docs/InlineResponseDefault.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/List.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/MapTest.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/MixedPropertiesAndAdditionalPropertiesClass.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/Model200Response.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/ModelReturn.md delete mode 100644 samples/openapi3/client/petstore/python/docs/Model_200Response.md delete mode 100644 samples/openapi3/client/petstore/python/docs/Model_Return.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/Name.md delete mode 100644 samples/openapi3/client/petstore/python/docs/NestedOneOf.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/NullableClass.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/NumberOnly.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/Order.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/OuterComposite.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/OuterEnum.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/OuterEnumDefaultValue.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/OuterEnumInteger.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/OuterEnumIntegerDefaultValue.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/Pet.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/PetApi.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/ReadOnlyFirst.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/SpecialModelName.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/StoreApi.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/Tag.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/User.md mode change 100755 => 100644 samples/openapi3/client/petstore/python/docs/UserApi.md create mode 100644 samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_any_type.py create mode 100644 samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_object.py create mode 100644 samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_with_description_only.py create mode 100644 samples/openapi3/client/petstore/python/test/test_additional_properties_any_type.py create mode 100644 samples/openapi3/client/petstore/python/test/test_additional_properties_object.py create mode 100644 samples/openapi3/client/petstore/python/test/test_additional_properties_with_description_only.py diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java index 6c2842fec4cd..b1fd059befa0 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java @@ -149,7 +149,10 @@ public class CodegenModel implements IJsonSchemaValidationProperties { public String additionalPropertiesType; /** - * True if additionalProperties is set to true (boolean value) + * True if additionalProperties is set to true (boolean value), any type, free form object, etc + * + * TODO: we may rename this to isAdditionalPropertiesEnabled or something + * else to avoid confusions */ public boolean isAdditionalPropertiesTrue; @@ -1088,6 +1091,7 @@ public boolean equals(Object o) { Objects.equals(externalDocumentation, that.externalDocumentation) && Objects.equals(vendorExtensions, that.vendorExtensions) && Objects.equals(additionalPropertiesType, that.additionalPropertiesType) && + Objects.equals(isAdditionalPropertiesTrue, that.isAdditionalPropertiesTrue) && Objects.equals(getMaxProperties(), that.getMaxProperties()) && Objects.equals(getMinProperties(), that.getMinProperties()) && Objects.equals(getMaxItems(), that.getMaxItems()) && @@ -1193,6 +1197,7 @@ public String toString() { sb.append(", externalDocumentation=").append(externalDocumentation); sb.append(", vendorExtensions=").append(vendorExtensions); sb.append(", additionalPropertiesType='").append(additionalPropertiesType).append('\''); + sb.append(", isAdditionalPropertiesTrue='").append(isAdditionalPropertiesTrue).append('\''); sb.append(", maxProperties=").append(maxProperties); sb.append(", minProperties=").append(minProperties); sb.append(", uniqueItems=").append(uniqueItems); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java index 082f378c695b..be13495b7598 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java @@ -3179,6 +3179,9 @@ protected void setAddProps(Schema schema, IJsonSchemaValidationProperties proper // if we are trying to set additionalProperties on an empty schema stop recursing return; } + // Note: This flag is set to true if additioanl properties + // is set (any type, free form object, boolean true, string, etc). + // The variable name may be renamed later to avoid confusion. boolean additionalPropertiesIsAnyType = false; CodegenModel m = null; if (property instanceof CodegenModel) { @@ -3199,15 +3202,14 @@ protected void setAddProps(Schema schema, IJsonSchemaValidationProperties proper additionalPropertiesIsAnyType = true; } } else { + // if additioanl properties is set (e.g. free form object, any type, string, etc) addPropProp = fromProperty(getAdditionalPropertiesName(), (Schema) schema.getAdditionalProperties(), false); - if (ModelUtils.isAnyType((Schema) schema.getAdditionalProperties())) { - additionalPropertiesIsAnyType = true; - } + additionalPropertiesIsAnyType = true; } if (additionalPropertiesIsAnyType) { property.setAdditionalPropertiesIsAnyType(true); } - if (m != null && isAdditionalPropertiesTrue) { + if (m != null && (isAdditionalPropertiesTrue || additionalPropertiesIsAnyType)) { m.isAdditionalPropertiesTrue = true; } if (ModelUtils.isComposedSchema(schema) && !supportsAdditionalPropertiesWithComposedSchema) { diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java index df6069002d4e..c5c960b62d5c 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java @@ -2616,7 +2616,7 @@ public void testAdditionalPropertiesPresentInModels() { cm = codegen.fromModel(modelName, sc); CodegenProperty stringCp = codegen.fromProperty("additional_properties", new Schema().type("string")); assertEquals(cm.getAdditionalProperties(), stringCp); - assertFalse(cm.getAdditionalPropertiesIsAnyType()); + assertTrue(cm.getAdditionalPropertiesIsAnyType()); } @Test @@ -2656,7 +2656,7 @@ public void testAdditionalPropertiesPresentInModelProperties() { assertFalse(mapWithAddPropsFalse.getAdditionalPropertiesIsAnyType()); mapWithAddPropsSchema = cm.getVars().get(3); assertEquals(mapWithAddPropsSchema.getAdditionalProperties(), stringCp); - assertFalse(mapWithAddPropsSchema.getAdditionalPropertiesIsAnyType()); + assertTrue(mapWithAddPropsSchema.getAdditionalPropertiesIsAnyType()); modelName = "ObjectModelWithAddPropsInProps"; sc = openAPI.getComponents().getSchemas().get(modelName); @@ -2672,7 +2672,7 @@ public void testAdditionalPropertiesPresentInModelProperties() { assertFalse(mapWithAddPropsFalse.getAdditionalPropertiesIsAnyType()); mapWithAddPropsSchema = cm.getVars().get(3); assertEquals(mapWithAddPropsSchema.getAdditionalProperties(), stringCp); - assertFalse(mapWithAddPropsSchema.getAdditionalPropertiesIsAnyType()); + assertTrue(mapWithAddPropsSchema.getAdditionalPropertiesIsAnyType()); if (isGenerateAliasAsModel) { // restore the setting GlobalSettings.setProperty("generateAliasAsModel", "true"); @@ -2717,7 +2717,7 @@ public void testAdditionalPropertiesPresentInParameters() { assertFalse(mapWithAddPropsFalse.getAdditionalPropertiesIsAnyType()); mapWithAddPropsSchema = co.queryParams.get(3); assertEquals(mapWithAddPropsSchema.getAdditionalProperties(), stringCp); - assertFalse(mapWithAddPropsSchema.getAdditionalPropertiesIsAnyType()); + assertTrue(mapWithAddPropsSchema.getAdditionalPropertiesIsAnyType()); path = "/additional_properties/"; operation = openAPI.getPaths().get(path).getPost(); @@ -2733,7 +2733,7 @@ public void testAdditionalPropertiesPresentInParameters() { assertFalse(mapWithAddPropsFalse.getAdditionalPropertiesIsAnyType()); mapWithAddPropsSchema = co.queryParams.get(3); assertEquals(mapWithAddPropsSchema.getAdditionalProperties(), stringCp); - assertFalse(mapWithAddPropsSchema.getAdditionalPropertiesIsAnyType()); + assertTrue(mapWithAddPropsSchema.getAdditionalPropertiesIsAnyType()); if (isGenerateAliasAsModel) { // restore the setting GlobalSettings.setProperty("generateAliasAsModel", "true"); @@ -2778,7 +2778,7 @@ public void testAdditionalPropertiesPresentInResponses() { assertFalse(mapWithAddPropsFalse.getAdditionalPropertiesIsAnyType()); mapWithAddPropsSchema = co.responses.get(3); assertEquals(mapWithAddPropsSchema.getAdditionalProperties(), stringCp); - assertFalse(mapWithAddPropsSchema.getAdditionalPropertiesIsAnyType()); + assertTrue(mapWithAddPropsSchema.getAdditionalPropertiesIsAnyType()); path = "/additional_properties/"; operation = openAPI.getPaths().get(path).getPost(); @@ -2794,7 +2794,7 @@ public void testAdditionalPropertiesPresentInResponses() { assertFalse(mapWithAddPropsFalse.getAdditionalPropertiesIsAnyType()); mapWithAddPropsSchema = co.responses.get(3); assertEquals(mapWithAddPropsSchema.getAdditionalProperties(), stringCp); - assertFalse(mapWithAddPropsSchema.getAdditionalPropertiesIsAnyType()); + assertTrue(mapWithAddPropsSchema.getAdditionalPropertiesIsAnyType()); if (isGenerateAliasAsModel) { // restore the setting GlobalSettings.setProperty("generateAliasAsModel", "true"); diff --git a/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing.yaml index 4b16bbcff1c4..85fa9290074f 100644 --- a/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing.yaml @@ -2272,4 +2272,23 @@ components: properties: skill: type: string - + AdditionalPropertiesObject: + type: object + properties: + name: + type: string + additionalProperties: + type: object + AdditionalPropertiesAnyType: + type: object + properties: + name: + type: string + additionalProperties: {} + AdditionalPropertiesWithDescriptionOnly: + type: object + properties: + name: + type: string + additionalProperties: + description: This is what the additional property is diff --git a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Drawing.cs index bc7147733eed..13e9311fab62 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Drawing.cs @@ -61,6 +61,7 @@ public partial class Drawing : Dictionary, IEquatable, I { this._flagShapes = true; } + this.AdditionalProperties = new Dictionary(); } /// @@ -159,6 +160,12 @@ public bool ShouldSerializeShapes() { return _flagShapes; } + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + /// /// Returns the string presentation of the object /// @@ -172,6 +179,7 @@ public override string ToString() sb.Append(" ShapeOrNull: ").Append(ShapeOrNull).Append("\n"); sb.Append(" NullableShape: ").Append(NullableShape).Append("\n"); sb.Append(" Shapes: ").Append(Shapes).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); } @@ -230,6 +238,10 @@ public override int GetHashCode() { hashCode = (hashCode * 59) + this.Shapes.GetHashCode(); } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/NullableClass.cs index 0262e604be03..b05622141cc2 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/NullableClass.cs @@ -109,6 +109,7 @@ public partial class NullableClass : Dictionary, IEquatable(); } /// @@ -400,6 +401,12 @@ public bool ShouldSerializeObjectItemsNullable() { return _flagObjectItemsNullable; } + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + /// /// Returns the string presentation of the object /// @@ -421,6 +428,7 @@ public override string ToString() sb.Append(" ObjectNullableProp: ").Append(ObjectNullableProp).Append("\n"); sb.Append(" ObjectAndItemsNullableProp: ").Append(ObjectAndItemsNullableProp).Append("\n"); sb.Append(" ObjectItemsNullable: ").Append(ObjectItemsNullable).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); } @@ -511,6 +519,10 @@ public override int GetHashCode() { hashCode = (hashCode * 59) + this.ObjectItemsNullable.GetHashCode(); } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Drawing.cs index a8bd88c42c45..9152566699ed 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Drawing.cs @@ -73,6 +73,12 @@ public Drawing(Shape mainShape, List shapes, NullableShape? nullableShape [JsonPropertyName("shapeOrNull")] public ShapeOrNull? ShapeOrNull { get; set; } + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + /// /// Returns the string presentation of the object /// @@ -86,6 +92,7 @@ public override string ToString() sb.Append(" Shapes: ").Append(Shapes).Append("\n"); sb.Append(" NullableShape: ").Append(NullableShape).Append("\n"); sb.Append(" ShapeOrNull: ").Append(ShapeOrNull).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NullableClass.cs index 8ccc53f42468..feb89d9a8dd8 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NullableClass.cs @@ -137,6 +137,12 @@ public NullableClass(List arrayItemsNullable, Dictionary [JsonPropertyName("string_prop")] public string? StringProp { get; set; } + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + /// /// Returns the string presentation of the object /// @@ -158,6 +164,7 @@ public override string ToString() sb.Append(" ObjectAndItemsNullableProp: ").Append(ObjectAndItemsNullableProp).Append("\n"); sb.Append(" ObjectNullableProp: ").Append(ObjectNullableProp).Append("\n"); sb.Append(" StringProp: ").Append(StringProp).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Drawing.cs index 8fbe4cb9b341..034136979b5e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Drawing.cs @@ -71,6 +71,12 @@ public Drawing(Shape mainShape, List shapes, NullableShape nullableShape [JsonPropertyName("shapeOrNull")] public ShapeOrNull ShapeOrNull { get; set; } + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + /// /// Returns the string presentation of the object /// @@ -84,6 +90,7 @@ public override string ToString() sb.Append(" Shapes: ").Append(Shapes).Append("\n"); sb.Append(" NullableShape: ").Append(NullableShape).Append("\n"); sb.Append(" ShapeOrNull: ").Append(ShapeOrNull).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NullableClass.cs index 12a1e85138d5..fabf2a09c33b 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NullableClass.cs @@ -135,6 +135,12 @@ public NullableClass(List arrayItemsNullable, Dictionary [JsonPropertyName("string_prop")] public string StringProp { get; set; } + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + /// /// Returns the string presentation of the object /// @@ -156,6 +162,7 @@ public override string ToString() sb.Append(" ObjectAndItemsNullableProp: ").Append(ObjectAndItemsNullableProp).Append("\n"); sb.Append(" ObjectNullableProp: ").Append(ObjectNullableProp).Append("\n"); sb.Append(" StringProp: ").Append(StringProp).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Drawing.cs index 8fbe4cb9b341..034136979b5e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Drawing.cs @@ -71,6 +71,12 @@ public Drawing(Shape mainShape, List shapes, NullableShape nullableShape [JsonPropertyName("shapeOrNull")] public ShapeOrNull ShapeOrNull { get; set; } + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + /// /// Returns the string presentation of the object /// @@ -84,6 +90,7 @@ public override string ToString() sb.Append(" Shapes: ").Append(Shapes).Append("\n"); sb.Append(" NullableShape: ").Append(NullableShape).Append("\n"); sb.Append(" ShapeOrNull: ").Append(ShapeOrNull).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NullableClass.cs index 12a1e85138d5..fabf2a09c33b 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NullableClass.cs @@ -135,6 +135,12 @@ public NullableClass(List arrayItemsNullable, Dictionary [JsonPropertyName("string_prop")] public string StringProp { get; set; } + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + /// /// Returns the string presentation of the object /// @@ -156,6 +162,7 @@ public override string ToString() sb.Append(" ObjectAndItemsNullableProp: ").Append(ObjectAndItemsNullableProp).Append("\n"); sb.Append(" ObjectNullableProp: ").Append(ObjectNullableProp).Append("\n"); sb.Append(" StringProp: ").Append(StringProp).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); } diff --git a/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Drawing.cs index c5585ec01cfd..f533b3bfc2eb 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Drawing.cs @@ -46,6 +46,7 @@ public partial class Drawing : Dictionary, IEquatable, I this.ShapeOrNull = shapeOrNull; this.NullableShape = nullableShape; this.Shapes = shapes; + this.AdditionalProperties = new Dictionary(); } /// @@ -72,6 +73,12 @@ public partial class Drawing : Dictionary, IEquatable, I [DataMember(Name = "shapes", EmitDefaultValue = false)] public List Shapes { get; set; } + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + /// /// Returns the string presentation of the object /// @@ -85,6 +92,7 @@ public override string ToString() sb.Append(" ShapeOrNull: ").Append(ShapeOrNull).Append("\n"); sb.Append(" NullableShape: ").Append(NullableShape).Append("\n"); sb.Append(" Shapes: ").Append(Shapes).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); } @@ -143,6 +151,10 @@ public override int GetHashCode() { hashCode = (hashCode * 59) + this.Shapes.GetHashCode(); } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NullableClass.cs index ea40c1bba00a..9f936ccbd880 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NullableClass.cs @@ -62,6 +62,7 @@ public partial class NullableClass : Dictionary, IEquatable(); } /// @@ -137,6 +138,12 @@ public partial class NullableClass : Dictionary, IEquatable ObjectItemsNullable { get; set; } + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + /// /// Returns the string presentation of the object /// @@ -158,6 +165,7 @@ public override string ToString() sb.Append(" ObjectNullableProp: ").Append(ObjectNullableProp).Append("\n"); sb.Append(" ObjectAndItemsNullableProp: ").Append(ObjectAndItemsNullableProp).Append("\n"); sb.Append(" ObjectItemsNullable: ").Append(ObjectItemsNullable).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); } @@ -248,6 +256,10 @@ public override int GetHashCode() { hashCode = (hashCode * 59) + this.ObjectItemsNullable.GetHashCode(); } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Drawing.cs index 1713fb3cfb5d..d5d633ed3b31 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Drawing.cs @@ -45,6 +45,7 @@ public partial class Drawing : Dictionary, IEquatable, I this.ShapeOrNull = shapeOrNull; this.NullableShape = nullableShape; this.Shapes = shapes; + this.AdditionalProperties = new Dictionary(); } /// @@ -71,6 +72,12 @@ public partial class Drawing : Dictionary, IEquatable, I [DataMember(Name = "shapes", EmitDefaultValue = false)] public List Shapes { get; set; } + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + /// /// Returns the string presentation of the object /// @@ -84,6 +91,7 @@ public override string ToString() sb.Append(" ShapeOrNull: ").Append(ShapeOrNull).Append("\n"); sb.Append(" NullableShape: ").Append(NullableShape).Append("\n"); sb.Append(" Shapes: ").Append(Shapes).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); } @@ -142,6 +150,10 @@ public override int GetHashCode() { hashCode = (hashCode * 59) + this.Shapes.GetHashCode(); } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Model/NullableClass.cs index c31d0e9c15d0..919ed331163d 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Model/NullableClass.cs @@ -61,6 +61,7 @@ public partial class NullableClass : Dictionary, IEquatable(); } /// @@ -136,6 +137,12 @@ public partial class NullableClass : Dictionary, IEquatable ObjectItemsNullable { get; set; } + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + /// /// Returns the string presentation of the object /// @@ -157,6 +164,7 @@ public override string ToString() sb.Append(" ObjectNullableProp: ").Append(ObjectNullableProp).Append("\n"); sb.Append(" ObjectAndItemsNullableProp: ").Append(ObjectAndItemsNullableProp).Append("\n"); sb.Append(" ObjectItemsNullable: ").Append(ObjectItemsNullable).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); } @@ -247,6 +255,10 @@ public override int GetHashCode() { hashCode = (hashCode * 59) + this.ObjectItemsNullable.GetHashCode(); } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Drawing.cs index 1713fb3cfb5d..d5d633ed3b31 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Drawing.cs @@ -45,6 +45,7 @@ public partial class Drawing : Dictionary, IEquatable, I this.ShapeOrNull = shapeOrNull; this.NullableShape = nullableShape; this.Shapes = shapes; + this.AdditionalProperties = new Dictionary(); } /// @@ -71,6 +72,12 @@ public partial class Drawing : Dictionary, IEquatable, I [DataMember(Name = "shapes", EmitDefaultValue = false)] public List Shapes { get; set; } + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + /// /// Returns the string presentation of the object /// @@ -84,6 +91,7 @@ public override string ToString() sb.Append(" ShapeOrNull: ").Append(ShapeOrNull).Append("\n"); sb.Append(" NullableShape: ").Append(NullableShape).Append("\n"); sb.Append(" Shapes: ").Append(Shapes).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); } @@ -142,6 +150,10 @@ public override int GetHashCode() { hashCode = (hashCode * 59) + this.Shapes.GetHashCode(); } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Model/NullableClass.cs index c31d0e9c15d0..919ed331163d 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Model/NullableClass.cs @@ -61,6 +61,7 @@ public partial class NullableClass : Dictionary, IEquatable(); } /// @@ -136,6 +137,12 @@ public partial class NullableClass : Dictionary, IEquatable ObjectItemsNullable { get; set; } + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + /// /// Returns the string presentation of the object /// @@ -157,6 +164,7 @@ public override string ToString() sb.Append(" ObjectNullableProp: ").Append(ObjectNullableProp).Append("\n"); sb.Append(" ObjectAndItemsNullableProp: ").Append(ObjectAndItemsNullableProp).Append("\n"); sb.Append(" ObjectItemsNullable: ").Append(ObjectItemsNullable).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); } @@ -247,6 +255,10 @@ public override int GetHashCode() { hashCode = (hashCode * 59) + this.ObjectItemsNullable.GetHashCode(); } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Drawing.cs index 1713fb3cfb5d..d5d633ed3b31 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Drawing.cs @@ -45,6 +45,7 @@ public partial class Drawing : Dictionary, IEquatable, I this.ShapeOrNull = shapeOrNull; this.NullableShape = nullableShape; this.Shapes = shapes; + this.AdditionalProperties = new Dictionary(); } /// @@ -71,6 +72,12 @@ public partial class Drawing : Dictionary, IEquatable, I [DataMember(Name = "shapes", EmitDefaultValue = false)] public List Shapes { get; set; } + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + /// /// Returns the string presentation of the object /// @@ -84,6 +91,7 @@ public override string ToString() sb.Append(" ShapeOrNull: ").Append(ShapeOrNull).Append("\n"); sb.Append(" NullableShape: ").Append(NullableShape).Append("\n"); sb.Append(" Shapes: ").Append(Shapes).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); } @@ -142,6 +150,10 @@ public override int GetHashCode() { hashCode = (hashCode * 59) + this.Shapes.GetHashCode(); } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/NullableClass.cs index c31d0e9c15d0..919ed331163d 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/NullableClass.cs @@ -61,6 +61,7 @@ public partial class NullableClass : Dictionary, IEquatable(); } /// @@ -136,6 +137,12 @@ public partial class NullableClass : Dictionary, IEquatable ObjectItemsNullable { get; set; } + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + /// /// Returns the string presentation of the object /// @@ -157,6 +164,7 @@ public override string ToString() sb.Append(" ObjectNullableProp: ").Append(ObjectNullableProp).Append("\n"); sb.Append(" ObjectAndItemsNullableProp: ").Append(ObjectAndItemsNullableProp).Append("\n"); sb.Append(" ObjectItemsNullable: ").Append(ObjectItemsNullable).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); } @@ -247,6 +255,10 @@ public override int GetHashCode() { hashCode = (hashCode * 59) + this.ObjectItemsNullable.GetHashCode(); } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Model/Drawing.cs index 0d19d8d09ed6..9bfd0ce588da 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Model/Drawing.cs @@ -43,6 +43,7 @@ public partial class Drawing : Dictionary, IEquatable this.ShapeOrNull = shapeOrNull; this.NullableShape = nullableShape; this.Shapes = shapes; + this.AdditionalProperties = new Dictionary(); } /// @@ -69,6 +70,12 @@ public partial class Drawing : Dictionary, IEquatable [DataMember(Name = "shapes", EmitDefaultValue = false)] public List Shapes { get; set; } + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + /// /// Returns the string presentation of the object /// @@ -82,6 +89,7 @@ public override string ToString() sb.Append(" ShapeOrNull: ").Append(ShapeOrNull).Append("\n"); sb.Append(" NullableShape: ").Append(NullableShape).Append("\n"); sb.Append(" Shapes: ").Append(Shapes).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); } @@ -137,7 +145,8 @@ public bool Equals(Drawing input) this.Shapes != null && input.Shapes != null && this.Shapes.SequenceEqual(input.Shapes) - ); + ) + && (this.AdditionalProperties.Count == input.AdditionalProperties.Count && !this.AdditionalProperties.Except(input.AdditionalProperties).Any()); } /// @@ -165,6 +174,10 @@ public override int GetHashCode() { hashCode = (hashCode * 59) + this.Shapes.GetHashCode(); } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Model/NullableClass.cs index a6c79e5460ac..699f0c7881d8 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Model/NullableClass.cs @@ -59,6 +59,7 @@ public partial class NullableClass : Dictionary, IEquatable(); } /// @@ -134,6 +135,12 @@ public partial class NullableClass : Dictionary, IEquatable ObjectItemsNullable { get; set; } + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + /// /// Returns the string presentation of the object /// @@ -155,6 +162,7 @@ public override string ToString() sb.Append(" ObjectNullableProp: ").Append(ObjectNullableProp).Append("\n"); sb.Append(" ObjectAndItemsNullableProp: ").Append(ObjectAndItemsNullableProp).Append("\n"); sb.Append(" ObjectItemsNullable: ").Append(ObjectItemsNullable).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); } @@ -255,7 +263,8 @@ public bool Equals(NullableClass input) this.ObjectItemsNullable != null && input.ObjectItemsNullable != null && this.ObjectItemsNullable.SequenceEqual(input.ObjectItemsNullable) - ); + ) + && (this.AdditionalProperties.Count == input.AdditionalProperties.Count && !this.AdditionalProperties.Except(input.AdditionalProperties).Any()); } /// @@ -315,6 +324,10 @@ public override int GetHashCode() { hashCode = (hashCode * 59) + this.ObjectItemsNullable.GetHashCode(); } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/Drawing.cs index 1713fb3cfb5d..d5d633ed3b31 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/Drawing.cs @@ -45,6 +45,7 @@ public partial class Drawing : Dictionary, IEquatable, I this.ShapeOrNull = shapeOrNull; this.NullableShape = nullableShape; this.Shapes = shapes; + this.AdditionalProperties = new Dictionary(); } /// @@ -71,6 +72,12 @@ public partial class Drawing : Dictionary, IEquatable, I [DataMember(Name = "shapes", EmitDefaultValue = false)] public List Shapes { get; set; } + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + /// /// Returns the string presentation of the object /// @@ -84,6 +91,7 @@ public override string ToString() sb.Append(" ShapeOrNull: ").Append(ShapeOrNull).Append("\n"); sb.Append(" NullableShape: ").Append(NullableShape).Append("\n"); sb.Append(" Shapes: ").Append(Shapes).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); } @@ -142,6 +150,10 @@ public override int GetHashCode() { hashCode = (hashCode * 59) + this.Shapes.GetHashCode(); } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/NullableClass.cs index c31d0e9c15d0..919ed331163d 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/NullableClass.cs @@ -61,6 +61,7 @@ public partial class NullableClass : Dictionary, IEquatable(); } /// @@ -136,6 +137,12 @@ public partial class NullableClass : Dictionary, IEquatable ObjectItemsNullable { get; set; } + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + /// /// Returns the string presentation of the object /// @@ -157,6 +164,7 @@ public override string ToString() sb.Append(" ObjectNullableProp: ").Append(ObjectNullableProp).Append("\n"); sb.Append(" ObjectAndItemsNullableProp: ").Append(ObjectAndItemsNullableProp).Append("\n"); sb.Append(" ObjectItemsNullable: ").Append(ObjectItemsNullable).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); } @@ -247,6 +255,10 @@ public override int GetHashCode() { hashCode = (hashCode * 59) + this.ObjectItemsNullable.GetHashCode(); } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/Drawing.cs index 1713fb3cfb5d..d5d633ed3b31 100644 --- a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/Drawing.cs @@ -45,6 +45,7 @@ public partial class Drawing : Dictionary, IEquatable, I this.ShapeOrNull = shapeOrNull; this.NullableShape = nullableShape; this.Shapes = shapes; + this.AdditionalProperties = new Dictionary(); } /// @@ -71,6 +72,12 @@ public partial class Drawing : Dictionary, IEquatable, I [DataMember(Name = "shapes", EmitDefaultValue = false)] public List Shapes { get; set; } + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + /// /// Returns the string presentation of the object /// @@ -84,6 +91,7 @@ public override string ToString() sb.Append(" ShapeOrNull: ").Append(ShapeOrNull).Append("\n"); sb.Append(" NullableShape: ").Append(NullableShape).Append("\n"); sb.Append(" Shapes: ").Append(Shapes).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); } @@ -142,6 +150,10 @@ public override int GetHashCode() { hashCode = (hashCode * 59) + this.Shapes.GetHashCode(); } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/NullableClass.cs index c31d0e9c15d0..919ed331163d 100644 --- a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/NullableClass.cs @@ -61,6 +61,7 @@ public partial class NullableClass : Dictionary, IEquatable(); } /// @@ -136,6 +137,12 @@ public partial class NullableClass : Dictionary, IEquatable ObjectItemsNullable { get; set; } + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + /// /// Returns the string presentation of the object /// @@ -157,6 +164,7 @@ public override string ToString() sb.Append(" ObjectNullableProp: ").Append(ObjectNullableProp).Append("\n"); sb.Append(" ObjectAndItemsNullableProp: ").Append(ObjectAndItemsNullableProp).Append("\n"); sb.Append(" ObjectItemsNullable: ").Append(ObjectItemsNullable).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); } @@ -247,6 +255,10 @@ public override int GetHashCode() { hashCode = (hashCode * 59) + this.ObjectItemsNullable.GetHashCode(); } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/go/go-petstore/model_additional_properties_any_type.go b/samples/client/petstore/go/go-petstore/model_additional_properties_any_type.go index 9fd12d021bac..eadf2a95994a 100644 --- a/samples/client/petstore/go/go-petstore/model_additional_properties_any_type.go +++ b/samples/client/petstore/go/go-petstore/model_additional_properties_any_type.go @@ -20,8 +20,11 @@ var _ MappedNullable = &AdditionalPropertiesAnyType{} // AdditionalPropertiesAnyType struct for AdditionalPropertiesAnyType type AdditionalPropertiesAnyType struct { Name *string `json:"name,omitempty"` + AdditionalProperties map[string]interface{} } +type _AdditionalPropertiesAnyType AdditionalPropertiesAnyType + // NewAdditionalPropertiesAnyType instantiates a new AdditionalPropertiesAnyType object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments @@ -84,9 +87,31 @@ func (o AdditionalPropertiesAnyType) ToMap() (map[string]interface{}, error) { if !IsNil(o.Name) { toSerialize["name"] = o.Name } + + for key, value := range o.AdditionalProperties { + toSerialize[key] = value + } + return toSerialize, nil } +func (o *AdditionalPropertiesAnyType) UnmarshalJSON(bytes []byte) (err error) { + varAdditionalPropertiesAnyType := _AdditionalPropertiesAnyType{} + + if err = json.Unmarshal(bytes, &varAdditionalPropertiesAnyType); err == nil { + *o = AdditionalPropertiesAnyType(varAdditionalPropertiesAnyType) + } + + additionalProperties := make(map[string]interface{}) + + if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + delete(additionalProperties, "name") + o.AdditionalProperties = additionalProperties + } + + return err +} + type NullableAdditionalPropertiesAnyType struct { value *AdditionalPropertiesAnyType isSet bool diff --git a/samples/client/petstore/go/go-petstore/model_additional_properties_array.go b/samples/client/petstore/go/go-petstore/model_additional_properties_array.go index 9cbb26fec0d9..f2527113454e 100644 --- a/samples/client/petstore/go/go-petstore/model_additional_properties_array.go +++ b/samples/client/petstore/go/go-petstore/model_additional_properties_array.go @@ -20,8 +20,11 @@ var _ MappedNullable = &AdditionalPropertiesArray{} // AdditionalPropertiesArray struct for AdditionalPropertiesArray type AdditionalPropertiesArray struct { Name *string `json:"name,omitempty"` + AdditionalProperties map[string]interface{} } +type _AdditionalPropertiesArray AdditionalPropertiesArray + // NewAdditionalPropertiesArray instantiates a new AdditionalPropertiesArray object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments @@ -84,9 +87,31 @@ func (o AdditionalPropertiesArray) ToMap() (map[string]interface{}, error) { if !IsNil(o.Name) { toSerialize["name"] = o.Name } + + for key, value := range o.AdditionalProperties { + toSerialize[key] = value + } + return toSerialize, nil } +func (o *AdditionalPropertiesArray) UnmarshalJSON(bytes []byte) (err error) { + varAdditionalPropertiesArray := _AdditionalPropertiesArray{} + + if err = json.Unmarshal(bytes, &varAdditionalPropertiesArray); err == nil { + *o = AdditionalPropertiesArray(varAdditionalPropertiesArray) + } + + additionalProperties := make(map[string]interface{}) + + if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + delete(additionalProperties, "name") + o.AdditionalProperties = additionalProperties + } + + return err +} + type NullableAdditionalPropertiesArray struct { value *AdditionalPropertiesArray isSet bool diff --git a/samples/client/petstore/go/go-petstore/model_additional_properties_boolean.go b/samples/client/petstore/go/go-petstore/model_additional_properties_boolean.go index 5659b277e6d2..c1401d929123 100644 --- a/samples/client/petstore/go/go-petstore/model_additional_properties_boolean.go +++ b/samples/client/petstore/go/go-petstore/model_additional_properties_boolean.go @@ -20,8 +20,11 @@ var _ MappedNullable = &AdditionalPropertiesBoolean{} // AdditionalPropertiesBoolean struct for AdditionalPropertiesBoolean type AdditionalPropertiesBoolean struct { Name *string `json:"name,omitempty"` + AdditionalProperties map[string]interface{} } +type _AdditionalPropertiesBoolean AdditionalPropertiesBoolean + // NewAdditionalPropertiesBoolean instantiates a new AdditionalPropertiesBoolean object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments @@ -84,9 +87,31 @@ func (o AdditionalPropertiesBoolean) ToMap() (map[string]interface{}, error) { if !IsNil(o.Name) { toSerialize["name"] = o.Name } + + for key, value := range o.AdditionalProperties { + toSerialize[key] = value + } + return toSerialize, nil } +func (o *AdditionalPropertiesBoolean) UnmarshalJSON(bytes []byte) (err error) { + varAdditionalPropertiesBoolean := _AdditionalPropertiesBoolean{} + + if err = json.Unmarshal(bytes, &varAdditionalPropertiesBoolean); err == nil { + *o = AdditionalPropertiesBoolean(varAdditionalPropertiesBoolean) + } + + additionalProperties := make(map[string]interface{}) + + if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + delete(additionalProperties, "name") + o.AdditionalProperties = additionalProperties + } + + return err +} + type NullableAdditionalPropertiesBoolean struct { value *AdditionalPropertiesBoolean isSet bool diff --git a/samples/client/petstore/go/go-petstore/model_additional_properties_integer.go b/samples/client/petstore/go/go-petstore/model_additional_properties_integer.go index 9873644fe545..0147d6eaf856 100644 --- a/samples/client/petstore/go/go-petstore/model_additional_properties_integer.go +++ b/samples/client/petstore/go/go-petstore/model_additional_properties_integer.go @@ -20,8 +20,11 @@ var _ MappedNullable = &AdditionalPropertiesInteger{} // AdditionalPropertiesInteger struct for AdditionalPropertiesInteger type AdditionalPropertiesInteger struct { Name *string `json:"name,omitempty"` + AdditionalProperties map[string]interface{} } +type _AdditionalPropertiesInteger AdditionalPropertiesInteger + // NewAdditionalPropertiesInteger instantiates a new AdditionalPropertiesInteger object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments @@ -84,9 +87,31 @@ func (o AdditionalPropertiesInteger) ToMap() (map[string]interface{}, error) { if !IsNil(o.Name) { toSerialize["name"] = o.Name } + + for key, value := range o.AdditionalProperties { + toSerialize[key] = value + } + return toSerialize, nil } +func (o *AdditionalPropertiesInteger) UnmarshalJSON(bytes []byte) (err error) { + varAdditionalPropertiesInteger := _AdditionalPropertiesInteger{} + + if err = json.Unmarshal(bytes, &varAdditionalPropertiesInteger); err == nil { + *o = AdditionalPropertiesInteger(varAdditionalPropertiesInteger) + } + + additionalProperties := make(map[string]interface{}) + + if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + delete(additionalProperties, "name") + o.AdditionalProperties = additionalProperties + } + + return err +} + type NullableAdditionalPropertiesInteger struct { value *AdditionalPropertiesInteger isSet bool diff --git a/samples/client/petstore/go/go-petstore/model_additional_properties_number.go b/samples/client/petstore/go/go-petstore/model_additional_properties_number.go index a1cb5187a5b8..85b3663bf4cf 100644 --- a/samples/client/petstore/go/go-petstore/model_additional_properties_number.go +++ b/samples/client/petstore/go/go-petstore/model_additional_properties_number.go @@ -20,8 +20,11 @@ var _ MappedNullable = &AdditionalPropertiesNumber{} // AdditionalPropertiesNumber struct for AdditionalPropertiesNumber type AdditionalPropertiesNumber struct { Name *string `json:"name,omitempty"` + AdditionalProperties map[string]interface{} } +type _AdditionalPropertiesNumber AdditionalPropertiesNumber + // NewAdditionalPropertiesNumber instantiates a new AdditionalPropertiesNumber object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments @@ -84,9 +87,31 @@ func (o AdditionalPropertiesNumber) ToMap() (map[string]interface{}, error) { if !IsNil(o.Name) { toSerialize["name"] = o.Name } + + for key, value := range o.AdditionalProperties { + toSerialize[key] = value + } + return toSerialize, nil } +func (o *AdditionalPropertiesNumber) UnmarshalJSON(bytes []byte) (err error) { + varAdditionalPropertiesNumber := _AdditionalPropertiesNumber{} + + if err = json.Unmarshal(bytes, &varAdditionalPropertiesNumber); err == nil { + *o = AdditionalPropertiesNumber(varAdditionalPropertiesNumber) + } + + additionalProperties := make(map[string]interface{}) + + if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + delete(additionalProperties, "name") + o.AdditionalProperties = additionalProperties + } + + return err +} + type NullableAdditionalPropertiesNumber struct { value *AdditionalPropertiesNumber isSet bool diff --git a/samples/client/petstore/go/go-petstore/model_additional_properties_object.go b/samples/client/petstore/go/go-petstore/model_additional_properties_object.go index 201a624e05d6..7132cbe61bc4 100644 --- a/samples/client/petstore/go/go-petstore/model_additional_properties_object.go +++ b/samples/client/petstore/go/go-petstore/model_additional_properties_object.go @@ -20,8 +20,11 @@ var _ MappedNullable = &AdditionalPropertiesObject{} // AdditionalPropertiesObject struct for AdditionalPropertiesObject type AdditionalPropertiesObject struct { Name *string `json:"name,omitempty"` + AdditionalProperties map[string]interface{} } +type _AdditionalPropertiesObject AdditionalPropertiesObject + // NewAdditionalPropertiesObject instantiates a new AdditionalPropertiesObject object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments @@ -84,9 +87,31 @@ func (o AdditionalPropertiesObject) ToMap() (map[string]interface{}, error) { if !IsNil(o.Name) { toSerialize["name"] = o.Name } + + for key, value := range o.AdditionalProperties { + toSerialize[key] = value + } + return toSerialize, nil } +func (o *AdditionalPropertiesObject) UnmarshalJSON(bytes []byte) (err error) { + varAdditionalPropertiesObject := _AdditionalPropertiesObject{} + + if err = json.Unmarshal(bytes, &varAdditionalPropertiesObject); err == nil { + *o = AdditionalPropertiesObject(varAdditionalPropertiesObject) + } + + additionalProperties := make(map[string]interface{}) + + if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + delete(additionalProperties, "name") + o.AdditionalProperties = additionalProperties + } + + return err +} + type NullableAdditionalPropertiesObject struct { value *AdditionalPropertiesObject isSet bool diff --git a/samples/client/petstore/go/go-petstore/model_additional_properties_string.go b/samples/client/petstore/go/go-petstore/model_additional_properties_string.go index df649a265a1a..70882312adfe 100644 --- a/samples/client/petstore/go/go-petstore/model_additional_properties_string.go +++ b/samples/client/petstore/go/go-petstore/model_additional_properties_string.go @@ -20,8 +20,11 @@ var _ MappedNullable = &AdditionalPropertiesString{} // AdditionalPropertiesString struct for AdditionalPropertiesString type AdditionalPropertiesString struct { Name *string `json:"name,omitempty"` + AdditionalProperties map[string]interface{} } +type _AdditionalPropertiesString AdditionalPropertiesString + // NewAdditionalPropertiesString instantiates a new AdditionalPropertiesString object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments @@ -84,9 +87,31 @@ func (o AdditionalPropertiesString) ToMap() (map[string]interface{}, error) { if !IsNil(o.Name) { toSerialize["name"] = o.Name } + + for key, value := range o.AdditionalProperties { + toSerialize[key] = value + } + return toSerialize, nil } +func (o *AdditionalPropertiesString) UnmarshalJSON(bytes []byte) (err error) { + varAdditionalPropertiesString := _AdditionalPropertiesString{} + + if err = json.Unmarshal(bytes, &varAdditionalPropertiesString); err == nil { + *o = AdditionalPropertiesString(varAdditionalPropertiesString) + } + + additionalProperties := make(map[string]interface{}) + + if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + delete(additionalProperties, "name") + o.AdditionalProperties = additionalProperties + } + + return err +} + type NullableAdditionalPropertiesString struct { value *AdditionalPropertiesString isSet bool diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java index 38302f996d34..255661a68499 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java @@ -79,6 +79,50 @@ public void setName(String name) { this.name = name; } + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the AdditionalPropertiesAnyType instance itself + */ + public AdditionalPropertiesAnyType putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } @Override @@ -90,12 +134,13 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesAnyType additionalPropertiesAnyType = (AdditionalPropertiesAnyType) o; - return Objects.equals(this.name, additionalPropertiesAnyType.name); + return Objects.equals(this.name, additionalPropertiesAnyType.name)&& + Objects.equals(this.additionalProperties, additionalPropertiesAnyType.additionalProperties); } @Override public int hashCode() { - return Objects.hash(name); + return Objects.hash(name, additionalProperties); } @Override @@ -103,6 +148,7 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AdditionalPropertiesAnyType {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); sb.append("}"); return sb.toString(); } @@ -143,14 +189,6 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesAnyType is not found in the empty JSON string", AdditionalPropertiesAnyType.openapiRequiredFields.toString())); } } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Entry entry : entries) { - if (!AdditionalPropertiesAnyType.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesAnyType` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } JsonObject jsonObj = jsonElement.getAsJsonObject(); if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); @@ -172,6 +210,23 @@ public TypeAdapter create(Gson gson, TypeToken type) { @Override public void write(JsonWriter out, AdditionalPropertiesAnyType value) throws IOException { JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject()); + } + } + } elementAdapter.write(out, obj); } @@ -179,7 +234,28 @@ public void write(JsonWriter out, AdditionalPropertiesAnyType value) throws IOEx public AdditionalPropertiesAnyType read(JsonReader in) throws IOException { JsonElement jsonElement = elementAdapter.read(in); validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + AdditionalPropertiesAnyType instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; } }.nullSafe(); diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java index 5252f9e9f372..91767c706f47 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java @@ -80,6 +80,50 @@ public void setName(String name) { this.name = name; } + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the AdditionalPropertiesArray instance itself + */ + public AdditionalPropertiesArray putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } @Override @@ -91,12 +135,13 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesArray additionalPropertiesArray = (AdditionalPropertiesArray) o; - return Objects.equals(this.name, additionalPropertiesArray.name); + return Objects.equals(this.name, additionalPropertiesArray.name)&& + Objects.equals(this.additionalProperties, additionalPropertiesArray.additionalProperties); } @Override public int hashCode() { - return Objects.hash(name); + return Objects.hash(name, additionalProperties); } @Override @@ -104,6 +149,7 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AdditionalPropertiesArray {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); sb.append("}"); return sb.toString(); } @@ -144,14 +190,6 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesArray is not found in the empty JSON string", AdditionalPropertiesArray.openapiRequiredFields.toString())); } } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Entry entry : entries) { - if (!AdditionalPropertiesArray.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesArray` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } JsonObject jsonObj = jsonElement.getAsJsonObject(); if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); @@ -173,6 +211,23 @@ public TypeAdapter create(Gson gson, TypeToken type) { @Override public void write(JsonWriter out, AdditionalPropertiesArray value) throws IOException { JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject()); + } + } + } elementAdapter.write(out, obj); } @@ -180,7 +235,28 @@ public void write(JsonWriter out, AdditionalPropertiesArray value) throws IOExce public AdditionalPropertiesArray read(JsonReader in) throws IOException { JsonElement jsonElement = elementAdapter.read(in); validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + AdditionalPropertiesArray instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; } }.nullSafe(); diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java index 0ab06c7e54d5..803574cfa6a0 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java @@ -79,6 +79,50 @@ public void setName(String name) { this.name = name; } + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the AdditionalPropertiesBoolean instance itself + */ + public AdditionalPropertiesBoolean putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } @Override @@ -90,12 +134,13 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesBoolean additionalPropertiesBoolean = (AdditionalPropertiesBoolean) o; - return Objects.equals(this.name, additionalPropertiesBoolean.name); + return Objects.equals(this.name, additionalPropertiesBoolean.name)&& + Objects.equals(this.additionalProperties, additionalPropertiesBoolean.additionalProperties); } @Override public int hashCode() { - return Objects.hash(name); + return Objects.hash(name, additionalProperties); } @Override @@ -103,6 +148,7 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AdditionalPropertiesBoolean {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); sb.append("}"); return sb.toString(); } @@ -143,14 +189,6 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesBoolean is not found in the empty JSON string", AdditionalPropertiesBoolean.openapiRequiredFields.toString())); } } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Entry entry : entries) { - if (!AdditionalPropertiesBoolean.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesBoolean` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } JsonObject jsonObj = jsonElement.getAsJsonObject(); if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); @@ -172,6 +210,23 @@ public TypeAdapter create(Gson gson, TypeToken type) { @Override public void write(JsonWriter out, AdditionalPropertiesBoolean value) throws IOException { JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject()); + } + } + } elementAdapter.write(out, obj); } @@ -179,7 +234,28 @@ public void write(JsonWriter out, AdditionalPropertiesBoolean value) throws IOEx public AdditionalPropertiesBoolean read(JsonReader in) throws IOException { JsonElement jsonElement = elementAdapter.read(in); validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + AdditionalPropertiesBoolean instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; } }.nullSafe(); diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java index 92c9ca7cc50b..f07e09810b0e 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java @@ -79,6 +79,50 @@ public void setName(String name) { this.name = name; } + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the AdditionalPropertiesInteger instance itself + */ + public AdditionalPropertiesInteger putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } @Override @@ -90,12 +134,13 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesInteger additionalPropertiesInteger = (AdditionalPropertiesInteger) o; - return Objects.equals(this.name, additionalPropertiesInteger.name); + return Objects.equals(this.name, additionalPropertiesInteger.name)&& + Objects.equals(this.additionalProperties, additionalPropertiesInteger.additionalProperties); } @Override public int hashCode() { - return Objects.hash(name); + return Objects.hash(name, additionalProperties); } @Override @@ -103,6 +148,7 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AdditionalPropertiesInteger {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); sb.append("}"); return sb.toString(); } @@ -143,14 +189,6 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesInteger is not found in the empty JSON string", AdditionalPropertiesInteger.openapiRequiredFields.toString())); } } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Entry entry : entries) { - if (!AdditionalPropertiesInteger.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesInteger` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } JsonObject jsonObj = jsonElement.getAsJsonObject(); if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); @@ -172,6 +210,23 @@ public TypeAdapter create(Gson gson, TypeToken type) { @Override public void write(JsonWriter out, AdditionalPropertiesInteger value) throws IOException { JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject()); + } + } + } elementAdapter.write(out, obj); } @@ -179,7 +234,28 @@ public void write(JsonWriter out, AdditionalPropertiesInteger value) throws IOEx public AdditionalPropertiesInteger read(JsonReader in) throws IOException { JsonElement jsonElement = elementAdapter.read(in); validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + AdditionalPropertiesInteger instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; } }.nullSafe(); diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java index f786790043b1..02fe36ad9742 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java @@ -80,6 +80,50 @@ public void setName(String name) { this.name = name; } + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the AdditionalPropertiesNumber instance itself + */ + public AdditionalPropertiesNumber putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } @Override @@ -91,12 +135,13 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesNumber additionalPropertiesNumber = (AdditionalPropertiesNumber) o; - return Objects.equals(this.name, additionalPropertiesNumber.name); + return Objects.equals(this.name, additionalPropertiesNumber.name)&& + Objects.equals(this.additionalProperties, additionalPropertiesNumber.additionalProperties); } @Override public int hashCode() { - return Objects.hash(name); + return Objects.hash(name, additionalProperties); } @Override @@ -104,6 +149,7 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AdditionalPropertiesNumber {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); sb.append("}"); return sb.toString(); } @@ -144,14 +190,6 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesNumber is not found in the empty JSON string", AdditionalPropertiesNumber.openapiRequiredFields.toString())); } } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Entry entry : entries) { - if (!AdditionalPropertiesNumber.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesNumber` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } JsonObject jsonObj = jsonElement.getAsJsonObject(); if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); @@ -173,6 +211,23 @@ public TypeAdapter create(Gson gson, TypeToken type) { @Override public void write(JsonWriter out, AdditionalPropertiesNumber value) throws IOException { JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject()); + } + } + } elementAdapter.write(out, obj); } @@ -180,7 +235,28 @@ public void write(JsonWriter out, AdditionalPropertiesNumber value) throws IOExc public AdditionalPropertiesNumber read(JsonReader in) throws IOException { JsonElement jsonElement = elementAdapter.read(in); validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + AdditionalPropertiesNumber instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; } }.nullSafe(); diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java index 8d7686e9800d..6e7968267bd1 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java @@ -80,6 +80,50 @@ public void setName(String name) { this.name = name; } + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the AdditionalPropertiesObject instance itself + */ + public AdditionalPropertiesObject putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } @Override @@ -91,12 +135,13 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesObject additionalPropertiesObject = (AdditionalPropertiesObject) o; - return Objects.equals(this.name, additionalPropertiesObject.name); + return Objects.equals(this.name, additionalPropertiesObject.name)&& + Objects.equals(this.additionalProperties, additionalPropertiesObject.additionalProperties); } @Override public int hashCode() { - return Objects.hash(name); + return Objects.hash(name, additionalProperties); } @Override @@ -104,6 +149,7 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AdditionalPropertiesObject {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); sb.append("}"); return sb.toString(); } @@ -144,14 +190,6 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesObject is not found in the empty JSON string", AdditionalPropertiesObject.openapiRequiredFields.toString())); } } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Entry entry : entries) { - if (!AdditionalPropertiesObject.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesObject` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } JsonObject jsonObj = jsonElement.getAsJsonObject(); if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); @@ -173,6 +211,23 @@ public TypeAdapter create(Gson gson, TypeToken type) { @Override public void write(JsonWriter out, AdditionalPropertiesObject value) throws IOException { JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject()); + } + } + } elementAdapter.write(out, obj); } @@ -180,7 +235,28 @@ public void write(JsonWriter out, AdditionalPropertiesObject value) throws IOExc public AdditionalPropertiesObject read(JsonReader in) throws IOException { JsonElement jsonElement = elementAdapter.read(in); validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + AdditionalPropertiesObject instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; } }.nullSafe(); diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java index 6dae21f945b8..e957ecab1472 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java @@ -79,6 +79,50 @@ public void setName(String name) { this.name = name; } + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the AdditionalPropertiesString instance itself + */ + public AdditionalPropertiesString putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } @Override @@ -90,12 +134,13 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesString additionalPropertiesString = (AdditionalPropertiesString) o; - return Objects.equals(this.name, additionalPropertiesString.name); + return Objects.equals(this.name, additionalPropertiesString.name)&& + Objects.equals(this.additionalProperties, additionalPropertiesString.additionalProperties); } @Override public int hashCode() { - return Objects.hash(name); + return Objects.hash(name, additionalProperties); } @Override @@ -103,6 +148,7 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AdditionalPropertiesString {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); sb.append("}"); return sb.toString(); } @@ -143,14 +189,6 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesString is not found in the empty JSON string", AdditionalPropertiesString.openapiRequiredFields.toString())); } } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Entry entry : entries) { - if (!AdditionalPropertiesString.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesString` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } JsonObject jsonObj = jsonElement.getAsJsonObject(); if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); @@ -172,6 +210,23 @@ public TypeAdapter create(Gson gson, TypeToken type) { @Override public void write(JsonWriter out, AdditionalPropertiesString value) throws IOException { JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject()); + } + } + } elementAdapter.write(out, obj); } @@ -179,7 +234,28 @@ public void write(JsonWriter out, AdditionalPropertiesString value) throws IOExc public AdditionalPropertiesString read(JsonReader in) throws IOException { JsonElement jsonElement = elementAdapter.read(in); validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + AdditionalPropertiesString instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; } }.nullSafe(); diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java index 8d642af57bff..b93480b42e1a 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java @@ -81,6 +81,50 @@ public void setName(String name) { this.name = name; } + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the AdditionalPropertiesAnyType instance itself + */ + public AdditionalPropertiesAnyType putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } @Override @@ -92,12 +136,13 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesAnyType additionalPropertiesAnyType = (AdditionalPropertiesAnyType) o; - return Objects.equals(this.name, additionalPropertiesAnyType.name); + return Objects.equals(this.name, additionalPropertiesAnyType.name)&& + Objects.equals(this.additionalProperties, additionalPropertiesAnyType.additionalProperties); } @Override public int hashCode() { - return Objects.hash(name); + return Objects.hash(name, additionalProperties); } @Override @@ -105,6 +150,7 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AdditionalPropertiesAnyType {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); sb.append("}"); return sb.toString(); } @@ -166,14 +212,6 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesAnyType is not found in the empty JSON string", AdditionalPropertiesAnyType.openapiRequiredFields.toString())); } } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Entry entry : entries) { - if (!AdditionalPropertiesAnyType.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesAnyType` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } JsonObject jsonObj = jsonElement.getAsJsonObject(); if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); @@ -195,6 +233,23 @@ public TypeAdapter create(Gson gson, TypeToken type) { @Override public void write(JsonWriter out, AdditionalPropertiesAnyType value) throws IOException { JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject()); + } + } + } elementAdapter.write(out, obj); } @@ -202,7 +257,28 @@ public void write(JsonWriter out, AdditionalPropertiesAnyType value) throws IOEx public AdditionalPropertiesAnyType read(JsonReader in) throws IOException { JsonElement jsonElement = elementAdapter.read(in); validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + AdditionalPropertiesAnyType instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; } }.nullSafe(); diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java index fe46853e434c..a54c96aa592a 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java @@ -82,6 +82,50 @@ public void setName(String name) { this.name = name; } + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the AdditionalPropertiesArray instance itself + */ + public AdditionalPropertiesArray putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } @Override @@ -93,12 +137,13 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesArray additionalPropertiesArray = (AdditionalPropertiesArray) o; - return Objects.equals(this.name, additionalPropertiesArray.name); + return Objects.equals(this.name, additionalPropertiesArray.name)&& + Objects.equals(this.additionalProperties, additionalPropertiesArray.additionalProperties); } @Override public int hashCode() { - return Objects.hash(name); + return Objects.hash(name, additionalProperties); } @Override @@ -106,6 +151,7 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AdditionalPropertiesArray {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); sb.append("}"); return sb.toString(); } @@ -167,14 +213,6 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesArray is not found in the empty JSON string", AdditionalPropertiesArray.openapiRequiredFields.toString())); } } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Entry entry : entries) { - if (!AdditionalPropertiesArray.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesArray` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } JsonObject jsonObj = jsonElement.getAsJsonObject(); if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); @@ -196,6 +234,23 @@ public TypeAdapter create(Gson gson, TypeToken type) { @Override public void write(JsonWriter out, AdditionalPropertiesArray value) throws IOException { JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject()); + } + } + } elementAdapter.write(out, obj); } @@ -203,7 +258,28 @@ public void write(JsonWriter out, AdditionalPropertiesArray value) throws IOExce public AdditionalPropertiesArray read(JsonReader in) throws IOException { JsonElement jsonElement = elementAdapter.read(in); validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + AdditionalPropertiesArray instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; } }.nullSafe(); diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java index aa666774ec57..ea9c2dafd33a 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java @@ -81,6 +81,50 @@ public void setName(String name) { this.name = name; } + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the AdditionalPropertiesBoolean instance itself + */ + public AdditionalPropertiesBoolean putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } @Override @@ -92,12 +136,13 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesBoolean additionalPropertiesBoolean = (AdditionalPropertiesBoolean) o; - return Objects.equals(this.name, additionalPropertiesBoolean.name); + return Objects.equals(this.name, additionalPropertiesBoolean.name)&& + Objects.equals(this.additionalProperties, additionalPropertiesBoolean.additionalProperties); } @Override public int hashCode() { - return Objects.hash(name); + return Objects.hash(name, additionalProperties); } @Override @@ -105,6 +150,7 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AdditionalPropertiesBoolean {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); sb.append("}"); return sb.toString(); } @@ -166,14 +212,6 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesBoolean is not found in the empty JSON string", AdditionalPropertiesBoolean.openapiRequiredFields.toString())); } } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Entry entry : entries) { - if (!AdditionalPropertiesBoolean.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesBoolean` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } JsonObject jsonObj = jsonElement.getAsJsonObject(); if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); @@ -195,6 +233,23 @@ public TypeAdapter create(Gson gson, TypeToken type) { @Override public void write(JsonWriter out, AdditionalPropertiesBoolean value) throws IOException { JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject()); + } + } + } elementAdapter.write(out, obj); } @@ -202,7 +257,28 @@ public void write(JsonWriter out, AdditionalPropertiesBoolean value) throws IOEx public AdditionalPropertiesBoolean read(JsonReader in) throws IOException { JsonElement jsonElement = elementAdapter.read(in); validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + AdditionalPropertiesBoolean instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; } }.nullSafe(); diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java index 590b21a6a181..2c66d5540570 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java @@ -81,6 +81,50 @@ public void setName(String name) { this.name = name; } + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the AdditionalPropertiesInteger instance itself + */ + public AdditionalPropertiesInteger putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } @Override @@ -92,12 +136,13 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesInteger additionalPropertiesInteger = (AdditionalPropertiesInteger) o; - return Objects.equals(this.name, additionalPropertiesInteger.name); + return Objects.equals(this.name, additionalPropertiesInteger.name)&& + Objects.equals(this.additionalProperties, additionalPropertiesInteger.additionalProperties); } @Override public int hashCode() { - return Objects.hash(name); + return Objects.hash(name, additionalProperties); } @Override @@ -105,6 +150,7 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AdditionalPropertiesInteger {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); sb.append("}"); return sb.toString(); } @@ -166,14 +212,6 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesInteger is not found in the empty JSON string", AdditionalPropertiesInteger.openapiRequiredFields.toString())); } } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Entry entry : entries) { - if (!AdditionalPropertiesInteger.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesInteger` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } JsonObject jsonObj = jsonElement.getAsJsonObject(); if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); @@ -195,6 +233,23 @@ public TypeAdapter create(Gson gson, TypeToken type) { @Override public void write(JsonWriter out, AdditionalPropertiesInteger value) throws IOException { JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject()); + } + } + } elementAdapter.write(out, obj); } @@ -202,7 +257,28 @@ public void write(JsonWriter out, AdditionalPropertiesInteger value) throws IOEx public AdditionalPropertiesInteger read(JsonReader in) throws IOException { JsonElement jsonElement = elementAdapter.read(in); validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + AdditionalPropertiesInteger instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; } }.nullSafe(); diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java index 95c0c465ad8d..2da59e9905e2 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java @@ -82,6 +82,50 @@ public void setName(String name) { this.name = name; } + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the AdditionalPropertiesNumber instance itself + */ + public AdditionalPropertiesNumber putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } @Override @@ -93,12 +137,13 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesNumber additionalPropertiesNumber = (AdditionalPropertiesNumber) o; - return Objects.equals(this.name, additionalPropertiesNumber.name); + return Objects.equals(this.name, additionalPropertiesNumber.name)&& + Objects.equals(this.additionalProperties, additionalPropertiesNumber.additionalProperties); } @Override public int hashCode() { - return Objects.hash(name); + return Objects.hash(name, additionalProperties); } @Override @@ -106,6 +151,7 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AdditionalPropertiesNumber {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); sb.append("}"); return sb.toString(); } @@ -167,14 +213,6 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesNumber is not found in the empty JSON string", AdditionalPropertiesNumber.openapiRequiredFields.toString())); } } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Entry entry : entries) { - if (!AdditionalPropertiesNumber.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesNumber` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } JsonObject jsonObj = jsonElement.getAsJsonObject(); if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); @@ -196,6 +234,23 @@ public TypeAdapter create(Gson gson, TypeToken type) { @Override public void write(JsonWriter out, AdditionalPropertiesNumber value) throws IOException { JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject()); + } + } + } elementAdapter.write(out, obj); } @@ -203,7 +258,28 @@ public void write(JsonWriter out, AdditionalPropertiesNumber value) throws IOExc public AdditionalPropertiesNumber read(JsonReader in) throws IOException { JsonElement jsonElement = elementAdapter.read(in); validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + AdditionalPropertiesNumber instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; } }.nullSafe(); diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java index d6179b5e0623..57483da37672 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java @@ -82,6 +82,50 @@ public void setName(String name) { this.name = name; } + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the AdditionalPropertiesObject instance itself + */ + public AdditionalPropertiesObject putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } @Override @@ -93,12 +137,13 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesObject additionalPropertiesObject = (AdditionalPropertiesObject) o; - return Objects.equals(this.name, additionalPropertiesObject.name); + return Objects.equals(this.name, additionalPropertiesObject.name)&& + Objects.equals(this.additionalProperties, additionalPropertiesObject.additionalProperties); } @Override public int hashCode() { - return Objects.hash(name); + return Objects.hash(name, additionalProperties); } @Override @@ -106,6 +151,7 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AdditionalPropertiesObject {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); sb.append("}"); return sb.toString(); } @@ -167,14 +213,6 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesObject is not found in the empty JSON string", AdditionalPropertiesObject.openapiRequiredFields.toString())); } } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Entry entry : entries) { - if (!AdditionalPropertiesObject.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesObject` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } JsonObject jsonObj = jsonElement.getAsJsonObject(); if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); @@ -196,6 +234,23 @@ public TypeAdapter create(Gson gson, TypeToken type) { @Override public void write(JsonWriter out, AdditionalPropertiesObject value) throws IOException { JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject()); + } + } + } elementAdapter.write(out, obj); } @@ -203,7 +258,28 @@ public void write(JsonWriter out, AdditionalPropertiesObject value) throws IOExc public AdditionalPropertiesObject read(JsonReader in) throws IOException { JsonElement jsonElement = elementAdapter.read(in); validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + AdditionalPropertiesObject instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; } }.nullSafe(); diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java index a01f05e1b2be..c0ce3d56ba25 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java @@ -81,6 +81,50 @@ public void setName(String name) { this.name = name; } + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the AdditionalPropertiesString instance itself + */ + public AdditionalPropertiesString putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } @Override @@ -92,12 +136,13 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesString additionalPropertiesString = (AdditionalPropertiesString) o; - return Objects.equals(this.name, additionalPropertiesString.name); + return Objects.equals(this.name, additionalPropertiesString.name)&& + Objects.equals(this.additionalProperties, additionalPropertiesString.additionalProperties); } @Override public int hashCode() { - return Objects.hash(name); + return Objects.hash(name, additionalProperties); } @Override @@ -105,6 +150,7 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AdditionalPropertiesString {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); sb.append("}"); return sb.toString(); } @@ -166,14 +212,6 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesString is not found in the empty JSON string", AdditionalPropertiesString.openapiRequiredFields.toString())); } } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Entry entry : entries) { - if (!AdditionalPropertiesString.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesString` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } JsonObject jsonObj = jsonElement.getAsJsonObject(); if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); @@ -195,6 +233,23 @@ public TypeAdapter create(Gson gson, TypeToken type) { @Override public void write(JsonWriter out, AdditionalPropertiesString value) throws IOException { JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject()); + } + } + } elementAdapter.write(out, obj); } @@ -202,7 +257,28 @@ public void write(JsonWriter out, AdditionalPropertiesString value) throws IOExc public AdditionalPropertiesString read(JsonReader in) throws IOException { JsonElement jsonElement = elementAdapter.read(in); validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + AdditionalPropertiesString instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; } }.nullSafe(); diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Drawing.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Drawing.java index ea738037f869..2c4b7eff5726 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Drawing.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Drawing.java @@ -169,6 +169,50 @@ public void setShapes(List shapes) { this.shapes = shapes; } + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the Drawing instance itself + */ + public Drawing putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } @Override @@ -183,7 +227,8 @@ public boolean equals(Object o) { return Objects.equals(this.mainShape, drawing.mainShape) && Objects.equals(this.shapeOrNull, drawing.shapeOrNull) && Objects.equals(this.nullableShape, drawing.nullableShape) && - Objects.equals(this.shapes, drawing.shapes); + Objects.equals(this.shapes, drawing.shapes)&& + Objects.equals(this.additionalProperties, drawing.additionalProperties); } private static boolean equalsNullable(JsonNullable a, JsonNullable b) { @@ -192,7 +237,7 @@ private static boolean equalsNullable(JsonNullable a, JsonNullable b) @Override public int hashCode() { - return Objects.hash(mainShape, shapeOrNull, nullableShape, shapes); + return Objects.hash(mainShape, shapeOrNull, nullableShape, shapes, additionalProperties); } private static int hashCodeNullable(JsonNullable a) { @@ -210,6 +255,7 @@ public String toString() { sb.append(" shapeOrNull: ").append(toIndentedString(shapeOrNull)).append("\n"); sb.append(" nullableShape: ").append(toIndentedString(nullableShape)).append("\n"); sb.append(" shapes: ").append(toIndentedString(shapes)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); sb.append("}"); return sb.toString(); } @@ -253,14 +299,6 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti throw new IllegalArgumentException(String.format("The required field(s) %s in Drawing is not found in the empty JSON string", Drawing.openapiRequiredFields.toString())); } } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Entry entry : entries) { - if (!Drawing.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Drawing` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } JsonObject jsonObj = jsonElement.getAsJsonObject(); // validate the optional field `mainShape` if (jsonObj.get("mainShape") != null && !jsonObj.get("mainShape").isJsonNull()) { @@ -305,6 +343,23 @@ public TypeAdapter create(Gson gson, TypeToken type) { @Override public void write(JsonWriter out, Drawing value) throws IOException { JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject()); + } + } + } elementAdapter.write(out, obj); } @@ -312,7 +367,28 @@ public void write(JsonWriter out, Drawing value) throws IOException { public Drawing read(JsonReader in) throws IOException { JsonElement jsonElement = elementAdapter.read(in); validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + Drawing instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; } }.nullSafe(); diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NullableClass.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NullableClass.java index a6b7762819d1..8c2e799566d5 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NullableClass.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NullableClass.java @@ -410,6 +410,50 @@ public void setObjectItemsNullable(Map objectItemsNullable) { this.objectItemsNullable = objectItemsNullable; } + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the NullableClass instance itself + */ + public NullableClass putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } @Override @@ -432,7 +476,8 @@ public boolean equals(Object o) { Objects.equals(this.arrayItemsNullable, nullableClass.arrayItemsNullable) && Objects.equals(this.objectNullableProp, nullableClass.objectNullableProp) && Objects.equals(this.objectAndItemsNullableProp, nullableClass.objectAndItemsNullableProp) && - Objects.equals(this.objectItemsNullable, nullableClass.objectItemsNullable); + Objects.equals(this.objectItemsNullable, nullableClass.objectItemsNullable)&& + Objects.equals(this.additionalProperties, nullableClass.additionalProperties); } private static boolean equalsNullable(JsonNullable a, JsonNullable b) { @@ -441,7 +486,7 @@ private static boolean equalsNullable(JsonNullable a, JsonNullable b) @Override public int hashCode() { - return Objects.hash(integerProp, numberProp, booleanProp, stringProp, dateProp, datetimeProp, arrayNullableProp, arrayAndItemsNullableProp, arrayItemsNullable, objectNullableProp, objectAndItemsNullableProp, objectItemsNullable); + return Objects.hash(integerProp, numberProp, booleanProp, stringProp, dateProp, datetimeProp, arrayNullableProp, arrayAndItemsNullableProp, arrayItemsNullable, objectNullableProp, objectAndItemsNullableProp, objectItemsNullable, additionalProperties); } private static int hashCodeNullable(JsonNullable a) { @@ -467,6 +512,7 @@ public String toString() { sb.append(" objectNullableProp: ").append(toIndentedString(objectNullableProp)).append("\n"); sb.append(" objectAndItemsNullableProp: ").append(toIndentedString(objectAndItemsNullableProp)).append("\n"); sb.append(" objectItemsNullable: ").append(toIndentedString(objectItemsNullable)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); sb.append("}"); return sb.toString(); } @@ -518,14 +564,6 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti throw new IllegalArgumentException(String.format("The required field(s) %s in NullableClass is not found in the empty JSON string", NullableClass.openapiRequiredFields.toString())); } } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Entry entry : entries) { - if (!NullableClass.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `NullableClass` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } JsonObject jsonObj = jsonElement.getAsJsonObject(); if ((jsonObj.get("string_prop") != null && !jsonObj.get("string_prop").isJsonNull()) && !jsonObj.get("string_prop").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `string_prop` to be a primitive type in the JSON string but got `%s`", jsonObj.get("string_prop").toString())); @@ -559,6 +597,23 @@ public TypeAdapter create(Gson gson, TypeToken type) { @Override public void write(JsonWriter out, NullableClass value) throws IOException { JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject()); + } + } + } elementAdapter.write(out, obj); } @@ -566,7 +621,28 @@ public void write(JsonWriter out, NullableClass value) throws IOException { public NullableClass read(JsonReader in) throws IOException { JsonElement jsonElement = elementAdapter.read(in); validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + NullableClass instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; } }.nullSafe(); diff --git a/samples/client/petstore/powershell/src/PSPetstore/Model/Drawing.ps1 b/samples/client/petstore/powershell/src/PSPetstore/Model/Drawing.ps1 index 3db24f69486d..853e8b0b9a3b 100644 --- a/samples/client/petstore/powershell/src/PSPetstore/Model/Drawing.ps1 +++ b/samples/client/petstore/powershell/src/PSPetstore/Model/Drawing.ps1 @@ -89,12 +89,14 @@ function ConvertFrom-PSJsonToDrawing { $PSBoundParameters | Out-DebugParameter | Write-Debug $JsonParameters = ConvertFrom-Json -InputObject $Json + $PSDrawingAdditionalProperties = @{} # check if Json contains properties not defined in PSDrawing $AllProperties = ("mainShape", "shapeOrNull", "nullableShape", "shapes") foreach ($name in $JsonParameters.PsObject.Properties.Name) { + # store undefined properties in additionalProperties if (!($AllProperties.Contains($name))) { - throw "Error! JSON key '$name' not found in the properties: $($AllProperties)" + $PSDrawingAdditionalProperties[$name] = $JsonParameters.PSobject.Properties[$name].value } } @@ -127,6 +129,7 @@ function ConvertFrom-PSJsonToDrawing { "shapeOrNull" = ${ShapeOrNull} "nullableShape" = ${NullableShape} "shapes" = ${Shapes} + "AdditionalProperties" = $PSDrawingAdditionalProperties } return $PSO diff --git a/samples/client/petstore/powershell/src/PSPetstore/Model/NullableClass.ps1 b/samples/client/petstore/powershell/src/PSPetstore/Model/NullableClass.ps1 index 21755910978e..07dd0d94b712 100644 --- a/samples/client/petstore/powershell/src/PSPetstore/Model/NullableClass.ps1 +++ b/samples/client/petstore/powershell/src/PSPetstore/Model/NullableClass.ps1 @@ -137,12 +137,14 @@ function ConvertFrom-PSJsonToNullableClass { $PSBoundParameters | Out-DebugParameter | Write-Debug $JsonParameters = ConvertFrom-Json -InputObject $Json + $PSNullableClassAdditionalProperties = @{} # check if Json contains properties not defined in PSNullableClass $AllProperties = ("integer_prop", "number_prop", "boolean_prop", "string_prop", "date_prop", "datetime_prop", "array_nullable_prop", "array_and_items_nullable_prop", "array_items_nullable", "object_nullable_prop", "object_and_items_nullable_prop", "object_items_nullable") foreach ($name in $JsonParameters.PsObject.Properties.Name) { + # store undefined properties in additionalProperties if (!($AllProperties.Contains($name))) { - throw "Error! JSON key '$name' not found in the properties: $($AllProperties)" + $PSNullableClassAdditionalProperties[$name] = $JsonParameters.PSobject.Properties[$name].value } } @@ -231,6 +233,7 @@ function ConvertFrom-PSJsonToNullableClass { "object_nullable_prop" = ${ObjectNullableProp} "object_and_items_nullable_prop" = ${ObjectAndItemsNullableProp} "object_items_nullable" = ${ObjectItemsNullable} + "AdditionalProperties" = $PSNullableClassAdditionalProperties } return $PSO diff --git a/samples/client/petstore/typescript-axios/builds/test-petstore/api.ts b/samples/client/petstore/typescript-axios/builds/test-petstore/api.ts index dddf833bbb67..9a75bfa1ab15 100644 --- a/samples/client/petstore/typescript-axios/builds/test-petstore/api.ts +++ b/samples/client/petstore/typescript-axios/builds/test-petstore/api.ts @@ -447,7 +447,7 @@ export interface Dog extends Animal { * @interface Drawing */ export interface Drawing { - [key: string]: Fruit | any; + [key: string]: Fruit; /** * @@ -1043,7 +1043,7 @@ export interface Name { * @interface NullableClass */ export interface NullableClass { - [key: string]: object | any; + [key: string]: object; /** * diff --git a/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/api.ts b/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/api.ts index fbb65d707903..e4d6dc1e4db9 100644 --- a/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/api.ts @@ -811,7 +811,7 @@ export interface Name { * @interface NullableClass */ export interface NullableClass { - [key: string]: object | any; + [key: string]: object; /** * diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_nullable_class.go b/samples/openapi3/client/petstore/go/go-petstore/model_nullable_class.go index 0c173346d226..580936cff216 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_nullable_class.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_nullable_class.go @@ -32,8 +32,11 @@ type NullableClass struct { ObjectNullableProp map[string]map[string]interface{} `json:"object_nullable_prop,omitempty"` ObjectAndItemsNullableProp map[string]map[string]interface{} `json:"object_and_items_nullable_prop,omitempty"` ObjectItemsNullable map[string]map[string]interface{} `json:"object_items_nullable,omitempty"` + AdditionalProperties map[string]interface{} } +type _NullableClass NullableClass + // NewNullableClass instantiates a new NullableClass object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments @@ -549,9 +552,42 @@ func (o NullableClass) ToMap() (map[string]interface{}, error) { if !IsNil(o.ObjectItemsNullable) { toSerialize["object_items_nullable"] = o.ObjectItemsNullable } + + for key, value := range o.AdditionalProperties { + toSerialize[key] = value + } + return toSerialize, nil } +func (o *NullableClass) UnmarshalJSON(bytes []byte) (err error) { + varNullableClass := _NullableClass{} + + if err = json.Unmarshal(bytes, &varNullableClass); err == nil { + *o = NullableClass(varNullableClass) + } + + additionalProperties := make(map[string]interface{}) + + if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + delete(additionalProperties, "integer_prop") + delete(additionalProperties, "number_prop") + delete(additionalProperties, "boolean_prop") + delete(additionalProperties, "string_prop") + delete(additionalProperties, "date_prop") + delete(additionalProperties, "datetime_prop") + delete(additionalProperties, "array_nullable_prop") + delete(additionalProperties, "array_and_items_nullable_prop") + delete(additionalProperties, "array_items_nullable") + delete(additionalProperties, "object_nullable_prop") + delete(additionalProperties, "object_and_items_nullable_prop") + delete(additionalProperties, "object_items_nullable") + o.AdditionalProperties = additionalProperties + } + + return err +} + type NullableNullableClass struct { value *NullableClass isSet bool diff --git a/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/FILES b/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/FILES index a30ce812a9a4..7781fa1c1eda 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/FILES @@ -3,7 +3,10 @@ .gitlab-ci.yml .travis.yml README.md +docs/AdditionalPropertiesAnyType.md docs/AdditionalPropertiesClass.md +docs/AdditionalPropertiesObject.md +docs/AdditionalPropertiesWithDescriptionOnly.md docs/AllOfWithSingleRef.md docs/Animal.md docs/AnotherFakeApi.md @@ -100,7 +103,10 @@ petstore_api/api_response.py petstore_api/configuration.py petstore_api/exceptions.py petstore_api/models/__init__.py +petstore_api/models/additional_properties_any_type.py petstore_api/models/additional_properties_class.py +petstore_api/models/additional_properties_object.py +petstore_api/models/additional_properties_with_description_only.py petstore_api/models/all_of_with_single_ref.py petstore_api/models/animal.py petstore_api/models/any_of_color.py diff --git a/samples/openapi3/client/petstore/python-aiohttp/README.md b/samples/openapi3/client/petstore/python-aiohttp/README.md index a443818bd2f2..1c4f209dc5ad 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/README.md +++ b/samples/openapi3/client/petstore/python-aiohttp/README.md @@ -132,7 +132,10 @@ Class | Method | HTTP request | Description ## Documentation For Models + - [AdditionalPropertiesAnyType](docs/AdditionalPropertiesAnyType.md) - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) + - [AdditionalPropertiesObject](docs/AdditionalPropertiesObject.md) + - [AdditionalPropertiesWithDescriptionOnly](docs/AdditionalPropertiesWithDescriptionOnly.md) - [AllOfWithSingleRef](docs/AllOfWithSingleRef.md) - [Animal](docs/Animal.md) - [AnyOfColor](docs/AnyOfColor.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesAnyType.md b/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesAnyType.md new file mode 100644 index 000000000000..beedef76c051 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesAnyType.md @@ -0,0 +1,28 @@ +# AdditionalPropertiesAnyType + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **str** | | [optional] + +## Example + +```python +from petstore_api.models.additional_properties_any_type import AdditionalPropertiesAnyType + +# TODO update the JSON string below +json = "{}" +# create an instance of AdditionalPropertiesAnyType from a JSON string +additional_properties_any_type_instance = AdditionalPropertiesAnyType.from_json(json) +# print the JSON string representation of the object +print AdditionalPropertiesAnyType.to_json() + +# convert the object into a dict +additional_properties_any_type_dict = additional_properties_any_type_instance.to_dict() +# create an instance of AdditionalPropertiesAnyType from a dict +additional_properties_any_type_form_dict = additional_properties_any_type.from_dict(additional_properties_any_type_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesObject.md b/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesObject.md new file mode 100644 index 000000000000..8b9259c687f6 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesObject.md @@ -0,0 +1,28 @@ +# AdditionalPropertiesObject + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **str** | | [optional] + +## Example + +```python +from petstore_api.models.additional_properties_object import AdditionalPropertiesObject + +# TODO update the JSON string below +json = "{}" +# create an instance of AdditionalPropertiesObject from a JSON string +additional_properties_object_instance = AdditionalPropertiesObject.from_json(json) +# print the JSON string representation of the object +print AdditionalPropertiesObject.to_json() + +# convert the object into a dict +additional_properties_object_dict = additional_properties_object_instance.to_dict() +# create an instance of AdditionalPropertiesObject from a dict +additional_properties_object_form_dict = additional_properties_object.from_dict(additional_properties_object_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesWithDescriptionOnly.md b/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesWithDescriptionOnly.md new file mode 100644 index 000000000000..d66094f18e57 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesWithDescriptionOnly.md @@ -0,0 +1,28 @@ +# AdditionalPropertiesWithDescriptionOnly + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **str** | | [optional] + +## Example + +```python +from petstore_api.models.additional_properties_with_description_only import AdditionalPropertiesWithDescriptionOnly + +# TODO update the JSON string below +json = "{}" +# create an instance of AdditionalPropertiesWithDescriptionOnly from a JSON string +additional_properties_with_description_only_instance = AdditionalPropertiesWithDescriptionOnly.from_json(json) +# print the JSON string representation of the object +print AdditionalPropertiesWithDescriptionOnly.to_json() + +# convert the object into a dict +additional_properties_with_description_only_dict = additional_properties_with_description_only_instance.to_dict() +# create an instance of AdditionalPropertiesWithDescriptionOnly from a dict +additional_properties_with_description_only_form_dict = additional_properties_with_description_only.from_dict(additional_properties_with_description_only_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/__init__.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/__init__.py index 65b7d10c97bd..477c4bf24437 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/__init__.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/__init__.py @@ -38,7 +38,10 @@ from petstore_api.signing import HttpSigningConfiguration # import models into sdk package +from petstore_api.models.additional_properties_any_type import AdditionalPropertiesAnyType from petstore_api.models.additional_properties_class import AdditionalPropertiesClass +from petstore_api.models.additional_properties_object import AdditionalPropertiesObject +from petstore_api.models.additional_properties_with_description_only import AdditionalPropertiesWithDescriptionOnly from petstore_api.models.all_of_with_single_ref import AllOfWithSingleRef from petstore_api.models.animal import Animal from petstore_api.models.any_of_color import AnyOfColor diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/__init__.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/__init__.py index 144361528d08..3f90e0e18fd7 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/__init__.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/__init__.py @@ -14,7 +14,10 @@ # import models into model package +from petstore_api.models.additional_properties_any_type import AdditionalPropertiesAnyType from petstore_api.models.additional_properties_class import AdditionalPropertiesClass +from petstore_api.models.additional_properties_object import AdditionalPropertiesObject +from petstore_api.models.additional_properties_with_description_only import AdditionalPropertiesWithDescriptionOnly from petstore_api.models.all_of_with_single_ref import AllOfWithSingleRef from petstore_api.models.animal import Animal from petstore_api.models.any_of_color import AnyOfColor diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_any_type.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_any_type.py new file mode 100644 index 000000000000..025b73438c80 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_any_type.py @@ -0,0 +1,83 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Optional +from pydantic import BaseModel, StrictStr + +class AdditionalPropertiesAnyType(BaseModel): + """ + AdditionalPropertiesAnyType + """ + name: Optional[StrictStr] = None + additional_properties: Dict[str, Any] = {} + __properties = ["name"] + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> AdditionalPropertiesAnyType: + """Create an instance of AdditionalPropertiesAnyType from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + "additional_properties" + }, + exclude_none=True) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> AdditionalPropertiesAnyType: + """Create an instance of AdditionalPropertiesAnyType from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return AdditionalPropertiesAnyType.parse_obj(obj) + + _obj = AdditionalPropertiesAnyType.parse_obj({ + "name": obj.get("name") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_object.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_object.py new file mode 100644 index 000000000000..f554b782f706 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_object.py @@ -0,0 +1,83 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Optional +from pydantic import BaseModel, StrictStr + +class AdditionalPropertiesObject(BaseModel): + """ + AdditionalPropertiesObject + """ + name: Optional[StrictStr] = None + additional_properties: Dict[str, Any] = {} + __properties = ["name"] + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> AdditionalPropertiesObject: + """Create an instance of AdditionalPropertiesObject from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + "additional_properties" + }, + exclude_none=True) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> AdditionalPropertiesObject: + """Create an instance of AdditionalPropertiesObject from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return AdditionalPropertiesObject.parse_obj(obj) + + _obj = AdditionalPropertiesObject.parse_obj({ + "name": obj.get("name") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_with_description_only.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_with_description_only.py new file mode 100644 index 000000000000..a21bb9571f6c --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_with_description_only.py @@ -0,0 +1,83 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Optional +from pydantic import BaseModel, StrictStr + +class AdditionalPropertiesWithDescriptionOnly(BaseModel): + """ + AdditionalPropertiesWithDescriptionOnly + """ + name: Optional[StrictStr] = None + additional_properties: Dict[str, Any] = {} + __properties = ["name"] + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> AdditionalPropertiesWithDescriptionOnly: + """Create an instance of AdditionalPropertiesWithDescriptionOnly from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + "additional_properties" + }, + exclude_none=True) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> AdditionalPropertiesWithDescriptionOnly: + """Create an instance of AdditionalPropertiesWithDescriptionOnly from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return AdditionalPropertiesWithDescriptionOnly.parse_obj(obj) + + _obj = AdditionalPropertiesWithDescriptionOnly.parse_obj({ + "name": obj.get("name") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/nullable_class.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/nullable_class.py index d1ca0e060c19..42a110d479ea 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/nullable_class.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/nullable_class.py @@ -38,6 +38,7 @@ class NullableClass(BaseModel): object_nullable_prop: Optional[Dict[str, Dict[str, Any]]] = None object_and_items_nullable_prop: Optional[Dict[str, Dict[str, Any]]] = None object_items_nullable: Optional[Dict[str, Dict[str, Any]]] = None + additional_properties: Dict[str, Any] = {} __properties = ["required_integer_prop", "integer_prop", "number_prop", "boolean_prop", "string_prop", "date_prop", "datetime_prop", "array_nullable_prop", "array_and_items_nullable_prop", "array_items_nullable", "object_nullable_prop", "object_and_items_nullable_prop", "object_items_nullable"] class Config: @@ -62,8 +63,14 @@ def to_dict(self): """Returns the dictionary representation of the model using alias""" _dict = self.dict(by_alias=True, exclude={ + "additional_properties" }, exclude_none=True) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + # set to None if required_integer_prop (nullable) is None # and __fields_set__ contains the field if self.required_integer_prop is None and "required_integer_prop" in self.__fields_set__: @@ -145,6 +152,11 @@ def from_dict(cls, obj: dict) -> NullableClass: "object_and_items_nullable_prop": obj.get("object_and_items_nullable_prop"), "object_items_nullable": obj.get("object_items_nullable") }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/test/test_additional_properties_any_type.py b/samples/openapi3/client/petstore/python-aiohttp/test/test_additional_properties_any_type.py new file mode 100644 index 000000000000..c2c9c7c58069 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/test/test_additional_properties_any_type.py @@ -0,0 +1,54 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" + + +import unittest +import datetime + +import petstore_api +from petstore_api.models.additional_properties_any_type import AdditionalPropertiesAnyType # noqa: E501 +from petstore_api.rest import ApiException + +class TestAdditionalPropertiesAnyType(unittest.TestCase): + """AdditionalPropertiesAnyType unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional): + """Test AdditionalPropertiesAnyType + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `AdditionalPropertiesAnyType` + """ + model = petstore_api.models.additional_properties_any_type.AdditionalPropertiesAnyType() # noqa: E501 + if include_optional : + return AdditionalPropertiesAnyType( + name = '' + ) + else : + return AdditionalPropertiesAnyType( + ) + """ + + def testAdditionalPropertiesAnyType(self): + """Test AdditionalPropertiesAnyType""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-aiohttp/test/test_additional_properties_class.py b/samples/openapi3/client/petstore/python-aiohttp/test/test_additional_properties_class.py index 77df2fe73c5c..e3b48bedd571 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/test/test_additional_properties_class.py +++ b/samples/openapi3/client/petstore/python-aiohttp/test/test_additional_properties_class.py @@ -6,11 +6,11 @@ This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" -from __future__ import absolute_import import unittest import datetime @@ -33,7 +33,9 @@ def make_instance(self, include_optional): include_option is a boolean, when False only required params are included, when True both required and optional params are included """ - # model = petstore_api.models.additional_properties_class.AdditionalPropertiesClass() # noqa: E501 + # uncomment below to create an instance of `AdditionalPropertiesClass` + """ + model = petstore_api.models.additional_properties_class.AdditionalPropertiesClass() # noqa: E501 if include_optional : return AdditionalPropertiesClass( map_property = { @@ -48,6 +50,7 @@ def make_instance(self, include_optional): else : return AdditionalPropertiesClass( ) + """ def testAdditionalPropertiesClass(self): """Test AdditionalPropertiesClass""" diff --git a/samples/openapi3/client/petstore/python-aiohttp/test/test_additional_properties_object.py b/samples/openapi3/client/petstore/python-aiohttp/test/test_additional_properties_object.py new file mode 100644 index 000000000000..b68a8fda5790 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/test/test_additional_properties_object.py @@ -0,0 +1,54 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" + + +import unittest +import datetime + +import petstore_api +from petstore_api.models.additional_properties_object import AdditionalPropertiesObject # noqa: E501 +from petstore_api.rest import ApiException + +class TestAdditionalPropertiesObject(unittest.TestCase): + """AdditionalPropertiesObject unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional): + """Test AdditionalPropertiesObject + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `AdditionalPropertiesObject` + """ + model = petstore_api.models.additional_properties_object.AdditionalPropertiesObject() # noqa: E501 + if include_optional : + return AdditionalPropertiesObject( + name = '' + ) + else : + return AdditionalPropertiesObject( + ) + """ + + def testAdditionalPropertiesObject(self): + """Test AdditionalPropertiesObject""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-aiohttp/test/test_additional_properties_with_description_only.py b/samples/openapi3/client/petstore/python-aiohttp/test/test_additional_properties_with_description_only.py new file mode 100644 index 000000000000..d5166dfe1342 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/test/test_additional_properties_with_description_only.py @@ -0,0 +1,54 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" + + +import unittest +import datetime + +import petstore_api +from petstore_api.models.additional_properties_with_description_only import AdditionalPropertiesWithDescriptionOnly # noqa: E501 +from petstore_api.rest import ApiException + +class TestAdditionalPropertiesWithDescriptionOnly(unittest.TestCase): + """AdditionalPropertiesWithDescriptionOnly unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional): + """Test AdditionalPropertiesWithDescriptionOnly + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `AdditionalPropertiesWithDescriptionOnly` + """ + model = petstore_api.models.additional_properties_with_description_only.AdditionalPropertiesWithDescriptionOnly() # noqa: E501 + if include_optional : + return AdditionalPropertiesWithDescriptionOnly( + name = '' + ) + else : + return AdditionalPropertiesWithDescriptionOnly( + ) + """ + + def testAdditionalPropertiesWithDescriptionOnly(self): + """Test AdditionalPropertiesWithDescriptionOnly""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/.openapi-generator/FILES b/samples/openapi3/client/petstore/python/.openapi-generator/FILES index 370c0480ea25..fdd09778983b 100755 --- a/samples/openapi3/client/petstore/python/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python/.openapi-generator/FILES @@ -3,7 +3,10 @@ .gitlab-ci.yml .travis.yml README.md +docs/AdditionalPropertiesAnyType.md docs/AdditionalPropertiesClass.md +docs/AdditionalPropertiesObject.md +docs/AdditionalPropertiesWithDescriptionOnly.md docs/AllOfWithSingleRef.md docs/Animal.md docs/AnotherFakeApi.md @@ -100,7 +103,10 @@ petstore_api/api_response.py petstore_api/configuration.py petstore_api/exceptions.py petstore_api/models/__init__.py +petstore_api/models/additional_properties_any_type.py petstore_api/models/additional_properties_class.py +petstore_api/models/additional_properties_object.py +petstore_api/models/additional_properties_with_description_only.py petstore_api/models/all_of_with_single_ref.py petstore_api/models/animal.py petstore_api/models/any_of_color.py diff --git a/samples/openapi3/client/petstore/python/README.md b/samples/openapi3/client/petstore/python/README.md index 534b6c8135aa..e99d03b1d80a 100755 --- a/samples/openapi3/client/petstore/python/README.md +++ b/samples/openapi3/client/petstore/python/README.md @@ -132,7 +132,10 @@ Class | Method | HTTP request | Description ## Documentation For Models + - [AdditionalPropertiesAnyType](docs/AdditionalPropertiesAnyType.md) - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) + - [AdditionalPropertiesObject](docs/AdditionalPropertiesObject.md) + - [AdditionalPropertiesWithDescriptionOnly](docs/AdditionalPropertiesWithDescriptionOnly.md) - [AllOfWithSingleRef](docs/AllOfWithSingleRef.md) - [Animal](docs/Animal.md) - [AnyOfColor](docs/AnyOfColor.md) diff --git a/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesAnyType.md b/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesAnyType.md new file mode 100644 index 000000000000..beedef76c051 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesAnyType.md @@ -0,0 +1,28 @@ +# AdditionalPropertiesAnyType + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **str** | | [optional] + +## Example + +```python +from petstore_api.models.additional_properties_any_type import AdditionalPropertiesAnyType + +# TODO update the JSON string below +json = "{}" +# create an instance of AdditionalPropertiesAnyType from a JSON string +additional_properties_any_type_instance = AdditionalPropertiesAnyType.from_json(json) +# print the JSON string representation of the object +print AdditionalPropertiesAnyType.to_json() + +# convert the object into a dict +additional_properties_any_type_dict = additional_properties_any_type_instance.to_dict() +# create an instance of AdditionalPropertiesAnyType from a dict +additional_properties_any_type_form_dict = additional_properties_any_type.from_dict(additional_properties_any_type_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesClass.md b/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesClass.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesObject.md b/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesObject.md new file mode 100644 index 000000000000..8b9259c687f6 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesObject.md @@ -0,0 +1,28 @@ +# AdditionalPropertiesObject + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **str** | | [optional] + +## Example + +```python +from petstore_api.models.additional_properties_object import AdditionalPropertiesObject + +# TODO update the JSON string below +json = "{}" +# create an instance of AdditionalPropertiesObject from a JSON string +additional_properties_object_instance = AdditionalPropertiesObject.from_json(json) +# print the JSON string representation of the object +print AdditionalPropertiesObject.to_json() + +# convert the object into a dict +additional_properties_object_dict = additional_properties_object_instance.to_dict() +# create an instance of AdditionalPropertiesObject from a dict +additional_properties_object_form_dict = additional_properties_object.from_dict(additional_properties_object_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesWithDescriptionOnly.md b/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesWithDescriptionOnly.md new file mode 100644 index 000000000000..d66094f18e57 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesWithDescriptionOnly.md @@ -0,0 +1,28 @@ +# AdditionalPropertiesWithDescriptionOnly + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **str** | | [optional] + +## Example + +```python +from petstore_api.models.additional_properties_with_description_only import AdditionalPropertiesWithDescriptionOnly + +# TODO update the JSON string below +json = "{}" +# create an instance of AdditionalPropertiesWithDescriptionOnly from a JSON string +additional_properties_with_description_only_instance = AdditionalPropertiesWithDescriptionOnly.from_json(json) +# print the JSON string representation of the object +print AdditionalPropertiesWithDescriptionOnly.to_json() + +# convert the object into a dict +additional_properties_with_description_only_dict = additional_properties_with_description_only_instance.to_dict() +# create an instance of AdditionalPropertiesWithDescriptionOnly from a dict +additional_properties_with_description_only_form_dict = additional_properties_with_description_only.from_dict(additional_properties_with_description_only_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python/docs/Animal.md b/samples/openapi3/client/petstore/python/docs/Animal.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/AnotherFakeApi.md b/samples/openapi3/client/petstore/python/docs/AnotherFakeApi.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/ApiResponse.md b/samples/openapi3/client/petstore/python/docs/ApiResponse.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/ArrayOfArrayOfNumberOnly.md b/samples/openapi3/client/petstore/python/docs/ArrayOfArrayOfNumberOnly.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/ArrayOfNumberOnly.md b/samples/openapi3/client/petstore/python/docs/ArrayOfNumberOnly.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/ArrayTest.md b/samples/openapi3/client/petstore/python/docs/ArrayTest.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/Capitalization.md b/samples/openapi3/client/petstore/python/docs/Capitalization.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/Cat.md b/samples/openapi3/client/petstore/python/docs/Cat.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/Category.md b/samples/openapi3/client/petstore/python/docs/Category.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/ClassModel.md b/samples/openapi3/client/petstore/python/docs/ClassModel.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/Client.md b/samples/openapi3/client/petstore/python/docs/Client.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/DefaultApi.md b/samples/openapi3/client/petstore/python/docs/DefaultApi.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/Dog.md b/samples/openapi3/client/petstore/python/docs/Dog.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/EnumArrays.md b/samples/openapi3/client/petstore/python/docs/EnumArrays.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/EnumClass.md b/samples/openapi3/client/petstore/python/docs/EnumClass.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/EnumTest.md b/samples/openapi3/client/petstore/python/docs/EnumTest.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/FakeApi.md b/samples/openapi3/client/petstore/python/docs/FakeApi.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/FakeClassnameTags123Api.md b/samples/openapi3/client/petstore/python/docs/FakeClassnameTags123Api.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/File.md b/samples/openapi3/client/petstore/python/docs/File.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/FileSchemaTestClass.md b/samples/openapi3/client/petstore/python/docs/FileSchemaTestClass.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/Foo.md b/samples/openapi3/client/petstore/python/docs/Foo.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/FormatTest.md b/samples/openapi3/client/petstore/python/docs/FormatTest.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/HasOnlyReadOnly.md b/samples/openapi3/client/petstore/python/docs/HasOnlyReadOnly.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/HealthCheckResult.md b/samples/openapi3/client/petstore/python/docs/HealthCheckResult.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/InlineObject.md b/samples/openapi3/client/petstore/python/docs/InlineObject.md deleted file mode 100755 index f567ea188ce0..000000000000 --- a/samples/openapi3/client/petstore/python/docs/InlineObject.md +++ /dev/null @@ -1,11 +0,0 @@ -# InlineObject - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**name** | **str** | Updated name of the pet | [optional] -**status** | **str** | Updated status of the pet | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/samples/openapi3/client/petstore/python/docs/InlineObject1.md b/samples/openapi3/client/petstore/python/docs/InlineObject1.md deleted file mode 100755 index 42d38efa3013..000000000000 --- a/samples/openapi3/client/petstore/python/docs/InlineObject1.md +++ /dev/null @@ -1,11 +0,0 @@ -# InlineObject1 - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**additional_metadata** | **str** | Additional data to pass to server | [optional] -**file** | **file** | file to upload | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/samples/openapi3/client/petstore/python/docs/InlineObject2.md b/samples/openapi3/client/petstore/python/docs/InlineObject2.md deleted file mode 100755 index 9bfba12f6f15..000000000000 --- a/samples/openapi3/client/petstore/python/docs/InlineObject2.md +++ /dev/null @@ -1,11 +0,0 @@ -# InlineObject2 - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**enum_form_string_array** | **list[str]** | Form parameter enum test (string array) | [optional] -**enum_form_string** | **str** | Form parameter enum test (string) | [optional] [default to '-efg'] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/samples/openapi3/client/petstore/python/docs/InlineObject3.md b/samples/openapi3/client/petstore/python/docs/InlineObject3.md deleted file mode 100755 index ef9845fcd9c6..000000000000 --- a/samples/openapi3/client/petstore/python/docs/InlineObject3.md +++ /dev/null @@ -1,23 +0,0 @@ -# InlineObject3 - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**integer** | **int** | None | [optional] -**int32** | **int** | None | [optional] -**int64** | **int** | None | [optional] -**number** | **float** | None | -**float** | **float** | None | [optional] -**double** | **float** | None | -**string** | **str** | None | [optional] -**pattern_without_delimiter** | **str** | None | -**byte** | **str** | None | -**binary** | **file** | None | [optional] -**date** | **date** | None | [optional] -**date_time** | **datetime** | None | [optional] -**password** | **str** | None | [optional] -**callback** | **str** | None | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/samples/openapi3/client/petstore/python/docs/InlineObject4.md b/samples/openapi3/client/petstore/python/docs/InlineObject4.md deleted file mode 100755 index 07574d0d0769..000000000000 --- a/samples/openapi3/client/petstore/python/docs/InlineObject4.md +++ /dev/null @@ -1,11 +0,0 @@ -# InlineObject4 - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**param** | **str** | field1 | -**param2** | **str** | field2 | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/samples/openapi3/client/petstore/python/docs/InlineObject5.md b/samples/openapi3/client/petstore/python/docs/InlineObject5.md deleted file mode 100755 index c4502f70f9c8..000000000000 --- a/samples/openapi3/client/petstore/python/docs/InlineObject5.md +++ /dev/null @@ -1,11 +0,0 @@ -# InlineObject5 - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**additional_metadata** | **str** | Additional data to pass to server | [optional] -**required_file** | **file** | file to upload | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/samples/openapi3/client/petstore/python/docs/InlineResponseDefault.md b/samples/openapi3/client/petstore/python/docs/InlineResponseDefault.md deleted file mode 100755 index f0a52bc4639c..000000000000 --- a/samples/openapi3/client/petstore/python/docs/InlineResponseDefault.md +++ /dev/null @@ -1,11 +0,0 @@ -# InlineResponseDefault - - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**string** | [**Foo**](Foo.md) | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/samples/openapi3/client/petstore/python/docs/List.md b/samples/openapi3/client/petstore/python/docs/List.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/MapTest.md b/samples/openapi3/client/petstore/python/docs/MapTest.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/openapi3/client/petstore/python/docs/MixedPropertiesAndAdditionalPropertiesClass.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/Model200Response.md b/samples/openapi3/client/petstore/python/docs/Model200Response.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/ModelReturn.md b/samples/openapi3/client/petstore/python/docs/ModelReturn.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/Model_200Response.md b/samples/openapi3/client/petstore/python/docs/Model_200Response.md deleted file mode 100644 index 4fd119d12515..000000000000 --- a/samples/openapi3/client/petstore/python/docs/Model_200Response.md +++ /dev/null @@ -1,13 +0,0 @@ -# Model_200Response - -Model for testing model name starting with number - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**name** | **int** | | [optional] -**_class** | **str** | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/samples/openapi3/client/petstore/python/docs/Model_Return.md b/samples/openapi3/client/petstore/python/docs/Model_Return.md deleted file mode 100644 index 674c441551b3..000000000000 --- a/samples/openapi3/client/petstore/python/docs/Model_Return.md +++ /dev/null @@ -1,12 +0,0 @@ -# Model_Return - -Model for testing reserved words - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**_return** | **int** | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/samples/openapi3/client/petstore/python/docs/Name.md b/samples/openapi3/client/petstore/python/docs/Name.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/NestedOneOf.md b/samples/openapi3/client/petstore/python/docs/NestedOneOf.md deleted file mode 100644 index 913192432e77..000000000000 --- a/samples/openapi3/client/petstore/python/docs/NestedOneOf.md +++ /dev/null @@ -1,12 +0,0 @@ -# NestedOneOf - - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**size** | **int** | | [optional] -**nested_pig** | [**Pig**](Pig.md) | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/samples/openapi3/client/petstore/python/docs/NullableClass.md b/samples/openapi3/client/petstore/python/docs/NullableClass.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/NumberOnly.md b/samples/openapi3/client/petstore/python/docs/NumberOnly.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/Order.md b/samples/openapi3/client/petstore/python/docs/Order.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/OuterComposite.md b/samples/openapi3/client/petstore/python/docs/OuterComposite.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/OuterEnum.md b/samples/openapi3/client/petstore/python/docs/OuterEnum.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/OuterEnumDefaultValue.md b/samples/openapi3/client/petstore/python/docs/OuterEnumDefaultValue.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/OuterEnumInteger.md b/samples/openapi3/client/petstore/python/docs/OuterEnumInteger.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/OuterEnumIntegerDefaultValue.md b/samples/openapi3/client/petstore/python/docs/OuterEnumIntegerDefaultValue.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/Pet.md b/samples/openapi3/client/petstore/python/docs/Pet.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/PetApi.md b/samples/openapi3/client/petstore/python/docs/PetApi.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/ReadOnlyFirst.md b/samples/openapi3/client/petstore/python/docs/ReadOnlyFirst.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/SpecialModelName.md b/samples/openapi3/client/petstore/python/docs/SpecialModelName.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/StoreApi.md b/samples/openapi3/client/petstore/python/docs/StoreApi.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/Tag.md b/samples/openapi3/client/petstore/python/docs/Tag.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/User.md b/samples/openapi3/client/petstore/python/docs/User.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/docs/UserApi.md b/samples/openapi3/client/petstore/python/docs/UserApi.md old mode 100755 new mode 100644 diff --git a/samples/openapi3/client/petstore/python/petstore_api/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/__init__.py index 65b7d10c97bd..477c4bf24437 100755 --- a/samples/openapi3/client/petstore/python/petstore_api/__init__.py +++ b/samples/openapi3/client/petstore/python/petstore_api/__init__.py @@ -38,7 +38,10 @@ from petstore_api.signing import HttpSigningConfiguration # import models into sdk package +from petstore_api.models.additional_properties_any_type import AdditionalPropertiesAnyType from petstore_api.models.additional_properties_class import AdditionalPropertiesClass +from petstore_api.models.additional_properties_object import AdditionalPropertiesObject +from petstore_api.models.additional_properties_with_description_only import AdditionalPropertiesWithDescriptionOnly from petstore_api.models.all_of_with_single_ref import AllOfWithSingleRef from petstore_api.models.animal import Animal from petstore_api.models.any_of_color import AnyOfColor diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py index 144361528d08..3f90e0e18fd7 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py @@ -14,7 +14,10 @@ # import models into model package +from petstore_api.models.additional_properties_any_type import AdditionalPropertiesAnyType from petstore_api.models.additional_properties_class import AdditionalPropertiesClass +from petstore_api.models.additional_properties_object import AdditionalPropertiesObject +from petstore_api.models.additional_properties_with_description_only import AdditionalPropertiesWithDescriptionOnly from petstore_api.models.all_of_with_single_ref import AllOfWithSingleRef from petstore_api.models.animal import Animal from petstore_api.models.any_of_color import AnyOfColor diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_any_type.py b/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_any_type.py new file mode 100644 index 000000000000..3b6407e160d5 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_any_type.py @@ -0,0 +1,83 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, Dict, Optional +from pydantic import BaseModel, StrictStr + +class AdditionalPropertiesAnyType(BaseModel): + """ + AdditionalPropertiesAnyType + """ + name: Optional[StrictStr] = None + additional_properties: Dict[str, Any] = {} + __properties = ["name"] + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> AdditionalPropertiesAnyType: + """Create an instance of AdditionalPropertiesAnyType from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + "additional_properties" + }, + exclude_none=True) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> AdditionalPropertiesAnyType: + """Create an instance of AdditionalPropertiesAnyType from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return AdditionalPropertiesAnyType.parse_obj(obj) + + _obj = AdditionalPropertiesAnyType.parse_obj({ + "name": obj.get("name") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_object.py b/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_object.py new file mode 100644 index 000000000000..dc372c7d86be --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_object.py @@ -0,0 +1,83 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, Dict, Optional +from pydantic import BaseModel, StrictStr + +class AdditionalPropertiesObject(BaseModel): + """ + AdditionalPropertiesObject + """ + name: Optional[StrictStr] = None + additional_properties: Dict[str, Any] = {} + __properties = ["name"] + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> AdditionalPropertiesObject: + """Create an instance of AdditionalPropertiesObject from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + "additional_properties" + }, + exclude_none=True) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> AdditionalPropertiesObject: + """Create an instance of AdditionalPropertiesObject from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return AdditionalPropertiesObject.parse_obj(obj) + + _obj = AdditionalPropertiesObject.parse_obj({ + "name": obj.get("name") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_with_description_only.py b/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_with_description_only.py new file mode 100644 index 000000000000..eb9ac44cae8b --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_with_description_only.py @@ -0,0 +1,83 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, Dict, Optional +from pydantic import BaseModel, StrictStr + +class AdditionalPropertiesWithDescriptionOnly(BaseModel): + """ + AdditionalPropertiesWithDescriptionOnly + """ + name: Optional[StrictStr] = None + additional_properties: Dict[str, Any] = {} + __properties = ["name"] + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> AdditionalPropertiesWithDescriptionOnly: + """Create an instance of AdditionalPropertiesWithDescriptionOnly from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + "additional_properties" + }, + exclude_none=True) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> AdditionalPropertiesWithDescriptionOnly: + """Create an instance of AdditionalPropertiesWithDescriptionOnly from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return AdditionalPropertiesWithDescriptionOnly.parse_obj(obj) + + _obj = AdditionalPropertiesWithDescriptionOnly.parse_obj({ + "name": obj.get("name") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/nullable_class.py b/samples/openapi3/client/petstore/python/petstore_api/models/nullable_class.py index cfd086598f34..01343f9d82a6 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/nullable_class.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/nullable_class.py @@ -38,6 +38,7 @@ class NullableClass(BaseModel): object_nullable_prop: Optional[Dict[str, Dict[str, Any]]] = None object_and_items_nullable_prop: Optional[Dict[str, Dict[str, Any]]] = None object_items_nullable: Optional[Dict[str, Dict[str, Any]]] = None + additional_properties: Dict[str, Any] = {} __properties = ["required_integer_prop", "integer_prop", "number_prop", "boolean_prop", "string_prop", "date_prop", "datetime_prop", "array_nullable_prop", "array_and_items_nullable_prop", "array_items_nullable", "object_nullable_prop", "object_and_items_nullable_prop", "object_items_nullable"] class Config: @@ -62,8 +63,14 @@ def to_dict(self): """Returns the dictionary representation of the model using alias""" _dict = self.dict(by_alias=True, exclude={ + "additional_properties" }, exclude_none=True) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + # set to None if required_integer_prop (nullable) is None # and __fields_set__ contains the field if self.required_integer_prop is None and "required_integer_prop" in self.__fields_set__: @@ -145,6 +152,11 @@ def from_dict(cls, obj: dict) -> NullableClass: "object_and_items_nullable_prop": obj.get("object_and_items_nullable_prop"), "object_items_nullable": obj.get("object_items_nullable") }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + return _obj diff --git a/samples/openapi3/client/petstore/python/test/test_additional_properties_any_type.py b/samples/openapi3/client/petstore/python/test/test_additional_properties_any_type.py new file mode 100644 index 000000000000..c2c9c7c58069 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_additional_properties_any_type.py @@ -0,0 +1,54 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" + + +import unittest +import datetime + +import petstore_api +from petstore_api.models.additional_properties_any_type import AdditionalPropertiesAnyType # noqa: E501 +from petstore_api.rest import ApiException + +class TestAdditionalPropertiesAnyType(unittest.TestCase): + """AdditionalPropertiesAnyType unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional): + """Test AdditionalPropertiesAnyType + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `AdditionalPropertiesAnyType` + """ + model = petstore_api.models.additional_properties_any_type.AdditionalPropertiesAnyType() # noqa: E501 + if include_optional : + return AdditionalPropertiesAnyType( + name = '' + ) + else : + return AdditionalPropertiesAnyType( + ) + """ + + def testAdditionalPropertiesAnyType(self): + """Test AdditionalPropertiesAnyType""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_additional_properties_class.py b/samples/openapi3/client/petstore/python/test/test_additional_properties_class.py index 4383ae1726b8..e3b48bedd571 100644 --- a/samples/openapi3/client/petstore/python/test/test_additional_properties_class.py +++ b/samples/openapi3/client/petstore/python/test/test_additional_properties_class.py @@ -6,11 +6,11 @@ This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" -from __future__ import absolute_import import unittest import datetime @@ -33,7 +33,9 @@ def make_instance(self, include_optional): include_option is a boolean, when False only required params are included, when True both required and optional params are included """ - # model = petstore_api.models.additional_properties_class.AdditionalPropertiesClass() # noqa: E501 + # uncomment below to create an instance of `AdditionalPropertiesClass` + """ + model = petstore_api.models.additional_properties_class.AdditionalPropertiesClass() # noqa: E501 if include_optional : return AdditionalPropertiesClass( map_property = { @@ -48,11 +50,12 @@ def make_instance(self, include_optional): else : return AdditionalPropertiesClass( ) + """ def testAdditionalPropertiesClass(self): """Test AdditionalPropertiesClass""" - inst_req_only = self.make_instance(include_optional=False) - inst_req_and_optional = self.make_instance(include_optional=True) + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) if __name__ == '__main__': unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_additional_properties_object.py b/samples/openapi3/client/petstore/python/test/test_additional_properties_object.py new file mode 100644 index 000000000000..b68a8fda5790 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_additional_properties_object.py @@ -0,0 +1,54 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" + + +import unittest +import datetime + +import petstore_api +from petstore_api.models.additional_properties_object import AdditionalPropertiesObject # noqa: E501 +from petstore_api.rest import ApiException + +class TestAdditionalPropertiesObject(unittest.TestCase): + """AdditionalPropertiesObject unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional): + """Test AdditionalPropertiesObject + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `AdditionalPropertiesObject` + """ + model = petstore_api.models.additional_properties_object.AdditionalPropertiesObject() # noqa: E501 + if include_optional : + return AdditionalPropertiesObject( + name = '' + ) + else : + return AdditionalPropertiesObject( + ) + """ + + def testAdditionalPropertiesObject(self): + """Test AdditionalPropertiesObject""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_additional_properties_with_description_only.py b/samples/openapi3/client/petstore/python/test/test_additional_properties_with_description_only.py new file mode 100644 index 000000000000..d5166dfe1342 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_additional_properties_with_description_only.py @@ -0,0 +1,54 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" + + +import unittest +import datetime + +import petstore_api +from petstore_api.models.additional_properties_with_description_only import AdditionalPropertiesWithDescriptionOnly # noqa: E501 +from petstore_api.rest import ApiException + +class TestAdditionalPropertiesWithDescriptionOnly(unittest.TestCase): + """AdditionalPropertiesWithDescriptionOnly unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional): + """Test AdditionalPropertiesWithDescriptionOnly + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `AdditionalPropertiesWithDescriptionOnly` + """ + model = petstore_api.models.additional_properties_with_description_only.AdditionalPropertiesWithDescriptionOnly() # noqa: E501 + if include_optional : + return AdditionalPropertiesWithDescriptionOnly( + name = '' + ) + else : + return AdditionalPropertiesWithDescriptionOnly( + ) + """ + + def testAdditionalPropertiesWithDescriptionOnly(self): + """Test AdditionalPropertiesWithDescriptionOnly""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests/test_model.py b/samples/openapi3/client/petstore/python/tests/test_model.py index 7032ed8893e2..01d5d001fab8 100644 --- a/samples/openapi3/client/petstore/python/tests/test_model.py +++ b/samples/openapi3/client/petstore/python/tests/test_model.py @@ -519,4 +519,18 @@ def test_allof(self): # shouldn't throw NameError self.assertEqual(model.to_json(), '{"skill": "none", "type": "tiger", "info": {"name": "creature info"}}') - + def test_additional_properties(self): + a1 = petstore_api.AdditionalPropertiesAnyType() + a1.additional_properties = { "abc": 123 } + self.assertEqual(a1.to_dict(), {"abc": 123}) + self.assertEqual(a1.to_json(), "{\"abc\": 123}") + + a2 = petstore_api.AdditionalPropertiesObject() + a2.additional_properties = { "efg": 45.6 } + self.assertEqual(a2.to_dict(), {"efg": 45.6}) + self.assertEqual(a2.to_json(), "{\"efg\": 45.6}") + + a3 = petstore_api.AdditionalPropertiesWithDescriptionOnly() + a3.additional_properties = { "xyz": 45.6 } + self.assertEqual(a3.to_dict(), {"xyz": 45.6}) + self.assertEqual(a3.to_json(), "{\"xyz\": 45.6}") From d1f23ef6633a6dd8164cf98629c63fae235bb0a1 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Sat, 5 Aug 2023 13:34:34 +0800 Subject: [PATCH 011/292] add mapping features to crystal client generator (#16253) --- bin/configs/crystal.yaml | 9 + .../languages/CrystalClientCodegen.java | 20 ++ .../test/resources/3_0/crystal/petstore.yaml | 51 +++++ .../petstore/crystal/.openapi-generator/FILES | 2 + .../crystal/spec/api/fake_api_spec.cr | 41 ++++ .../another_property_name_mapping_spec.cr | 50 +++++ .../crystal/src/petstore/api/fake_api.cr | 104 ++++++++++ .../models/another_property_name_mapping.cr | 193 ++++++++++++++++++ 8 files changed, 470 insertions(+) create mode 100644 samples/client/petstore/crystal/spec/api/fake_api_spec.cr create mode 100644 samples/client/petstore/crystal/spec/models/another_property_name_mapping_spec.cr create mode 100644 samples/client/petstore/crystal/src/petstore/api/fake_api.cr create mode 100644 samples/client/petstore/crystal/src/petstore/models/another_property_name_mapping.cr diff --git a/bin/configs/crystal.yaml b/bin/configs/crystal.yaml index c578838173ac..db88d8bfd9b5 100644 --- a/bin/configs/crystal.yaml +++ b/bin/configs/crystal.yaml @@ -7,3 +7,12 @@ additionalProperties: moduleName: Petstore shardName: petstore strictSpecBehavior: false +modelNameMappings: + PropertyNameMapping: AnotherPropertyNameMapping +nameMappings: + _type: underscore_type + type_: type_with_underscore + type-: type_with_dash +parameterNameMappings: + _type: underscore_type + type_: type_with_underscore diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CrystalClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CrystalClientCodegen.java index 5afccae337b8..818d14939a4f 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CrystalClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CrystalClientCodegen.java @@ -368,6 +368,11 @@ public String toModelImport(String name) { @Override public String toModelName(final String name) { + // obtain the name from modelNameMapping directly if provided + if (modelNameMapping.containsKey(name)) { + return modelNameMapping.get(name); + } + String modelName; modelName = sanitizeModelName(name); @@ -409,6 +414,11 @@ public String sanitizeModelName(String modelName) { @Override public String toModelFilename(String name) { + // obtain the name from modelNameMapping directly if provided + if (modelNameMapping.containsKey(name)) { + return underscore(modelNameMapping.get(name)); + } + return underscore(toModelName(name)); } @@ -867,6 +877,11 @@ public String toEnumDefaultValue(String value, String datatype) { @Override public String toVarName(final String name) { + // obtain the name from nameMapping directly if provided + if (nameMapping.containsKey(name)) { + return nameMapping.get(name); + } + String varName; // sanitize name varName = sanitizeName(name); @@ -894,6 +909,11 @@ public String toRegularExpression(String pattern) { @Override public String toParamName(String name) { + // obtain the name from parameterNameMapping directly if provided + if (parameterNameMapping.containsKey(name)) { + return parameterNameMapping.get(name); + } + // should be the same as variable name return toVarName(name); } diff --git a/modules/openapi-generator/src/test/resources/3_0/crystal/petstore.yaml b/modules/openapi-generator/src/test/resources/3_0/crystal/petstore.yaml index 385b3e0e5e72..21cb43dc5fc1 100644 --- a/modules/openapi-generator/src/test/resources/3_0/crystal/petstore.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/crystal/petstore.yaml @@ -566,6 +566,47 @@ paths: description: User not found security: - api_key: [] + /fake/parameter-name-mapping: + get: + tags: + - fake + summary: parameter name mapping test + operationId: getParameterNameMapping + parameters: + - name: _type + in: header + description: _type + required: true + schema: + type: integer + format: int64 + - name: type + in: query + description: type + required: true + schema: + type: string + - name: type_ + in: header + description: type_ + required: true + schema: + type: string + - name: type- + in: header + description: type- + required: true + schema: + type: string + - name: http_debug_option + in: query + description: http debug option (to test parameter naming option) + required: true + schema: + type: string + responses: + 200: + description: OK externalDocs: description: Find out more about Swagger url: 'http://swagger.io' @@ -809,3 +850,13 @@ components: description: A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. type: string pattern: '/^image_\d{1,3}$/i' + PropertyNameMapping: + properties: + http_debug_operation: + type: string + _type: + type: string + type: + type: string + type_: + type: string diff --git a/samples/client/petstore/crystal/.openapi-generator/FILES b/samples/client/petstore/crystal/.openapi-generator/FILES index ab944b040a06..46d1bf5974e7 100644 --- a/samples/client/petstore/crystal/.openapi-generator/FILES +++ b/samples/client/petstore/crystal/.openapi-generator/FILES @@ -5,12 +5,14 @@ git_push.sh shard.yml spec/spec_helper.cr src/petstore.cr +src/petstore/api/fake_api.cr src/petstore/api/pet_api.cr src/petstore/api/store_api.cr src/petstore/api/user_api.cr src/petstore/api_client.cr src/petstore/api_error.cr src/petstore/configuration.cr +src/petstore/models/another_property_name_mapping.cr src/petstore/models/api_response.cr src/petstore/models/category.cr src/petstore/models/format_test.cr diff --git a/samples/client/petstore/crystal/spec/api/fake_api_spec.cr b/samples/client/petstore/crystal/spec/api/fake_api_spec.cr new file mode 100644 index 000000000000..b8b9922be4c4 --- /dev/null +++ b/samples/client/petstore/crystal/spec/api/fake_api_spec.cr @@ -0,0 +1,41 @@ +# #OpenAPI Petstore +# +##This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +# +#The version of the OpenAPI document: 1.0.0 +# +#Generated by: https://openapi-generator.tech +#OpenAPI Generator version: 7.0.0-SNAPSHOT +# + +require "../spec_helper" +require "json" +require "time" + +# Unit tests for Petstore::FakeApi +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe "FakeApi" do + describe "test an instance of FakeApi" do + it "should create an instance of FakeApi" do + api_instance = Petstore::FakeApi.new + # TODO expect(api_instance).to be_instance_of(Petstore::FakeApi) + end + end + + # unit tests for get_parameter_name_mapping + # parameter name mapping test + # @param _type _type + # @param _type2 type + # @param type_ type_ + # @param type_2 type- + # @param http_debug_option http debug option (to test parameter naming option) + # @param [Hash] opts the optional parameters + # @return [nil] + describe "get_parameter_name_mapping test" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + +end diff --git a/samples/client/petstore/crystal/spec/models/another_property_name_mapping_spec.cr b/samples/client/petstore/crystal/spec/models/another_property_name_mapping_spec.cr new file mode 100644 index 000000000000..c7491f69c04a --- /dev/null +++ b/samples/client/petstore/crystal/spec/models/another_property_name_mapping_spec.cr @@ -0,0 +1,50 @@ +# #OpenAPI Petstore +# +##This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +# +#The version of the OpenAPI document: 1.0.0 +# +#Generated by: https://openapi-generator.tech +#OpenAPI Generator version: 7.0.0-SNAPSHOT +# + +require "../spec_helper" +require "json" +require "time" + +# Unit tests for Petstore::AnotherPropertyNameMapping +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::AnotherPropertyNameMapping do + + describe "test an instance of AnotherPropertyNameMapping" do + it "should create an instance of AnotherPropertyNameMapping" do + #instance = Petstore::AnotherPropertyNameMapping.new + #expect(instance).to be_instance_of(Petstore::AnotherPropertyNameMapping) + end + end + describe "test attribute 'http_debug_operation'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'underscore_type'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute '_type'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'type_with_underscore'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + +end diff --git a/samples/client/petstore/crystal/src/petstore/api/fake_api.cr b/samples/client/petstore/crystal/src/petstore/api/fake_api.cr new file mode 100644 index 000000000000..c5703bcd2575 --- /dev/null +++ b/samples/client/petstore/crystal/src/petstore/api/fake_api.cr @@ -0,0 +1,104 @@ +# #OpenAPI Petstore +# +##This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +# +#The version of the OpenAPI document: 1.0.0 +# +#Generated by: https://openapi-generator.tech +#OpenAPI Generator version: 7.0.0-SNAPSHOT +# + +require "uri" + +module Petstore + class FakeApi + property api_client : ApiClient + + def initialize(api_client = ApiClient.default) + @api_client = api_client + end + # parameter name mapping test + # @param underscore_type [Int64] _type + # @param _type [String] type + # @param type_with_underscore [String] type_ + # @param type_with_dash [String] type- + # @param http_debug_option [String] http debug option (to test parameter naming option) + # @return [nil] + def get_parameter_name_mapping(underscore_type : Int64, _type : String, type_with_underscore : String, type_with_dash : String, http_debug_option : String) + get_parameter_name_mapping_with_http_info(underscore_type, _type, type_with_underscore, type_with_dash, http_debug_option) + nil + end + + # parameter name mapping test + # @param underscore_type [Int64] _type + # @param _type [String] type + # @param type_with_underscore [String] type_ + # @param type_with_dash [String] type- + # @param http_debug_option [String] http debug option (to test parameter naming option) + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def get_parameter_name_mapping_with_http_info(underscore_type : Int64, _type : String, type_with_underscore : String, type_with_dash : String, http_debug_option : String) + if @api_client.config.debugging + Log.debug {"Calling API: FakeApi.get_parameter_name_mapping ..."} + end + # verify the required parameter "underscore_type" is set + if @api_client.config.client_side_validation && underscore_type.nil? + raise ArgumentError.new("Missing the required parameter 'underscore_type' when calling FakeApi.get_parameter_name_mapping") + end + # verify the required parameter "_type" is set + if @api_client.config.client_side_validation && _type.nil? + raise ArgumentError.new("Missing the required parameter '_type' when calling FakeApi.get_parameter_name_mapping") + end + # verify the required parameter "type_with_underscore" is set + if @api_client.config.client_side_validation && type_with_underscore.nil? + raise ArgumentError.new("Missing the required parameter 'type_with_underscore' when calling FakeApi.get_parameter_name_mapping") + end + # verify the required parameter "type_with_dash" is set + if @api_client.config.client_side_validation && type_with_dash.nil? + raise ArgumentError.new("Missing the required parameter 'type_with_dash' when calling FakeApi.get_parameter_name_mapping") + end + # verify the required parameter "http_debug_option" is set + if @api_client.config.client_side_validation && http_debug_option.nil? + raise ArgumentError.new("Missing the required parameter 'http_debug_option' when calling FakeApi.get_parameter_name_mapping") + end + # resource path + local_var_path = "/fake/parameter-name-mapping" + + # query parameters + query_params = Hash(String, String).new + query_params["type"] = _type.to_s unless _type.nil? + query_params["http_debug_option"] = http_debug_option.to_s unless http_debug_option.nil? + + # header parameters + header_params = Hash(String, String).new + header_params["_type"] = underscore_type + header_params["type_"] = type_with_underscore + header_params["type-"] = type_with_dash + + # form parameters + form_params = Hash(Symbol, (String | ::File)).new + + # http body (model) + post_body = nil + + # return_type + return_type = nil + + # auth_names + auth_names = [] of String + + data, status_code, headers = @api_client.call_api(:GET, + local_var_path, + :"FakeApi.get_parameter_name_mapping", + return_type, + post_body, + auth_names, + header_params, + query_params, + form_params) + if @api_client.config.debugging + Log.debug {"API called: FakeApi#get_parameter_name_mapping\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"} + end + return nil, status_code, headers + end + end +end diff --git a/samples/client/petstore/crystal/src/petstore/models/another_property_name_mapping.cr b/samples/client/petstore/crystal/src/petstore/models/another_property_name_mapping.cr new file mode 100644 index 000000000000..19361be3efca --- /dev/null +++ b/samples/client/petstore/crystal/src/petstore/models/another_property_name_mapping.cr @@ -0,0 +1,193 @@ +# #OpenAPI Petstore +# +##This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +# +#The version of the OpenAPI document: 1.0.0 +# +#Generated by: https://openapi-generator.tech +#OpenAPI Generator version: 7.0.0-SNAPSHOT +# + +require "big" +require "json" +require "time" + +module Petstore + class AnotherPropertyNameMapping + include JSON::Serializable + + # Optional properties + @[JSON::Field(key: "http_debug_operation", type: String?, nillable: true, emit_null: false)] + property http_debug_operation : String? + + @[JSON::Field(key: "_type", type: String?, nillable: true, emit_null: false)] + property underscore_type : String? + + @[JSON::Field(key: "type", type: String?, nillable: true, emit_null: false)] + property _type : String? + + @[JSON::Field(key: "type_", type: String?, nillable: true, emit_null: false)] + property type_with_underscore : String? + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(@http_debug_operation : String?, @underscore_type : String?, @_type : String?, @type_with_underscore : String?) + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array(String).new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.same?(o) + self.class == o.class && + http_debug_operation == o.http_debug_operation && + underscore_type == o.underscore_type && + _type == o._type && + type_with_underscore == o.type_with_underscore + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [http_debug_operation, underscore_type, _type, type_with_underscore].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.openapi_types.each_pair do |key, type| + if !attributes[self.class.attribute_map[key]]? && self.class.openapi_nullable.includes?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + ({} of Symbol => String).tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} of Symbol => String + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.includes?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + ({} of Symbol => String).tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end From 6f05655101321b148827aa1d58467ebd0dbe1b72 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Sat, 5 Aug 2023 13:34:57 +0800 Subject: [PATCH 012/292] Add mapping features to R client generator (#16252) * add mapping features to r client generator * update samples --- bin/configs/r-httr2-client.yaml | 7 + .../codegen/languages/RClientCodegen.java | 20 ++ .../src/test/resources/3_0/r/petstore.yaml | 7 + .../R-httr2-wrapper/.openapi-generator/FILES | 2 + .../client/petstore/R-httr2-wrapper/NAMESPACE | 1 + .../petstore/R-httr2-wrapper/R/dummy_model.R | 196 ++++++++++++++++++ .../client/petstore/R-httr2-wrapper/README.md | 1 + .../R-httr2-wrapper/docs/DummyModel.md | 10 + .../tests/testthat/test_dummy_model.R | 13 ++ .../petstore/R-httr2/.openapi-generator/FILES | 2 + samples/client/petstore/R-httr2/NAMESPACE | 1 + samples/client/petstore/R-httr2/R/date.R | 28 +-- samples/client/petstore/R-httr2/R/fake_api.R | 26 +-- .../client/petstore/R-httr2/R/just_model.R | 163 +++++++++++++++ samples/client/petstore/R-httr2/README.md | 1 + samples/client/petstore/R-httr2/docs/Date.md | 2 +- .../client/petstore/R-httr2/docs/FakeApi.md | 8 +- .../client/petstore/R-httr2/docs/JustModel.md | 10 + .../R-httr2/tests/testthat/test_just_model.R | 13 ++ .../petstore/R/.openapi-generator/FILES | 2 + samples/client/petstore/R/NAMESPACE | 1 + samples/client/petstore/R/R/dummy_model.R | 196 ++++++++++++++++++ samples/client/petstore/R/README.md | 1 + samples/client/petstore/R/docs/DummyModel.md | 10 + .../R/tests/testthat/test_dummy_model.R | 13 ++ 25 files changed, 702 insertions(+), 32 deletions(-) create mode 100644 samples/client/petstore/R-httr2-wrapper/R/dummy_model.R create mode 100644 samples/client/petstore/R-httr2-wrapper/docs/DummyModel.md create mode 100644 samples/client/petstore/R-httr2-wrapper/tests/testthat/test_dummy_model.R create mode 100644 samples/client/petstore/R-httr2/R/just_model.R create mode 100644 samples/client/petstore/R-httr2/docs/JustModel.md create mode 100644 samples/client/petstore/R-httr2/tests/testthat/test_just_model.R create mode 100644 samples/client/petstore/R/R/dummy_model.R create mode 100644 samples/client/petstore/R/docs/DummyModel.md create mode 100644 samples/client/petstore/R/tests/testthat/test_dummy_model.R diff --git a/bin/configs/r-httr2-client.yaml b/bin/configs/r-httr2-client.yaml index 15779e26d36c..c842eefa49e4 100644 --- a/bin/configs/r-httr2-client.yaml +++ b/bin/configs/r-httr2-client.yaml @@ -4,6 +4,12 @@ inputSpec: modules/openapi-generator/src/test/resources/3_0/r/petstore.yaml templateDir: modules/openapi-generator/src/main/resources/r httpUserAgent: PetstoreAgent library: httr2 +modelNameMappings: + dummy_model: JustModel +parameterNameMappings: + path_array: path_array_parameter +nameMappings: + percent_description: percent additionalProperties: packageName: petstore exceptionPackage: rlang @@ -11,3 +17,4 @@ additionalProperties: returnExceptionOnFailure: true errorObjectType: "ModelApiResponse" operationIdNaming: snake_case + diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RClientCodegen.java index 5514520c0d03..872c75239d2b 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RClientCodegen.java @@ -393,6 +393,11 @@ public String modelFileFolder() { @Override public String toParamName(String name) { + // obtain the name from parameterNameMapping directly if provided + if (parameterNameMapping.containsKey(name)) { + return parameterNameMapping.get(name); + } + // replace - with _ e.g. created-at => created_at name = sanitizeName(name.replaceAll("-", "_")); @@ -417,6 +422,11 @@ public String toParamName(String name) { @Override public String toVarName(String name) { + // obtain the name from nameMapping directly if provided + if (nameMapping.containsKey(name)) { + return nameMapping.get(name); + } + // escape item reserved words with "item_" prefix if (itemReservedWords.contains(name)) { LOGGER.info("The item `{}` has been renamed to `item_{}` as it's a reserved word.", name, name); @@ -434,11 +444,21 @@ public String toVarName(String name) { @Override public String toModelFilename(String name) { + // obtain the name from modelNameMapping directly if provided + if (modelNameMapping.containsKey(name)) { + return underscore(modelNameMapping.get(name)); + } + return underscore(toModelName(name)); } @Override public String toModelName(String name) { + // obtain the name from modelNameMapping directly if provided + if (modelNameMapping.containsKey(name)) { + return modelNameMapping.get(name); + } + // We need to check if schema-mapping has a different model for this class, so we use it // instead of the auto-generated one. if (schemaMapping.containsKey(name)) { diff --git a/modules/openapi-generator/src/test/resources/3_0/r/petstore.yaml b/modules/openapi-generator/src/test/resources/3_0/r/petstore.yaml index fcddaaa8d608..2fd09bffbf84 100644 --- a/modules/openapi-generator/src/test/resources/3_0/r/petstore.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/r/petstore.yaml @@ -1121,6 +1121,12 @@ components: required: - className - url_property + dummy_model: + description: to test the model name mapping + type: object + properties: + property: + type: string format_test: type: object required: @@ -1189,3 +1195,4 @@ components: description: A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. type: string pattern: '/^image_\d{1,3}$/i' + diff --git a/samples/client/petstore/R-httr2-wrapper/.openapi-generator/FILES b/samples/client/petstore/R-httr2-wrapper/.openapi-generator/FILES index 3d39761f1354..5023966da14b 100644 --- a/samples/client/petstore/R-httr2-wrapper/.openapi-generator/FILES +++ b/samples/client/petstore/R-httr2-wrapper/.openapi-generator/FILES @@ -18,6 +18,7 @@ R/category.R R/danish_pig.R R/date.R R/dog.R +R/dummy_model.R R/fake_api.R R/format_test.R R/mammal.R @@ -48,6 +49,7 @@ docs/Category.md docs/DanishPig.md docs/Date.md docs/Dog.md +docs/DummyModel.md docs/FakeApi.md docs/FormatTest.md docs/Mammal.md diff --git a/samples/client/petstore/R-httr2-wrapper/NAMESPACE b/samples/client/petstore/R-httr2-wrapper/NAMESPACE index c4a03c842702..fd062786db13 100644 --- a/samples/client/petstore/R-httr2-wrapper/NAMESPACE +++ b/samples/client/petstore/R-httr2-wrapper/NAMESPACE @@ -26,6 +26,7 @@ export(Category) export(DanishPig) export(Date) export(Dog) +export(DummyModel) export(FormatTest) export(Mammal) export(ModelApiResponse) diff --git a/samples/client/petstore/R-httr2-wrapper/R/dummy_model.R b/samples/client/petstore/R-httr2-wrapper/R/dummy_model.R new file mode 100644 index 000000000000..75c7c5f8a567 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/dummy_model.R @@ -0,0 +1,196 @@ +#' Create a new DummyModel +#' +#' @description +#' to test the model name mapping +#' +#' @docType class +#' @title DummyModel +#' @description DummyModel Class +#' @format An \code{R6Class} generator object +#' @field property character [optional] +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +DummyModel <- R6::R6Class( + "DummyModel", + public = list( + `property` = NULL, + `_field_list` = c("property"), + `additional_properties` = list(), + #' Initialize a new DummyModel class. + #' + #' @description + #' Initialize a new DummyModel class. + #' + #' @param property property + #' @param additional_properties additional properties (optional) + #' @param ... Other optional arguments. + #' @export + initialize = function(`property` = NULL, additional_properties = NULL, ...) { + if (!is.null(`property`)) { + if (!(is.character(`property`) && length(`property`) == 1)) { + stop(paste("Error! Invalid data for `property`. Must be a string:", `property`)) + } + self$`property` <- `property` + } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return DummyModel in JSON format + #' @export + toJSON = function() { + DummyModelObject <- list() + if (!is.null(self$`property`)) { + DummyModelObject[["property"]] <- + self$`property` + } + for (key in names(self$additional_properties)) { + DummyModelObject[[key]] <- self$additional_properties[[key]] + } + + DummyModelObject + }, + #' Deserialize JSON string into an instance of DummyModel + #' + #' @description + #' Deserialize JSON string into an instance of DummyModel + #' + #' @param input_json the JSON input + #' @return the instance of DummyModel + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`property`)) { + self$`property` <- this_object$`property` + } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return DummyModel in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`property`)) { + sprintf( + '"property": + "%s" + ', + self$`property` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) + }, + #' Deserialize JSON string into an instance of DummyModel + #' + #' @description + #' Deserialize JSON string into an instance of DummyModel + #' + #' @param input_json the JSON input + #' @return the instance of DummyModel + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`property` <- this_object$`property` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' Validate JSON input with respect to DummyModel + #' + #' @description + #' Validate JSON input with respect to DummyModel and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of DummyModel + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# DummyModel$unlock() +# +## Below is an example to define the print function +# DummyModel$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# DummyModel$lock() + diff --git a/samples/client/petstore/R-httr2-wrapper/README.md b/samples/client/petstore/R-httr2-wrapper/README.md index e09946a3a057..1fbd788e2bbc 100644 --- a/samples/client/petstore/R-httr2-wrapper/README.md +++ b/samples/client/petstore/R-httr2-wrapper/README.md @@ -113,6 +113,7 @@ Class | Method | HTTP request | Description - [DanishPig](docs/DanishPig.md) - [Date](docs/Date.md) - [Dog](docs/Dog.md) + - [DummyModel](docs/DummyModel.md) - [FormatTest](docs/FormatTest.md) - [Mammal](docs/Mammal.md) - [ModelApiResponse](docs/ModelApiResponse.md) diff --git a/samples/client/petstore/R-httr2-wrapper/docs/DummyModel.md b/samples/client/petstore/R-httr2-wrapper/docs/DummyModel.md new file mode 100644 index 000000000000..fdf3ba12203c --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/docs/DummyModel.md @@ -0,0 +1,10 @@ +# petstore::DummyModel + +to test the model name mapping + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**property** | **character** | | [optional] + + diff --git a/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_dummy_model.R b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_dummy_model.R new file mode 100644 index 000000000000..b4f8e11b7f57 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_dummy_model.R @@ -0,0 +1,13 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test DummyModel") + +model_instance <- DummyModel$new() + +test_that("property", { + # tests for the property `property` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`property`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2/.openapi-generator/FILES b/samples/client/petstore/R-httr2/.openapi-generator/FILES index 781b048629bf..e3ca4f60cbc2 100644 --- a/samples/client/petstore/R-httr2/.openapi-generator/FILES +++ b/samples/client/petstore/R-httr2/.openapi-generator/FILES @@ -20,6 +20,7 @@ R/date.R R/dog.R R/fake_api.R R/format_test.R +R/just_model.R R/mammal.R R/model_api_response.R R/nested_one_of.R @@ -49,6 +50,7 @@ docs/Date.md docs/Dog.md docs/FakeApi.md docs/FormatTest.md +docs/JustModel.md docs/Mammal.md docs/ModelApiResponse.md docs/NestedOneOf.md diff --git a/samples/client/petstore/R-httr2/NAMESPACE b/samples/client/petstore/R-httr2/NAMESPACE index 26ea22705adb..e196ce103b39 100644 --- a/samples/client/petstore/R-httr2/NAMESPACE +++ b/samples/client/petstore/R-httr2/NAMESPACE @@ -25,6 +25,7 @@ export(DanishPig) export(Date) export(Dog) export(FormatTest) +export(JustModel) export(Mammal) export(ModelApiResponse) export(NestedOneOf) diff --git a/samples/client/petstore/R-httr2/R/date.R b/samples/client/petstore/R-httr2/R/date.R index 482bb1ef037f..9a09f05a5a99 100644 --- a/samples/client/petstore/R-httr2/R/date.R +++ b/samples/client/petstore/R-httr2/R/date.R @@ -8,7 +8,7 @@ #' @description Date Class #' @format An \code{R6Class} generator object #' @field className character -#' @field percent_description using \% in the description character [optional] +#' @field percent using \% in the description character [optional] #' @field url_property character #' @importFrom R6 R6Class #' @importFrom jsonlite fromJSON toJSON @@ -17,7 +17,7 @@ Date <- R6::R6Class( "Date", public = list( `className` = NULL, - `percent_description` = NULL, + `percent` = NULL, `url_property` = NULL, #' Initialize a new Date class. #' @@ -26,10 +26,10 @@ Date <- R6::R6Class( #' #' @param className className #' @param url_property url_property - #' @param percent_description using \% in the description + #' @param percent using \% in the description #' @param ... Other optional arguments. #' @export - initialize = function(`className`, `url_property`, `percent_description` = NULL, ...) { + initialize = function(`className`, `url_property`, `percent` = NULL, ...) { if (!missing(`className`)) { if (!(is.character(`className`) && length(`className`) == 1)) { stop(paste("Error! Invalid data for `className`. Must be a string:", `className`)) @@ -46,11 +46,11 @@ Date <- R6::R6Class( } self$`url_property` <- `url_property` } - if (!is.null(`percent_description`)) { - if (!(is.character(`percent_description`) && length(`percent_description`) == 1)) { - stop(paste("Error! Invalid data for `percent_description`. Must be a string:", `percent_description`)) + if (!is.null(`percent`)) { + if (!(is.character(`percent`) && length(`percent`) == 1)) { + stop(paste("Error! Invalid data for `percent`. Must be a string:", `percent`)) } - self$`percent_description` <- `percent_description` + self$`percent` <- `percent` } }, #' To JSON string @@ -66,9 +66,9 @@ Date <- R6::R6Class( DateObject[["className"]] <- self$`className` } - if (!is.null(self$`percent_description`)) { + if (!is.null(self$`percent`)) { DateObject[["percent_description"]] <- - self$`percent_description` + self$`percent` } if (!is.null(self$`url_property`)) { DateObject[["url_property"]] <- @@ -90,7 +90,7 @@ Date <- R6::R6Class( self$`className` <- this_object$`className` } if (!is.null(this_object$`percent_description`)) { - self$`percent_description` <- this_object$`percent_description` + self$`percent` <- this_object$`percent_description` } if (!is.null(this_object$`url_property`)) { # to validate URL. ref: https://stackoverflow.com/questions/73952024/url-validation-in-r @@ -118,12 +118,12 @@ Date <- R6::R6Class( self$`className` ) }, - if (!is.null(self$`percent_description`)) { + if (!is.null(self$`percent`)) { sprintf( '"percent_description": "%s" ', - self$`percent_description` + self$`percent` ) }, if (!is.null(self$`url_property`)) { @@ -149,7 +149,7 @@ Date <- R6::R6Class( fromJSONString = function(input_json) { this_object <- jsonlite::fromJSON(input_json) self$`className` <- this_object$`className` - self$`percent_description` <- this_object$`percent_description` + self$`percent` <- this_object$`percent` # to validate URL. ref: https://stackoverflow.com/questions/73952024/url-validation-in-r if (!stringr::str_detect(this_object$`url_property`, "(https?|ftp)://[^ /$.?#].[^\\s]*")) { stop(paste("Error! Invalid data for `url_property`. Must be a URL:", this_object$`url_property`)) diff --git a/samples/client/petstore/R-httr2/R/fake_api.R b/samples/client/petstore/R-httr2/R/fake_api.R index e5977eb139ae..c0c1324e56b8 100644 --- a/samples/client/petstore/R-httr2/R/fake_api.R +++ b/samples/client/petstore/R-httr2/R/fake_api.R @@ -61,7 +61,7 @@ #' #' #' \itemize{ -#' \item \emph{ @param } path_array list( character ) +#' \item \emph{ @param } path_array_parameter list( character ) #' #' \item On encountering errors, an error of subclass ApiException will be thrown. #' @@ -188,14 +188,14 @@ #' #################### fake_path_array #################### #' #' library(petstore) -#' var_path_array <- c("inner_example") # array[character] | dummy path parameter +#' var_path_array_parameter <- c("inner_example") # array[character] | dummy path parameter #' #' #test array parameter in path #' api_instance <- FakeApi$new() #' #' result <- tryCatch( #' -#' api_instance$fake_path_array(var_path_array), +#' api_instance$fake_path_array(var_path_array_parameter), #' ApiException = function(ex) ex #' ) #' # In case of error, print the error object @@ -525,12 +525,12 @@ FakeApi <- R6::R6Class( #' @description #' test array parameter in path #' - #' @param path_array dummy path parameter + #' @param path_array_parameter dummy path parameter #' @param ... Other optional arguments #' @return void #' @export - fake_path_array = function(path_array, ...) { - local_var_response <- self$fake_path_array_with_http_info(path_array, ...) + fake_path_array = function(path_array_parameter, ...) { + local_var_response <- self$fake_path_array_with_http_info(path_array_parameter, ...) if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { local_var_response$content } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { @@ -546,11 +546,11 @@ FakeApi <- R6::R6Class( #' @description #' test array parameter in path #' - #' @param path_array dummy path parameter + #' @param path_array_parameter dummy path parameter #' @param ... Other optional arguments #' @return API response (void) with additional information such as HTTP status code, headers #' @export - fake_path_array_with_http_info = function(path_array, ...) { + fake_path_array_with_http_info = function(path_array_parameter, ...) { args <- list(...) query_params <- list() header_params <- c() @@ -560,17 +560,17 @@ FakeApi <- R6::R6Class( oauth_scopes <- NULL is_oauth <- FALSE - if (missing(`path_array`)) { - rlang::abort(message = "Missing required parameter `path_array`.", + if (missing(`path_array_parameter`)) { + rlang::abort(message = "Missing required parameter `path_array_parameter`.", .subclass = "ApiException", ApiException = ApiException$new(status = 0, - reason = "Missing required parameter `path_array`.")) + reason = "Missing required parameter `path_array_parameter`.")) } local_var_url_path <- "/fake/path_array/{path_array}/testing" - if (!missing(`path_array`)) { - local_var_url_path <- gsub("\\{path_array\\}", paste(URLencode(as.character(`path_array`), reserved = TRUE), collapse= ",", sep=""), local_var_url_path) + if (!missing(`path_array_parameter`)) { + local_var_url_path <- gsub("\\{path_array\\}", paste(URLencode(as.character(`path_array_parameter`), reserved = TRUE), collapse= ",", sep=""), local_var_url_path) } diff --git a/samples/client/petstore/R-httr2/R/just_model.R b/samples/client/petstore/R-httr2/R/just_model.R new file mode 100644 index 000000000000..163e3721638d --- /dev/null +++ b/samples/client/petstore/R-httr2/R/just_model.R @@ -0,0 +1,163 @@ +#' Create a new JustModel +#' +#' @description +#' to test the model name mapping +#' +#' @docType class +#' @title JustModel +#' @description JustModel Class +#' @format An \code{R6Class} generator object +#' @field property character [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +JustModel <- R6::R6Class( + "JustModel", + public = list( + `property` = NULL, + #' Initialize a new JustModel class. + #' + #' @description + #' Initialize a new JustModel class. + #' + #' @param property property + #' @param ... Other optional arguments. + #' @export + initialize = function(`property` = NULL, ...) { + if (!is.null(`property`)) { + if (!(is.character(`property`) && length(`property`) == 1)) { + stop(paste("Error! Invalid data for `property`. Must be a string:", `property`)) + } + self$`property` <- `property` + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return JustModel in JSON format + #' @export + toJSON = function() { + JustModelObject <- list() + if (!is.null(self$`property`)) { + JustModelObject[["property"]] <- + self$`property` + } + JustModelObject + }, + #' Deserialize JSON string into an instance of JustModel + #' + #' @description + #' Deserialize JSON string into an instance of JustModel + #' + #' @param input_json the JSON input + #' @return the instance of JustModel + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`property`)) { + self$`property` <- this_object$`property` + } + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return JustModel in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`property`)) { + sprintf( + '"property": + "%s" + ', + self$`property` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Deserialize JSON string into an instance of JustModel + #' + #' @description + #' Deserialize JSON string into an instance of JustModel + #' + #' @param input_json the JSON input + #' @return the instance of JustModel + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`property` <- this_object$`property` + self + }, + #' Validate JSON input with respect to JustModel + #' + #' @description + #' Validate JSON input with respect to JustModel and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of JustModel + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# JustModel$unlock() +# +## Below is an example to define the print function +# JustModel$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# JustModel$lock() + diff --git a/samples/client/petstore/R-httr2/README.md b/samples/client/petstore/R-httr2/README.md index e09946a3a057..a64dcb83e2cf 100644 --- a/samples/client/petstore/R-httr2/README.md +++ b/samples/client/petstore/R-httr2/README.md @@ -114,6 +114,7 @@ Class | Method | HTTP request | Description - [Date](docs/Date.md) - [Dog](docs/Dog.md) - [FormatTest](docs/FormatTest.md) + - [JustModel](docs/JustModel.md) - [Mammal](docs/Mammal.md) - [ModelApiResponse](docs/ModelApiResponse.md) - [NestedOneOf](docs/NestedOneOf.md) diff --git a/samples/client/petstore/R-httr2/docs/Date.md b/samples/client/petstore/R-httr2/docs/Date.md index ed61f58682ca..756d058569ce 100644 --- a/samples/client/petstore/R-httr2/docs/Date.md +++ b/samples/client/petstore/R-httr2/docs/Date.md @@ -6,7 +6,7 @@ to test the model name `Date` Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **className** | **character** | | -**percent_description** | **character** | using % in the description | [optional] +**percent** | **character** | using % in the description | [optional] **url_property** | **character** | | diff --git a/samples/client/petstore/R-httr2/docs/FakeApi.md b/samples/client/petstore/R-httr2/docs/FakeApi.md index a6a30c06e096..3bdabfe235c2 100644 --- a/samples/client/petstore/R-httr2/docs/FakeApi.md +++ b/samples/client/petstore/R-httr2/docs/FakeApi.md @@ -140,7 +140,7 @@ No authorization required | **200** | successful operation | - | # **fake_path_array** -> fake_path_array(path_array) +> fake_path_array(path_array_parameter) test array parameter in path @@ -153,11 +153,11 @@ library(petstore) # test array parameter in path # # prepare function argument(s) -var_path_array <- c("inner_example") # array[character] | dummy path parameter +var_path_array_parameter <- c("inner_example") # array[character] | dummy path parameter api_instance <- FakeApi$new() result <- tryCatch( - api_instance$fake_path_array(var_path_array), + api_instance$fake_path_array(var_path_array_parameter), ApiException = function(ex) ex ) # In case of error, print the error object @@ -174,7 +174,7 @@ if (!is.null(result$ApiException)) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **path_array** | list( **character** )| dummy path parameter | + **path_array_parameter** | list( **character** )| dummy path parameter | ### Return type diff --git a/samples/client/petstore/R-httr2/docs/JustModel.md b/samples/client/petstore/R-httr2/docs/JustModel.md new file mode 100644 index 000000000000..f5420acfe06b --- /dev/null +++ b/samples/client/petstore/R-httr2/docs/JustModel.md @@ -0,0 +1,10 @@ +# petstore::JustModel + +to test the model name mapping + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**property** | **character** | | [optional] + + diff --git a/samples/client/petstore/R-httr2/tests/testthat/test_just_model.R b/samples/client/petstore/R-httr2/tests/testthat/test_just_model.R new file mode 100644 index 000000000000..01a5592d5755 --- /dev/null +++ b/samples/client/petstore/R-httr2/tests/testthat/test_just_model.R @@ -0,0 +1,13 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test JustModel") + +model_instance <- JustModel$new() + +test_that("property", { + # tests for the property `property` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`property`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R/.openapi-generator/FILES b/samples/client/petstore/R/.openapi-generator/FILES index 781b048629bf..9a7a9f21724e 100644 --- a/samples/client/petstore/R/.openapi-generator/FILES +++ b/samples/client/petstore/R/.openapi-generator/FILES @@ -18,6 +18,7 @@ R/category.R R/danish_pig.R R/date.R R/dog.R +R/dummy_model.R R/fake_api.R R/format_test.R R/mammal.R @@ -47,6 +48,7 @@ docs/Category.md docs/DanishPig.md docs/Date.md docs/Dog.md +docs/DummyModel.md docs/FakeApi.md docs/FormatTest.md docs/Mammal.md diff --git a/samples/client/petstore/R/NAMESPACE b/samples/client/petstore/R/NAMESPACE index e392e3ea9bd8..afcc404eca78 100644 --- a/samples/client/petstore/R/NAMESPACE +++ b/samples/client/petstore/R/NAMESPACE @@ -24,6 +24,7 @@ export(Category) export(DanishPig) export(Date) export(Dog) +export(DummyModel) export(FormatTest) export(Mammal) export(ModelApiResponse) diff --git a/samples/client/petstore/R/R/dummy_model.R b/samples/client/petstore/R/R/dummy_model.R new file mode 100644 index 000000000000..75c7c5f8a567 --- /dev/null +++ b/samples/client/petstore/R/R/dummy_model.R @@ -0,0 +1,196 @@ +#' Create a new DummyModel +#' +#' @description +#' to test the model name mapping +#' +#' @docType class +#' @title DummyModel +#' @description DummyModel Class +#' @format An \code{R6Class} generator object +#' @field property character [optional] +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +DummyModel <- R6::R6Class( + "DummyModel", + public = list( + `property` = NULL, + `_field_list` = c("property"), + `additional_properties` = list(), + #' Initialize a new DummyModel class. + #' + #' @description + #' Initialize a new DummyModel class. + #' + #' @param property property + #' @param additional_properties additional properties (optional) + #' @param ... Other optional arguments. + #' @export + initialize = function(`property` = NULL, additional_properties = NULL, ...) { + if (!is.null(`property`)) { + if (!(is.character(`property`) && length(`property`) == 1)) { + stop(paste("Error! Invalid data for `property`. Must be a string:", `property`)) + } + self$`property` <- `property` + } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return DummyModel in JSON format + #' @export + toJSON = function() { + DummyModelObject <- list() + if (!is.null(self$`property`)) { + DummyModelObject[["property"]] <- + self$`property` + } + for (key in names(self$additional_properties)) { + DummyModelObject[[key]] <- self$additional_properties[[key]] + } + + DummyModelObject + }, + #' Deserialize JSON string into an instance of DummyModel + #' + #' @description + #' Deserialize JSON string into an instance of DummyModel + #' + #' @param input_json the JSON input + #' @return the instance of DummyModel + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`property`)) { + self$`property` <- this_object$`property` + } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return DummyModel in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`property`)) { + sprintf( + '"property": + "%s" + ', + self$`property` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) + }, + #' Deserialize JSON string into an instance of DummyModel + #' + #' @description + #' Deserialize JSON string into an instance of DummyModel + #' + #' @param input_json the JSON input + #' @return the instance of DummyModel + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`property` <- this_object$`property` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' Validate JSON input with respect to DummyModel + #' + #' @description + #' Validate JSON input with respect to DummyModel and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of DummyModel + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# DummyModel$unlock() +# +## Below is an example to define the print function +# DummyModel$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# DummyModel$lock() + diff --git a/samples/client/petstore/R/README.md b/samples/client/petstore/R/README.md index 5975b55d476c..95f7e3e86502 100644 --- a/samples/client/petstore/R/README.md +++ b/samples/client/petstore/R/README.md @@ -113,6 +113,7 @@ Class | Method | HTTP request | Description - [DanishPig](docs/DanishPig.md) - [Date](docs/Date.md) - [Dog](docs/Dog.md) + - [DummyModel](docs/DummyModel.md) - [FormatTest](docs/FormatTest.md) - [Mammal](docs/Mammal.md) - [ModelApiResponse](docs/ModelApiResponse.md) diff --git a/samples/client/petstore/R/docs/DummyModel.md b/samples/client/petstore/R/docs/DummyModel.md new file mode 100644 index 000000000000..fdf3ba12203c --- /dev/null +++ b/samples/client/petstore/R/docs/DummyModel.md @@ -0,0 +1,10 @@ +# petstore::DummyModel + +to test the model name mapping + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**property** | **character** | | [optional] + + diff --git a/samples/client/petstore/R/tests/testthat/test_dummy_model.R b/samples/client/petstore/R/tests/testthat/test_dummy_model.R new file mode 100644 index 000000000000..b4f8e11b7f57 --- /dev/null +++ b/samples/client/petstore/R/tests/testthat/test_dummy_model.R @@ -0,0 +1,13 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test DummyModel") + +model_instance <- DummyModel$new() + +test_that("property", { + # tests for the property `property` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`property`, "EXPECTED_RESULT") +}) From d9e32a79a5cb80e53b78cb60a7174526f7f96091 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Sat, 5 Aug 2023 13:41:04 +0800 Subject: [PATCH 013/292] Support library option via additionalProperties (#16242) * set library option obtain from additionalProperties * test library * update samples * remove old files --- bin/configs/java-resteasy.yaml | 2 +- .../codegen/config/CodegenConfigurator.java | 5 + .../.openapi-generator/FILES | 20 +- .../openapitools/client/apis/DefaultApi.kt | 0 .../client/infrastructure/ByteArrayAdapter.kt | 0 .../infrastructure/CollectionFormats.kt | 0 .../client/infrastructure/LocalDateAdapter.kt | 0 .../infrastructure/LocalDateTimeAdapter.kt | 0 .../infrastructure/OffsetDateTimeAdapter.kt | 0 .../client/request/GsonRequest.kt | 0 .../client/request/IRequestFactory.kt | 0 .../client/request/RequestFactory.kt | 0 .../.openapi-generator/FILES | 30 +- .../openapitools/client/apis/DefaultApi.kt | 68 + .../openapitools/client/auth/ApiKeyAuth.kt | 0 .../client/auth/Authentication.kt | 0 .../openapitools/client/auth/HttpBasicAuth.kt | 0 .../client/auth/HttpBearerAuth.kt | 0 .../org/openapitools/client/auth/OAuth.kt | 0 .../client/infrastructure/ApiAbstractions.kt | 0 .../client/infrastructure/ApiClient.kt | 0 .../client/infrastructure/Base64ByteArray.kt | 0 .../client/infrastructure/Bytes.kt | 0 .../client/infrastructure/HttpResponse.kt | 0 .../client/infrastructure/OctetByteArray.kt | 0 .../client/infrastructure/PartConfig.kt | 0 .../client/infrastructure/RequestConfig.kt | 0 .../client/infrastructure/RequestMethod.kt | 0 .../.openapi-generator/FILES | 32 +- .../openapitools/client/apis/DefaultApi.kt | 69 + .../openapitools/client/auth/ApiKeyAuth.kt | 16 + .../client/auth/Authentication.kt | 13 + .../openapitools/client/auth/HttpBasicAuth.kt | 17 + .../client/auth/HttpBearerAuth.kt | 14 + .../org/openapitools/client/auth/OAuth.kt | 10 + .../client/infrastructure/ApiAbstractions.kt | 23 + .../client/infrastructure/ApiClient.kt | 172 ++ .../client/infrastructure/Base64ByteArray.kt | 30 + .../client/infrastructure/Bytes.kt | 100 + .../client/infrastructure/HttpResponse.kt | 51 + .../client/infrastructure/OctetByteArray.kt | 30 + .../client/infrastructure/PartConfig.kt | 11 + .../client/infrastructure/RequestConfig.kt | 18 + .../client/infrastructure/RequestMethod.kt | 8 + .../org/openapitools/client/models/Apa.kt | 51 + .../.openapi-generator/FILES | 26 +- .../openapitools/client/apis/DefaultApi.kt | 0 .../client/infrastructure/ByteArrayAdapter.kt | 0 .../infrastructure/CollectionFormats.kt | 0 .../infrastructure/ITransformForStorage.kt | 0 .../client/infrastructure/LocalDateAdapter.kt | 0 .../infrastructure/LocalDateTimeAdapter.kt | 0 .../infrastructure/OffsetDateTimeAdapter.kt | 0 .../org/openapitools/client/models/Apa.kt | 0 .../client/models/room/ApaRoomModel.kt | 0 .../client/request/GsonRequest.kt | 0 .../client/request/IRequestFactory.kt | 0 .../client/request/RequestFactory.kt | 0 .../.openapi-generator/FILES | 32 +- .../openapitools/client/apis/DefaultApi.kt | 0 .../openapitools/client/auth/ApiKeyAuth.kt | 16 + .../client/auth/Authentication.kt | 13 + .../openapitools/client/auth/HttpBasicAuth.kt | 17 + .../client/auth/HttpBearerAuth.kt | 14 + .../org/openapitools/client/auth/OAuth.kt | 10 + .../client/infrastructure/ApiAbstractions.kt | 23 + .../client/infrastructure/ApiClient.kt | 172 ++ .../client/infrastructure/Base64ByteArray.kt | 30 + .../client/infrastructure/Bytes.kt | 100 + .../client/infrastructure/HttpResponse.kt | 51 + .../client/infrastructure/OctetByteArray.kt | 30 + .../client/infrastructure/PartConfig.kt | 11 + .../client/infrastructure/RequestConfig.kt | 18 + .../client/infrastructure/RequestMethod.kt | 8 + .../org/openapitools/client/models/Apa.kt | 0 .../.openapi-generator/FILES | 2 +- .../pom.xml | 7 - .../org/openapitools/api/AnotherFakeApi.java | 6 - .../java/org/openapitools/api/FakeApi.java | 80 +- .../api/FakeClassnameTestApi.java | 9 - .../gen/java/org/openapitools/api/PetApi.java | 89 +- .../java/org/openapitools/api/StoreApi.java | 29 +- .../java/org/openapitools/api/UserApi.java | 47 +- .../model/AdditionalPropertiesAnyType.java | 4 - .../model/AdditionalPropertiesArray.java | 4 - .../model/AdditionalPropertiesBoolean.java | 4 - .../model/AdditionalPropertiesClass.java | 14 - .../model/AdditionalPropertiesInteger.java | 4 - .../model/AdditionalPropertiesNumber.java | 4 - .../model/AdditionalPropertiesObject.java | 4 - .../model/AdditionalPropertiesString.java | 4 - .../java/org/openapitools/model/Animal.java | 5 - .../model/ArrayOfArrayOfNumberOnly.java | 4 - .../openapitools/model/ArrayOfNumberOnly.java | 4 - .../org/openapitools/model/ArrayTest.java | 6 - .../java/org/openapitools/model/BigCat.java | 4 - .../openapitools/model/Capitalization.java | 9 - .../gen/java/org/openapitools/model/Cat.java | 4 - .../java/org/openapitools/model/Category.java | 5 - .../org/openapitools/model/ClassModel.java | 6 +- .../java/org/openapitools/model/Client.java | 4 - .../gen/java/org/openapitools/model/Dog.java | 4 - .../org/openapitools/model/EnumArrays.java | 5 - .../java/org/openapitools/model/EnumTest.java | 8 - .../model/FileSchemaTestClass.java | 5 - .../org/openapitools/model/FormatTest.java | 17 - .../openapitools/model/HasOnlyReadOnly.java | 5 - .../java/org/openapitools/model/MapTest.java | 7 - ...ropertiesAndAdditionalPropertiesClass.java | 6 - .../openapitools/model/Model200Response.java | 7 +- .../openapitools/model/ModelApiResponse.java | 6 - .../org/openapitools/model/ModelFile.java | 6 +- .../org/openapitools/model/ModelList.java | 4 - .../org/openapitools/model/ModelReturn.java | 6 +- .../gen/java/org/openapitools/model/Name.java | 9 +- .../org/openapitools/model/NumberOnly.java | 4 - .../java/org/openapitools/model/Order.java | 9 - .../openapitools/model/OuterComposite.java | 6 - .../gen/java/org/openapitools/model/Pet.java | 9 - .../org/openapitools/model/ReadOnlyFirst.java | 5 - .../openapitools/model/SpecialModelName.java | 4 - .../gen/java/org/openapitools/model/Tag.java | 5 - .../openapitools/model/TypeHolderDefault.java | 8 - .../openapitools/model/TypeHolderExample.java | 9 - .../gen/java/org/openapitools/model/User.java | 11 - .../java/org/openapitools/model/XmlItem.java | 32 - .../src/main/resources/META-INF/openapi.yaml | 2276 +++++++++++++++++ 127 files changed, 3587 insertions(+), 609 deletions(-) rename samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/{kotlin => java}/org/openapitools/client/apis/DefaultApi.kt (100%) rename samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/{kotlin => java}/org/openapitools/client/infrastructure/ByteArrayAdapter.kt (100%) rename samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/{kotlin => java}/org/openapitools/client/infrastructure/CollectionFormats.kt (100%) rename samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/{kotlin => java}/org/openapitools/client/infrastructure/LocalDateAdapter.kt (100%) rename samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/{kotlin => java}/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt (100%) rename samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/{kotlin => java}/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt (100%) rename samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/{kotlin => java}/org/openapitools/client/request/GsonRequest.kt (100%) rename samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/{kotlin => java}/org/openapitools/client/request/IRequestFactory.kt (100%) rename samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/{kotlin => java}/org/openapitools/client/request/RequestFactory.kt (100%) create mode 100644 samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/DefaultApi.kt rename samples/client/petstore/{kotlin-default-values-multiplatform/src/main => kotlin-array-simple-string-multiplatform/src/commonMain}/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt (100%) rename samples/client/petstore/{kotlin-default-values-multiplatform/src/main => kotlin-array-simple-string-multiplatform/src/commonMain}/kotlin/org/openapitools/client/auth/Authentication.kt (100%) rename samples/client/petstore/{kotlin-default-values-multiplatform/src/main => kotlin-array-simple-string-multiplatform/src/commonMain}/kotlin/org/openapitools/client/auth/HttpBasicAuth.kt (100%) rename samples/client/petstore/{kotlin-default-values-multiplatform/src/main => kotlin-array-simple-string-multiplatform/src/commonMain}/kotlin/org/openapitools/client/auth/HttpBearerAuth.kt (100%) rename samples/client/petstore/{kotlin-default-values-multiplatform/src/main => kotlin-array-simple-string-multiplatform/src/commonMain}/kotlin/org/openapitools/client/auth/OAuth.kt (100%) rename samples/client/petstore/{kotlin-default-values-multiplatform/src/main => kotlin-array-simple-string-multiplatform/src/commonMain}/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt (100%) rename samples/client/petstore/{kotlin-default-values-multiplatform/src/main => kotlin-array-simple-string-multiplatform/src/commonMain}/kotlin/org/openapitools/client/infrastructure/ApiClient.kt (100%) rename samples/client/petstore/{kotlin-default-values-multiplatform/src/main => kotlin-array-simple-string-multiplatform/src/commonMain}/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt (100%) rename samples/client/petstore/{kotlin-default-values-multiplatform/src/main => kotlin-array-simple-string-multiplatform/src/commonMain}/kotlin/org/openapitools/client/infrastructure/Bytes.kt (100%) rename samples/client/petstore/{kotlin-default-values-multiplatform/src/main => kotlin-array-simple-string-multiplatform/src/commonMain}/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt (100%) rename samples/client/petstore/{kotlin-default-values-multiplatform/src/main => kotlin-array-simple-string-multiplatform/src/commonMain}/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt (100%) rename samples/client/petstore/{kotlin-default-values-multiplatform/src/main => kotlin-array-simple-string-multiplatform/src/commonMain}/kotlin/org/openapitools/client/infrastructure/PartConfig.kt (100%) rename samples/client/petstore/{kotlin-default-values-multiplatform/src/main => kotlin-array-simple-string-multiplatform/src/commonMain}/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt (100%) rename samples/client/petstore/{kotlin-default-values-multiplatform/src/main => kotlin-array-simple-string-multiplatform/src/commonMain}/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt (100%) create mode 100644 samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/DefaultApi.kt create mode 100644 samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt create mode 100644 samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/Authentication.kt create mode 100644 samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/HttpBasicAuth.kt create mode 100644 samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/HttpBearerAuth.kt create mode 100644 samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/OAuth.kt create mode 100644 samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt create mode 100644 samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt create mode 100644 samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt create mode 100644 samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt create mode 100644 samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt create mode 100644 samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt create mode 100644 samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/PartConfig.kt create mode 100644 samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt create mode 100644 samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt create mode 100644 samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Apa.kt rename samples/client/petstore/kotlin-default-values-jvm-volley/src/main/{kotlin => java}/org/openapitools/client/apis/DefaultApi.kt (100%) rename samples/client/petstore/kotlin-default-values-jvm-volley/src/main/{kotlin => java}/org/openapitools/client/infrastructure/ByteArrayAdapter.kt (100%) rename samples/client/petstore/kotlin-default-values-jvm-volley/src/main/{kotlin => java}/org/openapitools/client/infrastructure/CollectionFormats.kt (100%) rename samples/client/petstore/kotlin-default-values-jvm-volley/src/main/{kotlin => java}/org/openapitools/client/infrastructure/ITransformForStorage.kt (100%) rename samples/client/petstore/kotlin-default-values-jvm-volley/src/main/{kotlin => java}/org/openapitools/client/infrastructure/LocalDateAdapter.kt (100%) rename samples/client/petstore/kotlin-default-values-jvm-volley/src/main/{kotlin => java}/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt (100%) rename samples/client/petstore/kotlin-default-values-jvm-volley/src/main/{kotlin => java}/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt (100%) rename samples/client/petstore/kotlin-default-values-jvm-volley/src/main/{kotlin => java}/org/openapitools/client/models/Apa.kt (100%) rename samples/client/petstore/kotlin-default-values-jvm-volley/src/main/{kotlin => java}/org/openapitools/client/models/room/ApaRoomModel.kt (100%) rename samples/client/petstore/kotlin-default-values-jvm-volley/src/main/{kotlin => java}/org/openapitools/client/request/GsonRequest.kt (100%) rename samples/client/petstore/kotlin-default-values-jvm-volley/src/main/{kotlin => java}/org/openapitools/client/request/IRequestFactory.kt (100%) rename samples/client/petstore/kotlin-default-values-jvm-volley/src/main/{kotlin => java}/org/openapitools/client/request/RequestFactory.kt (100%) rename samples/client/petstore/kotlin-default-values-multiplatform/src/{main => commonMain}/kotlin/org/openapitools/client/apis/DefaultApi.kt (100%) create mode 100644 samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt create mode 100644 samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/Authentication.kt create mode 100644 samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/HttpBasicAuth.kt create mode 100644 samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/HttpBearerAuth.kt create mode 100644 samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/OAuth.kt create mode 100644 samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt create mode 100644 samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt create mode 100644 samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt create mode 100644 samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt create mode 100644 samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt create mode 100644 samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt create mode 100644 samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/PartConfig.kt create mode 100644 samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt create mode 100644 samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt rename samples/client/petstore/kotlin-default-values-multiplatform/src/{main => commonMain}/kotlin/org/openapitools/client/models/Apa.kt (100%) create mode 100644 samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/main/resources/META-INF/openapi.yaml diff --git a/bin/configs/java-resteasy.yaml b/bin/configs/java-resteasy.yaml index a6b099248583..16142531108f 100644 --- a/bin/configs/java-resteasy.yaml +++ b/bin/configs/java-resteasy.yaml @@ -1,8 +1,8 @@ generatorName: java outputDir: samples/client/petstore/java/resteasy -library: resteasy inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml templateDir: modules/openapi-generator/src/main/resources/Java additionalProperties: artifactId: petstore-resteasy hideGenerationTimestamp: "true" + library: resteasy diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java index f494204a184c..635bc0b13d7f 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java @@ -746,6 +746,11 @@ public ClientOptInput toClientOptInput() { config.additionalProperties().put(CodegenConstants.TEMPLATE_DIR, workflowSettings.getTemplateDir()); } + // if library is found in additionalProperties, set the library option accordingly + if (config.additionalProperties().containsKey("library")) { + config.setLibrary(String.valueOf(config.additionalProperties().get("library"))); + } + ClientOptInput input = new ClientOptInput() .config(config) .userDefinedTemplates(userDefinedTemplates); diff --git a/samples/client/petstore/kotlin-array-simple-string-jvm-volley/.openapi-generator/FILES b/samples/client/petstore/kotlin-array-simple-string-jvm-volley/.openapi-generator/FILES index 9cfbb4909249..fa7d703fae23 100644 --- a/samples/client/petstore/kotlin-array-simple-string-jvm-volley/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-array-simple-string-jvm-volley/.openapi-generator/FILES @@ -8,13 +8,13 @@ gradlew gradlew.bat settings.gradle src/main/AndroidManifest.xml -src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt -src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt -src/main/kotlin/org/openapitools/client/infrastructure/CollectionFormats.kt -src/main/kotlin/org/openapitools/client/infrastructure/CollectionFormats.kt -src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt -src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt -src/main/kotlin/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt -src/main/kotlin/org/openapitools/client/request/GsonRequest.kt -src/main/kotlin/org/openapitools/client/request/IRequestFactory.kt -src/main/kotlin/org/openapitools/client/request/RequestFactory.kt +src/main/java/org/openapitools/client/apis/DefaultApi.kt +src/main/java/org/openapitools/client/infrastructure/ByteArrayAdapter.kt +src/main/java/org/openapitools/client/infrastructure/CollectionFormats.kt +src/main/java/org/openapitools/client/infrastructure/CollectionFormats.kt +src/main/java/org/openapitools/client/infrastructure/LocalDateAdapter.kt +src/main/java/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt +src/main/java/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt +src/main/java/org/openapitools/client/request/GsonRequest.kt +src/main/java/org/openapitools/client/request/IRequestFactory.kt +src/main/java/org/openapitools/client/request/RequestFactory.kt diff --git a/samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt b/samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/java/org/openapitools/client/apis/DefaultApi.kt similarity index 100% rename from samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt rename to samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/java/org/openapitools/client/apis/DefaultApi.kt diff --git a/samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt b/samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/java/org/openapitools/client/infrastructure/ByteArrayAdapter.kt similarity index 100% rename from samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt rename to samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/java/org/openapitools/client/infrastructure/ByteArrayAdapter.kt diff --git a/samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/kotlin/org/openapitools/client/infrastructure/CollectionFormats.kt b/samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/java/org/openapitools/client/infrastructure/CollectionFormats.kt similarity index 100% rename from samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/kotlin/org/openapitools/client/infrastructure/CollectionFormats.kt rename to samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/java/org/openapitools/client/infrastructure/CollectionFormats.kt diff --git a/samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt b/samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/java/org/openapitools/client/infrastructure/LocalDateAdapter.kt similarity index 100% rename from samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt rename to samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/java/org/openapitools/client/infrastructure/LocalDateAdapter.kt diff --git a/samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt b/samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/java/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt similarity index 100% rename from samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt rename to samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/java/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt diff --git a/samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/kotlin/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt b/samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/java/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt similarity index 100% rename from samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/kotlin/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt rename to samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/java/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt diff --git a/samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/kotlin/org/openapitools/client/request/GsonRequest.kt b/samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/java/org/openapitools/client/request/GsonRequest.kt similarity index 100% rename from samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/kotlin/org/openapitools/client/request/GsonRequest.kt rename to samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/java/org/openapitools/client/request/GsonRequest.kt diff --git a/samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/kotlin/org/openapitools/client/request/IRequestFactory.kt b/samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/java/org/openapitools/client/request/IRequestFactory.kt similarity index 100% rename from samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/kotlin/org/openapitools/client/request/IRequestFactory.kt rename to samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/java/org/openapitools/client/request/IRequestFactory.kt diff --git a/samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/kotlin/org/openapitools/client/request/RequestFactory.kt b/samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/java/org/openapitools/client/request/RequestFactory.kt similarity index 100% rename from samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/kotlin/org/openapitools/client/request/RequestFactory.kt rename to samples/client/petstore/kotlin-array-simple-string-jvm-volley/src/main/java/org/openapitools/client/request/RequestFactory.kt diff --git a/samples/client/petstore/kotlin-array-simple-string-multiplatform/.openapi-generator/FILES b/samples/client/petstore/kotlin-array-simple-string-multiplatform/.openapi-generator/FILES index 6d9189fa063f..78f5b4e762f0 100644 --- a/samples/client/petstore/kotlin-array-simple-string-multiplatform/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-array-simple-string-multiplatform/.openapi-generator/FILES @@ -6,22 +6,22 @@ gradle/wrapper/gradle-wrapper.properties gradlew gradlew.bat settings.gradle.kts +src/commonMain/kotlin/org/openapitools/client/apis/DefaultApi.kt +src/commonMain/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt +src/commonMain/kotlin/org/openapitools/client/auth/Authentication.kt +src/commonMain/kotlin/org/openapitools/client/auth/HttpBasicAuth.kt +src/commonMain/kotlin/org/openapitools/client/auth/HttpBearerAuth.kt +src/commonMain/kotlin/org/openapitools/client/auth/OAuth.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/PartConfig.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt src/commonTest/kotlin/util/Coroutine.kt src/iosTest/kotlin/util/Coroutine.kt src/jsTest/kotlin/util/Coroutine.kt src/jvmTest/kotlin/util/Coroutine.kt -src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt -src/main/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt -src/main/kotlin/org/openapitools/client/auth/Authentication.kt -src/main/kotlin/org/openapitools/client/auth/HttpBasicAuth.kt -src/main/kotlin/org/openapitools/client/auth/HttpBearerAuth.kt -src/main/kotlin/org/openapitools/client/auth/OAuth.kt -src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt -src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt -src/main/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt -src/main/kotlin/org/openapitools/client/infrastructure/Bytes.kt -src/main/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt -src/main/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt -src/main/kotlin/org/openapitools/client/infrastructure/PartConfig.kt -src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt -src/main/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt diff --git a/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/DefaultApi.kt b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/DefaultApi.kt new file mode 100644 index 000000000000..7478c1af4ec9 --- /dev/null +++ b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/DefaultApi.kt @@ -0,0 +1,68 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.apis + + +import org.openapitools.client.infrastructure.* +import io.ktor.client.HttpClientConfig +import io.ktor.client.request.forms.formData +import io.ktor.client.engine.HttpClientEngine +import kotlinx.serialization.json.Json +import io.ktor.http.ParametersBuilder +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* + +open class DefaultApi( + baseUrl: String = ApiClient.BASE_URL, + httpClientEngine: HttpClientEngine? = null, + httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, + jsonSerializer: Json = ApiClient.JSON_DEFAULT +) : ApiClient(baseUrl, httpClientEngine, httpClientConfig, jsonSerializer) { + + /** + * + * + * @param ids + * @return void + */ + open suspend fun idsGet(ids: kotlin.collections.List): HttpResponse { + + val localVariableAuthNames = listOf() + + val localVariableBody = + io.ktor.client.utils.EmptyContent + + val localVariableQuery = mutableMapOf>() + val localVariableHeaders = mutableMapOf() + + val localVariableConfig = RequestConfig( + RequestMethod.GET, + "/{ids}".replace("{" + "ids" + "}", ids.joinToString(",")), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = false, + ) + + return request( + localVariableConfig, + localVariableBody, + localVariableAuthNames + ).wrap() + } + + +} diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt similarity index 100% rename from samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt rename to samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/auth/Authentication.kt b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/Authentication.kt similarity index 100% rename from samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/auth/Authentication.kt rename to samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/Authentication.kt diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/auth/HttpBasicAuth.kt b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/HttpBasicAuth.kt similarity index 100% rename from samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/auth/HttpBasicAuth.kt rename to samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/HttpBasicAuth.kt diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/auth/HttpBearerAuth.kt b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/HttpBearerAuth.kt similarity index 100% rename from samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/auth/HttpBearerAuth.kt rename to samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/HttpBearerAuth.kt diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/auth/OAuth.kt b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/OAuth.kt similarity index 100% rename from samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/auth/OAuth.kt rename to samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/OAuth.kt diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt similarity index 100% rename from samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt rename to samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt similarity index 100% rename from samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt rename to samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt similarity index 100% rename from samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt rename to samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/Bytes.kt b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt similarity index 100% rename from samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/Bytes.kt rename to samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt similarity index 100% rename from samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt rename to samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt similarity index 100% rename from samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt rename to samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/PartConfig.kt b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/PartConfig.kt similarity index 100% rename from samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/PartConfig.kt rename to samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/PartConfig.kt diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt similarity index 100% rename from samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt rename to samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt similarity index 100% rename from samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt rename to samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/.openapi-generator/FILES b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/.openapi-generator/FILES index 109097a52c79..b3293eef4edb 100644 --- a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/.openapi-generator/FILES @@ -7,23 +7,23 @@ gradle/wrapper/gradle-wrapper.properties gradlew gradlew.bat settings.gradle.kts +src/commonMain/kotlin/org/openapitools/client/apis/DefaultApi.kt +src/commonMain/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt +src/commonMain/kotlin/org/openapitools/client/auth/Authentication.kt +src/commonMain/kotlin/org/openapitools/client/auth/HttpBasicAuth.kt +src/commonMain/kotlin/org/openapitools/client/auth/HttpBearerAuth.kt +src/commonMain/kotlin/org/openapitools/client/auth/OAuth.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/PartConfig.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt +src/commonMain/kotlin/org/openapitools/client/models/Apa.kt src/commonTest/kotlin/util/Coroutine.kt src/iosTest/kotlin/util/Coroutine.kt src/jsTest/kotlin/util/Coroutine.kt src/jvmTest/kotlin/util/Coroutine.kt -src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt -src/main/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt -src/main/kotlin/org/openapitools/client/auth/Authentication.kt -src/main/kotlin/org/openapitools/client/auth/HttpBasicAuth.kt -src/main/kotlin/org/openapitools/client/auth/HttpBearerAuth.kt -src/main/kotlin/org/openapitools/client/auth/OAuth.kt -src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt -src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt -src/main/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt -src/main/kotlin/org/openapitools/client/infrastructure/Bytes.kt -src/main/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt -src/main/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt -src/main/kotlin/org/openapitools/client/infrastructure/PartConfig.kt -src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt -src/main/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt -src/main/kotlin/org/openapitools/client/models/Apa.kt diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/DefaultApi.kt b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/DefaultApi.kt new file mode 100644 index 000000000000..3ca371d4e091 --- /dev/null +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/DefaultApi.kt @@ -0,0 +1,69 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.apis + +import org.openapitools.client.models.Apa + +import org.openapitools.client.infrastructure.* +import io.ktor.client.HttpClientConfig +import io.ktor.client.request.forms.formData +import io.ktor.client.engine.HttpClientEngine +import kotlinx.serialization.json.Json +import io.ktor.http.ParametersBuilder +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* + +open class DefaultApi( + baseUrl: String = ApiClient.BASE_URL, + httpClientEngine: HttpClientEngine? = null, + httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, + jsonSerializer: Json = ApiClient.JSON_DEFAULT +) : ApiClient(baseUrl, httpClientEngine, httpClientConfig, jsonSerializer) { + + /** + * + * + * @param apa + * @return void + */ + open suspend fun testPost(apa: Apa): HttpResponse { + + val localVariableAuthNames = listOf() + + val localVariableBody = apa + + val localVariableQuery = mutableMapOf>() + val localVariableHeaders = mutableMapOf() + + val localVariableConfig = RequestConfig( + RequestMethod.POST, + "/test", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = false, + ) + + return jsonRequest( + localVariableConfig, + localVariableBody, + localVariableAuthNames + ).wrap() + } + + + +} diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt new file mode 100644 index 000000000000..8bd8b59a8f82 --- /dev/null +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt @@ -0,0 +1,16 @@ +package org.openapitools.client.auth + +class ApiKeyAuth(private val location: String, val paramName: String) : Authentication { + var apiKey: String? = null + var apiKeyPrefix: String? = null + + override fun apply(query: MutableMap>, headers: MutableMap) { + val key: String = apiKey ?: return + val prefix: String? = apiKeyPrefix + val value: String = if (prefix != null) "$prefix $key" else key + when (location) { + "query" -> query[paramName] = listOf(value) + "header" -> headers[paramName] = value + } + } +} diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/Authentication.kt b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/Authentication.kt new file mode 100644 index 000000000000..2c5dfb4acc56 --- /dev/null +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/Authentication.kt @@ -0,0 +1,13 @@ +package org.openapitools.client.auth + +interface Authentication { + + /** + * Apply authentication settings to header and query params. + * + * @param query Query parameters. + * @param headers Header parameters. + */ + fun apply(query: MutableMap>, headers: MutableMap) + +} diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/HttpBasicAuth.kt b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/HttpBasicAuth.kt new file mode 100644 index 000000000000..40276dbb985e --- /dev/null +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/HttpBasicAuth.kt @@ -0,0 +1,17 @@ +package org.openapitools.client.auth + +import io.ktor.util.InternalAPI +import io.ktor.util.encodeBase64 + +class HttpBasicAuth : Authentication { + var username: String? = null + var password: String? = null + + @OptIn(InternalAPI::class) + override fun apply(query: MutableMap>, headers: MutableMap) { + if (username == null && password == null) return + val str = (username ?: "") + ":" + (password ?: "") + val auth = str.encodeBase64() + headers["Authorization"] = "Basic $auth" + } +} diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/HttpBearerAuth.kt b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/HttpBearerAuth.kt new file mode 100644 index 000000000000..a6fb285af5c3 --- /dev/null +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/HttpBearerAuth.kt @@ -0,0 +1,14 @@ +package org.openapitools.client.auth + +class HttpBearerAuth(private val scheme: String?) : Authentication { + var bearerToken: String? = null + + override fun apply(query: MutableMap>, headers: MutableMap) { + val token: String = bearerToken ?: return + headers["Authorization"] = (if (scheme != null) upperCaseBearer(scheme)!! + " " else "") + token + } + + private fun upperCaseBearer(scheme: String): String? { + return if ("bearer".equals(scheme, ignoreCase = true)) "Bearer" else scheme + } +} diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/OAuth.kt b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/OAuth.kt new file mode 100644 index 000000000000..0e8f30f39383 --- /dev/null +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/OAuth.kt @@ -0,0 +1,10 @@ +package org.openapitools.client.auth + +class OAuth : Authentication { + var accessToken: String? = null + + override fun apply(query: MutableMap>, headers: MutableMap) { + val token: String = accessToken ?: return + headers["Authorization"] = "Bearer $token" + } +} diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt new file mode 100644 index 000000000000..a4a4491eac0d --- /dev/null +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt @@ -0,0 +1,23 @@ +package org.openapitools.client.infrastructure + +typealias MultiValueMap = MutableMap> + +fun collectionDelimiter(collectionFormat: String) = when(collectionFormat) { + "csv" -> "," + "tsv" -> "\t" + "pipe" -> "|" + "space" -> " " + else -> "" +} + +val defaultMultiValueConverter: (item: Any?) -> String = { item -> "$item" } + +fun toMultiValue(items: Array, collectionFormat: String, map: (item: T) -> String = defaultMultiValueConverter) + = toMultiValue(items.asIterable(), collectionFormat, map) + +fun toMultiValue(items: Iterable, collectionFormat: String, map: (item: T) -> String = defaultMultiValueConverter): List { + return when(collectionFormat) { + "multi" -> items.map(map) + else -> listOf(items.joinToString(separator = collectionDelimiter(collectionFormat), transform = map)) + } +} diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt new file mode 100644 index 000000000000..789d093c0c7a --- /dev/null +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -0,0 +1,172 @@ +package org.openapitools.client.infrastructure + +import io.ktor.client.HttpClient +import io.ktor.client.HttpClientConfig +import io.ktor.client.engine.HttpClientEngine +import io.ktor.client.plugins.contentnegotiation.ContentNegotiation +import io.ktor.client.request.* +import io.ktor.client.request.forms.FormDataContent +import io.ktor.client.request.forms.MultiPartFormDataContent +import io.ktor.client.request.header +import io.ktor.client.request.parameter +import io.ktor.client.statement.HttpResponse +import io.ktor.serialization.kotlinx.json.json +import io.ktor.http.* +import io.ktor.http.content.PartData +import kotlin.Unit +import kotlinx.serialization.json.Json + +import org.openapitools.client.auth.* + +open class ApiClient( + private val baseUrl: String, + httpClientEngine: HttpClientEngine?, + httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, + private val jsonBlock: Json +) { + + private val clientConfig: (HttpClientConfig<*>) -> Unit by lazy { + { + it.install(ContentNegotiation) { json(jsonBlock) } + httpClientConfig?.invoke(it) + } + } + + private val client: HttpClient by lazy { + httpClientEngine?.let { HttpClient(it, clientConfig) } ?: HttpClient(clientConfig) + } + + private val authentications: kotlin.collections.Map? = null + + companion object { + const val BASE_URL = "http://localhost" + val JSON_DEFAULT = Json { + ignoreUnknownKeys = true + prettyPrint = true + isLenient = true + } + protected val UNSAFE_HEADERS = listOf(HttpHeaders.ContentType) + } + + /** + * Set the username for the first HTTP basic authentication. + * + * @param username Username + */ + fun setUsername(username: String) { + val auth = authentications?.values?.firstOrNull { it is HttpBasicAuth } as HttpBasicAuth? + ?: throw Exception("No HTTP basic authentication configured") + auth.username = username + } + + /** + * Set the password for the first HTTP basic authentication. + * + * @param password Password + */ + fun setPassword(password: String) { + val auth = authentications?.values?.firstOrNull { it is HttpBasicAuth } as HttpBasicAuth? + ?: throw Exception("No HTTP basic authentication configured") + auth.password = password + } + + /** + * Set the API key value for the first API key authentication. + * + * @param apiKey API key + * @param paramName The name of the API key parameter, or null or set the first key. + */ + fun setApiKey(apiKey: String, paramName: String? = null) { + val auth = authentications?.values?.firstOrNull { it is ApiKeyAuth && (paramName == null || paramName == it.paramName)} as ApiKeyAuth? + ?: throw Exception("No API key authentication configured") + auth.apiKey = apiKey + } + + /** + * Set the API key prefix for the first API key authentication. + * + * @param apiKeyPrefix API key prefix + * @param paramName The name of the API key parameter, or null or set the first key. + */ + fun setApiKeyPrefix(apiKeyPrefix: String, paramName: String? = null) { + val auth = authentications?.values?.firstOrNull { it is ApiKeyAuth && (paramName == null || paramName == it.paramName) } as ApiKeyAuth? + ?: throw Exception("No API key authentication configured") + auth.apiKeyPrefix = apiKeyPrefix + } + + /** + * Set the access token for the first OAuth2 authentication. + * + * @param accessToken Access token + */ + fun setAccessToken(accessToken: String) { + val auth = authentications?.values?.firstOrNull { it is OAuth } as OAuth? + ?: throw Exception("No OAuth2 authentication configured") + auth.accessToken = accessToken + } + + /** + * Set the access token for the first Bearer authentication. + * + * @param bearerToken The bearer token. + */ + fun setBearerToken(bearerToken: String) { + val auth = authentications?.values?.firstOrNull { it is HttpBearerAuth } as HttpBearerAuth? + ?: throw Exception("No Bearer authentication configured") + auth.bearerToken = bearerToken + } + + protected suspend fun multipartFormRequest(requestConfig: RequestConfig, body: kotlin.collections.List?, authNames: kotlin.collections.List): HttpResponse { + return request(requestConfig, MultiPartFormDataContent(body ?: listOf()), authNames) + } + + protected suspend fun urlEncodedFormRequest(requestConfig: RequestConfig, body: Parameters?, authNames: kotlin.collections.List): HttpResponse { + return request(requestConfig, FormDataContent(body ?: Parameters.Empty), authNames) + } + + protected suspend fun jsonRequest(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse = request(requestConfig, body, authNames) + + protected suspend fun request(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse { + requestConfig.updateForAuth(authNames) + val headers = requestConfig.headers + + return client.request { + this.url { + this.takeFrom(URLBuilder(baseUrl)) + appendPath(requestConfig.path.trimStart('/').split('/')) + requestConfig.query.forEach { query -> + query.value.forEach { value -> + parameter(query.key, value) + } + } + } + this.method = requestConfig.method.httpMethod + headers.filter { header -> !UNSAFE_HEADERS.contains(header.key) }.forEach { header -> this.header(header.key, header.value) } + if (requestConfig.method in listOf(RequestMethod.PUT, RequestMethod.POST, RequestMethod.PATCH)) { + this.setBody(body) + } + } + } + + private fun RequestConfig.updateForAuth(authNames: kotlin.collections.List) { + for (authName in authNames) { + val auth = authentications?.get(authName) ?: throw Exception("Authentication undefined: $authName") + auth.apply(query, headers) + } + } + + private fun URLBuilder.appendPath(components: kotlin.collections.List): URLBuilder = apply { + encodedPath = encodedPath.trimEnd('/') + components.joinToString("/", prefix = "/") { it.encodeURLQueryComponent() } + } + + private val RequestMethod.httpMethod: HttpMethod + get() = when (this) { + RequestMethod.DELETE -> HttpMethod.Delete + RequestMethod.GET -> HttpMethod.Get + RequestMethod.HEAD -> HttpMethod.Head + RequestMethod.PATCH -> HttpMethod.Patch + RequestMethod.PUT -> HttpMethod.Put + RequestMethod.POST -> HttpMethod.Post + RequestMethod.OPTIONS -> HttpMethod.Options + } +} diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt new file mode 100644 index 000000000000..5aeea0894894 --- /dev/null +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt @@ -0,0 +1,30 @@ +package org.openapitools.client.infrastructure + +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* + +@Serializable +class Base64ByteArray(val value: ByteArray) { + @Serializer(Base64ByteArray::class) + companion object : KSerializer { + override val descriptor = PrimitiveSerialDescriptor("Base64ByteArray", PrimitiveKind.STRING) + override fun serialize(encoder: Encoder, obj: Base64ByteArray) = encoder.encodeString(obj.value.encodeBase64()) + override fun deserialize(decoder: Decoder) = Base64ByteArray(decoder.decodeString().decodeBase64Bytes()) + } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other == null || this::class != other::class) return false + other as Base64ByteArray + return value.contentEquals(other.value) + } + + override fun hashCode(): Int { + return value.contentHashCode() + } + + override fun toString(): String { + return "Base64ByteArray(${hex(value)})" + } +} diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt new file mode 100644 index 000000000000..0ff85787389a --- /dev/null +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt @@ -0,0 +1,100 @@ +package org.openapitools.client.infrastructure + +import io.ktor.utils.io.core.* +import kotlin.experimental.and + +private val digits = "0123456789abcdef".toCharArray() +private const val BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" +private const val BASE64_MASK: Byte = 0x3f +private const val BASE64_PAD = '=' +private val BASE64_INVERSE_ALPHABET = IntArray(256) { BASE64_ALPHABET.indexOf(it.toChar()) } + +private fun String.toCharArray(): CharArray = CharArray(length) { get(it) } +private fun ByteArray.clearFrom(from: Int) = (from until size).forEach { this[it] = 0 } +private fun Int.toBase64(): Char = BASE64_ALPHABET[this] +private fun Byte.fromBase64(): Byte = BASE64_INVERSE_ALPHABET[toInt() and 0xff].toByte() and BASE64_MASK +internal fun ByteArray.encodeBase64(): String = buildPacket { writeFully(this@encodeBase64) }.encodeBase64() +internal fun String.decodeBase64Bytes(): ByteArray = buildPacket { dropLastWhile { it == BASE64_PAD } }.decodeBase64Bytes().readBytes() + +/** + * Encode [bytes] as a HEX string with no spaces, newlines and `0x` prefixes. + * + * Taken from https://github.com/ktorio/ktor/blob/master/ktor-utils/common/src/io/ktor/util/Crypto.kt + */ +internal fun hex(bytes: ByteArray): String { + val result = CharArray(bytes.size * 2) + var resultIndex = 0 + val digits = digits + + for (element in bytes) { + val b = element.toInt() and 0xff + result[resultIndex++] = digits[b shr 4] + result[resultIndex++] = digits[b and 0x0f] + } + + return result.concatToString() +} + +/** + * Decode bytes from HEX string. It should be no spaces and `0x` prefixes. + * + * Taken from https://github.com/ktorio/ktor/blob/master/ktor-utils/common/src/io/ktor/util/Crypto.kt + */ +internal fun hex(s: String): ByteArray { + val result = ByteArray(s.length / 2) + for (idx in result.indices) { + val srcIdx = idx * 2 + val high = s[srcIdx].toString().toInt(16) shl 4 + val low = s[srcIdx + 1].toString().toInt(16) + result[idx] = (high or low).toByte() + } + + return result +} + +/** + * Encode [ByteReadPacket] in base64 format. + * + * Taken from https://github.com/ktorio/ktor/blob/424d1d2cfaa3281302c60af9500f738c8c2fc846/ktor-utils/common/src/io/ktor/util/Base64.kt + */ +private fun ByteReadPacket.encodeBase64(): String = buildString { + val data = ByteArray(3) + while (remaining > 0) { + val read = readAvailable(data) + data.clearFrom(read) + + val padSize = (data.size - read) * 8 / 6 + val chunk = ((data[0].toInt() and 0xFF) shl 16) or + ((data[1].toInt() and 0xFF) shl 8) or + (data[2].toInt() and 0xFF) + + for (index in data.size downTo padSize) { + val char = (chunk shr (6 * index)) and BASE64_MASK.toInt() + append(char.toBase64()) + } + + repeat(padSize) { append(BASE64_PAD) } + } +} + +/** + * Decode [ByteReadPacket] from base64 format + * + * Taken from https://github.com/ktorio/ktor/blob/424d1d2cfaa3281302c60af9500f738c8c2fc846/ktor-utils/common/src/io/ktor/util/Base64.kt + */ +private fun ByteReadPacket.decodeBase64Bytes(): Input = buildPacket { + val data = ByteArray(4) + + while (remaining > 0) { + val read = readAvailable(data) + + val chunk = data.foldIndexed(0) { index, result, current -> + result or (current.fromBase64().toInt() shl ((3 - index) * 6)) + } + + for (index in data.size - 2 downTo (data.size - read)) { + val origin = (chunk shr (8 * index)) and 0xff + writeByte(origin.toByte()) + } + } +} diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt new file mode 100644 index 000000000000..4285d605ea62 --- /dev/null +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt @@ -0,0 +1,51 @@ +package org.openapitools.client.infrastructure + +import io.ktor.http.Headers +import io.ktor.http.isSuccess +import io.ktor.util.reflect.TypeInfo +import io.ktor.util.reflect.typeInfo + +open class HttpResponse(val response: io.ktor.client.statement.HttpResponse, val provider: BodyProvider) { + val status: Int = response.status.value + val success: Boolean = response.status.isSuccess() + val headers: Map> = response.headers.mapEntries() + suspend fun body(): T = provider.body(response) + suspend fun typedBody(type: TypeInfo): V = provider.typedBody(response, type) + + companion object { + private fun Headers.mapEntries(): Map> { + val result = mutableMapOf>() + entries().forEach { result[it.key] = it.value } + return result + } + } +} + +interface BodyProvider { + suspend fun body(response: io.ktor.client.statement.HttpResponse): T + suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V +} + +class TypedBodyProvider(private val type: TypeInfo) : BodyProvider { + @Suppress("UNCHECKED_CAST") + override suspend fun body(response: io.ktor.client.statement.HttpResponse): T = + response.call.body(type) as T + + @Suppress("UNCHECKED_CAST") + override suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V = + response.call.body(type) as V +} + +class MappedBodyProvider(private val provider: BodyProvider, private val block: S.() -> T) : BodyProvider { + override suspend fun body(response: io.ktor.client.statement.HttpResponse): T = + block(provider.body(response)) + + override suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V = + provider.typedBody(response, type) +} + +inline fun io.ktor.client.statement.HttpResponse.wrap(): HttpResponse = + HttpResponse(this, TypedBodyProvider(typeInfo())) + +fun HttpResponse.map(block: T.() -> V): HttpResponse = + HttpResponse(response, MappedBodyProvider(provider, block)) diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt new file mode 100644 index 000000000000..d10d7c506523 --- /dev/null +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt @@ -0,0 +1,30 @@ +package org.openapitools.client.infrastructure + +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* + +@Serializable +class OctetByteArray(val value: ByteArray) { + @Serializer(OctetByteArray::class) + companion object : KSerializer { + override val descriptor = PrimitiveSerialDescriptor("OctetByteArray", PrimitiveKind.STRING) + override fun serialize(encoder: Encoder, obj: OctetByteArray) = encoder.encodeString(hex(obj.value)) + override fun deserialize(decoder: Decoder) = OctetByteArray(hex(decoder.decodeString())) + } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other == null || this::class != other::class) return false + other as OctetByteArray + return value.contentEquals(other.value) + } + + override fun hashCode(): Int { + return value.contentHashCode() + } + + override fun toString(): String { + return "OctetByteArray(${hex(value)})" + } +} diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/PartConfig.kt b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/PartConfig.kt new file mode 100644 index 000000000000..be00e38fbaee --- /dev/null +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/PartConfig.kt @@ -0,0 +1,11 @@ +package org.openapitools.client.infrastructure + +/** + * Defines a config object for a given part of a multi-part request. + * NOTE: Headers is a Map because rfc2616 defines + * multi-valued headers as csv-only. + */ +data class PartConfig( + val headers: MutableMap = mutableMapOf(), + val body: T? = null +) diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt new file mode 100644 index 000000000000..c3518a2d173c --- /dev/null +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -0,0 +1,18 @@ +package org.openapitools.client.infrastructure + +/** + * Defines a config object for a given request. + * NOTE: This object doesn't include 'body' because it + * allows for caching of the constructed object + * for many request definitions. + * NOTE: Headers is a Map because rfc2616 defines + * multi-valued headers as csv-only. + */ +data class RequestConfig( + val method: RequestMethod, + val path: String, + val headers: MutableMap = mutableMapOf(), + val query: MutableMap> = mutableMapOf(), + val requiresAuthentication: Boolean, + val body: T? = null +) diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt new file mode 100644 index 000000000000..beb56f07cdde --- /dev/null +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt @@ -0,0 +1,8 @@ +package org.openapitools.client.infrastructure + +/** + * Provides enumerated HTTP verbs + */ +enum class RequestMethod { + GET, DELETE, HEAD, OPTIONS, PATCH, POST, PUT +} diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Apa.kt b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Apa.kt new file mode 100644 index 000000000000..08e06c597b42 --- /dev/null +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Apa.kt @@ -0,0 +1,51 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + + +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* + +/** + * + * + * @param bepa + * @param cepa + * @param depa + * @param epa + * @param fepa + * @param gepa + */ +@Serializable + +data class Apa ( + + @SerialName(value = "bepa") @Required val bepa: kotlin.Double = (0).toDouble(), + + @SerialName(value = "cepa") @Required val cepa: kotlin.Double = (6.28318).toDouble(), + + @SerialName(value = "depa") val depa: kotlin.Double? = (71).toDouble(), + + @SerialName(value = "epa") val epa: kotlin.Double? = (-71).toDouble(), + + @Deprecated(message = "This property is deprecated.") + @SerialName(value = "fepa") val fepa: kotlin.Double? = (100).toDouble(), + + @SerialName(value = "gepa") val gepa: kotlin.Double? = null + +) + diff --git a/samples/client/petstore/kotlin-default-values-jvm-volley/.openapi-generator/FILES b/samples/client/petstore/kotlin-default-values-jvm-volley/.openapi-generator/FILES index 921e2bcf09d1..a0ca34edb5c8 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-volley/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-default-values-jvm-volley/.openapi-generator/FILES @@ -9,16 +9,16 @@ gradlew gradlew.bat settings.gradle src/main/AndroidManifest.xml -src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt -src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt -src/main/kotlin/org/openapitools/client/infrastructure/CollectionFormats.kt -src/main/kotlin/org/openapitools/client/infrastructure/CollectionFormats.kt -src/main/kotlin/org/openapitools/client/infrastructure/ITransformForStorage.kt -src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt -src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt -src/main/kotlin/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt -src/main/kotlin/org/openapitools/client/models/Apa.kt -src/main/kotlin/org/openapitools/client/models/room/ApaRoomModel.kt -src/main/kotlin/org/openapitools/client/request/GsonRequest.kt -src/main/kotlin/org/openapitools/client/request/IRequestFactory.kt -src/main/kotlin/org/openapitools/client/request/RequestFactory.kt +src/main/java/org/openapitools/client/apis/DefaultApi.kt +src/main/java/org/openapitools/client/infrastructure/ByteArrayAdapter.kt +src/main/java/org/openapitools/client/infrastructure/CollectionFormats.kt +src/main/java/org/openapitools/client/infrastructure/CollectionFormats.kt +src/main/java/org/openapitools/client/infrastructure/ITransformForStorage.kt +src/main/java/org/openapitools/client/infrastructure/LocalDateAdapter.kt +src/main/java/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt +src/main/java/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt +src/main/java/org/openapitools/client/models/Apa.kt +src/main/java/org/openapitools/client/models/room/ApaRoomModel.kt +src/main/java/org/openapitools/client/request/GsonRequest.kt +src/main/java/org/openapitools/client/request/IRequestFactory.kt +src/main/java/org/openapitools/client/request/RequestFactory.kt diff --git a/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt b/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/java/org/openapitools/client/apis/DefaultApi.kt similarity index 100% rename from samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt rename to samples/client/petstore/kotlin-default-values-jvm-volley/src/main/java/org/openapitools/client/apis/DefaultApi.kt diff --git a/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt b/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/java/org/openapitools/client/infrastructure/ByteArrayAdapter.kt similarity index 100% rename from samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt rename to samples/client/petstore/kotlin-default-values-jvm-volley/src/main/java/org/openapitools/client/infrastructure/ByteArrayAdapter.kt diff --git a/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/infrastructure/CollectionFormats.kt b/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/java/org/openapitools/client/infrastructure/CollectionFormats.kt similarity index 100% rename from samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/infrastructure/CollectionFormats.kt rename to samples/client/petstore/kotlin-default-values-jvm-volley/src/main/java/org/openapitools/client/infrastructure/CollectionFormats.kt diff --git a/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/infrastructure/ITransformForStorage.kt b/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/java/org/openapitools/client/infrastructure/ITransformForStorage.kt similarity index 100% rename from samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/infrastructure/ITransformForStorage.kt rename to samples/client/petstore/kotlin-default-values-jvm-volley/src/main/java/org/openapitools/client/infrastructure/ITransformForStorage.kt diff --git a/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt b/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/java/org/openapitools/client/infrastructure/LocalDateAdapter.kt similarity index 100% rename from samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt rename to samples/client/petstore/kotlin-default-values-jvm-volley/src/main/java/org/openapitools/client/infrastructure/LocalDateAdapter.kt diff --git a/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt b/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/java/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt similarity index 100% rename from samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt rename to samples/client/petstore/kotlin-default-values-jvm-volley/src/main/java/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt diff --git a/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt b/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/java/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt similarity index 100% rename from samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt rename to samples/client/petstore/kotlin-default-values-jvm-volley/src/main/java/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt diff --git a/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/models/Apa.kt b/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/java/org/openapitools/client/models/Apa.kt similarity index 100% rename from samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/models/Apa.kt rename to samples/client/petstore/kotlin-default-values-jvm-volley/src/main/java/org/openapitools/client/models/Apa.kt diff --git a/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/models/room/ApaRoomModel.kt b/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/java/org/openapitools/client/models/room/ApaRoomModel.kt similarity index 100% rename from samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/models/room/ApaRoomModel.kt rename to samples/client/petstore/kotlin-default-values-jvm-volley/src/main/java/org/openapitools/client/models/room/ApaRoomModel.kt diff --git a/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/request/GsonRequest.kt b/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/java/org/openapitools/client/request/GsonRequest.kt similarity index 100% rename from samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/request/GsonRequest.kt rename to samples/client/petstore/kotlin-default-values-jvm-volley/src/main/java/org/openapitools/client/request/GsonRequest.kt diff --git a/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/request/IRequestFactory.kt b/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/java/org/openapitools/client/request/IRequestFactory.kt similarity index 100% rename from samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/request/IRequestFactory.kt rename to samples/client/petstore/kotlin-default-values-jvm-volley/src/main/java/org/openapitools/client/request/IRequestFactory.kt diff --git a/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/request/RequestFactory.kt b/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/java/org/openapitools/client/request/RequestFactory.kt similarity index 100% rename from samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/request/RequestFactory.kt rename to samples/client/petstore/kotlin-default-values-jvm-volley/src/main/java/org/openapitools/client/request/RequestFactory.kt diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/.openapi-generator/FILES b/samples/client/petstore/kotlin-default-values-multiplatform/.openapi-generator/FILES index 109097a52c79..b3293eef4edb 100644 --- a/samples/client/petstore/kotlin-default-values-multiplatform/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-default-values-multiplatform/.openapi-generator/FILES @@ -7,23 +7,23 @@ gradle/wrapper/gradle-wrapper.properties gradlew gradlew.bat settings.gradle.kts +src/commonMain/kotlin/org/openapitools/client/apis/DefaultApi.kt +src/commonMain/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt +src/commonMain/kotlin/org/openapitools/client/auth/Authentication.kt +src/commonMain/kotlin/org/openapitools/client/auth/HttpBasicAuth.kt +src/commonMain/kotlin/org/openapitools/client/auth/HttpBearerAuth.kt +src/commonMain/kotlin/org/openapitools/client/auth/OAuth.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/PartConfig.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt +src/commonMain/kotlin/org/openapitools/client/models/Apa.kt src/commonTest/kotlin/util/Coroutine.kt src/iosTest/kotlin/util/Coroutine.kt src/jsTest/kotlin/util/Coroutine.kt src/jvmTest/kotlin/util/Coroutine.kt -src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt -src/main/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt -src/main/kotlin/org/openapitools/client/auth/Authentication.kt -src/main/kotlin/org/openapitools/client/auth/HttpBasicAuth.kt -src/main/kotlin/org/openapitools/client/auth/HttpBearerAuth.kt -src/main/kotlin/org/openapitools/client/auth/OAuth.kt -src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt -src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt -src/main/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt -src/main/kotlin/org/openapitools/client/infrastructure/Bytes.kt -src/main/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt -src/main/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt -src/main/kotlin/org/openapitools/client/infrastructure/PartConfig.kt -src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt -src/main/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt -src/main/kotlin/org/openapitools/client/models/Apa.kt diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/DefaultApi.kt similarity index 100% rename from samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt rename to samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/DefaultApi.kt diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt new file mode 100644 index 000000000000..8bd8b59a8f82 --- /dev/null +++ b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt @@ -0,0 +1,16 @@ +package org.openapitools.client.auth + +class ApiKeyAuth(private val location: String, val paramName: String) : Authentication { + var apiKey: String? = null + var apiKeyPrefix: String? = null + + override fun apply(query: MutableMap>, headers: MutableMap) { + val key: String = apiKey ?: return + val prefix: String? = apiKeyPrefix + val value: String = if (prefix != null) "$prefix $key" else key + when (location) { + "query" -> query[paramName] = listOf(value) + "header" -> headers[paramName] = value + } + } +} diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/Authentication.kt b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/Authentication.kt new file mode 100644 index 000000000000..2c5dfb4acc56 --- /dev/null +++ b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/Authentication.kt @@ -0,0 +1,13 @@ +package org.openapitools.client.auth + +interface Authentication { + + /** + * Apply authentication settings to header and query params. + * + * @param query Query parameters. + * @param headers Header parameters. + */ + fun apply(query: MutableMap>, headers: MutableMap) + +} diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/HttpBasicAuth.kt b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/HttpBasicAuth.kt new file mode 100644 index 000000000000..40276dbb985e --- /dev/null +++ b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/HttpBasicAuth.kt @@ -0,0 +1,17 @@ +package org.openapitools.client.auth + +import io.ktor.util.InternalAPI +import io.ktor.util.encodeBase64 + +class HttpBasicAuth : Authentication { + var username: String? = null + var password: String? = null + + @OptIn(InternalAPI::class) + override fun apply(query: MutableMap>, headers: MutableMap) { + if (username == null && password == null) return + val str = (username ?: "") + ":" + (password ?: "") + val auth = str.encodeBase64() + headers["Authorization"] = "Basic $auth" + } +} diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/HttpBearerAuth.kt b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/HttpBearerAuth.kt new file mode 100644 index 000000000000..a6fb285af5c3 --- /dev/null +++ b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/HttpBearerAuth.kt @@ -0,0 +1,14 @@ +package org.openapitools.client.auth + +class HttpBearerAuth(private val scheme: String?) : Authentication { + var bearerToken: String? = null + + override fun apply(query: MutableMap>, headers: MutableMap) { + val token: String = bearerToken ?: return + headers["Authorization"] = (if (scheme != null) upperCaseBearer(scheme)!! + " " else "") + token + } + + private fun upperCaseBearer(scheme: String): String? { + return if ("bearer".equals(scheme, ignoreCase = true)) "Bearer" else scheme + } +} diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/OAuth.kt b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/OAuth.kt new file mode 100644 index 000000000000..0e8f30f39383 --- /dev/null +++ b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/auth/OAuth.kt @@ -0,0 +1,10 @@ +package org.openapitools.client.auth + +class OAuth : Authentication { + var accessToken: String? = null + + override fun apply(query: MutableMap>, headers: MutableMap) { + val token: String = accessToken ?: return + headers["Authorization"] = "Bearer $token" + } +} diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt new file mode 100644 index 000000000000..a4a4491eac0d --- /dev/null +++ b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt @@ -0,0 +1,23 @@ +package org.openapitools.client.infrastructure + +typealias MultiValueMap = MutableMap> + +fun collectionDelimiter(collectionFormat: String) = when(collectionFormat) { + "csv" -> "," + "tsv" -> "\t" + "pipe" -> "|" + "space" -> " " + else -> "" +} + +val defaultMultiValueConverter: (item: Any?) -> String = { item -> "$item" } + +fun toMultiValue(items: Array, collectionFormat: String, map: (item: T) -> String = defaultMultiValueConverter) + = toMultiValue(items.asIterable(), collectionFormat, map) + +fun toMultiValue(items: Iterable, collectionFormat: String, map: (item: T) -> String = defaultMultiValueConverter): List { + return when(collectionFormat) { + "multi" -> items.map(map) + else -> listOf(items.joinToString(separator = collectionDelimiter(collectionFormat), transform = map)) + } +} diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt new file mode 100644 index 000000000000..789d093c0c7a --- /dev/null +++ b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -0,0 +1,172 @@ +package org.openapitools.client.infrastructure + +import io.ktor.client.HttpClient +import io.ktor.client.HttpClientConfig +import io.ktor.client.engine.HttpClientEngine +import io.ktor.client.plugins.contentnegotiation.ContentNegotiation +import io.ktor.client.request.* +import io.ktor.client.request.forms.FormDataContent +import io.ktor.client.request.forms.MultiPartFormDataContent +import io.ktor.client.request.header +import io.ktor.client.request.parameter +import io.ktor.client.statement.HttpResponse +import io.ktor.serialization.kotlinx.json.json +import io.ktor.http.* +import io.ktor.http.content.PartData +import kotlin.Unit +import kotlinx.serialization.json.Json + +import org.openapitools.client.auth.* + +open class ApiClient( + private val baseUrl: String, + httpClientEngine: HttpClientEngine?, + httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, + private val jsonBlock: Json +) { + + private val clientConfig: (HttpClientConfig<*>) -> Unit by lazy { + { + it.install(ContentNegotiation) { json(jsonBlock) } + httpClientConfig?.invoke(it) + } + } + + private val client: HttpClient by lazy { + httpClientEngine?.let { HttpClient(it, clientConfig) } ?: HttpClient(clientConfig) + } + + private val authentications: kotlin.collections.Map? = null + + companion object { + const val BASE_URL = "http://localhost" + val JSON_DEFAULT = Json { + ignoreUnknownKeys = true + prettyPrint = true + isLenient = true + } + protected val UNSAFE_HEADERS = listOf(HttpHeaders.ContentType) + } + + /** + * Set the username for the first HTTP basic authentication. + * + * @param username Username + */ + fun setUsername(username: String) { + val auth = authentications?.values?.firstOrNull { it is HttpBasicAuth } as HttpBasicAuth? + ?: throw Exception("No HTTP basic authentication configured") + auth.username = username + } + + /** + * Set the password for the first HTTP basic authentication. + * + * @param password Password + */ + fun setPassword(password: String) { + val auth = authentications?.values?.firstOrNull { it is HttpBasicAuth } as HttpBasicAuth? + ?: throw Exception("No HTTP basic authentication configured") + auth.password = password + } + + /** + * Set the API key value for the first API key authentication. + * + * @param apiKey API key + * @param paramName The name of the API key parameter, or null or set the first key. + */ + fun setApiKey(apiKey: String, paramName: String? = null) { + val auth = authentications?.values?.firstOrNull { it is ApiKeyAuth && (paramName == null || paramName == it.paramName)} as ApiKeyAuth? + ?: throw Exception("No API key authentication configured") + auth.apiKey = apiKey + } + + /** + * Set the API key prefix for the first API key authentication. + * + * @param apiKeyPrefix API key prefix + * @param paramName The name of the API key parameter, or null or set the first key. + */ + fun setApiKeyPrefix(apiKeyPrefix: String, paramName: String? = null) { + val auth = authentications?.values?.firstOrNull { it is ApiKeyAuth && (paramName == null || paramName == it.paramName) } as ApiKeyAuth? + ?: throw Exception("No API key authentication configured") + auth.apiKeyPrefix = apiKeyPrefix + } + + /** + * Set the access token for the first OAuth2 authentication. + * + * @param accessToken Access token + */ + fun setAccessToken(accessToken: String) { + val auth = authentications?.values?.firstOrNull { it is OAuth } as OAuth? + ?: throw Exception("No OAuth2 authentication configured") + auth.accessToken = accessToken + } + + /** + * Set the access token for the first Bearer authentication. + * + * @param bearerToken The bearer token. + */ + fun setBearerToken(bearerToken: String) { + val auth = authentications?.values?.firstOrNull { it is HttpBearerAuth } as HttpBearerAuth? + ?: throw Exception("No Bearer authentication configured") + auth.bearerToken = bearerToken + } + + protected suspend fun multipartFormRequest(requestConfig: RequestConfig, body: kotlin.collections.List?, authNames: kotlin.collections.List): HttpResponse { + return request(requestConfig, MultiPartFormDataContent(body ?: listOf()), authNames) + } + + protected suspend fun urlEncodedFormRequest(requestConfig: RequestConfig, body: Parameters?, authNames: kotlin.collections.List): HttpResponse { + return request(requestConfig, FormDataContent(body ?: Parameters.Empty), authNames) + } + + protected suspend fun jsonRequest(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse = request(requestConfig, body, authNames) + + protected suspend fun request(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse { + requestConfig.updateForAuth(authNames) + val headers = requestConfig.headers + + return client.request { + this.url { + this.takeFrom(URLBuilder(baseUrl)) + appendPath(requestConfig.path.trimStart('/').split('/')) + requestConfig.query.forEach { query -> + query.value.forEach { value -> + parameter(query.key, value) + } + } + } + this.method = requestConfig.method.httpMethod + headers.filter { header -> !UNSAFE_HEADERS.contains(header.key) }.forEach { header -> this.header(header.key, header.value) } + if (requestConfig.method in listOf(RequestMethod.PUT, RequestMethod.POST, RequestMethod.PATCH)) { + this.setBody(body) + } + } + } + + private fun RequestConfig.updateForAuth(authNames: kotlin.collections.List) { + for (authName in authNames) { + val auth = authentications?.get(authName) ?: throw Exception("Authentication undefined: $authName") + auth.apply(query, headers) + } + } + + private fun URLBuilder.appendPath(components: kotlin.collections.List): URLBuilder = apply { + encodedPath = encodedPath.trimEnd('/') + components.joinToString("/", prefix = "/") { it.encodeURLQueryComponent() } + } + + private val RequestMethod.httpMethod: HttpMethod + get() = when (this) { + RequestMethod.DELETE -> HttpMethod.Delete + RequestMethod.GET -> HttpMethod.Get + RequestMethod.HEAD -> HttpMethod.Head + RequestMethod.PATCH -> HttpMethod.Patch + RequestMethod.PUT -> HttpMethod.Put + RequestMethod.POST -> HttpMethod.Post + RequestMethod.OPTIONS -> HttpMethod.Options + } +} diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt new file mode 100644 index 000000000000..5aeea0894894 --- /dev/null +++ b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt @@ -0,0 +1,30 @@ +package org.openapitools.client.infrastructure + +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* + +@Serializable +class Base64ByteArray(val value: ByteArray) { + @Serializer(Base64ByteArray::class) + companion object : KSerializer { + override val descriptor = PrimitiveSerialDescriptor("Base64ByteArray", PrimitiveKind.STRING) + override fun serialize(encoder: Encoder, obj: Base64ByteArray) = encoder.encodeString(obj.value.encodeBase64()) + override fun deserialize(decoder: Decoder) = Base64ByteArray(decoder.decodeString().decodeBase64Bytes()) + } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other == null || this::class != other::class) return false + other as Base64ByteArray + return value.contentEquals(other.value) + } + + override fun hashCode(): Int { + return value.contentHashCode() + } + + override fun toString(): String { + return "Base64ByteArray(${hex(value)})" + } +} diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt new file mode 100644 index 000000000000..0ff85787389a --- /dev/null +++ b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt @@ -0,0 +1,100 @@ +package org.openapitools.client.infrastructure + +import io.ktor.utils.io.core.* +import kotlin.experimental.and + +private val digits = "0123456789abcdef".toCharArray() +private const val BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" +private const val BASE64_MASK: Byte = 0x3f +private const val BASE64_PAD = '=' +private val BASE64_INVERSE_ALPHABET = IntArray(256) { BASE64_ALPHABET.indexOf(it.toChar()) } + +private fun String.toCharArray(): CharArray = CharArray(length) { get(it) } +private fun ByteArray.clearFrom(from: Int) = (from until size).forEach { this[it] = 0 } +private fun Int.toBase64(): Char = BASE64_ALPHABET[this] +private fun Byte.fromBase64(): Byte = BASE64_INVERSE_ALPHABET[toInt() and 0xff].toByte() and BASE64_MASK +internal fun ByteArray.encodeBase64(): String = buildPacket { writeFully(this@encodeBase64) }.encodeBase64() +internal fun String.decodeBase64Bytes(): ByteArray = buildPacket { dropLastWhile { it == BASE64_PAD } }.decodeBase64Bytes().readBytes() + +/** + * Encode [bytes] as a HEX string with no spaces, newlines and `0x` prefixes. + * + * Taken from https://github.com/ktorio/ktor/blob/master/ktor-utils/common/src/io/ktor/util/Crypto.kt + */ +internal fun hex(bytes: ByteArray): String { + val result = CharArray(bytes.size * 2) + var resultIndex = 0 + val digits = digits + + for (element in bytes) { + val b = element.toInt() and 0xff + result[resultIndex++] = digits[b shr 4] + result[resultIndex++] = digits[b and 0x0f] + } + + return result.concatToString() +} + +/** + * Decode bytes from HEX string. It should be no spaces and `0x` prefixes. + * + * Taken from https://github.com/ktorio/ktor/blob/master/ktor-utils/common/src/io/ktor/util/Crypto.kt + */ +internal fun hex(s: String): ByteArray { + val result = ByteArray(s.length / 2) + for (idx in result.indices) { + val srcIdx = idx * 2 + val high = s[srcIdx].toString().toInt(16) shl 4 + val low = s[srcIdx + 1].toString().toInt(16) + result[idx] = (high or low).toByte() + } + + return result +} + +/** + * Encode [ByteReadPacket] in base64 format. + * + * Taken from https://github.com/ktorio/ktor/blob/424d1d2cfaa3281302c60af9500f738c8c2fc846/ktor-utils/common/src/io/ktor/util/Base64.kt + */ +private fun ByteReadPacket.encodeBase64(): String = buildString { + val data = ByteArray(3) + while (remaining > 0) { + val read = readAvailable(data) + data.clearFrom(read) + + val padSize = (data.size - read) * 8 / 6 + val chunk = ((data[0].toInt() and 0xFF) shl 16) or + ((data[1].toInt() and 0xFF) shl 8) or + (data[2].toInt() and 0xFF) + + for (index in data.size downTo padSize) { + val char = (chunk shr (6 * index)) and BASE64_MASK.toInt() + append(char.toBase64()) + } + + repeat(padSize) { append(BASE64_PAD) } + } +} + +/** + * Decode [ByteReadPacket] from base64 format + * + * Taken from https://github.com/ktorio/ktor/blob/424d1d2cfaa3281302c60af9500f738c8c2fc846/ktor-utils/common/src/io/ktor/util/Base64.kt + */ +private fun ByteReadPacket.decodeBase64Bytes(): Input = buildPacket { + val data = ByteArray(4) + + while (remaining > 0) { + val read = readAvailable(data) + + val chunk = data.foldIndexed(0) { index, result, current -> + result or (current.fromBase64().toInt() shl ((3 - index) * 6)) + } + + for (index in data.size - 2 downTo (data.size - read)) { + val origin = (chunk shr (8 * index)) and 0xff + writeByte(origin.toByte()) + } + } +} diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt new file mode 100644 index 000000000000..4285d605ea62 --- /dev/null +++ b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt @@ -0,0 +1,51 @@ +package org.openapitools.client.infrastructure + +import io.ktor.http.Headers +import io.ktor.http.isSuccess +import io.ktor.util.reflect.TypeInfo +import io.ktor.util.reflect.typeInfo + +open class HttpResponse(val response: io.ktor.client.statement.HttpResponse, val provider: BodyProvider) { + val status: Int = response.status.value + val success: Boolean = response.status.isSuccess() + val headers: Map> = response.headers.mapEntries() + suspend fun body(): T = provider.body(response) + suspend fun typedBody(type: TypeInfo): V = provider.typedBody(response, type) + + companion object { + private fun Headers.mapEntries(): Map> { + val result = mutableMapOf>() + entries().forEach { result[it.key] = it.value } + return result + } + } +} + +interface BodyProvider { + suspend fun body(response: io.ktor.client.statement.HttpResponse): T + suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V +} + +class TypedBodyProvider(private val type: TypeInfo) : BodyProvider { + @Suppress("UNCHECKED_CAST") + override suspend fun body(response: io.ktor.client.statement.HttpResponse): T = + response.call.body(type) as T + + @Suppress("UNCHECKED_CAST") + override suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V = + response.call.body(type) as V +} + +class MappedBodyProvider(private val provider: BodyProvider, private val block: S.() -> T) : BodyProvider { + override suspend fun body(response: io.ktor.client.statement.HttpResponse): T = + block(provider.body(response)) + + override suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V = + provider.typedBody(response, type) +} + +inline fun io.ktor.client.statement.HttpResponse.wrap(): HttpResponse = + HttpResponse(this, TypedBodyProvider(typeInfo())) + +fun HttpResponse.map(block: T.() -> V): HttpResponse = + HttpResponse(response, MappedBodyProvider(provider, block)) diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt new file mode 100644 index 000000000000..d10d7c506523 --- /dev/null +++ b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt @@ -0,0 +1,30 @@ +package org.openapitools.client.infrastructure + +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* + +@Serializable +class OctetByteArray(val value: ByteArray) { + @Serializer(OctetByteArray::class) + companion object : KSerializer { + override val descriptor = PrimitiveSerialDescriptor("OctetByteArray", PrimitiveKind.STRING) + override fun serialize(encoder: Encoder, obj: OctetByteArray) = encoder.encodeString(hex(obj.value)) + override fun deserialize(decoder: Decoder) = OctetByteArray(hex(decoder.decodeString())) + } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other == null || this::class != other::class) return false + other as OctetByteArray + return value.contentEquals(other.value) + } + + override fun hashCode(): Int { + return value.contentHashCode() + } + + override fun toString(): String { + return "OctetByteArray(${hex(value)})" + } +} diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/PartConfig.kt b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/PartConfig.kt new file mode 100644 index 000000000000..be00e38fbaee --- /dev/null +++ b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/PartConfig.kt @@ -0,0 +1,11 @@ +package org.openapitools.client.infrastructure + +/** + * Defines a config object for a given part of a multi-part request. + * NOTE: Headers is a Map because rfc2616 defines + * multi-valued headers as csv-only. + */ +data class PartConfig( + val headers: MutableMap = mutableMapOf(), + val body: T? = null +) diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt new file mode 100644 index 000000000000..c3518a2d173c --- /dev/null +++ b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -0,0 +1,18 @@ +package org.openapitools.client.infrastructure + +/** + * Defines a config object for a given request. + * NOTE: This object doesn't include 'body' because it + * allows for caching of the constructed object + * for many request definitions. + * NOTE: Headers is a Map because rfc2616 defines + * multi-valued headers as csv-only. + */ +data class RequestConfig( + val method: RequestMethod, + val path: String, + val headers: MutableMap = mutableMapOf(), + val query: MutableMap> = mutableMapOf(), + val requiresAuthentication: Boolean, + val body: T? = null +) diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt new file mode 100644 index 000000000000..beb56f07cdde --- /dev/null +++ b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt @@ -0,0 +1,8 @@ +package org.openapitools.client.infrastructure + +/** + * Provides enumerated HTTP verbs + */ +enum class RequestMethod { + GET, DELETE, HEAD, OPTIONS, PATCH, POST, PUT +} diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/models/Apa.kt b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Apa.kt similarity index 100% rename from samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/models/Apa.kt rename to samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Apa.kt diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/.openapi-generator/FILES b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/.openapi-generator/FILES index fb0e5751e4a4..038f8f765497 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/.openapi-generator/FILES +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/.openapi-generator/FILES @@ -56,5 +56,5 @@ src/gen/java/org/openapitools/model/User.java src/gen/java/org/openapitools/model/XmlItem.java src/main/docker/Dockerfile.jvm src/main/docker/Dockerfile.native -src/main/openapi/openapi.yaml +src/main/resources/META-INF/openapi.yaml src/main/resources/application.properties diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/pom.xml b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/pom.xml index 2b84d8826d5a..ab81a897fa4d 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/pom.xml +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/pom.xml @@ -22,7 +22,6 @@ 2.22.1 2.1.1 1.3.2 - 1.6.10 @@ -65,12 +64,6 @@ javax.annotation-api ${javax.annotation-api-version} - - io.swagger - swagger-annotations - ${io.swagger.annotations.version} - provided - diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/api/AnotherFakeApi.java index b06f4a03534d..db6516e3f3bf 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/api/AnotherFakeApi.java @@ -6,7 +6,6 @@ import javax.ws.rs.core.Response; -import io.swagger.annotations.*; import java.io.InputStream; @@ -55,7 +54,6 @@ scheme = "basic" ) }) -@Api(description = "the another-fake API") @Path("/another-fake/dummy") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class AnotherFakeApi { @@ -63,10 +61,6 @@ public class AnotherFakeApi { @PATCH @Consumes({ "application/json" }) @Produces({ "application/json" }) - @ApiOperation(value = "To test special tags", notes = "To test special tags and operation ID starting with number", response = Client.class, tags={ "$another-fake?" }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "successful operation", response = Client.class) - }) @org.eclipse.microprofile.openapi.annotations.Operation(operationId = "call123testSpecialTags", summary = "To test special tags", description = "To test special tags and operation ID starting with number") @org.eclipse.microprofile.openapi.annotations.tags.Tag(name="$another-fake?") diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/api/FakeApi.java index 61401ef4311e..ff33d5f57976 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/api/FakeApi.java @@ -16,7 +16,6 @@ import javax.ws.rs.core.Response; -import io.swagger.annotations.*; import java.io.InputStream; @@ -65,7 +64,6 @@ scheme = "basic" ) }) -@Api(description = "the fake API") @Path("/fake") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class FakeApi { @@ -73,10 +71,6 @@ public class FakeApi { @POST @Path("/create_xml_item") @Consumes({ "application/xml", "application/xml; charset=utf-8", "application/xml; charset=utf-16", "text/xml", "text/xml; charset=utf-8", "text/xml; charset=utf-16" }) - @ApiOperation(value = "creates an XmlItem", notes = "this route creates an XmlItem", response = Void.class, tags={ "fake" }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "successful operation", response = Void.class) - }) @org.eclipse.microprofile.openapi.annotations.Operation(operationId = "createXmlItem", summary = "creates an XmlItem", description = "this route creates an XmlItem") @org.eclipse.microprofile.openapi.annotations.tags.Tag(name="fake") @@ -92,10 +86,6 @@ public Response createXmlItem(@Valid @NotNull XmlItem xmlItem) { @POST @Path("/outer/boolean") @Produces({ "*/*" }) - @ApiOperation(value = "", notes = "Test serialization of outer boolean types", response = Boolean.class, tags={ "fake" }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Output boolean", response = Boolean.class) - }) @org.eclipse.microprofile.openapi.annotations.Operation(operationId = "fakeOuterBooleanSerialize", summary = "", description = "Test serialization of outer boolean types") @org.eclipse.microprofile.openapi.annotations.tags.Tag(name="fake") @@ -111,10 +101,6 @@ public Response fakeOuterBooleanSerialize(@Valid Boolean body) { @POST @Path("/outer/composite") @Produces({ "*/*" }) - @ApiOperation(value = "", notes = "Test serialization of object with outer number type", response = OuterComposite.class, tags={ "fake" }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Output composite", response = OuterComposite.class) - }) @org.eclipse.microprofile.openapi.annotations.Operation(operationId = "fakeOuterCompositeSerialize", summary = "", description = "Test serialization of object with outer number type") @org.eclipse.microprofile.openapi.annotations.tags.Tag(name="fake") @@ -130,10 +116,6 @@ public Response fakeOuterCompositeSerialize(@Valid OuterComposite body) { @POST @Path("/outer/number") @Produces({ "*/*" }) - @ApiOperation(value = "", notes = "Test serialization of outer number types", response = BigDecimal.class, tags={ "fake" }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Output number", response = BigDecimal.class) - }) @org.eclipse.microprofile.openapi.annotations.Operation(operationId = "fakeOuterNumberSerialize", summary = "", description = "Test serialization of outer number types") @org.eclipse.microprofile.openapi.annotations.tags.Tag(name="fake") @@ -149,10 +131,6 @@ public Response fakeOuterNumberSerialize(@Valid BigDecimal body) { @POST @Path("/outer/string") @Produces({ "*/*" }) - @ApiOperation(value = "", notes = "Test serialization of outer string types", response = String.class, tags={ "fake" }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Output string", response = String.class) - }) @org.eclipse.microprofile.openapi.annotations.Operation(operationId = "fakeOuterStringSerialize", summary = "", description = "Test serialization of outer string types") @org.eclipse.microprofile.openapi.annotations.tags.Tag(name="fake") @@ -168,10 +146,6 @@ public Response fakeOuterStringSerialize(@Valid String body) { @PUT @Path("/body-with-file-schema") @Consumes({ "application/json" }) - @ApiOperation(value = "", notes = "For this test, the body for this request much reference a schema named `File`.", response = Void.class, tags={ "fake" }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Success", response = Void.class) - }) @org.eclipse.microprofile.openapi.annotations.Operation(operationId = "testBodyWithFileSchema", summary = "", description = "For this test, the body for this request much reference a schema named `File`.") @org.eclipse.microprofile.openapi.annotations.tags.Tag(name="fake") @@ -187,10 +161,6 @@ public Response testBodyWithFileSchema(@Valid @NotNull FileSchemaTestClass body) @PUT @Path("/body-with-query-params") @Consumes({ "application/json" }) - @ApiOperation(value = "", notes = "", response = Void.class, tags={ "fake" }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Success", response = Void.class) - }) @org.eclipse.microprofile.openapi.annotations.Operation(operationId = "testBodyWithQueryParams", summary = "", description = "") @org.eclipse.microprofile.openapi.annotations.tags.Tag(name="fake") @@ -206,10 +176,6 @@ public Response testBodyWithQueryParams(@QueryParam("query") @NotNull String q @PATCH @Consumes({ "application/json" }) @Produces({ "application/json" }) - @ApiOperation(value = "To test \"client\" model", notes = "To test \"client\" model", response = Client.class, tags={ "fake" }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "successful operation", response = Client.class) - }) @org.eclipse.microprofile.openapi.annotations.Operation(operationId = "testClientModel", summary = "To test \"client\" model", description = "To test \"client\" model") @org.eclipse.microprofile.openapi.annotations.tags.Tag(name="fake") @@ -224,14 +190,6 @@ public Response testClientModel(@Valid @NotNull Client body) { @POST @Consumes({ "application/x-www-form-urlencoded" }) - @ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트", notes = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트", response = Void.class, authorizations = { - - @Authorization(value = "http_basic_test") - }, tags={ "fake" }) - @ApiResponses(value = { - @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), - @ApiResponse(code = 404, message = "User not found", response = Void.class) - }) @org.eclipse.microprofile.openapi.annotations.security.SecurityRequirements(value={ @org.eclipse.microprofile.openapi.annotations.security.SecurityRequirement(name = "http_basic_test") }) @@ -251,14 +209,6 @@ public Response testEndpointParameters(@FormParam(value = "number") BigDecimal @GET @Consumes({ "application/x-www-form-urlencoded" }) - @ApiOperation(value = "To test enum parameters", notes = "To test enum parameters", response = Void.class, tags={ "fake" }) - @io.swagger.annotations.ApiImplicitParams({ - @io.swagger.annotations.ApiImplicitParam(name = "enum_header_string", value = "Header parameter enum test (string)", dataType = "String", paramType = "header") - }) - @ApiResponses(value = { - @ApiResponse(code = 400, message = "Invalid request", response = Void.class), - @ApiResponse(code = 404, message = "Not found", response = Void.class) - }) @org.eclipse.microprofile.openapi.annotations.Operation(operationId = "testEnumParameters", summary = "To test enum parameters", description = "To test enum parameters") @org.eclipse.microprofile.openapi.annotations.tags.Tag(name="fake") @@ -270,15 +220,11 @@ public Response testEndpointParameters(@FormParam(value = "number") BigDecimal }) }) - public Response testEnumParameters(@HeaderParam("enum_header_string_array") @ApiParam("Header parameter enum test (string array)") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="Header parameter enum test (string array)") List enumHeaderStringArray,@QueryParam("enum_query_string_array") @ApiParam("Query parameter enum test (string array)") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="Query parameter enum test (string array)") List enumQueryStringArray,@QueryParam("enum_query_string") @DefaultValue("-efg") @ApiParam("Query parameter enum test (string)") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="Query parameter enum test (string)") String enumQueryString,@QueryParam("enum_query_integer") @ApiParam("Query parameter enum test (double)") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="Query parameter enum test (double)") Integer enumQueryInteger,@QueryParam("enum_query_double") @ApiParam("Query parameter enum test (double)") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="Query parameter enum test (double)") Double enumQueryDouble,@FormParam(value = "enum_form_string_array") List enumFormStringArray,@FormParam(value = "enum_form_string") String enumFormString) { + public Response testEnumParameters(@HeaderParam("enum_header_string_array") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="Header parameter enum test (string array)") List enumHeaderStringArray,@QueryParam("enum_query_string_array") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="Query parameter enum test (string array)") List enumQueryStringArray,@QueryParam("enum_query_string") @DefaultValue("-efg") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="Query parameter enum test (string)") String enumQueryString,@QueryParam("enum_query_integer") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="Query parameter enum test (double)") Integer enumQueryInteger,@QueryParam("enum_query_double") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="Query parameter enum test (double)") Double enumQueryDouble,@FormParam(value = "enum_form_string_array") List enumFormStringArray,@FormParam(value = "enum_form_string") String enumFormString) { return Response.ok().entity("magic!").build(); } @DELETE - @ApiOperation(value = "Fake endpoint to test group parameters (optional)", notes = "Fake endpoint to test group parameters (optional)", response = Void.class, tags={ "fake" }) - @ApiResponses(value = { - @ApiResponse(code = 400, message = "Something wrong", response = Void.class) - }) @org.eclipse.microprofile.openapi.annotations.Operation(operationId = "testGroupParameters", summary = "Fake endpoint to test group parameters (optional)", description = "Fake endpoint to test group parameters (optional)") @org.eclipse.microprofile.openapi.annotations.tags.Tag(name="fake") @@ -287,17 +233,13 @@ public Response testEnumParameters(@HeaderParam("enum_header_string_array") @A }) }) - public Response testGroupParameters(@QueryParam("required_string_group") @NotNull @ApiParam("Required String in group parameters") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="Required String in group parameters") Integer requiredStringGroup,@HeaderParam("required_boolean_group") @NotNull @ApiParam("Required Boolean in group parameters") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="Required Boolean in group parameters") Boolean requiredBooleanGroup,@QueryParam("required_int64_group") @NotNull @ApiParam("Required Integer in group parameters") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="Required Integer in group parameters") Long requiredInt64Group,@QueryParam("string_group") @ApiParam("String in group parameters") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="String in group parameters") Integer stringGroup,@HeaderParam("boolean_group") @ApiParam("Boolean in group parameters") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="Boolean in group parameters") Boolean booleanGroup,@QueryParam("int64_group") @ApiParam("Integer in group parameters") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="Integer in group parameters") Long int64Group) { + public Response testGroupParameters(@QueryParam("required_string_group") @NotNull @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="Required String in group parameters") Integer requiredStringGroup,@HeaderParam("required_boolean_group") @NotNull @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="Required Boolean in group parameters") Boolean requiredBooleanGroup,@QueryParam("required_int64_group") @NotNull @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="Required Integer in group parameters") Long requiredInt64Group,@QueryParam("string_group") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="String in group parameters") Integer stringGroup,@HeaderParam("boolean_group") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="Boolean in group parameters") Boolean booleanGroup,@QueryParam("int64_group") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="Integer in group parameters") Long int64Group) { return Response.ok().entity("magic!").build(); } @POST @Path("/inline-additionalProperties") @Consumes({ "application/json" }) - @ApiOperation(value = "test inline additionalProperties", notes = "", response = Void.class, tags={ "fake" }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "successful operation", response = Void.class) - }) @org.eclipse.microprofile.openapi.annotations.Operation(operationId = "testInlineAdditionalProperties", summary = "test inline additionalProperties", description = "") @org.eclipse.microprofile.openapi.annotations.tags.Tag(name="fake") @@ -313,10 +255,6 @@ public Response testInlineAdditionalProperties(@Valid @NotNull Map status) { + public Response findPetsByStatus(@QueryParam("status") @NotNull @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="Status values that need to be considered for filter") List status) { return Response.ok().entity("magic!").build(); } @GET @Path("/findByTags") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "Set", authorizations = { - @Authorization(value = "petstore_auth", scopes = { - @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }, tags={ "pet" }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "Set"), - @ApiResponse(code = 400, message = "Invalid tag value", response = Void.class) - }) @org.eclipse.microprofile.openapi.annotations.security.SecurityRequirements(value={ @org.eclipse.microprofile.openapi.annotations.security.SecurityRequirement(name = "petstore_auth", scopes = { "write:pets", "read:pets" }) }) @@ -180,22 +139,13 @@ public Response findPetsByStatus(@QueryParam("status") @NotNull @ApiParam("Stat @org.eclipse.microprofile.openapi.annotations.media.Content(mediaType="application/json") }) }) - public Response findPetsByTags(@QueryParam("tags") @NotNull @ApiParam("Tags to filter by") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="Tags to filter by") Set tags) { + public Response findPetsByTags(@QueryParam("tags") @NotNull @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="Tags to filter by") Set tags) { return Response.ok().entity("magic!").build(); } @GET @Path("/{petId}") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { - - @Authorization(value = "api_key") - }, tags={ "pet" }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "successful operation", response = Pet.class), - @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), - @ApiResponse(code = 404, message = "Pet not found", response = Void.class) - }) @org.eclipse.microprofile.openapi.annotations.security.SecurityRequirements(value={ @org.eclipse.microprofile.openapi.annotations.security.SecurityRequirement(name = "api_key") }) @@ -215,23 +165,12 @@ public Response findPetsByTags(@QueryParam("tags") @NotNull @ApiParam("Tags to @org.eclipse.microprofile.openapi.annotations.media.Content(mediaType="application/json") }) }) - public Response getPetById(@PathParam("petId") @ApiParam("ID of pet to return") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="ID of pet to return") Long petId) { + public Response getPetById(@PathParam("petId") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="ID of pet to return") Long petId) { return Response.ok().entity("magic!").build(); } @PUT @Consumes({ "application/json", "application/xml" }) - @ApiOperation(value = "Update an existing pet", notes = "", response = Void.class, authorizations = { - @Authorization(value = "petstore_auth", scopes = { - @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }, tags={ "pet" }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "successful operation", response = Void.class), - @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), - @ApiResponse(code = 404, message = "Pet not found", response = Void.class), - @ApiResponse(code = 405, message = "Validation exception", response = Void.class) - }) @org.eclipse.microprofile.openapi.annotations.security.SecurityRequirements(value={ @org.eclipse.microprofile.openapi.annotations.security.SecurityRequirement(name = "petstore_auth", scopes = { "write:pets", "read:pets" }) }) @@ -258,14 +197,6 @@ public Response updatePet(@Valid @NotNull Pet body) { @POST @Path("/{petId}") @Consumes({ "application/x-www-form-urlencoded" }) - @ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class, authorizations = { - @Authorization(value = "petstore_auth", scopes = { - @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }, tags={ "pet" }) - @ApiResponses(value = { - @ApiResponse(code = 405, message = "Invalid input", response = Void.class) - }) @org.eclipse.microprofile.openapi.annotations.security.SecurityRequirements(value={ @org.eclipse.microprofile.openapi.annotations.security.SecurityRequirement(name = "petstore_auth", scopes = { "write:pets", "read:pets" }) }) @@ -276,7 +207,7 @@ public Response updatePet(@Valid @NotNull Pet body) { }) }) - public Response updatePetWithForm(@PathParam("petId") @ApiParam("ID of pet that needs to be updated") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="ID of pet that needs to be updated") Long petId,@FormParam(value = "name") String name,@FormParam(value = "status") String status) { + public Response updatePetWithForm(@PathParam("petId") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="ID of pet that needs to be updated") Long petId,@FormParam(value = "name") String name,@FormParam(value = "status") String status) { return Response.ok().entity("magic!").build(); } @@ -284,14 +215,6 @@ public Response updatePetWithForm(@PathParam("petId") @ApiParam("ID of pet that @Path("/{petId}/uploadImage") @Consumes({ "multipart/form-data" }) @Produces({ "application/json" }) - @ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = { - @Authorization(value = "petstore_auth", scopes = { - @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }, tags={ "pet" }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) - }) @org.eclipse.microprofile.openapi.annotations.security.SecurityRequirements(value={ @org.eclipse.microprofile.openapi.annotations.security.SecurityRequirement(name = "petstore_auth", scopes = { "write:pets", "read:pets" }) }) @@ -302,7 +225,7 @@ public Response updatePetWithForm(@PathParam("petId") @ApiParam("ID of pet that @org.eclipse.microprofile.openapi.annotations.media.Content(mediaType="application/json", schema = @org.eclipse.microprofile.openapi.annotations.media.Schema(implementation = ModelApiResponse.class)) }) }) - public Response uploadFile(@PathParam("petId") @ApiParam("ID of pet to update") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="ID of pet to update") Long petId,@FormParam(value = "additionalMetadata") String additionalMetadata, @FormParam(value = "file") InputStream _fileInputStream) { + public Response uploadFile(@PathParam("petId") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="ID of pet to update") Long petId,@FormParam(value = "additionalMetadata") String additionalMetadata, @FormParam(value = "file") InputStream _fileInputStream) { return Response.ok().entity("magic!").build(); } } diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/api/StoreApi.java index 73c4630de841..7145db220ec7 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/api/StoreApi.java @@ -7,7 +7,6 @@ import javax.ws.rs.core.Response; -import io.swagger.annotations.*; import java.io.InputStream; @@ -56,18 +55,12 @@ scheme = "basic" ) }) -@Api(description = "the store API") @Path("/store") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class StoreApi { @DELETE @Path("/order/{order_id}") - @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class, tags={ "store" }) - @ApiResponses(value = { - @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), - @ApiResponse(code = 404, message = "Order not found", response = Void.class) - }) @org.eclipse.microprofile.openapi.annotations.Operation(operationId = "deleteOrder", summary = "Delete purchase order by ID", description = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors") @org.eclipse.microprofile.openapi.annotations.tags.Tag(name="store") @@ -79,20 +72,13 @@ public class StoreApi { }) }) - public Response deleteOrder(@PathParam("order_id") @ApiParam("ID of the order that needs to be deleted") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="ID of the order that needs to be deleted") String orderId) { + public Response deleteOrder(@PathParam("order_id") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="ID of the order that needs to be deleted") String orderId) { return Response.ok().entity("magic!").build(); } @GET @Path("/inventory") @Produces({ "application/json" }) - @ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { - - @Authorization(value = "api_key") - }, tags={ "store" }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "successful operation", response = Map.class, responseContainer = "Map") - }) @org.eclipse.microprofile.openapi.annotations.security.SecurityRequirements(value={ @org.eclipse.microprofile.openapi.annotations.security.SecurityRequirement(name = "api_key") }) @@ -110,12 +96,6 @@ public Response getInventory() { @GET @Path("/order/{order_id}") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions", response = Order.class, tags={ "store" }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "successful operation", response = Order.class), - @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), - @ApiResponse(code = 404, message = "Order not found", response = Void.class) - }) @org.eclipse.microprofile.openapi.annotations.Operation(operationId = "getOrderById", summary = "Find purchase order by ID", description = "For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions") @org.eclipse.microprofile.openapi.annotations.tags.Tag(name="store") @@ -133,18 +113,13 @@ public Response getInventory() { @org.eclipse.microprofile.openapi.annotations.media.Content(mediaType="application/json") }) }) - public Response getOrderById(@PathParam("order_id") @Min(1L) @Max(5L) @ApiParam("ID of pet that needs to be fetched") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="ID of pet that needs to be fetched") Long orderId) { + public Response getOrderById(@PathParam("order_id") @Min(1L) @Max(5L) @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="ID of pet that needs to be fetched") Long orderId) { return Response.ok().entity("magic!").build(); } @POST @Path("/order") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store" }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "successful operation", response = Order.class), - @ApiResponse(code = 400, message = "Invalid Order", response = Void.class) - }) @org.eclipse.microprofile.openapi.annotations.Operation(operationId = "placeOrder", summary = "Place an order for a pet", description = "") @org.eclipse.microprofile.openapi.annotations.tags.Tag(name="store") diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/api/UserApi.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/api/UserApi.java index 6c571ba222a6..cf63562ad52d 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/api/UserApi.java @@ -7,7 +7,6 @@ import javax.ws.rs.core.Response; -import io.swagger.annotations.*; import java.io.InputStream; @@ -56,16 +55,11 @@ scheme = "basic" ) }) -@Api(description = "the user API") @Path("/user") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class UserApi { @POST - @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user" }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "successful operation", response = Void.class) - }) @org.eclipse.microprofile.openapi.annotations.Operation(operationId = "createUser", summary = "Create user", description = "This can only be done by the logged in user.") @org.eclipse.microprofile.openapi.annotations.tags.Tag(name="user") @@ -80,10 +74,6 @@ public Response createUser(@Valid @NotNull User body) { @POST @Path("/createWithArray") - @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user" }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "successful operation", response = Void.class) - }) @org.eclipse.microprofile.openapi.annotations.Operation(operationId = "createUsersWithArrayInput", summary = "Creates list of users with given input array", description = "") @org.eclipse.microprofile.openapi.annotations.tags.Tag(name="user") @@ -98,10 +88,6 @@ public Response createUsersWithArrayInput(@Valid @NotNull List body) { @POST @Path("/createWithList") - @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user" }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "successful operation", response = Void.class) - }) @org.eclipse.microprofile.openapi.annotations.Operation(operationId = "createUsersWithListInput", summary = "Creates list of users with given input array", description = "") @org.eclipse.microprofile.openapi.annotations.tags.Tag(name="user") @@ -116,11 +102,6 @@ public Response createUsersWithListInput(@Valid @NotNull List body) { @DELETE @Path("/{username}") - @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user" }) - @ApiResponses(value = { - @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), - @ApiResponse(code = 404, message = "User not found", response = Void.class) - }) @org.eclipse.microprofile.openapi.annotations.Operation(operationId = "deleteUser", summary = "Delete user", description = "This can only be done by the logged in user.") @org.eclipse.microprofile.openapi.annotations.tags.Tag(name="user") @@ -132,19 +113,13 @@ public Response createUsersWithListInput(@Valid @NotNull List body) { }) }) - public Response deleteUser(@PathParam("username") @ApiParam("The name that needs to be deleted") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="The name that needs to be deleted") String username) { + public Response deleteUser(@PathParam("username") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="The name that needs to be deleted") String username) { return Response.ok().entity("magic!").build(); } @GET @Path("/{username}") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user" }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "successful operation", response = User.class), - @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), - @ApiResponse(code = 404, message = "User not found", response = Void.class) - }) @org.eclipse.microprofile.openapi.annotations.Operation(operationId = "getUserByName", summary = "Get user by user name", description = "") @org.eclipse.microprofile.openapi.annotations.tags.Tag(name="user") @@ -162,18 +137,13 @@ public Response deleteUser(@PathParam("username") @ApiParam("The name that needs @org.eclipse.microprofile.openapi.annotations.media.Content(mediaType="application/json") }) }) - public Response getUserByName(@PathParam("username") @ApiParam("The name that needs to be fetched. Use user1 for testing.") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="The name that needs to be fetched. Use user1 for testing.") String username) { + public Response getUserByName(@PathParam("username") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="The name that needs to be fetched. Use user1 for testing.") String username) { return Response.ok().entity("magic!").build(); } @GET @Path("/login") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user" }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "successful operation", response = String.class), - @ApiResponse(code = 400, message = "Invalid username/password supplied", response = Void.class) - }) @org.eclipse.microprofile.openapi.annotations.Operation(operationId = "loginUser", summary = "Logs user into the system", description = "") @org.eclipse.microprofile.openapi.annotations.tags.Tag(name="user") @@ -190,16 +160,12 @@ public Response getUserByName(@PathParam("username") @ApiParam("The name that ne @org.eclipse.microprofile.openapi.annotations.media.Content(mediaType="application/json") }) }) - public Response loginUser(@QueryParam("username") @NotNull @ApiParam("The user name for login") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="The user name for login") String username,@QueryParam("password") @NotNull @ApiParam("The password for login in clear text") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="The password for login in clear text") String password) { + public Response loginUser(@QueryParam("username") @NotNull @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="The user name for login") String username,@QueryParam("password") @NotNull @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="The password for login in clear text") String password) { return Response.ok().entity("magic!").build(); } @GET @Path("/logout") - @ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class, tags={ "user" }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "successful operation", response = Void.class) - }) @org.eclipse.microprofile.openapi.annotations.Operation(operationId = "logoutUser", summary = "Logs out current logged in user session", description = "") @org.eclipse.microprofile.openapi.annotations.tags.Tag(name="user") @@ -214,11 +180,6 @@ public Response logoutUser() { @PUT @Path("/{username}") - @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user" }) - @ApiResponses(value = { - @ApiResponse(code = 400, message = "Invalid user supplied", response = Void.class), - @ApiResponse(code = 404, message = "User not found", response = Void.class) - }) @org.eclipse.microprofile.openapi.annotations.Operation(operationId = "updateUser", summary = "Updated user", description = "This can only be done by the logged in user.") @org.eclipse.microprofile.openapi.annotations.tags.Tag(name="user") @@ -230,7 +191,7 @@ public Response logoutUser() { }) }) - public Response updateUser(@PathParam("username") @ApiParam("name that need to be deleted") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="name that need to be deleted") String username,@Valid @NotNull User body) { + public Response updateUser(@PathParam("username") @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="name that need to be deleted") String username,@Valid @NotNull User body) { return Response.ok().entity("magic!").build(); } } diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java index 5e6dcbc18a01..f523f2dfc3a8 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java @@ -1,14 +1,11 @@ package org.openapitools.model; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; import java.util.Map; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -31,7 +28,6 @@ public AdditionalPropertiesAnyType name(String name) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("name") public String getName() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java index e83b83c7c064..75a3feaa86c4 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java @@ -1,7 +1,5 @@ package org.openapitools.model; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -9,7 +7,6 @@ import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -32,7 +29,6 @@ public AdditionalPropertiesArray name(String name) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("name") public String getName() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java index 335b344a9d19..844ee598e7c3 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java @@ -1,14 +1,11 @@ package org.openapitools.model; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; import java.util.Map; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -31,7 +28,6 @@ public AdditionalPropertiesBoolean name(String name) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("name") public String getName() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java index 7470375ebd39..487447f725ca 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java @@ -1,7 +1,5 @@ package org.openapitools.model; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import java.util.HashMap; import java.util.List; @@ -10,7 +8,6 @@ import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -60,7 +57,6 @@ public AdditionalPropertiesClass mapString(Map mapString) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("map_string") public Map getMapString() { @@ -96,7 +92,6 @@ public AdditionalPropertiesClass mapNumber(Map mapNumber) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("map_number") public Map getMapNumber() { @@ -132,7 +127,6 @@ public AdditionalPropertiesClass mapInteger(Map mapInteger) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("map_integer") public Map getMapInteger() { @@ -168,7 +162,6 @@ public AdditionalPropertiesClass mapBoolean(Map mapBoolean) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("map_boolean") public Map getMapBoolean() { @@ -204,7 +197,6 @@ public AdditionalPropertiesClass mapArrayInteger(Map> mapA } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("map_array_integer") public Map> getMapArrayInteger() { @@ -240,7 +232,6 @@ public AdditionalPropertiesClass mapArrayAnytype(Map> mapAr } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("map_array_anytype") public Map> getMapArrayAnytype() { @@ -276,7 +267,6 @@ public AdditionalPropertiesClass mapMapString(Map> m } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("map_map_string") public Map> getMapMapString() { @@ -312,7 +302,6 @@ public AdditionalPropertiesClass mapMapAnytype(Map> } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("map_map_anytype") public Map> getMapMapAnytype() { @@ -348,7 +337,6 @@ public AdditionalPropertiesClass anytype1(Object anytype1) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("anytype_1") public Object getAnytype1() { @@ -368,7 +356,6 @@ public AdditionalPropertiesClass anytype2(Object anytype2) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("anytype_2") public Object getAnytype2() { @@ -388,7 +375,6 @@ public AdditionalPropertiesClass anytype3(Object anytype3) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("anytype_3") public Object getAnytype3() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java index 14c944e3a890..d8f656105a0a 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java @@ -1,14 +1,11 @@ package org.openapitools.model; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; import java.util.Map; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -31,7 +28,6 @@ public AdditionalPropertiesInteger name(String name) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("name") public String getName() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java index 0f2a791d6586..5d54f8f12c38 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java @@ -1,7 +1,5 @@ package org.openapitools.model; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; @@ -9,7 +7,6 @@ import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -32,7 +29,6 @@ public AdditionalPropertiesNumber name(String name) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("name") public String getName() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java index bce0bd580cb8..a545ce84df81 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java @@ -1,14 +1,11 @@ package org.openapitools.model; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; import java.util.Map; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -31,7 +28,6 @@ public AdditionalPropertiesObject name(String name) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("name") public String getName() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java index 49c4103a291d..97e95145eda6 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java @@ -1,14 +1,11 @@ package org.openapitools.model; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; import java.util.Map; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -31,7 +28,6 @@ public AdditionalPropertiesString name(String name) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("name") public String getName() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Animal.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Animal.java index 25d8d641ed7b..bef18919cb73 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Animal.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Animal.java @@ -3,13 +3,10 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -47,7 +44,6 @@ public Animal className(String className) { } - @ApiModelProperty(required = true, value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(required = true, description = "") @JsonProperty("className") @NotNull @@ -68,7 +64,6 @@ public Animal color(String color) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("color") public String getColor() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java index 3ba36e8ad041..de54ff268529 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java @@ -1,7 +1,5 @@ package org.openapitools.model; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; @@ -9,7 +7,6 @@ import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -39,7 +36,6 @@ public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArr } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("ArrayArrayNumber") public List> getArrayArrayNumber() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java index 03061373b7d6..7cd3974f72ec 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java @@ -1,7 +1,5 @@ package org.openapitools.model; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; @@ -9,7 +7,6 @@ import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -39,7 +36,6 @@ public ArrayOfNumberOnly arrayNumber(List arrayNumber) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("ArrayNumber") public List getArrayNumber() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ArrayTest.java index d3bd3d2af08b..02b2b5825521 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ArrayTest.java @@ -1,7 +1,5 @@ package org.openapitools.model; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; import org.openapitools.model.ReadOnlyFirst; @@ -9,7 +7,6 @@ import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -43,7 +40,6 @@ public ArrayTest arrayOfString(List arrayOfString) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("array_of_string") public List getArrayOfString() { @@ -79,7 +75,6 @@ public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("array_array_of_integer") public List> getArrayArrayOfInteger() { @@ -115,7 +110,6 @@ public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("array_array_of_model") public List> getArrayArrayOfModel() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/BigCat.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/BigCat.java index 3d9d08170e5c..6579d5bf287a 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/BigCat.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/BigCat.java @@ -1,13 +1,10 @@ package org.openapitools.model; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import org.openapitools.model.Cat; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -85,7 +82,6 @@ public BigCat kind(KindEnum kind) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("kind") public KindEnum getKind() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Capitalization.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Capitalization.java index a28d39de52d0..b576c29b1b34 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Capitalization.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Capitalization.java @@ -1,12 +1,9 @@ package org.openapitools.model; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -46,7 +43,6 @@ public Capitalization smallCamel(String smallCamel) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("smallCamel") public String getSmallCamel() { @@ -66,7 +62,6 @@ public Capitalization capitalCamel(String capitalCamel) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("CapitalCamel") public String getCapitalCamel() { @@ -86,7 +81,6 @@ public Capitalization smallSnake(String smallSnake) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("small_Snake") public String getSmallSnake() { @@ -106,7 +100,6 @@ public Capitalization capitalSnake(String capitalSnake) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("Capital_Snake") public String getCapitalSnake() { @@ -126,7 +119,6 @@ public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("SCA_ETH_Flow_Points") public String getScAETHFlowPoints() { @@ -147,7 +139,6 @@ public Capitalization ATT_NAME(String ATT_NAME) { } - @ApiModelProperty(value = "Name of the pet ") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "Name of the pet ") @JsonProperty("ATT_NAME") public String getATTNAME() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Cat.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Cat.java index 261092ceff1e..e157f2f26a4a 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Cat.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Cat.java @@ -1,13 +1,10 @@ package org.openapitools.model; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import org.openapitools.model.Animal; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -38,7 +35,6 @@ public Cat declawed(Boolean declawed) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("declawed") public Boolean getDeclawed() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Category.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Category.java index 0b651b8c4812..6042f69858d8 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Category.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Category.java @@ -1,12 +1,9 @@ package org.openapitools.model; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -38,7 +35,6 @@ public Category id(Long id) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("id") public Long getId() { @@ -58,7 +54,6 @@ public Category name(String name) { } - @ApiModelProperty(required = true, value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(required = true, description = "") @JsonProperty("name") @NotNull diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ClassModel.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ClassModel.java index c66044c0a526..64ef907cca07 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ClassModel.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ClassModel.java @@ -1,12 +1,9 @@ package org.openapitools.model; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -16,7 +13,7 @@ /** * Model for testing model with \"_class\" property **/ -@ApiModel(description = "Model for testing model with \"_class\" property") + @org.eclipse.microprofile.openapi.annotations.media.Schema(description="Model for testing model with \"_class\" property") @JsonTypeName("ClassModel") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") @@ -38,7 +35,6 @@ public ClassModel propertyClass(String propertyClass) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("_class") public String getPropertyClass() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Client.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Client.java index 19978679674b..fea01a8c1745 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Client.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Client.java @@ -1,12 +1,9 @@ package org.openapitools.model; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -36,7 +33,6 @@ public Client client(String client) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("client") public String getClient() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Dog.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Dog.java index ea094ca80fb5..ae5bee8c43eb 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Dog.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Dog.java @@ -1,13 +1,10 @@ package org.openapitools.model; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import org.openapitools.model.Animal; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -38,7 +35,6 @@ public Dog breed(String breed) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("breed") public String getBreed() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/EnumArrays.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/EnumArrays.java index a68d69b7b2cc..4078a504e365 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/EnumArrays.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/EnumArrays.java @@ -1,14 +1,11 @@ package org.openapitools.model; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -134,7 +131,6 @@ public EnumArrays justSymbol(JustSymbolEnum justSymbol) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("just_symbol") public JustSymbolEnum getJustSymbol() { @@ -154,7 +150,6 @@ public EnumArrays arrayEnum(List arrayEnum) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("array_enum") public List getArrayEnum() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/EnumTest.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/EnumTest.java index cace39eb4623..c929ea4d07e3 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/EnumTest.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/EnumTest.java @@ -1,14 +1,11 @@ package org.openapitools.model; import com.fasterxml.jackson.annotation.JsonTypeName; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import org.openapitools.model.OuterEnum; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -234,7 +231,6 @@ public EnumTest enumString(EnumStringEnum enumString) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("enum_string") public EnumStringEnum getEnumString() { @@ -254,7 +250,6 @@ public EnumTest enumStringRequired(EnumStringRequiredEnum enumStringRequired) { } - @ApiModelProperty(required = true, value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(required = true, description = "") @JsonProperty("enum_string_required") @NotNull @@ -275,7 +270,6 @@ public EnumTest enumInteger(EnumIntegerEnum enumInteger) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("enum_integer") public EnumIntegerEnum getEnumInteger() { @@ -295,7 +289,6 @@ public EnumTest enumNumber(EnumNumberEnum enumNumber) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("enum_number") public EnumNumberEnum getEnumNumber() { @@ -315,7 +308,6 @@ public EnumTest outerEnum(OuterEnum outerEnum) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("outerEnum") public OuterEnum getOuterEnum() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/FileSchemaTestClass.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/FileSchemaTestClass.java index 19afafdf601a..ce3d333c2d26 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/FileSchemaTestClass.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/FileSchemaTestClass.java @@ -1,7 +1,5 @@ package org.openapitools.model; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; import org.openapitools.model.ModelFile; @@ -9,7 +7,6 @@ import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -41,7 +38,6 @@ public FileSchemaTestClass _file(ModelFile _file) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("file") public ModelFile getFile() { @@ -61,7 +57,6 @@ public FileSchemaTestClass files(List files) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("files") public List getFiles() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/FormatTest.java index 41a5aac47d14..4bf137765e8e 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/FormatTest.java @@ -1,8 +1,6 @@ package org.openapitools.model; import com.fasterxml.jackson.annotation.JsonTypeName; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.io.File; import java.math.BigDecimal; import java.time.LocalDate; @@ -13,7 +11,6 @@ import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -71,7 +68,6 @@ public FormatTest integer(Integer integer) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("integer") @Min(10) @Max(100) public Integer getInteger() { @@ -93,7 +89,6 @@ public FormatTest int32(Integer int32) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("int32") @Min(20) @Max(200) public Integer getInt32() { @@ -113,7 +108,6 @@ public FormatTest int64(Long int64) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("int64") public Long getInt64() { @@ -135,7 +129,6 @@ public FormatTest number(BigDecimal number) { } - @ApiModelProperty(required = true, value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(required = true, description = "") @JsonProperty("number") @NotNull @@ -158,7 +151,6 @@ public FormatTest _float(Float _float) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("float") @DecimalMin("54.3") @DecimalMax("987.6") public Float getFloat() { @@ -180,7 +172,6 @@ public FormatTest _double(Double _double) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("double") @DecimalMin("67.8") @DecimalMax("123.4") public Double getDouble() { @@ -200,7 +191,6 @@ public FormatTest string(String string) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("string") @Pattern(regexp="/[a-z]/i") public String getString() { @@ -220,7 +210,6 @@ public FormatTest _byte(byte[] _byte) { } - @ApiModelProperty(required = true, value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(required = true, description = "") @JsonProperty("byte") @NotNull @@ -241,7 +230,6 @@ public FormatTest binary(File binary) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("binary") public File getBinary() { @@ -261,7 +249,6 @@ public FormatTest date(LocalDate date) { } - @ApiModelProperty(required = true, value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(required = true, description = "") @JsonProperty("date") @NotNull @@ -282,7 +269,6 @@ public FormatTest dateTime(LocalDateTime dateTime) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("dateTime") public LocalDateTime getDateTime() { @@ -302,7 +288,6 @@ public FormatTest uuid(UUID uuid) { } - @ApiModelProperty(example = "72f98069-206d-4f12-9f12-3d1e525a8e84", value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(example = "72f98069-206d-4f12-9f12-3d1e525a8e84", description = "") @JsonProperty("uuid") public UUID getUuid() { @@ -322,7 +307,6 @@ public FormatTest password(String password) { } - @ApiModelProperty(required = true, value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(required = true, description = "") @JsonProperty("password") @NotNull @@ -343,7 +327,6 @@ public FormatTest bigDecimal(BigDecimal bigDecimal) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("BigDecimal") public BigDecimal getBigDecimal() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java index 0584fe0ee6f9..bf267cb8170a 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java @@ -1,13 +1,10 @@ package org.openapitools.model; import com.fasterxml.jackson.annotation.JsonTypeName; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -39,7 +36,6 @@ public HasOnlyReadOnly bar(String bar) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("bar") public String getBar() { @@ -59,7 +55,6 @@ public HasOnlyReadOnly foo(String foo) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("foo") public String getFoo() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/MapTest.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/MapTest.java index d43c57dc79c8..6dcb32d2662a 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/MapTest.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/MapTest.java @@ -1,14 +1,11 @@ package org.openapitools.model; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; import java.util.Map; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -91,7 +88,6 @@ public MapTest mapMapOfString(Map> mapMapOfString) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("map_map_of_string") public Map> getMapMapOfString() { @@ -127,7 +123,6 @@ public MapTest mapOfEnumString(Map mapOfEnumString) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("map_of_enum_string") public Map getMapOfEnumString() { @@ -163,7 +158,6 @@ public MapTest directMap(Map directMap) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("direct_map") public Map getDirectMap() { @@ -199,7 +193,6 @@ public MapTest indirectMap(Map indirectMap) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("indirect_map") public Map getIndirectMap() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java index 52df830f8fda..bab8ecb9aa91 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -1,7 +1,5 @@ package org.openapitools.model; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.time.LocalDateTime; import java.util.HashMap; import java.util.Map; @@ -11,7 +9,6 @@ import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -45,7 +42,6 @@ public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("uuid") public UUID getUuid() { @@ -65,7 +61,6 @@ public MixedPropertiesAndAdditionalPropertiesClass dateTime(LocalDateTime dateTi } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("dateTime") public LocalDateTime getDateTime() { @@ -85,7 +80,6 @@ public MixedPropertiesAndAdditionalPropertiesClass map(Map map) } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("map") public Map getMap() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Model200Response.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Model200Response.java index ee5ff5d3e86c..c940dad7d45d 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Model200Response.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Model200Response.java @@ -1,13 +1,10 @@ package org.openapitools.model; import com.fasterxml.jackson.annotation.JsonTypeName; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -17,7 +14,7 @@ /** * Model for testing model name starting with number **/ -@ApiModel(description = "Model for testing model name starting with number") + @org.eclipse.microprofile.openapi.annotations.media.Schema(description="Model for testing model name starting with number") @JsonTypeName("200_response") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") @@ -41,7 +38,6 @@ public Model200Response name(Integer name) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("name") public Integer getName() { @@ -61,7 +57,6 @@ public Model200Response propertyClass(String propertyClass) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("class") public String getPropertyClass() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ModelApiResponse.java index e0cbfb7d6628..9ae159bb65ec 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ModelApiResponse.java @@ -1,13 +1,10 @@ package org.openapitools.model; import com.fasterxml.jackson.annotation.JsonTypeName; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -41,7 +38,6 @@ public ModelApiResponse code(Integer code) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("code") public Integer getCode() { @@ -61,7 +57,6 @@ public ModelApiResponse type(String type) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("type") public String getType() { @@ -81,7 +76,6 @@ public ModelApiResponse message(String message) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("message") public String getMessage() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ModelFile.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ModelFile.java index 3d88d4cef9cf..45cb3818c8a7 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ModelFile.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ModelFile.java @@ -1,13 +1,10 @@ package org.openapitools.model; import com.fasterxml.jackson.annotation.JsonTypeName; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -17,7 +14,7 @@ /** * Must be named `File` for test. **/ -@ApiModel(description = "Must be named `File` for test.") + @org.eclipse.microprofile.openapi.annotations.media.Schema(description="Must be named `File` for test.") @JsonTypeName("File") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") @@ -40,7 +37,6 @@ public ModelFile sourceURI(String sourceURI) { } - @ApiModelProperty(value = "Test capitalization") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "Test capitalization") @JsonProperty("sourceURI") public String getSourceURI() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ModelList.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ModelList.java index 44b300c0b2a0..b9bc20f72c0d 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ModelList.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ModelList.java @@ -1,13 +1,10 @@ package org.openapitools.model; import com.fasterxml.jackson.annotation.JsonTypeName; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -37,7 +34,6 @@ public ModelList _123list(String _123list) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("123-list") public String get123list() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ModelReturn.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ModelReturn.java index f0129830c505..3323530e072b 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ModelReturn.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ModelReturn.java @@ -1,13 +1,10 @@ package org.openapitools.model; import com.fasterxml.jackson.annotation.JsonTypeName; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -17,7 +14,7 @@ /** * Model for testing reserved words **/ -@ApiModel(description = "Model for testing reserved words") + @org.eclipse.microprofile.openapi.annotations.media.Schema(description="Model for testing reserved words") @JsonTypeName("Return") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") @@ -39,7 +36,6 @@ public ModelReturn _return(Integer _return) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("return") public Integer getReturn() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Name.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Name.java index 1bc085a16fe8..a9d989197606 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Name.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Name.java @@ -1,12 +1,9 @@ package org.openapitools.model; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -16,7 +13,7 @@ /** * Model for testing model name same as property name **/ -@ApiModel(description = "Model for testing model name same as property name") + @org.eclipse.microprofile.openapi.annotations.media.Schema(description="Model for testing model name same as property name") @JsonTypeName("Name") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") @@ -44,7 +41,6 @@ public Name name(Integer name) { } - @ApiModelProperty(required = true, value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(required = true, description = "") @JsonProperty("name") @NotNull @@ -65,7 +61,6 @@ public Name snakeCase(Integer snakeCase) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("snake_case") public Integer getSnakeCase() { @@ -85,7 +80,6 @@ public Name property(String property) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("property") public String getProperty() { @@ -105,7 +99,6 @@ public Name _123number(Integer _123number) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("123Number") public Integer get123number() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/NumberOnly.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/NumberOnly.java index 2c8d35de677f..9ff873b25b7a 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/NumberOnly.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/NumberOnly.java @@ -1,13 +1,10 @@ package org.openapitools.model; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -37,7 +34,6 @@ public NumberOnly justNumber(BigDecimal justNumber) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("JustNumber") public BigDecimal getJustNumber() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Order.java index bde0f4e504b7..325a1392d1b5 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Order.java @@ -1,13 +1,10 @@ package org.openapitools.model; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.time.LocalDateTime; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -94,7 +91,6 @@ public Order id(Long id) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("id") public Long getId() { @@ -114,7 +110,6 @@ public Order petId(Long petId) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("petId") public Long getPetId() { @@ -134,7 +129,6 @@ public Order quantity(Integer quantity) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("quantity") public Integer getQuantity() { @@ -154,7 +148,6 @@ public Order shipDate(LocalDateTime shipDate) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("shipDate") public LocalDateTime getShipDate() { @@ -175,7 +168,6 @@ public Order status(StatusEnum status) { } - @ApiModelProperty(value = "Order Status") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "Order Status") @JsonProperty("status") public StatusEnum getStatus() { @@ -195,7 +187,6 @@ public Order complete(Boolean complete) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("complete") public Boolean getComplete() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/OuterComposite.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/OuterComposite.java index e9e8e43ad769..70e4b8f73e5c 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/OuterComposite.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/OuterComposite.java @@ -1,13 +1,10 @@ package org.openapitools.model; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -41,7 +38,6 @@ public OuterComposite myNumber(BigDecimal myNumber) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("my_number") public BigDecimal getMyNumber() { @@ -61,7 +57,6 @@ public OuterComposite myString(String myString) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("my_string") public String getMyString() { @@ -81,7 +76,6 @@ public OuterComposite myBoolean(Boolean myBoolean) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("my_boolean") public Boolean getMyBoolean() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Pet.java index 814ab97e40f5..de2fb0fc4067 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Pet.java @@ -1,8 +1,6 @@ package org.openapitools.model; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; @@ -13,7 +11,6 @@ import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -100,7 +97,6 @@ public Pet id(Long id) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("id") public Long getId() { @@ -120,7 +116,6 @@ public Pet category(Category category) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("category") public Category getCategory() { @@ -140,7 +135,6 @@ public Pet name(String name) { } - @ApiModelProperty(example = "doggie", required = true, value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(example = "doggie", required = true, description = "") @JsonProperty("name") @NotNull @@ -161,7 +155,6 @@ public Pet photoUrls(Set photoUrls) { } - @ApiModelProperty(required = true, value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(required = true, description = "") @JsonProperty("photoUrls") @NotNull @@ -199,7 +192,6 @@ public Pet tags(List tags) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("tags") public List getTags() { @@ -236,7 +228,6 @@ public Pet status(StatusEnum status) { } - @ApiModelProperty(value = "pet status in the store") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "pet status in the store") @JsonProperty("status") public StatusEnum getStatus() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ReadOnlyFirst.java index e544200620ca..eed1298e2340 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ReadOnlyFirst.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ReadOnlyFirst.java @@ -1,12 +1,9 @@ package org.openapitools.model; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -38,7 +35,6 @@ public ReadOnlyFirst bar(String bar) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("bar") public String getBar() { @@ -58,7 +54,6 @@ public ReadOnlyFirst baz(String baz) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("baz") public String getBaz() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/SpecialModelName.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/SpecialModelName.java index 61db35744e0e..d4ed4d445106 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/SpecialModelName.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/SpecialModelName.java @@ -1,13 +1,10 @@ package org.openapitools.model; import com.fasterxml.jackson.annotation.JsonTypeName; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -37,7 +34,6 @@ public SpecialModelName() { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("$special[property.name]") public Long get$SpecialPropertyName() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Tag.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Tag.java index e113a876a48e..5eef1df4ab91 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Tag.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Tag.java @@ -1,12 +1,9 @@ package org.openapitools.model; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -38,7 +35,6 @@ public Tag id(Long id) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("id") public Long getId() { @@ -58,7 +54,6 @@ public Tag name(String name) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("name") public String getName() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/TypeHolderDefault.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/TypeHolderDefault.java index 295441b2fdd0..c742fb7a90a7 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/TypeHolderDefault.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/TypeHolderDefault.java @@ -1,7 +1,5 @@ package org.openapitools.model; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; @@ -9,7 +7,6 @@ import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -47,7 +44,6 @@ public TypeHolderDefault stringItem(String stringItem) { } - @ApiModelProperty(required = true, value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(required = true, description = "") @JsonProperty("string_item") @NotNull @@ -68,7 +64,6 @@ public TypeHolderDefault numberItem(BigDecimal numberItem) { } - @ApiModelProperty(required = true, value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(required = true, description = "") @JsonProperty("number_item") @NotNull @@ -89,7 +84,6 @@ public TypeHolderDefault integerItem(Integer integerItem) { } - @ApiModelProperty(required = true, value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(required = true, description = "") @JsonProperty("integer_item") @NotNull @@ -110,7 +104,6 @@ public TypeHolderDefault boolItem(Boolean boolItem) { } - @ApiModelProperty(required = true, value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(required = true, description = "") @JsonProperty("bool_item") @NotNull @@ -131,7 +124,6 @@ public TypeHolderDefault arrayItem(List arrayItem) { } - @ApiModelProperty(required = true, value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(required = true, description = "") @JsonProperty("array_item") @NotNull diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/TypeHolderExample.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/TypeHolderExample.java index a75b956bd672..6d547b839ff0 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/TypeHolderExample.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/TypeHolderExample.java @@ -1,7 +1,5 @@ package org.openapitools.model; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; @@ -9,7 +7,6 @@ import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -49,7 +46,6 @@ public TypeHolderExample stringItem(String stringItem) { } - @ApiModelProperty(example = "what", required = true, value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(example = "what", required = true, description = "") @JsonProperty("string_item") @NotNull @@ -70,7 +66,6 @@ public TypeHolderExample numberItem(BigDecimal numberItem) { } - @ApiModelProperty(example = "1.234", required = true, value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(example = "1.234", required = true, description = "") @JsonProperty("number_item") @NotNull @@ -91,7 +86,6 @@ public TypeHolderExample floatItem(Float floatItem) { } - @ApiModelProperty(example = "1.234", required = true, value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(example = "1.234", required = true, description = "") @JsonProperty("float_item") @NotNull @@ -112,7 +106,6 @@ public TypeHolderExample integerItem(Integer integerItem) { } - @ApiModelProperty(example = "-2", required = true, value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(example = "-2", required = true, description = "") @JsonProperty("integer_item") @NotNull @@ -133,7 +126,6 @@ public TypeHolderExample boolItem(Boolean boolItem) { } - @ApiModelProperty(example = "true", required = true, value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(example = "true", required = true, description = "") @JsonProperty("bool_item") @NotNull @@ -154,7 +146,6 @@ public TypeHolderExample arrayItem(List arrayItem) { } - @ApiModelProperty(example = "[0, 1, 2, 3]", required = true, value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(example = "[0, 1, 2, 3]", required = true, description = "") @JsonProperty("array_item") @NotNull diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/User.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/User.java index c8516ebe602a..aed3620354eb 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/User.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/User.java @@ -1,12 +1,9 @@ package org.openapitools.model; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -50,7 +47,6 @@ public User id(Long id) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("id") public Long getId() { @@ -70,7 +66,6 @@ public User username(String username) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("username") public String getUsername() { @@ -90,7 +85,6 @@ public User firstName(String firstName) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("firstName") public String getFirstName() { @@ -110,7 +104,6 @@ public User lastName(String lastName) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("lastName") public String getLastName() { @@ -130,7 +123,6 @@ public User email(String email) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("email") public String getEmail() { @@ -150,7 +142,6 @@ public User password(String password) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("password") public String getPassword() { @@ -170,7 +161,6 @@ public User phone(String phone) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("phone") public String getPhone() { @@ -191,7 +181,6 @@ public User userStatus(Integer userStatus) { } - @ApiModelProperty(value = "User Status") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "User Status") @JsonProperty("userStatus") public Integer getUserStatus() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/XmlItem.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/XmlItem.java index 144d26fc69cc..e1bfb8270a0f 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/XmlItem.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/XmlItem.java @@ -1,7 +1,5 @@ package org.openapitools.model; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; @@ -9,7 +7,6 @@ import javax.validation.constraints.*; import javax.validation.Valid; -import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @@ -95,7 +92,6 @@ public XmlItem attributeString(String attributeString) { } - @ApiModelProperty(example = "string", value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(example = "string", description = "") @JsonProperty("attribute_string") public String getAttributeString() { @@ -115,7 +111,6 @@ public XmlItem attributeNumber(BigDecimal attributeNumber) { } - @ApiModelProperty(example = "1.234", value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(example = "1.234", description = "") @JsonProperty("attribute_number") public BigDecimal getAttributeNumber() { @@ -135,7 +130,6 @@ public XmlItem attributeInteger(Integer attributeInteger) { } - @ApiModelProperty(example = "-2", value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(example = "-2", description = "") @JsonProperty("attribute_integer") public Integer getAttributeInteger() { @@ -155,7 +149,6 @@ public XmlItem attributeBoolean(Boolean attributeBoolean) { } - @ApiModelProperty(example = "true", value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(example = "true", description = "") @JsonProperty("attribute_boolean") public Boolean getAttributeBoolean() { @@ -175,7 +168,6 @@ public XmlItem wrappedArray(List wrappedArray) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("wrapped_array") public List getWrappedArray() { @@ -211,7 +203,6 @@ public XmlItem nameString(String nameString) { } - @ApiModelProperty(example = "string", value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(example = "string", description = "") @JsonProperty("name_string") public String getNameString() { @@ -231,7 +222,6 @@ public XmlItem nameNumber(BigDecimal nameNumber) { } - @ApiModelProperty(example = "1.234", value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(example = "1.234", description = "") @JsonProperty("name_number") public BigDecimal getNameNumber() { @@ -251,7 +241,6 @@ public XmlItem nameInteger(Integer nameInteger) { } - @ApiModelProperty(example = "-2", value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(example = "-2", description = "") @JsonProperty("name_integer") public Integer getNameInteger() { @@ -271,7 +260,6 @@ public XmlItem nameBoolean(Boolean nameBoolean) { } - @ApiModelProperty(example = "true", value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(example = "true", description = "") @JsonProperty("name_boolean") public Boolean getNameBoolean() { @@ -291,7 +279,6 @@ public XmlItem nameArray(List nameArray) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("name_array") public List getNameArray() { @@ -327,7 +314,6 @@ public XmlItem nameWrappedArray(List nameWrappedArray) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("name_wrapped_array") public List getNameWrappedArray() { @@ -363,7 +349,6 @@ public XmlItem prefixString(String prefixString) { } - @ApiModelProperty(example = "string", value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(example = "string", description = "") @JsonProperty("prefix_string") public String getPrefixString() { @@ -383,7 +368,6 @@ public XmlItem prefixNumber(BigDecimal prefixNumber) { } - @ApiModelProperty(example = "1.234", value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(example = "1.234", description = "") @JsonProperty("prefix_number") public BigDecimal getPrefixNumber() { @@ -403,7 +387,6 @@ public XmlItem prefixInteger(Integer prefixInteger) { } - @ApiModelProperty(example = "-2", value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(example = "-2", description = "") @JsonProperty("prefix_integer") public Integer getPrefixInteger() { @@ -423,7 +406,6 @@ public XmlItem prefixBoolean(Boolean prefixBoolean) { } - @ApiModelProperty(example = "true", value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(example = "true", description = "") @JsonProperty("prefix_boolean") public Boolean getPrefixBoolean() { @@ -443,7 +425,6 @@ public XmlItem prefixArray(List prefixArray) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("prefix_array") public List getPrefixArray() { @@ -479,7 +460,6 @@ public XmlItem prefixWrappedArray(List prefixWrappedArray) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("prefix_wrapped_array") public List getPrefixWrappedArray() { @@ -515,7 +495,6 @@ public XmlItem namespaceString(String namespaceString) { } - @ApiModelProperty(example = "string", value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(example = "string", description = "") @JsonProperty("namespace_string") public String getNamespaceString() { @@ -535,7 +514,6 @@ public XmlItem namespaceNumber(BigDecimal namespaceNumber) { } - @ApiModelProperty(example = "1.234", value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(example = "1.234", description = "") @JsonProperty("namespace_number") public BigDecimal getNamespaceNumber() { @@ -555,7 +533,6 @@ public XmlItem namespaceInteger(Integer namespaceInteger) { } - @ApiModelProperty(example = "-2", value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(example = "-2", description = "") @JsonProperty("namespace_integer") public Integer getNamespaceInteger() { @@ -575,7 +552,6 @@ public XmlItem namespaceBoolean(Boolean namespaceBoolean) { } - @ApiModelProperty(example = "true", value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(example = "true", description = "") @JsonProperty("namespace_boolean") public Boolean getNamespaceBoolean() { @@ -595,7 +571,6 @@ public XmlItem namespaceArray(List namespaceArray) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("namespace_array") public List getNamespaceArray() { @@ -631,7 +606,6 @@ public XmlItem namespaceWrappedArray(List namespaceWrappedArray) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("namespace_wrapped_array") public List getNamespaceWrappedArray() { @@ -667,7 +641,6 @@ public XmlItem prefixNsString(String prefixNsString) { } - @ApiModelProperty(example = "string", value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(example = "string", description = "") @JsonProperty("prefix_ns_string") public String getPrefixNsString() { @@ -687,7 +660,6 @@ public XmlItem prefixNsNumber(BigDecimal prefixNsNumber) { } - @ApiModelProperty(example = "1.234", value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(example = "1.234", description = "") @JsonProperty("prefix_ns_number") public BigDecimal getPrefixNsNumber() { @@ -707,7 +679,6 @@ public XmlItem prefixNsInteger(Integer prefixNsInteger) { } - @ApiModelProperty(example = "-2", value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(example = "-2", description = "") @JsonProperty("prefix_ns_integer") public Integer getPrefixNsInteger() { @@ -727,7 +698,6 @@ public XmlItem prefixNsBoolean(Boolean prefixNsBoolean) { } - @ApiModelProperty(example = "true", value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(example = "true", description = "") @JsonProperty("prefix_ns_boolean") public Boolean getPrefixNsBoolean() { @@ -747,7 +717,6 @@ public XmlItem prefixNsArray(List prefixNsArray) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("prefix_ns_array") public List getPrefixNsArray() { @@ -783,7 +752,6 @@ public XmlItem prefixNsWrappedArray(List prefixNsWrappedArray) { } - @ApiModelProperty(value = "") @org.eclipse.microprofile.openapi.annotations.media.Schema(description = "") @JsonProperty("prefix_ns_wrapped_array") public List getPrefixNsWrappedArray() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/main/resources/META-INF/openapi.yaml b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/main/resources/META-INF/openapi.yaml new file mode 100644 index 000000000000..eded577e74f9 --- /dev/null +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/main/resources/META-INF/openapi.yaml @@ -0,0 +1,2276 @@ +openapi: 3.0.1 +info: + description: "This spec is mainly for testing Petstore server and contains fake\ + \ endpoints, models. Please do not use this for any other purpose. Special characters:\ + \ \" \\" + license: + name: Apache-2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html + title: OpenAPI Petstore + version: 1.0.0 +servers: +- url: http://petstore.swagger.io:80/v2 +tags: +- description: Everything about your Pets + name: pet +- description: Access to Petstore orders + name: store +- description: Operations about user + name: user +paths: + /pet: + post: + operationId: addPet + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + required: true + responses: + "200": + content: {} + description: successful operation + "405": + content: {} + description: Invalid input + security: + - petstore_auth: + - write:pets + - read:pets + summary: Add a new pet to the store + tags: + - pet + x-codegen-request-body-name: body + x-content-type: application/json + x-accepts: application/json + x-tags: + - tag: pet + put: + operationId: updatePet + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + required: true + responses: + "200": + content: {} + description: successful operation + "400": + content: {} + description: Invalid ID supplied + "404": + content: {} + description: Pet not found + "405": + content: {} + description: Validation exception + security: + - petstore_auth: + - write:pets + - read:pets + summary: Update an existing pet + tags: + - pet + x-codegen-request-body-name: body + x-content-type: application/json + x-accepts: application/json + x-tags: + - tag: pet + /pet/findByStatus: + get: + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + parameters: + - description: Status values that need to be considered for filter + explode: false + in: query + name: status + required: true + schema: + items: + default: available + enum: + - available + - pending + - sold + type: string + type: array + style: form + responses: + "200": + content: + application/xml: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + application/json: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + description: successful operation + "400": + content: {} + description: Invalid status value + security: + - petstore_auth: + - write:pets + - read:pets + summary: Finds Pets by status + tags: + - pet + x-accepts: application/json + x-tags: + - tag: pet + /pet/findByTags: + get: + deprecated: true + description: "Multiple tags can be provided with comma separated strings. Use\ + \ tag1, tag2, tag3 for testing." + operationId: findPetsByTags + parameters: + - description: Tags to filter by + explode: false + in: query + name: tags + required: true + schema: + items: + type: string + type: array + uniqueItems: true + style: form + responses: + "200": + content: + application/xml: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + uniqueItems: true + application/json: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + uniqueItems: true + description: successful operation + "400": + content: {} + description: Invalid tag value + security: + - petstore_auth: + - write:pets + - read:pets + summary: Finds Pets by tags + tags: + - pet + x-accepts: application/json + x-tags: + - tag: pet + /pet/{petId}: + delete: + operationId: deletePet + parameters: + - in: header + name: api_key + schema: + type: string + - description: Pet id to delete + in: path + name: petId + required: true + schema: + format: int64 + type: integer + responses: + "200": + content: {} + description: successful operation + "400": + content: {} + description: Invalid pet value + security: + - petstore_auth: + - write:pets + - read:pets + summary: Deletes a pet + tags: + - pet + x-accepts: application/json + x-tags: + - tag: pet + get: + description: Returns a single pet + operationId: getPetById + parameters: + - description: ID of pet to return + in: path + name: petId + required: true + schema: + format: int64 + type: integer + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + description: successful operation + "400": + content: {} + description: Invalid ID supplied + "404": + content: {} + description: Pet not found + security: + - api_key: [] + summary: Find pet by ID + tags: + - pet + x-accepts: application/json + x-tags: + - tag: pet + post: + operationId: updatePetWithForm + parameters: + - description: ID of pet that needs to be updated + in: path + name: petId + required: true + schema: + format: int64 + type: integer + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/updatePetWithForm_request' + responses: + "405": + content: {} + description: Invalid input + security: + - petstore_auth: + - write:pets + - read:pets + summary: Updates a pet in the store with form data + tags: + - pet + x-content-type: application/x-www-form-urlencoded + x-accepts: application/json + x-tags: + - tag: pet + /pet/{petId}/uploadImage: + post: + operationId: uploadFile + parameters: + - description: ID of pet to update + in: path + name: petId + required: true + schema: + format: int64 + type: integer + requestBody: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/uploadFile_request' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: successful operation + security: + - petstore_auth: + - write:pets + - read:pets + summary: uploads an image + tags: + - pet + x-content-type: multipart/form-data + x-accepts: application/json + x-tags: + - tag: pet + /store/inventory: + get: + description: Returns a map of status codes to quantities + operationId: getInventory + responses: + "200": + content: + application/json: + schema: + additionalProperties: + format: int32 + type: integer + type: object + description: successful operation + security: + - api_key: [] + summary: Returns pet inventories by status + tags: + - store + x-accepts: application/json + x-tags: + - tag: store + /store/order: + post: + operationId: placeOrder + requestBody: + content: + '*/*': + schema: + $ref: '#/components/schemas/Order' + description: order placed for purchasing the pet + required: true + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + description: successful operation + "400": + content: {} + description: Invalid Order + summary: Place an order for a pet + tags: + - store + x-codegen-request-body-name: body + x-content-type: '*/*' + x-accepts: application/json + x-tags: + - tag: store + /store/order/{order_id}: + delete: + description: For valid response try integer IDs with value < 1000. Anything + above 1000 or nonintegers will generate API errors + operationId: deleteOrder + parameters: + - description: ID of the order that needs to be deleted + in: path + name: order_id + required: true + schema: + type: string + responses: + "400": + content: {} + description: Invalid ID supplied + "404": + content: {} + description: Order not found + summary: Delete purchase order by ID + tags: + - store + x-accepts: application/json + x-tags: + - tag: store + get: + description: For valid response try integer IDs with value <= 5 or > 10. Other + values will generate exceptions + operationId: getOrderById + parameters: + - description: ID of pet that needs to be fetched + in: path + name: order_id + required: true + schema: + format: int64 + maximum: 5 + minimum: 1 + type: integer + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + description: successful operation + "400": + content: {} + description: Invalid ID supplied + "404": + content: {} + description: Order not found + summary: Find purchase order by ID + tags: + - store + x-accepts: application/json + x-tags: + - tag: store + /user: + post: + description: This can only be done by the logged in user. + operationId: createUser + requestBody: + content: + '*/*': + schema: + $ref: '#/components/schemas/User' + description: Created user object + required: true + responses: + default: + content: {} + description: successful operation + summary: Create user + tags: + - user + x-codegen-request-body-name: body + x-content-type: '*/*' + x-accepts: application/json + x-tags: + - tag: user + /user/createWithArray: + post: + operationId: createUsersWithArrayInput + requestBody: + content: + '*/*': + schema: + items: + $ref: '#/components/schemas/User' + type: array + description: List of user object + required: true + responses: + default: + content: {} + description: successful operation + summary: Creates list of users with given input array + tags: + - user + x-codegen-request-body-name: body + x-content-type: '*/*' + x-accepts: application/json + x-tags: + - tag: user + /user/createWithList: + post: + operationId: createUsersWithListInput + requestBody: + content: + '*/*': + schema: + items: + $ref: '#/components/schemas/User' + type: array + description: List of user object + required: true + responses: + default: + content: {} + description: successful operation + summary: Creates list of users with given input array + tags: + - user + x-codegen-request-body-name: body + x-content-type: '*/*' + x-accepts: application/json + x-tags: + - tag: user + /user/login: + get: + operationId: loginUser + parameters: + - description: The user name for login + in: query + name: username + required: true + schema: + type: string + - description: The password for login in clear text + in: query + name: password + required: true + schema: + type: string + responses: + "200": + content: + application/xml: + schema: + type: string + application/json: + schema: + type: string + description: successful operation + headers: + X-Rate-Limit: + description: calls per hour allowed by the user + schema: + format: int32 + type: integer + X-Expires-After: + description: date in UTC when token expires + schema: + format: date-time + type: string + "400": + content: {} + description: Invalid username/password supplied + summary: Logs user into the system + tags: + - user + x-accepts: application/json + x-tags: + - tag: user + /user/logout: + get: + operationId: logoutUser + responses: + default: + content: {} + description: successful operation + summary: Logs out current logged in user session + tags: + - user + x-accepts: application/json + x-tags: + - tag: user + /user/{username}: + delete: + description: This can only be done by the logged in user. + operationId: deleteUser + parameters: + - description: The name that needs to be deleted + in: path + name: username + required: true + schema: + type: string + responses: + "400": + content: {} + description: Invalid username supplied + "404": + content: {} + description: User not found + summary: Delete user + tags: + - user + x-accepts: application/json + x-tags: + - tag: user + get: + operationId: getUserByName + parameters: + - description: The name that needs to be fetched. Use user1 for testing. + in: path + name: username + required: true + schema: + type: string + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/User' + application/json: + schema: + $ref: '#/components/schemas/User' + description: successful operation + "400": + content: {} + description: Invalid username supplied + "404": + content: {} + description: User not found + summary: Get user by user name + tags: + - user + x-accepts: application/json + x-tags: + - tag: user + put: + description: This can only be done by the logged in user. + operationId: updateUser + parameters: + - description: name that need to be deleted + in: path + name: username + required: true + schema: + type: string + requestBody: + content: + '*/*': + schema: + $ref: '#/components/schemas/User' + description: Updated user object + required: true + responses: + "400": + content: {} + description: Invalid user supplied + "404": + content: {} + description: User not found + summary: Updated user + tags: + - user + x-codegen-request-body-name: body + x-content-type: '*/*' + x-accepts: application/json + x-tags: + - tag: user + /fake_classname_test: + patch: + description: To test class name in snake case + operationId: testClassname + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + description: client model + required: true + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + description: successful operation + security: + - api_key_query: [] + summary: To test class name in snake case + tags: + - fake_classname_tags 123#$%^ + x-codegen-request-body-name: body + x-content-type: application/json + x-accepts: application/json + x-tags: + - tag: fake_classname_tags 123#$%^ + /fake: + delete: + description: Fake endpoint to test group parameters (optional) + operationId: testGroupParameters + parameters: + - description: Required String in group parameters + in: query + name: required_string_group + required: true + schema: + type: integer + - description: Required Boolean in group parameters + in: header + name: required_boolean_group + required: true + schema: + type: boolean + - description: Required Integer in group parameters + in: query + name: required_int64_group + required: true + schema: + format: int64 + type: integer + - description: String in group parameters + in: query + name: string_group + schema: + type: integer + - description: Boolean in group parameters + in: header + name: boolean_group + schema: + type: boolean + - description: Integer in group parameters + in: query + name: int64_group + schema: + format: int64 + type: integer + responses: + "400": + content: {} + description: Something wrong + summary: Fake endpoint to test group parameters (optional) + tags: + - fake + x-group-parameters: true + x-accepts: application/json + x-tags: + - tag: fake + get: + description: To test enum parameters + operationId: testEnumParameters + parameters: + - description: Header parameter enum test (string array) + explode: false + in: header + name: enum_header_string_array + schema: + items: + default: $ + enum: + - '>' + - $ + type: string + type: array + style: simple + - description: Header parameter enum test (string) + in: header + name: enum_header_string + schema: + default: -efg + enum: + - _abc + - -efg + - (xyz) + type: string + - description: Query parameter enum test (string array) + explode: false + in: query + name: enum_query_string_array + schema: + items: + default: $ + enum: + - '>' + - $ + type: string + type: array + style: form + - description: Query parameter enum test (string) + in: query + name: enum_query_string + schema: + default: -efg + enum: + - _abc + - -efg + - (xyz) + type: string + - description: Query parameter enum test (double) + in: query + name: enum_query_integer + schema: + enum: + - 1 + - -2 + format: int32 + type: integer + - description: Query parameter enum test (double) + in: query + name: enum_query_double + schema: + enum: + - 1.1 + - -1.2 + format: double + type: number + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/testEnumParameters_request' + responses: + "400": + content: {} + description: Invalid request + "404": + content: {} + description: Not found + summary: To test enum parameters + tags: + - fake + x-content-type: application/x-www-form-urlencoded + x-accepts: application/json + x-tags: + - tag: fake + patch: + description: To test "client" model + operationId: testClientModel + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + description: client model + required: true + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + description: successful operation + summary: To test "client" model + tags: + - fake + x-codegen-request-body-name: body + x-content-type: application/json + x-accepts: application/json + x-tags: + - tag: fake + post: + description: |- + Fake endpoint for testing various parameters + 假端點 + 偽のエンドポイント + 가짜 엔드 포인트 + operationId: testEndpointParameters + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/testEndpointParameters_request' + required: true + responses: + "400": + content: {} + description: Invalid username supplied + "404": + content: {} + description: User not found + security: + - http_basic_test: [] + summary: |- + Fake endpoint for testing various parameters + 假端點 + 偽のエンドポイント + 가짜 엔드 포인트 + tags: + - fake + x-content-type: application/x-www-form-urlencoded + x-accepts: application/json + x-tags: + - tag: fake + /fake/outer/number: + post: + description: Test serialization of outer number types + operationId: fakeOuterNumberSerialize + requestBody: + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterNumber' + description: Input number as post body + required: false + responses: + "200": + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterNumber' + description: Output number + tags: + - fake + x-codegen-request-body-name: body + x-content-type: '*/*' + x-accepts: '*/*' + x-tags: + - tag: fake + /fake/outer/string: + post: + description: Test serialization of outer string types + operationId: fakeOuterStringSerialize + requestBody: + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterString' + description: Input string as post body + required: false + responses: + "200": + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterString' + description: Output string + tags: + - fake + x-codegen-request-body-name: body + x-content-type: '*/*' + x-accepts: '*/*' + x-tags: + - tag: fake + /fake/outer/boolean: + post: + description: Test serialization of outer boolean types + operationId: fakeOuterBooleanSerialize + requestBody: + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterBoolean' + description: Input boolean as post body + required: false + responses: + "200": + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterBoolean' + description: Output boolean + tags: + - fake + x-codegen-request-body-name: body + x-content-type: '*/*' + x-accepts: '*/*' + x-tags: + - tag: fake + /fake/outer/composite: + post: + description: Test serialization of object with outer number type + operationId: fakeOuterCompositeSerialize + requestBody: + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterComposite' + description: Input composite as post body + required: false + responses: + "200": + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterComposite' + description: Output composite + tags: + - fake + x-codegen-request-body-name: body + x-content-type: '*/*' + x-accepts: '*/*' + x-tags: + - tag: fake + /fake/jsonFormData: + get: + operationId: testJsonFormData + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/testJsonFormData_request' + required: true + responses: + "200": + content: {} + description: successful operation + summary: test json serialization of form data + tags: + - fake + x-content-type: application/x-www-form-urlencoded + x-accepts: application/json + x-tags: + - tag: fake + /fake/inline-additionalProperties: + post: + operationId: testInlineAdditionalProperties + requestBody: + content: + application/json: + schema: + additionalProperties: + type: string + type: object + description: request body + required: true + responses: + "200": + content: {} + description: successful operation + summary: test inline additionalProperties + tags: + - fake + x-codegen-request-body-name: param + x-content-type: application/json + x-accepts: application/json + x-tags: + - tag: fake + /fake/body-with-query-params: + put: + operationId: testBodyWithQueryParams + parameters: + - in: query + name: query + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + required: true + responses: + "200": + content: {} + description: Success + tags: + - fake + x-codegen-request-body-name: body + x-content-type: application/json + x-accepts: application/json + x-tags: + - tag: fake + /fake/create_xml_item: + post: + description: this route creates an XmlItem + operationId: createXmlItem + requestBody: + content: + application/xml: + schema: + $ref: '#/components/schemas/XmlItem' + application/xml; charset=utf-8: + schema: + $ref: '#/components/schemas/XmlItem' + application/xml; charset=utf-16: + schema: + $ref: '#/components/schemas/XmlItem' + text/xml: + schema: + $ref: '#/components/schemas/XmlItem' + text/xml; charset=utf-8: + schema: + $ref: '#/components/schemas/XmlItem' + text/xml; charset=utf-16: + schema: + $ref: '#/components/schemas/XmlItem' + description: XmlItem Body + required: true + responses: + "200": + content: {} + description: successful operation + summary: creates an XmlItem + tags: + - fake + x-codegen-request-body-name: XmlItem + x-content-type: application/xml + x-accepts: application/json + x-tags: + - tag: fake + /another-fake/dummy: + patch: + description: To test special tags and operation ID starting with number + operationId: 123_test_@#$%_special_tags + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + description: client model + required: true + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + description: successful operation + summary: To test special tags + tags: + - $another-fake? + x-codegen-request-body-name: body + x-content-type: application/json + x-accepts: application/json + x-tags: + - tag: $another-fake? + /fake/body-with-file-schema: + put: + description: "For this test, the body for this request much reference a schema\ + \ named `File`." + operationId: testBodyWithFileSchema + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FileSchemaTestClass' + required: true + responses: + "200": + content: {} + description: Success + tags: + - fake + x-codegen-request-body-name: body + x-content-type: application/json + x-accepts: application/json + x-tags: + - tag: fake + /fake/test-query-parameters: + put: + description: To test the collection format in query parameters + operationId: testQueryParameterCollectionFormat + parameters: + - explode: false + in: query + name: pipe + required: true + schema: + items: + type: string + type: array + style: form + - in: query + name: ioutil + required: true + schema: + items: + type: string + type: array + - in: query + name: http + required: true + schema: + items: + type: string + type: array + style: spaceDelimited + - explode: false + in: query + name: url + required: true + schema: + items: + type: string + type: array + style: form + - explode: true + in: query + name: context + required: true + schema: + items: + type: string + type: array + style: form + responses: + "200": + content: {} + description: Success + tags: + - fake + x-accepts: application/json + x-tags: + - tag: fake + /fake/{petId}/uploadImageWithRequiredFile: + post: + operationId: uploadFileWithRequiredFile + parameters: + - description: ID of pet to update + in: path + name: petId + required: true + schema: + format: int64 + type: integer + requestBody: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/uploadFileWithRequiredFile_request' + required: true + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: successful operation + security: + - petstore_auth: + - write:pets + - read:pets + summary: uploads an image (required) + tags: + - pet + x-content-type: multipart/form-data + x-accepts: application/json + x-tags: + - tag: pet +components: + schemas: + Order: + example: + petId: 6 + quantity: 1 + id: 0 + shipDate: 2000-01-23T04:56:07.000+00:00 + complete: false + status: placed + properties: + id: + format: int64 + type: integer + petId: + format: int64 + type: integer + quantity: + format: int32 + type: integer + shipDate: + format: date-time + type: string + status: + description: Order Status + enum: + - placed + - approved + - delivered + type: string + complete: + default: false + type: boolean + type: object + xml: + name: Order + Category: + example: + name: default-name + id: 6 + properties: + id: + format: int64 + type: integer + name: + default: default-name + type: string + required: + - name + type: object + xml: + name: Category + User: + example: + firstName: firstName + lastName: lastName + password: password + userStatus: 6 + phone: phone + id: 0 + email: email + username: username + properties: + id: + format: int64 + type: integer + x-is-unique: true + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + description: User Status + format: int32 + type: integer + type: object + xml: + name: User + Tag: + example: + name: name + id: 1 + properties: + id: + format: int64 + type: integer + name: + type: string + type: object + xml: + name: Tag + Pet: + example: + photoUrls: + - photoUrls + - photoUrls + name: doggie + id: 0 + category: + name: default-name + id: 6 + tags: + - name: name + id: 1 + - name: name + id: 1 + status: available + properties: + id: + format: int64 + type: integer + x-is-unique: true + category: + $ref: '#/components/schemas/Category' + name: + example: doggie + type: string + photoUrls: + items: + type: string + type: array + uniqueItems: true + xml: + name: photoUrl + wrapped: true + tags: + items: + $ref: '#/components/schemas/Tag' + type: array + xml: + name: tag + wrapped: true + status: + description: pet status in the store + enum: + - available + - pending + - sold + type: string + required: + - name + - photoUrls + type: object + xml: + name: Pet + ApiResponse: + example: + code: 0 + type: type + message: message + properties: + code: + format: int32 + type: integer + type: + type: string + message: + type: string + type: object + $special[model.name]: + properties: + $special[property.name]: + format: int64 + type: integer + type: object + xml: + name: "$special[model.name]" + Return: + description: Model for testing reserved words + properties: + return: + format: int32 + type: integer + type: object + xml: + name: Return + Name: + description: Model for testing model name same as property name + properties: + name: + format: int32 + type: integer + snake_case: + format: int32 + readOnly: true + type: integer + property: + type: string + "123Number": + readOnly: true + type: integer + required: + - name + type: object + xml: + name: Name + "200_response": + description: Model for testing model name starting with number + properties: + name: + format: int32 + type: integer + class: + type: string + type: object + xml: + name: Name + ClassModel: + description: Model for testing model with "_class" property + properties: + _class: + type: string + type: object + Dog: + allOf: + - $ref: '#/components/schemas/Animal' + - properties: + breed: + type: string + type: object + Cat: + allOf: + - $ref: '#/components/schemas/Animal' + - properties: + declawed: + type: boolean + type: object + BigCat: + allOf: + - $ref: '#/components/schemas/Cat' + - properties: + kind: + enum: + - lions + - tigers + - leopards + - jaguars + type: string + type: object + Animal: + discriminator: + propertyName: className + properties: + className: + type: string + color: + default: red + type: string + required: + - className + type: object + AnimalFarm: + items: + $ref: '#/components/schemas/Animal' + type: array + format_test: + properties: + integer: + maximum: 100 + minimum: 10 + type: integer + int32: + format: int32 + maximum: 200 + minimum: 20 + type: integer + int64: + format: int64 + type: integer + number: + maximum: 543.2 + minimum: 32.1 + type: number + float: + format: float + maximum: 987.6 + minimum: 54.3 + type: number + double: + format: double + maximum: 123.4 + minimum: 67.8 + type: number + string: + pattern: "/[a-z]/i" + type: string + byte: + format: byte + pattern: "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$" + type: string + binary: + format: binary + type: string + date: + format: date + type: string + dateTime: + format: date-time + type: string + uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + type: string + password: + format: password + maxLength: 64 + minLength: 10 + type: string + BigDecimal: + format: number + type: string + required: + - byte + - date + - number + - password + type: object + EnumClass: + default: -efg + enum: + - _abc + - -efg + - (xyz) + type: string + Enum_Test: + properties: + enum_string: + enum: + - UPPER + - lower + - "" + type: string + enum_string_required: + enum: + - UPPER + - lower + - "" + type: string + enum_integer: + enum: + - 1 + - -1 + format: int32 + type: integer + enum_number: + enum: + - 1.1 + - -1.2 + format: double + type: number + outerEnum: + $ref: '#/components/schemas/OuterEnum' + required: + - enum_string_required + type: object + AdditionalPropertiesClass: + properties: + map_string: + additionalProperties: + type: string + type: object + map_number: + additionalProperties: + type: number + type: object + map_integer: + additionalProperties: + type: integer + type: object + map_boolean: + additionalProperties: + type: boolean + type: object + map_array_integer: + additionalProperties: + items: + type: integer + type: array + type: object + map_array_anytype: + additionalProperties: + items: + properties: {} + type: object + type: array + type: object + map_map_string: + additionalProperties: + additionalProperties: + type: string + type: object + type: object + map_map_anytype: + additionalProperties: + additionalProperties: + properties: {} + type: object + type: object + type: object + anytype_1: + properties: {} + type: object + anytype_2: + type: object + anytype_3: + properties: {} + type: object + type: object + AdditionalPropertiesString: + additionalProperties: + type: string + properties: + name: + type: string + type: object + AdditionalPropertiesInteger: + additionalProperties: + type: integer + properties: + name: + type: string + type: object + AdditionalPropertiesNumber: + additionalProperties: + type: number + properties: + name: + type: string + type: object + AdditionalPropertiesBoolean: + additionalProperties: + type: boolean + properties: + name: + type: string + type: object + AdditionalPropertiesArray: + additionalProperties: + items: + properties: {} + type: object + type: array + properties: + name: + type: string + type: object + AdditionalPropertiesObject: + additionalProperties: + additionalProperties: + properties: {} + type: object + type: object + properties: + name: + type: string + type: object + AdditionalPropertiesAnyType: + additionalProperties: + properties: {} + type: object + properties: + name: + type: string + type: object + MixedPropertiesAndAdditionalPropertiesClass: + properties: + uuid: + format: uuid + type: string + dateTime: + format: date-time + type: string + map: + additionalProperties: + $ref: '#/components/schemas/Animal' + type: object + type: object + List: + properties: + "123-list": + type: string + type: object + Client: + example: + client: client + properties: + client: + type: string + type: object + ReadOnlyFirst: + properties: + bar: + readOnly: true + type: string + baz: + type: string + type: object + hasOnlyReadOnly: + properties: + bar: + readOnly: true + type: string + foo: + readOnly: true + type: string + type: object + Capitalization: + properties: + smallCamel: + type: string + CapitalCamel: + type: string + small_Snake: + type: string + Capital_Snake: + type: string + SCA_ETH_Flow_Points: + type: string + ATT_NAME: + description: | + Name of the pet + type: string + type: object + MapTest: + properties: + map_map_of_string: + additionalProperties: + additionalProperties: + type: string + type: object + type: object + map_of_enum_string: + additionalProperties: + enum: + - UPPER + - lower + type: string + type: object + direct_map: + additionalProperties: + type: boolean + type: object + indirect_map: + additionalProperties: + type: boolean + type: object + type: object + ArrayTest: + properties: + array_of_string: + items: + type: string + type: array + array_array_of_integer: + items: + items: + format: int64 + type: integer + type: array + type: array + array_array_of_model: + items: + items: + $ref: '#/components/schemas/ReadOnlyFirst' + type: array + type: array + type: object + NumberOnly: + properties: + JustNumber: + type: number + type: object + ArrayOfNumberOnly: + properties: + ArrayNumber: + items: + type: number + type: array + type: object + ArrayOfArrayOfNumberOnly: + properties: + ArrayArrayNumber: + items: + items: + type: number + type: array + type: array + type: object + EnumArrays: + properties: + just_symbol: + enum: + - '>=' + - $ + type: string + array_enum: + items: + enum: + - fish + - crab + type: string + type: array + type: object + OuterEnum: + enum: + - placed + - approved + - delivered + type: string + OuterComposite: + example: + my_string: my_string + my_number: 0.8008281904610115 + my_boolean: true + properties: + my_number: + type: number + my_string: + type: string + my_boolean: + type: boolean + x-codegen-body-parameter-name: boolean_post_body + type: object + OuterNumber: + type: number + OuterString: + type: string + OuterBoolean: + type: boolean + x-codegen-body-parameter-name: boolean_post_body + StringBooleanMap: + additionalProperties: + type: boolean + type: object + FileSchemaTestClass: + example: + file: + sourceURI: sourceURI + files: + - sourceURI: sourceURI + - sourceURI: sourceURI + properties: + file: + $ref: '#/components/schemas/File' + files: + items: + $ref: '#/components/schemas/File' + type: array + type: object + File: + description: Must be named `File` for test. + example: + sourceURI: sourceURI + properties: + sourceURI: + description: Test capitalization + type: string + type: object + TypeHolderDefault: + properties: + string_item: + default: what + type: string + number_item: + type: number + integer_item: + type: integer + bool_item: + default: true + type: boolean + array_item: + items: + type: integer + type: array + required: + - array_item + - bool_item + - integer_item + - number_item + - string_item + type: object + TypeHolderExample: + properties: + string_item: + example: what + type: string + number_item: + example: 1.234 + type: number + float_item: + example: 1.234 + format: float + type: number + integer_item: + example: -2 + type: integer + bool_item: + example: true + type: boolean + array_item: + example: + - 0 + - 1 + - 2 + - 3 + items: + type: integer + type: array + required: + - array_item + - bool_item + - float_item + - integer_item + - number_item + - string_item + type: object + XmlItem: + properties: + attribute_string: + example: string + type: string + xml: + attribute: true + attribute_number: + example: 1.234 + type: number + xml: + attribute: true + attribute_integer: + example: -2 + type: integer + xml: + attribute: true + attribute_boolean: + example: true + type: boolean + xml: + attribute: true + wrapped_array: + items: + type: integer + type: array + xml: + wrapped: true + name_string: + example: string + type: string + xml: + name: xml_name_string + name_number: + example: 1.234 + type: number + xml: + name: xml_name_number + name_integer: + example: -2 + type: integer + xml: + name: xml_name_integer + name_boolean: + example: true + type: boolean + xml: + name: xml_name_boolean + name_array: + items: + type: integer + xml: + name: xml_name_array_item + type: array + name_wrapped_array: + items: + type: integer + xml: + name: xml_name_wrapped_array_item + type: array + xml: + name: xml_name_wrapped_array + wrapped: true + prefix_string: + example: string + type: string + xml: + prefix: ab + prefix_number: + example: 1.234 + type: number + xml: + prefix: cd + prefix_integer: + example: -2 + type: integer + xml: + prefix: ef + prefix_boolean: + example: true + type: boolean + xml: + prefix: gh + prefix_array: + items: + type: integer + xml: + prefix: ij + type: array + prefix_wrapped_array: + items: + type: integer + xml: + prefix: mn + type: array + xml: + prefix: kl + wrapped: true + namespace_string: + example: string + type: string + xml: + namespace: http://a.com/schema + namespace_number: + example: 1.234 + type: number + xml: + namespace: http://b.com/schema + namespace_integer: + example: -2 + type: integer + xml: + namespace: http://c.com/schema + namespace_boolean: + example: true + type: boolean + xml: + namespace: http://d.com/schema + namespace_array: + items: + type: integer + xml: + namespace: http://e.com/schema + type: array + namespace_wrapped_array: + items: + type: integer + xml: + namespace: http://g.com/schema + type: array + xml: + namespace: http://f.com/schema + wrapped: true + prefix_ns_string: + example: string + type: string + xml: + namespace: http://a.com/schema + prefix: a + prefix_ns_number: + example: 1.234 + type: number + xml: + namespace: http://b.com/schema + prefix: b + prefix_ns_integer: + example: -2 + type: integer + xml: + namespace: http://c.com/schema + prefix: c + prefix_ns_boolean: + example: true + type: boolean + xml: + namespace: http://d.com/schema + prefix: d + prefix_ns_array: + items: + type: integer + xml: + namespace: http://e.com/schema + prefix: e + type: array + prefix_ns_wrapped_array: + items: + type: integer + xml: + namespace: http://g.com/schema + prefix: g + type: array + xml: + namespace: http://f.com/schema + prefix: f + wrapped: true + type: object + xml: + namespace: http://a.com/schema + prefix: pre + updatePetWithForm_request: + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + type: object + uploadFile_request: + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + format: binary + type: string + type: object + testEnumParameters_request: + properties: + enum_form_string_array: + description: Form parameter enum test (string array) + items: + default: $ + enum: + - '>' + - $ + type: string + type: array + enum_form_string: + default: -efg + description: Form parameter enum test (string) + enum: + - _abc + - -efg + - (xyz) + type: string + type: object + testEndpointParameters_request: + properties: + integer: + description: None + format: int32 + maximum: 100 + minimum: 10 + type: integer + int32: + description: None + format: int32 + maximum: 200 + minimum: 20 + type: integer + int64: + description: None + format: int64 + type: integer + number: + description: None + maximum: 543.2 + minimum: 32.1 + type: number + float: + description: None + format: float + maximum: 987.6 + type: number + double: + description: None + format: double + maximum: 123.4 + minimum: 67.8 + type: number + string: + description: None + pattern: "/[a-z]/i" + type: string + pattern_without_delimiter: + description: None + pattern: "^[A-Z].*" + type: string + byte: + description: None + format: byte + type: string + binary: + description: None + format: binary + type: string + date: + description: None + format: date + type: string + dateTime: + description: None + format: date-time + type: string + password: + description: None + format: password + maxLength: 64 + minLength: 10 + type: string + callback: + description: None + type: string + required: + - byte + - double + - number + - pattern_without_delimiter + type: object + testJsonFormData_request: + properties: + param: + description: field1 + type: string + param2: + description: field2 + type: string + required: + - param + - param2 + type: object + uploadFileWithRequiredFile_request: + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + requiredFile: + description: file to upload + format: binary + type: string + required: + - requiredFile + type: object + securitySchemes: + petstore_auth: + flows: + implicit: + authorizationUrl: http://petstore.swagger.io/api/oauth/dialog + scopes: + write:pets: modify pets in your account + read:pets: read your pets + type: oauth2 + api_key: + in: header + name: api_key + type: apiKey + api_key_query: + in: query + name: api_key_query + type: apiKey + http_basic_test: + scheme: basic + type: http +x-original-swagger-version: "2.0" From e299382a4258f3c8887a4d6d87e5b09d0f5d1013 Mon Sep 17 00:00:00 2001 From: karzang <66318084+karzang@users.noreply.github.com> Date: Sun, 6 Aug 2023 05:16:50 +0200 Subject: [PATCH 014/292] [Java][Client] Fix handling of 'number' types in oneOf (#16202) --- docs/generators/java.md | 1 - .../codegen/languages/JavaClientCodegen.java | 12 -------- .../okhttp-gson/oneof_model.mustache | 30 +++++++++++++++++++ .../java/apache-httpclient/docs/FakeApi.md | 2 +- .../model/ArrayOfArrayOfNumberOnly.java | 16 +++++----- .../client/model/ArrayOfNumberOnly.java | 16 +++++----- .../java/google-api-client/docs/FakeApi.md | 2 +- .../petstore/java/jersey1/docs/FakeApi.md | 2 +- .../docs/FakeApi.md | 2 +- .../java/jersey2-java8/docs/FakeApi.md | 2 +- .../petstore/java/jersey3/docs/FakeApi.md | 2 +- .../java/native-async/docs/FakeApi.md | 4 +-- .../model/ArrayOfArrayOfNumberOnly.java | 8 +++-- .../client/model/ArrayOfNumberOnly.java | 8 +++-- .../petstore/java/native/docs/FakeApi.md | 4 +-- .../model/ArrayOfArrayOfNumberOnly.java | 8 +++-- .../client/model/ArrayOfNumberOnly.java | 8 +++-- .../docs/FakeApi.md | 2 +- .../docs/FakeApi.md | 2 +- .../model/AdditionalPropertiesClass.java | 2 +- .../client/model/ArrayOfNumberOnly.java | 2 +- .../openapitools/client/model/FormatTest.java | 4 +-- .../openapitools/client/model/NumberOnly.java | 2 +- .../client/model/OuterComposite.java | 2 +- .../client/model/TypeHolderDefault.java | 2 +- .../client/model/TypeHolderExample.java | 2 +- .../openapitools/client/model/XmlItem.java | 10 +++---- .../petstore/java/okhttp-gson/docs/FakeApi.md | 2 +- .../org/openapitools/client/model/Scalar.java | 4 +-- .../java/rest-assured-jackson/docs/FakeApi.md | 2 +- .../model/AdditionalPropertiesClass.java | 1 + .../client/model/ArrayOfNumberOnly.java | 1 + .../openapitools/client/model/FormatTest.java | 2 ++ .../openapitools/client/model/NumberOnly.java | 1 + .../client/model/OuterComposite.java | 1 + .../client/model/TypeHolderDefault.java | 1 + .../client/model/TypeHolderExample.java | 1 + .../openapitools/client/model/XmlItem.java | 5 ++++ .../java/rest-assured/docs/FakeApi.md | 2 +- .../model/AdditionalPropertiesClass.java | 1 + .../client/model/ArrayOfNumberOnly.java | 1 + .../openapitools/client/model/FormatTest.java | 2 ++ .../openapitools/client/model/NumberOnly.java | 1 + .../client/model/OuterComposite.java | 1 + .../client/model/TypeHolderDefault.java | 1 + .../client/model/TypeHolderExample.java | 1 + .../openapitools/client/model/XmlItem.java | 5 ++++ .../petstore/java/resteasy/docs/FakeApi.md | 2 +- .../java/resttemplate-withXml/docs/FakeApi.md | 2 +- .../java/resttemplate/docs/FakeApi.md | 2 +- .../java/retrofit2-play26/docs/FakeApi.md | 2 +- .../model/AdditionalPropertiesClass.java | 1 + .../client/model/ArrayOfNumberOnly.java | 1 + .../openapitools/client/model/FormatTest.java | 2 ++ .../openapitools/client/model/NumberOnly.java | 1 + .../client/model/OuterComposite.java | 1 + .../client/model/TypeHolderDefault.java | 1 + .../client/model/TypeHolderExample.java | 1 + .../openapitools/client/model/XmlItem.java | 5 ++++ .../petstore/java/retrofit2/docs/FakeApi.md | 2 +- .../java/retrofit2rx2/docs/FakeApi.md | 2 +- .../java/retrofit2rx3/docs/FakeApi.md | 2 +- .../java/vertx-no-nullable/docs/FakeApi.md | 2 +- .../petstore/java/vertx/docs/FakeApi.md | 2 +- .../java/webclient-jakarta/docs/FakeApi.md | 2 +- .../java/webclient-swagger2/docs/FakeApi.md | 2 +- .../petstore/java/webclient/docs/FakeApi.md | 2 +- .../java/jersey2-java8/docs/FakeApi.md | 2 +- 68 files changed, 150 insertions(+), 82 deletions(-) diff --git a/docs/generators/java.md b/docs/generators/java.md index 70aee6e9d7cb..941e1c4e2ea9 100644 --- a/docs/generators/java.md +++ b/docs/generators/java.md @@ -149,7 +149,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl ## LANGUAGE PRIMITIVES