Skip to content

[JAVA] [SPRING] Extensible enum for spring generator using oneOf. Fix #7272 #21298

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions bin/configs/spring-boot-useOneOfExtensibleEnum.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
generatorName: spring
outputDir: samples/server/petstore/springboot-useoneofextensibleenum
inputSpec: modules/openapi-generator/src/test/resources/3_0/java/extended-enums.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
groupId: org.openapitools.openapi3
documentationProvider: springfox
useOneOfExtensibleEnums: true
useOneOfInterfaces: true
useBeanValidation: true
artifactId: spring-boot-useoneofextensibleenum
hideGenerationTimestamp: "true"
1 change: 1 addition & 0 deletions docs/generators/java-camel.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|useFeignClientContextId|Whether to generate Feign client with contextId parameter.| |true|
|useFeignClientUrl|Whether to generate Feign client with url parameter.| |true|
|useJakartaEe|whether to use Jakarta EE namespace instead of javax| |false|
|useOneOfExtensibleEnums|whether to generate custom extensible enumeration using the extensible enums with interface pattern| |false|
|useOneOfInterfaces|whether to use a java interface to describe a set of oneOf options, where each option is a class that implements the interface| |false|
|useOptional|Use Optional container for optional parameters| |false|
|useResponseEntity|Use the `ResponseEntity` type to wrap return values of generated API methods. If disabled, method are annotated using a `@ResponseStatus` annotation, which has the status of the first response declared in the Api definition| |true|
Expand Down
1 change: 1 addition & 0 deletions docs/generators/spring.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|useFeignClientContextId|Whether to generate Feign client with contextId parameter.| |true|
|useFeignClientUrl|Whether to generate Feign client with url parameter.| |true|
|useJakartaEe|whether to use Jakarta EE namespace instead of javax| |false|
|useOneOfExtensibleEnums|whether to generate custom extensible enumeration using the extensible enums with interface pattern| |false|
|useOneOfInterfaces|whether to use a java interface to describe a set of oneOf options, where each option is a class that implements the interface| |false|
|useOptional|Use Optional container for optional parameters| |false|
|useResponseEntity|Use the `ResponseEntity` type to wrap return values of generated API methods. If disabled, method are annotated using a `@ResponseStatus` annotation, which has the status of the first response declared in the Api definition| |true|
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -514,6 +514,7 @@ public Map<String, ModelsMap> postProcessAllModels(Map<String, ModelsMap> objs)
CodegenModel cm = mo.getModel();
if (cm.oneOf.size() > 0) {
cm.vendorExtensions.put("x-is-one-of-interface", true);

for (String one : cm.oneOf) {
if (!additionalDataMap.containsKey(one)) {
additionalDataMap.put(one, new OneOfImplementorAdditionalData(one));
Expand All @@ -522,6 +523,10 @@ public Map<String, ModelsMap> postProcessAllModels(Map<String, ModelsMap> objs)
}
// if this is oneOf interface, make sure we include the necessary imports for it
addImportsToOneOfInterface(modelsImports);
boolean hasOfEnum = (cm.interfaceModels != null) && cm.interfaceModels.stream().anyMatch(m -> m.isEnum) ;
if (hasOfEnum) {
addExtensibleEnum(objs, cm, modelsImports);
}
}
}
}
Expand Down Expand Up @@ -8385,6 +8390,9 @@ public void addOneOfInterfaceModel(Schema cs, String type) {
addOneOfInterfaces.add(cm);
}

public void addExtensibleEnum(Map<String, ModelsMap> objs, CodegenModel cm, List<Map<String, String>> imports) {
}

public void addImportsToOneOfInterface(List<Map<String, String>> imports) {
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code

public static final String CAMEL_CASE_DOLLAR_SIGN = "camelCaseDollarSign";
public static final String USE_ONE_OF_INTERFACES = "useOneOfInterfaces";
public static final String USE_ONE_OF_EXTENSIBLE_ENUMS = "useOneOfExtensibleEnums";
public static final String LOMBOK = "lombok";
public static final String DEFAULT_TEST_FOLDER = "${project.build.directory}/generated-test-sources/openapi";
public static final String GENERATE_CONSTRUCTOR_WITH_ALL_ARGS = "generateConstructorWithAllArgs";
Expand Down Expand Up @@ -153,6 +154,8 @@ protected enum ENUM_PROPERTY_NAMING_TYPE {MACRO_CASE, legacy, original}
protected static final String ENUM_PROPERTY_NAMING_DESC = "Naming convention for enum properties: 'MACRO_CASE', 'legacy' and 'original'";
@Getter protected ENUM_PROPERTY_NAMING_TYPE enumPropertyNaming = ENUM_PROPERTY_NAMING_TYPE.MACRO_CASE;

@Getter @Setter
protected boolean useOneOfExtensibleEnums = false;
/**
* -- SETTER --
* Set whether discriminator value lookup is case-sensitive or not.
Expand Down Expand Up @@ -570,6 +573,7 @@ public void processOpts() {
convertPropertyToStringAndWriteBack(IMPLICIT_HEADERS_REGEX, this::setImplicitHeadersRegex);
convertPropertyToBooleanAndWriteBack(CAMEL_CASE_DOLLAR_SIGN, this::setCamelCaseDollarSign);
convertPropertyToBooleanAndWriteBack(USE_ONE_OF_INTERFACES, this::setUseOneOfInterfaces);
convertPropertyToBooleanAndWriteBack(USE_ONE_OF_EXTENSIBLE_ENUMS, this::setUseOneOfExtensibleEnums);
convertPropertyToStringAndWriteBack(CodegenConstants.ENUM_PROPERTY_NAMING, this::setEnumPropertyNaming);

if (!StringUtils.isEmpty(parentGroupId) && !StringUtils.isEmpty(parentArtifactId) && !StringUtils.isEmpty(parentVersion)) {
Expand Down Expand Up @@ -621,6 +625,11 @@ public void processOpts() {
// used later in recursive import in postProcessingModels
importMapping.put("com.fasterxml.jackson.annotation.JsonProperty", "com.fasterxml.jackson.annotation.JsonCreator");

if (useOneOfExtensibleEnums) {
importMapping.put("DeserializationContext", "com.fasterxml.jackson.databind.DeserializationContext");
importMapping.put("StdDeserializer", "com.fasterxml.jackson.databind.deser.std.StdDeserializer");
importMapping.put("JsonParser", "com.fasterxml.jackson.core.JsonParser");
}
convertPropertyToBooleanAndWriteBack(SUPPORT_ASYNC, this::setSupportAsync);
convertPropertyToStringAndWriteBack(DATE_LIBRARY, this::setDateLibrary);

Expand Down Expand Up @@ -2395,16 +2404,51 @@ private boolean shouldBeImplicitHeader(CodegenParameter parameter) {
@Override
public void addImportsToOneOfInterface(List<Map<String, String>> imports) {
if (jackson) {
for (String i : Arrays.asList("JsonSubTypes", "JsonTypeInfo")) {
Map<String, String> oneImport = new HashMap<>();
oneImport.put("import", importMapping.get(i));
if (!imports.contains(oneImport)) {
imports.add(oneImport);
}
addAdditionalImports(imports, "JsonSubTypes", "JsonTypeInfo");
}
}

protected void addAdditionalImports(List<Map<String, String>> imports, String... additionalImports) {
for (String i : additionalImports) {
Map<String, String> oneImport = new HashMap<>();
oneImport.put("import", Objects.requireNonNull(importMapping.get(i), "importMapping not found " + i));
if (!imports.contains(oneImport)) {
imports.add(oneImport);
}
}
}

@Override
public void addExtensibleEnum(Map<String, ModelsMap> objs, CodegenModel cm, List<Map<String, String>> imports) {
if (jackson) {
addAdditionalImports(imports,
"DeserializationContext",
"JsonDeserialize",
"StdDeserializer",
"JsonValue",
"JsonParser",
"IOException");

ExtensibleEnumParam param = new ExtensibleEnumParam();
cm.vendorExtensions.put("x-extensible-enum", param);
if (cm.oneOf.contains("String")) {
param.useString = true;
param.property = cm.getComposedSchemas().getOneOf().stream().filter(p -> "String".equals(p.datatypeWithEnum))
.findFirst().orElseThrow();
// The name of the String property looks like oneOf1
// Use a sensible name instead
param.stringClassName = cm.classname + "String";

}
}
}

static class ExtensibleEnumParam {
public boolean useString;
public String stringClassName;
public CodegenProperty property;
}

@Override
public List<VendorExtension> getSupportedVendorExtensions() {
List<VendorExtension> extensions = super.getSupportedVendorExtensions();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,7 @@ public SpringCodegen() {
cliOptions
.add(CliOption.newBoolean(RETURN_SUCCESS_CODE, "Generated server returns 2xx code", returnSuccessCode));
cliOptions.add(CliOption.newBoolean(SPRING_CONTROLLER, "Annotate the generated API as a Spring Controller", useSpringController));
cliOptions.add(CliOption.newBoolean(USE_ONE_OF_EXTENSIBLE_ENUMS, "whether to generate custom extensible enumeration using the extensible enums with interface pattern", useOneOfExtensibleEnums));

CliOption requestMappingOpt = new CliOption(REQUEST_MAPPING_OPTION,
"Where to generate the class level @RequestMapping annotation.")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,82 @@
{{>typeInfoAnnotation}}
{{/discriminator}}
{{>generatedAnnotation}}
{{#vendorExtensions.x-extensible-enum}}
@JsonDeserialize(using = {{classname}}.EnumDeserializer.class)
{{/vendorExtensions.x-extensible-enum}}
public {{>sealed}}interface {{classname}}{{#vendorExtensions.x-implements}}{{#-first}} extends {{{.}}}{{/-first}}{{^-first}}, {{{.}}}{{/-first}}{{/vendorExtensions.x-implements}} {{>permits}}{
{{#discriminator}}
public {{propertyType}} {{propertyGetter}}();
{{/discriminator}}
{{^discriminator}}
{{#vendorExtensions.x-extensible-enum}}
{{#useBeanValidation}}@Valid{{/useBeanValidation}}
@JsonValue
String getValue();

static {{classname}} fromValue(String value) {
{{#interfaceModels}}
try {
return {{classname}}.fromValue(value);
} catch (IllegalArgumentException e) {
// continue
}
{{/interfaceModels}}
{{#useString}}
return new {{stringClassName}}(value);
{{/useString}}
{{^useString}}
throw new IllegalArgumentException(value + " not supported in classes " + Arrays.asList({{#interfaceModels}}"{{classname}}"{{^-last}}, {{/-last}}{{/interfaceModels}}));
{{/useString}}
}

// custom jackson deserializer
class EnumDeserializer extends StdDeserializer<{{classname}}> {

public EnumDeserializer() {
super({{classname}}.class);
}

@Override
public {{classname}} deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
String value = p.readValueAs(String.class);
return {{classname}}.fromValue(value);
}
}
{{#useString}}
{{#property.description}}
/**
* {{{.}}}
*/
{{/property.description}}
class {{stringClassName}} implements {{classname}} {
private final String value;
public {{stringClassName}}(String value) {
this.value = value;
}

{{#useBeanValidation}}@NotNull {{#property}}{{>beanValidationCore}} {{/property}}{{/useBeanValidation}}
@Override
public String getValue() {
return value;
}
@Override
public String toString() {
return "{{stringClassName}}:" + value;
}

@Override
public final boolean equals(Object o) {
if (!(o instanceof {{stringClassName}} )) return false;
return value.equals((({{stringClassName}})o).value);
}

@Override
public int hashCode() {
return value.hashCode();
}
}
{{/useString}}
{{/vendorExtensions.x-extensible-enum}}
{{/discriminator}}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5501,4 +5501,23 @@ public void testEnumFieldShouldBeFinal_issue21018() throws IOException {
JavaFileAssert.assertThat(files.get("SomeObject.java"))
.fileContains("private final String value");
}

@Test
public void testExtensibleEnum() throws IOException {
SpringCodegen codegen = new SpringCodegen();
codegen.setUseOneOfExtensibleEnums(true);
codegen.setUseBeanValidation(true);
Map<String, File> files = generateFiles(codegen,"src/test/resources/3_0/java/extended-enums.yaml");
JavaFileAssert.assertThat(files.get("Country.java"))
.fileContains("@JsonDeserialize(using = Country.EnumDeserializer.class)",
"String getValue()",
"class EnumDeserializer extends StdDeserializer<Country>",
"class CountryString implements Country");
JavaFileAssert.assertThat(files.get("CountryOrOther.java"))
.fileContains("@JsonDeserialize(using = CountryOrOther.EnumDeserializer.class)",
"String getValue()",
"class EnumDeserializer extends StdDeserializer<CountryOrOther>",
"static CountryOrOther fromValue(String value)");

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
openapi: 3.0.3
info:
title: Extended enum
description: ''
version: v1
servers:
- url: http://localhost
description: test
paths:
/test:
get:
operationId: test
responses:
200:
description: Successful operation
content:
application/json:
schema:
$ref: '#/components/schemas/Address'
components:
schemas:
Address:
properties:
street:
type: string
countryOrString:
$ref: '#/components/schemas/Country'
countryOrOther:
$ref: '#/components/schemas/countryOrOther'
Country:
oneOf:
- $ref: '#/components/schemas/SubsetCountry'
- type: string
description: other coutries
title: OtherCountry
pattern: ^[A-Z]{2}$
SubsetCountry:
type: string
enum:
- BE
- LU
- NL
countryOrOther:
oneOf:
- $ref: '#/components/schemas/SubsetCountry'
- $ref: '#/components/schemas/OtherCountryEnum'
OtherCountryEnum:
type: string
enum:
- IT
- DE
- FR


Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
README.md
pom.xml
src/main/java/org/openapitools/OpenApiGeneratorApplication.java
src/main/java/org/openapitools/RFC3339DateFormat.java
src/main/java/org/openapitools/api/ApiUtil.java
src/main/java/org/openapitools/api/TestApi.java
src/main/java/org/openapitools/configuration/EnumConverterConfiguration.java
src/main/java/org/openapitools/configuration/HomeController.java
src/main/java/org/openapitools/configuration/SpringFoxConfiguration.java
src/main/java/org/openapitools/model/Address.java
src/main/java/org/openapitools/model/Country.java
src/main/java/org/openapitools/model/CountryOrOther.java
src/main/java/org/openapitools/model/OtherCountryEnum.java
src/main/java/org/openapitools/model/SubsetCountry.java
src/main/resources/application.properties
src/main/resources/openapi.yaml
src/main/resources/static/swagger-ui.html
src/test/java/org/openapitools/OpenApiGeneratorApplicationTests.java
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
7.14.0-SNAPSHOT
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# OpenAPI generated server

Spring Boot Server

## Overview
This server was generated by the [OpenAPI Generator](https://openapi-generator.tech) project.
By using the [OpenAPI-Spec](https://openapis.org), you can easily generate a server stub.
This is an example of building a OpenAPI-enabled server in Java using the SpringBoot framework.

The underlying library integrating OpenAPI to Spring Boot is [springfox](https://github.com/springfox/springfox).
Springfox will generate an OpenAPI v2 (fka Swagger RESTful API Documentation Specification) specification based on the
generated Controller and Model classes. The specification is available to download using the following url:
http://localhost:8080/v2/api-docs/

**HEADS-UP**: Springfox is deprecated for removal in version 6.0.0 of openapi-generator. The project seems to be no longer
maintained (last commit is of Oct 14, 2020). It works with Spring Boot 2.5.x but not with 2.6. Spring Boot 2.5 is
supported until 2022-05-19. Users of openapi-generator should migrate to the springdoc documentation provider which is,
as an added bonus, OpenAPI v3 compatible.



Start your server as a simple java application

You can view the api documentation in swagger-ui by pointing to
http://localhost:8080/swagger-ui.html

Change default port value in application.properties
Loading
Loading