Skip to content

Commit 6983a3a

Browse files
authored
Add nameMapping option to Java client, server generators (#16103)
* add nameMapping to java codegen * update doc * update samples * fix typo * update toParamName
1 parent b107ff9 commit 6983a3a

File tree

23 files changed

+652
-3
lines changed

23 files changed

+652
-3
lines changed

bin/configs/java-okhttp-gson.yaml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@ outputDir: samples/client/petstore/java/okhttp-gson
33
library: okhttp-gson
44
inputSpec: modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-okhttp-gson.yaml
55
templateDir: modules/openapi-generator/src/main/resources/Java
6+
nameMappings:
7+
_type: underscoreType
8+
type_: typeWithUnderscore
69
additionalProperties:
710
artifactId: petstore-okhttp-gson
811
hideGenerationTimestamp: "true"

docs/customization.md

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -395,11 +395,34 @@ or
395395
--import-mappings Pet=my.models.MyPet --import-mappings Order=my.models.MyOrder
396396
```
397397
398+
## Name Mapping
399+
400+
One can map the name of the property/parameter to something else. Consider the following schema:
401+
```
402+
PropertyNameCollision:
403+
properties:
404+
_type:
405+
type: string
406+
type:
407+
type: string
408+
type_:
409+
type: string
410+
type: object
411+
```
412+
`_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`.
413+
414+
Here is an example to use `nameMappings` in CLI:
415+
```sh
416+
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
417+
```
418+
419+
(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.)
420+
398421
## Schema Mapping
399422

400423
One can map the schema to something else (e.g. external objects/models outside of the package) using the `schemaMappings` option, e.g. in CLI
401424
```sh
402-
java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generate -g java -i modules/openapi-generator/src/test/resources/3_0/type-alias.yaml -o /tmp/java2/ --schema-mapping TypeAlias=foo.bar.TypeAlias
425+
java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generate -g java -i modules/openapi-generator/src/test/resources/3_0/type-alias.yaml -o /tmp/java2/ --schema-mappings TypeAlias=foo.bar.TypeAlias
403426
```
404427
Another example (in conjunction with --type-mappings):
405428
```sh

modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/ConfigHelp.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,9 @@ public class ConfigHelp extends OpenApiGeneratorCommand {
8080
@Option(name = {"--inline-schema-options"}, title = "inline schema options", description = "options for handling inline schemas in inline model resolver")
8181
private Boolean inlineSchemaOptions;
8282

83+
@Option(name = {"--name-mappings"}, title = "property/parameter name mappings", description = "displays the property/parameter name mappings (none)")
84+
private Boolean nameMappings;
85+
8386
@Option(name = {"--openapi-normalizer"}, title = "openapi normalizer rules", description = "displays the OpenAPI normalizer rules (none)")
8487
private Boolean openapiNormalizer;
8588

@@ -497,6 +500,18 @@ private void generatePlainTextHelp(StringBuilder sb, CodegenConfig config) {
497500
sb.append(newline);
498501
}
499502

503+
if (Boolean.TRUE.equals(nameMappings)) {
504+
sb.append(newline).append("PROPERTY, PARAMETER NAME MAPPING").append(newline).append(newline);
505+
Map<String, String> map = config.nameMapping()
506+
.entrySet()
507+
.stream()
508+
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> {
509+
throw new IllegalStateException(String.format(Locale.ROOT, "Duplicated options! %s and %s", a, b));
510+
}, TreeMap::new));
511+
writePlainTextFromMap(sb, map, optIndent, optNestedIndent, "property, parameter name", "Mapped to");
512+
sb.append(newline);
513+
}
514+
500515
if (Boolean.TRUE.equals(openapiNormalizer)) {
501516
sb.append(newline).append("OPENAPI NORMALIZER RULES").append(newline).append(newline);
502517
Map<String, String> map = config.openapiNormalizer()

modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Generate.java

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -182,11 +182,19 @@ public class Generate extends OpenApiGeneratorCommand {
182182
private List<String> inlineSchemaNameMappings = new ArrayList<>();
183183

184184
@Option(
185-
name = {"--inline-schema-optionss"},
185+
name = {"--inline-schema-options"},
186186
title = "inline schema options",
187-
description = "specifies the options for handling inline schemas in the inline model resolver.")
187+
description = "specifies the options for handling inline schemas in the inline model resolver."
188+
+ " Please refer to https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md for a list of options.")
188189
private List<String> inlineSchemaOptions = new ArrayList<>();
189190

191+
@Option(
192+
name = {"--name-mappings"},
193+
title = "property, parameter name mappings",
194+
description = "specifies mappings between the property, parameter name and the new name in the format of param_name=paramName,prop_name=PropName."
195+
+ " You can also have multiple occurrences of this option.")
196+
private List<String> nameMappings = new ArrayList<>();
197+
190198
@Option(
191199
name = {"--openapi-normalizer"},
192200
title = "OpenAPI normalizer rules",
@@ -467,6 +475,7 @@ public void execute() {
467475
applySchemaMappingsKvpList(schemaMappings, configurator);
468476
applyInlineSchemaNameMappingsKvpList(inlineSchemaNameMappings, configurator);
469477
applyInlineSchemaOptionsKvpList(inlineSchemaOptions, configurator);
478+
applyNameMappingsKvpList(nameMappings, configurator);
470479
applyOpenAPINormalizerKvpList(openapiNormalizer, configurator);
471480
applyTypeMappingsKvpList(typeMappings, configurator);
472481
applyAdditionalPropertiesKvpList(additionalProperties, configurator);

modules/openapi-generator-core/src/main/java/org/openapitools/codegen/config/GeneratorSettings.java

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ public final class GeneratorSettings implements Serializable {
5353
private final Map<String, String> schemaMappings;
5454
private final Map<String, String> inlineSchemaNameMappings;
5555
private final Map<String, String> inlineSchemaOptions;
56+
private final Map<String, String> nameMappings;
5657
private final Map<String, String> openapiNormalizer;
5758
private final Set<String> languageSpecificPrimitives;
5859
private final Map<String, String> reservedWordsMappings;
@@ -265,6 +266,15 @@ public Map<String, String> getInlineSchemaOptions() {
265266
return inlineSchemaOptions;
266267
}
267268

269+
/**
270+
* Gets property, parameter name mappings between a property, parameter name and the new name.
271+
*
272+
* @return the property, parameter name mappings
273+
*/
274+
public Map<String, String> getNameMappings() {
275+
return nameMappings;
276+
}
277+
268278
/**
269279
* Gets OpenAPI normalizer rules
270280
*
@@ -392,6 +402,7 @@ private GeneratorSettings(Builder builder) {
392402
schemaMappings = Collections.unmodifiableMap(builder.schemaMappings);
393403
inlineSchemaNameMappings = Collections.unmodifiableMap(builder.inlineSchemaNameMappings);
394404
inlineSchemaOptions = Collections.unmodifiableMap(builder.inlineSchemaOptions);
405+
nameMappings = Collections.unmodifiableMap(builder.nameMappings);
395406
openapiNormalizer = Collections.unmodifiableMap(builder.openapiNormalizer);
396407
languageSpecificPrimitives = Collections.unmodifiableSet(builder.languageSpecificPrimitives);
397408
reservedWordsMappings = Collections.unmodifiableMap(builder.reservedWordsMappings);
@@ -466,6 +477,7 @@ public GeneratorSettings() {
466477
schemaMappings = Collections.unmodifiableMap(new HashMap<>(0));
467478
inlineSchemaNameMappings = Collections.unmodifiableMap(new HashMap<>(0));
468479
inlineSchemaOptions = Collections.unmodifiableMap(new HashMap<>(0));
480+
nameMappings = Collections.unmodifiableMap(new HashMap<>(0));
469481
openapiNormalizer = Collections.unmodifiableMap(new HashMap<>(0));
470482
languageSpecificPrimitives = Collections.unmodifiableSet(new HashSet<>(0));
471483
reservedWordsMappings = Collections.unmodifiableMap(new HashMap<>(0));
@@ -527,6 +539,9 @@ public static Builder newBuilder(GeneratorSettings copy) {
527539
if (copy.getInlineSchemaOptions() != null) {
528540
builder.inlineSchemaOptions.putAll(copy.getInlineSchemaOptions());
529541
}
542+
if (copy.getNameMappings() != null) {
543+
builder.nameMappings.putAll(copy.getNameMappings());
544+
}
530545
if (copy.getOpenAPINormalizer() != null) {
531546
builder.openapiNormalizer.putAll(copy.getOpenAPINormalizer());
532547
}
@@ -572,6 +587,7 @@ public static final class Builder {
572587
private Map<String, String> schemaMappings;
573588
private Map<String, String> inlineSchemaNameMappings;
574589
private Map<String, String> inlineSchemaOptions;
590+
private Map<String, String> nameMappings;
575591
private Map<String, String> openapiNormalizer;
576592
private Set<String> languageSpecificPrimitives;
577593
private Map<String, String> reservedWordsMappings;
@@ -593,6 +609,7 @@ public Builder() {
593609
schemaMappings = new HashMap<>();
594610
inlineSchemaNameMappings = new HashMap<>();
595611
inlineSchemaOptions = new HashMap<>();
612+
nameMappings = new HashMap<>();
596613
openapiNormalizer = new HashMap<>();
597614
languageSpecificPrimitives = new HashSet<>();
598615
reservedWordsMappings = new HashMap<>();
@@ -914,6 +931,32 @@ public Builder withInlineSchemaNameMapping(String key, String value) {
914931
return this;
915932
}
916933

934+
/**
935+
* Sets the {@code nameMappings} and returns a reference to this Builder so that the methods can be chained together.
936+
*
937+
* @param nameMappings the {@code nameMappings} to set
938+
* @return a reference to this Builder
939+
*/
940+
public Builder withNameMappings(Map<String, String> nameMappings) {
941+
this.nameMappings = nameMappings;
942+
return this;
943+
}
944+
945+
/**
946+
* Sets a single {@code nameMappings} and returns a reference to this Builder so that the methods can be chained together.
947+
*
948+
* @param key A key for the name mapping
949+
* @param value The value of name mapping
950+
* @return a reference to this Builder
951+
*/
952+
public Builder withNameMapping(String key, String value) {
953+
if (this.nameMappings == null) {
954+
this.nameMappings = new HashMap<>();
955+
}
956+
this.nameMappings.put(key, value);
957+
return this;
958+
}
959+
917960
/**
918961
* Sets the {@code openapiNormalizer} and returns a reference to this Builder so that the methods can be chained together.
919962
*
@@ -1128,6 +1171,7 @@ public boolean equals(Object o) {
11281171
Objects.equals(getSchemaMappings(), that.getSchemaMappings()) &&
11291172
Objects.equals(getInlineSchemaNameMappings(), that.getInlineSchemaNameMappings()) &&
11301173
Objects.equals(getInlineSchemaOptions(), that.getInlineSchemaOptions()) &&
1174+
Objects.equals(getNameMappings(), that.getNameMappings()) &&
11311175
Objects.equals(getOpenAPINormalizer(), that.getOpenAPINormalizer()) &&
11321176
Objects.equals(getLanguageSpecificPrimitives(), that.getLanguageSpecificPrimitives()) &&
11331177
Objects.equals(getReservedWordsMappings(), that.getReservedWordsMappings()) &&
@@ -1160,6 +1204,7 @@ public int hashCode() {
11601204
getSchemaMappings(),
11611205
getInlineSchemaNameMappings(),
11621206
getInlineSchemaOptions(),
1207+
getNameMappings(),
11631208
getOpenAPINormalizer(),
11641209
getLanguageSpecificPrimitives(),
11651210
getReservedWordsMappings(),

modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/extensions/OpenApiGeneratorGenerateExtension.kt

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,11 @@ open class OpenApiGeneratorGenerateExtension(project: Project) {
167167
*/
168168
val inlineSchemaOptions = project.objects.mapProperty<String, String>()
169169

170+
/**
171+
* Specifies mappings between a property, parameter name and the new name
172+
*/
173+
val nameMappings = project.objects.mapProperty<String, String>()
174+
170175
/**
171176
* Specifies mappings (rules) in OpenAPI normalizer
172177
*/

modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/GenerateTask.kt

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,13 @@ open class GenerateTask @Inject constructor(private val objectFactory: ObjectFac
272272
@Input
273273
val inlineSchemaOptions = project.objects.mapProperty<String, String>()
274274

275+
/**
276+
* Specifies mappings between the property, parameter name and the new name
277+
*/
278+
@Optional
279+
@Input
280+
val nameMappings = project.objects.mapProperty<String, String>()
281+
275282
/**
276283
* Specifies mappings (rules) in OpenAPI normalizer
277284
*/
@@ -807,6 +814,12 @@ open class GenerateTask @Inject constructor(private val objectFactory: ObjectFac
807814
}
808815
}
809816

817+
if (nameMappings.isPresent) {
818+
nameMappings.get().forEach { entry ->
819+
configurator.addNameMapping(entry.key, entry.value)
820+
}
821+
}
822+
810823
if (openapiNormalizer.isPresent) {
811824
openapiNormalizer.get().forEach { entry ->
812825
configurator.addOpenAPINormalizer(entry.key, entry.value)

modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -332,6 +332,12 @@ public class CodeGenMojo extends AbstractMojo {
332332
@Parameter(name = "inlineSchemaOptions", property = "openapi.generator.maven.plugin.inlineSchemaOptions")
333333
private List<String> inlineSchemaOptions;
334334

335+
/**
336+
* A map of property, parameter names and the new names
337+
*/
338+
@Parameter(name = "nameMappings", property = "openapi.generator.maven.plugin.nameMappings")
339+
private List<String> nameMappings;
340+
335341
/**
336342
* A set of rules for OpenAPI normalizer
337343
*/

modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,8 @@ public interface CodegenConfig {
147147

148148
Map<String, String> inlineSchemaOption();
149149

150+
Map<String, String> nameMapping();
151+
150152
Map<String, String> openapiNormalizer();
151153

152154
Map<String, String> apiTemplateFiles();

modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,8 @@ public class DefaultCodegen implements CodegenConfig {
164164
protected Map<String, String> inlineSchemaNameMapping = new HashMap<>();
165165
// a map to store the inline schema naming conventions
166166
protected Map<String, String> inlineSchemaOption = new HashMap<>();
167+
// a map to store the mapping between property, parameter name and the name provided by the user
168+
protected Map<String, String> nameMapping = new HashMap<>();
167169
// a map to store the rules in OpenAPI Normalizer
168170
protected Map<String, String> openapiNormalizer = new HashMap<>();
169171
protected String modelPackage = "", apiPackage = "", fileSuffix;
@@ -1199,6 +1201,11 @@ public Map<String, String> inlineSchemaOption() {
11991201
return inlineSchemaOption;
12001202
}
12011203

1204+
@Override
1205+
public Map<String, String> nameMapping() {
1206+
return nameMapping;
1207+
}
1208+
12021209
@Override
12031210
public Map<String, String> openapiNormalizer() {
12041211
return openapiNormalizer;

0 commit comments

Comments
 (0)