From 0a02860b50994caca037b515cfe65dfa7fccb1c7 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Mon, 24 Jul 2023 15:54:40 +0800 Subject: [PATCH] add parameter name mapping (#16160) --- bin/configs/java-okhttp-gson.yaml | 3 + docs/customization.md | 8 +- .../openapitools/codegen/cmd/ConfigHelp.java | 21 ++- .../openapitools/codegen/cmd/Generate.java | 12 +- .../codegen/config/GeneratorSettings.java | 49 +++++- .../OpenApiGeneratorGenerateExtension.kt | 7 +- .../gradle/plugin/tasks/GenerateTask.kt | 15 +- .../codegen/plugin/CodeGenMojo.java | 18 ++- .../openapitools/codegen/CodegenConfig.java | 2 + .../openapitools/codegen/DefaultCodegen.java | 9 +- .../codegen/config/CodegenConfigurator.java | 17 ++ .../config/CodegenConfiguratorUtils.java | 13 ++ .../languages/AbstractJavaCodegen.java | 6 +- .../languages/AbstractPythonCodegen.java | 6 +- ...points-models-for-testing-okhttp-gson.yaml | 29 ++++ .../petstore/java/okhttp-gson/README.md | 1 + .../java/okhttp-gson/api/openapi.yaml | 36 +++++ .../petstore/java/okhttp-gson/docs/FakeApi.md | 64 ++++++++ .../org/openapitools/client/api/FakeApi.java | 147 ++++++++++++++++++ 19 files changed, 442 insertions(+), 21 deletions(-) diff --git a/bin/configs/java-okhttp-gson.yaml b/bin/configs/java-okhttp-gson.yaml index 064c19197f..a93c8263dd 100644 --- a/bin/configs/java-okhttp-gson.yaml +++ b/bin/configs/java-okhttp-gson.yaml @@ -6,6 +6,9 @@ templateDir: modules/openapi-generator/src/main/resources/Java nameMappings: _type: underscoreType type_: typeWithUnderscore +parameterNameMappings: + _type: underscoreType + type_: typeWithUnderscore additionalProperties: artifactId: petstore-okhttp-gson hideGenerationTimestamp: "true" diff --git a/docs/customization.md b/docs/customization.md index e2ad04aa16..38772ab718 100644 --- a/docs/customization.md +++ b/docs/customization.md @@ -397,7 +397,7 @@ or ## Name Mapping -One can map the name of the property/parameter to something else. Consider the following schema: +One can map the property name using `nameMappings` option and parameter name using `parameterNameMappings` option to something else. Consider the following schema: ``` PropertyNameCollision: properties: @@ -411,12 +411,12 @@ One can map the name of the property/parameter to something else. Consider the f ``` `_type`, `type`, `type_` will result in property name collision in the Java client generator for example. We can resolve the issue using `nameMappings` by mapping `_type` to `underscoreType`, `type_` to `typeWithUnderscore`. -Here is an example to use `nameMappings` in CLI: +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 +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 open an issue (ticket) to let us know which generators you would like to have this feature enabled and we'll prioritize accordingly.) +(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.) ## 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 d3f3a9c824..2871642347 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 @@ -80,9 +80,12 @@ public class ConfigHelp extends OpenApiGeneratorCommand { @Option(name = {"--inline-schema-options"}, title = "inline schema options", description = "options for handling inline schemas in inline model resolver") private Boolean inlineSchemaOptions; - @Option(name = {"--name-mappings"}, title = "property/parameter name mappings", description = "displays the property/parameter name mappings (none)") + @Option(name = {"--name-mappings"}, title = "property name mappings", description = "displays the property name mappings (none)") private Boolean nameMappings; + @Option(name = {"--parameter-name-mappings"}, title = "parameter name mappings", description = "displays the parameter name mappings (none)") + private Boolean parameterNameMappings; + @Option(name = {"--openapi-normalizer"}, title = "openapi normalizer rules", description = "displays the OpenAPI normalizer rules (none)") private Boolean openapiNormalizer; @@ -501,14 +504,26 @@ public class ConfigHelp extends OpenApiGeneratorCommand { } if (Boolean.TRUE.equals(nameMappings)) { - sb.append(newline).append("PROPERTY, PARAMETER NAME MAPPING").append(newline).append(newline); + sb.append(newline).append("PROPERTY NAME MAPPING").append(newline).append(newline); Map map = config.nameMapping() .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, "property, parameter name", "Mapped to"); + writePlainTextFromMap(sb, map, optIndent, optNestedIndent, "property name", "Mapped to"); + sb.append(newline); + } + + if (Boolean.TRUE.equals(parameterNameMappings)) { + sb.append(newline).append("PARAMETER NAME MAPPING").append(newline).append(newline); + Map map = config.parameterNameMapping() + .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, "parameter name", "Mapped to"); sb.append(newline); } 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 0243954478..c64e44757c 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 @@ -190,11 +190,18 @@ public class Generate extends OpenApiGeneratorCommand { @Option( name = {"--name-mappings"}, - title = "property, parameter name mappings", - description = "specifies mappings between the property, parameter name and the new name in the format of param_name=paramName,prop_name=PropName." + title = "property name mappings", + description = "specifies mappings between the property name and the new name in the format of prop_name=PropName,prop_name2=PropName2." + " You can also have multiple occurrences of this option.") private List nameMappings = new ArrayList<>(); + @Option( + name = {"--parameter-name-mappings"}, + title = "parameter name mappings", + description = "specifies mappings between the parameter name and the new name in the format of param_name=paramName,param_name2=paramName2." + + " You can also have multiple occurrences of this option.") + private List parameterNameMappings = new ArrayList<>(); + @Option( name = {"--openapi-normalizer"}, title = "OpenAPI normalizer rules", @@ -476,6 +483,7 @@ public class Generate extends OpenApiGeneratorCommand { applyInlineSchemaNameMappingsKvpList(inlineSchemaNameMappings, configurator); applyInlineSchemaOptionsKvpList(inlineSchemaOptions, configurator); applyNameMappingsKvpList(nameMappings, configurator); + applyParameterNameMappingsKvpList(parameterNameMappings, 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 4ff11a044e..4b5b41dd1b 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 @@ -54,6 +54,7 @@ public final class GeneratorSettings implements Serializable { private final Map inlineSchemaNameMappings; private final Map inlineSchemaOptions; private final Map nameMappings; + private final Map parameterNameMappings; private final Map openapiNormalizer; private final Set languageSpecificPrimitives; private final Map reservedWordsMappings; @@ -267,14 +268,23 @@ public final class GeneratorSettings implements Serializable { } /** - * Gets property, parameter name mappings between a property, parameter name and the new name. + * Gets property name mappings between a property name and the new name. * - * @return the property, parameter name mappings + * @return the property name mappings */ public Map getNameMappings() { return nameMappings; } + /** + * Gets parameter name mappings between a parameter name and the new name. + * + * @return the parameter name mappings + */ + public Map getParameterNameMappings() { + return parameterNameMappings; + } + /** * Gets OpenAPI normalizer rules * @@ -403,6 +413,7 @@ public final class GeneratorSettings implements Serializable { inlineSchemaNameMappings = Collections.unmodifiableMap(builder.inlineSchemaNameMappings); inlineSchemaOptions = Collections.unmodifiableMap(builder.inlineSchemaOptions); nameMappings = Collections.unmodifiableMap(builder.nameMappings); + parameterNameMappings = Collections.unmodifiableMap(builder.parameterNameMappings); openapiNormalizer = Collections.unmodifiableMap(builder.openapiNormalizer); languageSpecificPrimitives = Collections.unmodifiableSet(builder.languageSpecificPrimitives); reservedWordsMappings = Collections.unmodifiableMap(builder.reservedWordsMappings); @@ -478,6 +489,7 @@ public final class GeneratorSettings implements Serializable { inlineSchemaNameMappings = Collections.unmodifiableMap(new HashMap<>(0)); inlineSchemaOptions = Collections.unmodifiableMap(new HashMap<>(0)); nameMappings = Collections.unmodifiableMap(new HashMap<>(0)); + parameterNameMappings = Collections.unmodifiableMap(new HashMap<>(0)); openapiNormalizer = Collections.unmodifiableMap(new HashMap<>(0)); languageSpecificPrimitives = Collections.unmodifiableSet(new HashSet<>(0)); reservedWordsMappings = Collections.unmodifiableMap(new HashMap<>(0)); @@ -542,6 +554,9 @@ public final class GeneratorSettings implements Serializable { if (copy.getNameMappings() != null) { builder.nameMappings.putAll(copy.getNameMappings()); } + if (copy.getParameterNameMappings() != null) { + builder.parameterNameMappings.putAll(copy.getParameterNameMappings()); + } if (copy.getOpenAPINormalizer() != null) { builder.openapiNormalizer.putAll(copy.getOpenAPINormalizer()); } @@ -588,6 +603,7 @@ public final class GeneratorSettings implements Serializable { private Map inlineSchemaNameMappings; private Map inlineSchemaOptions; private Map nameMappings; + private Map parameterNameMappings; private Map openapiNormalizer; private Set languageSpecificPrimitives; private Map reservedWordsMappings; @@ -610,6 +626,7 @@ public final class GeneratorSettings implements Serializable { inlineSchemaNameMappings = new HashMap<>(); inlineSchemaOptions = new HashMap<>(); nameMappings = new HashMap<>(); + parameterNameMappings = new HashMap<>(); openapiNormalizer = new HashMap<>(); languageSpecificPrimitives = new HashSet<>(); reservedWordsMappings = new HashMap<>(); @@ -957,6 +974,32 @@ public final class GeneratorSettings implements Serializable { return this; } + /** + * Sets the {@code parameterNameMappings} and returns a reference to this Builder so that the methods can be chained together. + * + * @param parameterNameMappings the {@code parameterNameMappings} to set + * @return a reference to this Builder + */ + public Builder withParameterNameMappings(Map parameterNameMappings) { + this.parameterNameMappings = parameterNameMappings; + return this; + } + + /** + * Sets a single {@code parameterNameMappings} 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 withParameterNameMapping(String key, String value) { + if (this.parameterNameMappings == null) { + this.parameterNameMappings = new HashMap<>(); + } + this.parameterNameMappings.put(key, value); + return this; + } + /** * Sets the {@code openapiNormalizer} and returns a reference to this Builder so that the methods can be chained together. * @@ -1172,6 +1215,7 @@ public final class GeneratorSettings implements Serializable { Objects.equals(getInlineSchemaNameMappings(), that.getInlineSchemaNameMappings()) && Objects.equals(getInlineSchemaOptions(), that.getInlineSchemaOptions()) && Objects.equals(getNameMappings(), that.getNameMappings()) && + Objects.equals(getParameterNameMappings(), that.getParameterNameMappings()) && Objects.equals(getOpenAPINormalizer(), that.getOpenAPINormalizer()) && Objects.equals(getLanguageSpecificPrimitives(), that.getLanguageSpecificPrimitives()) && Objects.equals(getReservedWordsMappings(), that.getReservedWordsMappings()) && @@ -1205,6 +1249,7 @@ public final class GeneratorSettings implements Serializable { getInlineSchemaNameMappings(), getInlineSchemaOptions(), getNameMappings(), + getParameterNameMappings(), 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 bffbaa13d3..76c89b263e 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 @@ -168,10 +168,15 @@ open class OpenApiGeneratorGenerateExtension(project: Project) { val inlineSchemaOptions = project.objects.mapProperty() /** - * Specifies mappings between a property, parameter name and the new name + * Specifies mappings between a property name and the new name */ val nameMappings = project.objects.mapProperty() + /** + * Specifies mappings between a parameter name and the new name + */ + val parameterNameMappings = 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 415ce83a44..a4fa91b375 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 @@ -273,12 +273,19 @@ open class GenerateTask @Inject constructor(private val objectFactory: ObjectFac val inlineSchemaOptions = project.objects.mapProperty() /** - * Specifies mappings between the property, parameter name and the new name + * Specifies mappings between the property name and the new name */ @Optional @Input val nameMappings = project.objects.mapProperty() + /** + * Specifies mappings between the parameter name and the new name + */ + @Optional + @Input + val parameterNameMappings = project.objects.mapProperty() + /** * Specifies mappings (rules) in OpenAPI normalizer */ @@ -820,6 +827,12 @@ open class GenerateTask @Inject constructor(private val objectFactory: ObjectFac } } + if (parameterNameMappings.isPresent) { + parameterNameMappings.get().forEach { entry -> + configurator.addParameterNameMapping(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 0e073c3f98..d887357349 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 @@ -333,11 +333,17 @@ public class CodeGenMojo extends AbstractMojo { private List inlineSchemaOptions; /** - * A map of property, parameter names and the new names + * A map of property names and the new names */ @Parameter(name = "nameMappings", property = "openapi.generator.maven.plugin.nameMappings") private List nameMappings; + /** + * A map of parameter names and the new names + */ + @Parameter(name = "parameterNameMappings", property = "openapi.generator.maven.plugin.parameterNameMappings") + private List parameterNameMappings; + /** * A set of rules for OpenAPI normalizer */ @@ -807,6 +813,16 @@ public class CodeGenMojo extends AbstractMojo { applyInlineSchemaOptionsKvpList(inlineSchemaOptions, configurator); } + // Apply Name Mappings + if (nameMappings != null && (configOptions == null || !configOptions.containsKey("name-mappings"))) { + applyNameMappingsKvpList(nameMappings, configurator); + } + + // Apply Parameter Name Mappings + if (parameterNameMappings != null && (configOptions == null || !configOptions.containsKey("paramter-name-mappings"))) { + applyParameterNameMappingsKvpList(parameterNameMappings, 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 1ab39a82ba..5bcd76b737 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 @@ -149,6 +149,8 @@ public interface CodegenConfig { Map nameMapping(); + Map parameterNameMapping(); + 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 f5cb6bf593..ea019917d2 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 @@ -164,8 +164,10 @@ public class DefaultCodegen implements CodegenConfig { protected Map inlineSchemaNameMapping = new HashMap<>(); // a map to store the inline schema naming conventions protected Map inlineSchemaOption = new HashMap<>(); - // a map to store the mapping between property, parameter name and the name provided by the user + // a map to store the mapping between property name and the name provided by the user 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 rules in OpenAPI Normalizer protected Map openapiNormalizer = new HashMap<>(); protected String modelPackage = "", apiPackage = "", fileSuffix; @@ -1206,6 +1208,11 @@ public class DefaultCodegen implements CodegenConfig { return nameMapping; } + @Override + public Map parameterNameMapping() { + return parameterNameMapping; + } + @Override public Map openapiNormalizer() { return openapiNormalizer; 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 7a1e3e0327..c2268ab79e 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 @@ -72,6 +72,7 @@ public class CodegenConfigurator { private Map inlineSchemaNameMappings = new HashMap<>(); private Map inlineSchemaOptions = new HashMap<>(); private Map nameMappings = new HashMap<>(); + private Map parameterNameMappings = new HashMap<>(); private Map openapiNormalizer = new HashMap<>(); private Set languageSpecificPrimitives = new HashSet<>(); private Map reservedWordsMappings = new HashMap<>(); @@ -128,6 +129,9 @@ public class CodegenConfigurator { if(generatorSettings.getNameMappings() != null) { configurator.nameMappings.putAll(generatorSettings.getNameMappings()); } + if(generatorSettings.getParameterNameMappings() != null) { + configurator.parameterNameMappings.putAll(generatorSettings.getParameterNameMappings()); + } if(generatorSettings.getOpenAPINormalizer() != null) { configurator.openapiNormalizer.putAll(generatorSettings.getOpenAPINormalizer()); } @@ -224,6 +228,12 @@ public class CodegenConfigurator { return this; } + public CodegenConfigurator addParameterNameMapping(String key, String value) { + this.parameterNameMappings.put(key, value); + generatorSettingsBuilder.withParameterNameMapping(key, value); + return this; + } + public CodegenConfigurator addOpenAPINormalizer(String key, String value) { this.openapiNormalizer.put(key, value); generatorSettingsBuilder.withOpenAPINormalizer(key, value); @@ -408,6 +418,12 @@ public class CodegenConfigurator { return this; } + public CodegenConfigurator setParameterNameMappings(Map parameterNameMappings) { + this.parameterNameMappings = parameterNameMappings; + generatorSettingsBuilder.withParameterNameMappings(parameterNameMappings); + return this; + } + public CodegenConfigurator setOpenAPINormalizer(Map openapiNormalizer) { this.openapiNormalizer = openapiNormalizer; generatorSettingsBuilder.withOpenAPINormalizer(openapiNormalizer); @@ -694,6 +710,7 @@ public class CodegenConfigurator { config.inlineSchemaNameMapping().putAll(generatorSettings.getInlineSchemaNameMappings()); config.inlineSchemaOption().putAll(generatorSettings.getInlineSchemaOptions()); config.nameMapping().putAll(generatorSettings.getNameMappings()); + config.parameterNameMapping().putAll(generatorSettings.getParameterNameMappings()); 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 02460bb38d..32c921c7f7 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 @@ -133,6 +133,19 @@ public final class CodegenConfiguratorUtils { } } + public static void applyParameterNameMappingsKvpList(List parameterNameMappings, CodegenConfigurator configurator) { + for (String propString : parameterNameMappings) { + applyParameterNameMappingsKvp(propString, configurator); + } + } + + public static void applyParameterNameMappingsKvp(String parameterNameMappings, CodegenConfigurator configurator) { + final Map map = createMapFromKeyValuePairs(parameterNameMappings); + for (Map.Entry entry : map.entrySet()) { + configurator.addParameterNameMapping(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/AbstractJavaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java index e106b2a689..9dae2c164b 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java @@ -858,9 +858,9 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code @Override public String toParamName(String name) { - // obtain the name from nameMapping directly if provided - if (nameMapping.containsKey(name)) { - return nameMapping.get(name); + // obtain the name from paramterNameMapping directly if provided + if (parameterNameMapping.containsKey(name)) { + return parameterNameMapping.get(name); } // to avoid conflicts with 'callback' parameter for async call diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonCodegen.java index c0775155bb..fbfa68f3a4 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonCodegen.java @@ -223,9 +223,9 @@ public abstract class AbstractPythonCodegen extends DefaultCodegen implements Co @Override public String toParamName(String name) { - // obtain the name from nameMapping directly if provided - if (nameMapping.containsKey(name)) { - return nameMapping.get(name); + // obtain the name from parameterNameMapping directly if provided + if (parameterNameMapping.containsKey(name)) { + return parameterNameMapping.get(name); } // to avoid conflicts with 'callback' parameter for async call diff --git a/modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-okhttp-gson.yaml b/modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-okhttp-gson.yaml index adcf22f6db..0bf7e4f668 100644 --- a/modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-okhttp-gson.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-okhttp-gson.yaml @@ -1109,6 +1109,35 @@ paths: application/json: schema: $ref: '#/components/schemas/ArrayOfEnums' + /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 + responses: + 200: + description: OK /values: get: tags: diff --git a/samples/client/petstore/java/okhttp-gson/README.md b/samples/client/petstore/java/okhttp-gson/README.md index cb6361af34..d582a2fceb 100644 --- a/samples/client/petstore/java/okhttp-gson/README.md +++ b/samples/client/petstore/java/okhttp-gson/README.md @@ -121,6 +121,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**fakeOuterNumberSerialize**](docs/FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | *FakeApi* | [**fakeOuterStringSerialize**](docs/FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | *FakeApi* | [**getArrayOfEnums**](docs/FakeApi.md#getArrayOfEnums) | **GET** /fake/array-of-enums | Array of Enums +*FakeApi* | [**getParameterNameMapping**](docs/FakeApi.md#getParameterNameMapping) | **GET** /fake/parameter-name-mapping | parameter name mapping test *FakeApi* | [**testBodyWithFileSchema**](docs/FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**testBodyWithQueryParams**](docs/FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | *FakeApi* | [**testClientModel**](docs/FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model diff --git a/samples/client/petstore/java/okhttp-gson/api/openapi.yaml b/samples/client/petstore/java/okhttp-gson/api/openapi.yaml index d8e6dd956e..45829b3ca5 100644 --- a/samples/client/petstore/java/okhttp-gson/api/openapi.yaml +++ b/samples/client/petstore/java/okhttp-gson/api/openapi.yaml @@ -1132,6 +1132,42 @@ paths: tags: - fake x-accepts: application/json + /fake/parameter-name-mapping: + get: + operationId: getParameterNameMapping + parameters: + - description: _type + explode: false + in: header + name: _type + required: true + schema: + format: int64 + type: integer + style: simple + - description: type + explode: true + in: query + name: type + required: true + schema: + type: string + style: form + - description: type_ + explode: false + in: header + name: type_ + required: true + schema: + type: string + style: simple + responses: + "200": + description: OK + summary: parameter name mapping test + tags: + - fake + x-accepts: application/json /values: get: description: "" diff --git a/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md b/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md index fbda6fca39..085074844a 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md +++ b/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md @@ -10,6 +10,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**fakeOuterNumberSerialize**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | | | [**fakeOuterStringSerialize**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | | | [**getArrayOfEnums**](FakeApi.md#getArrayOfEnums) | **GET** /fake/array-of-enums | Array of Enums | +| [**getParameterNameMapping**](FakeApi.md#getParameterNameMapping) | **GET** /fake/parameter-name-mapping | parameter name mapping test | | [**testBodyWithFileSchema**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | | | [**testBodyWithQueryParams**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | | | [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model | @@ -381,6 +382,69 @@ No authorization required |-------------|-------------|------------------| | **200** | Got named array of enums | - | + +# **getParameterNameMapping** +> getParameterNameMapping(underscoreType, type, typeWithUnderscore) + +parameter name mapping test + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Long underscoreType = 56L; // Long | _type + String type = "type_example"; // String | type + String typeWithUnderscore = "typeWithUnderscore_example"; // String | type_ + try { + apiInstance.getParameterNameMapping(underscoreType, type, typeWithUnderscore); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#getParameterNameMapping"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **underscoreType** | **Long**| _type | | +| **type** | **String**| type | | +| **typeWithUnderscore** | **String**| type_ | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | OK | - | + # **testBodyWithFileSchema** > testBodyWithFileSchema(fileSchemaTestClass) diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/FakeApi.java index 7afd88ae61..a06829a248 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/FakeApi.java @@ -779,6 +779,153 @@ public class FakeApi { localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } + /** + * Build call for getParameterNameMapping + * @param underscoreType _type (required) + * @param type type (required) + * @param typeWithUnderscore type_ (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 OK -
+ */ + public okhttp3.Call getParameterNameMappingCall(Long underscoreType, String type, String typeWithUnderscore, final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/fake/parameter-name-mapping"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (type != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("type", type)); + } + + if (underscoreType != null) { + localVarHeaderParams.put("_type", localVarApiClient.parameterToString(underscoreType)); + } + + if (typeWithUnderscore != null) { + localVarHeaderParams.put("type_", localVarApiClient.parameterToString(typeWithUnderscore)); + } + + final String[] localVarAccepts = { + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call getParameterNameMappingValidateBeforeCall(Long underscoreType, String type, String typeWithUnderscore, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'underscoreType' is set + if (underscoreType == null) { + throw new ApiException("Missing the required parameter 'underscoreType' when calling getParameterNameMapping(Async)"); + } + + // verify the required parameter 'type' is set + if (type == null) { + throw new ApiException("Missing the required parameter 'type' when calling getParameterNameMapping(Async)"); + } + + // verify the required parameter 'typeWithUnderscore' is set + if (typeWithUnderscore == null) { + throw new ApiException("Missing the required parameter 'typeWithUnderscore' when calling getParameterNameMapping(Async)"); + } + + return getParameterNameMappingCall(underscoreType, type, typeWithUnderscore, _callback); + + } + + /** + * parameter name mapping test + * + * @param underscoreType _type (required) + * @param type type (required) + * @param typeWithUnderscore type_ (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 OK -
+ */ + public void getParameterNameMapping(Long underscoreType, String type, String typeWithUnderscore) throws ApiException { + getParameterNameMappingWithHttpInfo(underscoreType, type, typeWithUnderscore); + } + + /** + * parameter name mapping test + * + * @param underscoreType _type (required) + * @param type type (required) + * @param typeWithUnderscore type_ (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 OK -
+ */ + public ApiResponse getParameterNameMappingWithHttpInfo(Long underscoreType, String type, String typeWithUnderscore) throws ApiException { + okhttp3.Call localVarCall = getParameterNameMappingValidateBeforeCall(underscoreType, type, typeWithUnderscore, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * parameter name mapping test (asynchronously) + * + * @param underscoreType _type (required) + * @param type type (required) + * @param typeWithUnderscore type_ (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 OK -
+ */ + public okhttp3.Call getParameterNameMappingAsync(Long underscoreType, String type, String typeWithUnderscore, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = getParameterNameMappingValidateBeforeCall(underscoreType, type, typeWithUnderscore, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } /** * Build call for testBodyWithFileSchema * @param fileSchemaTestClass (required)