diff --git a/docs/generators/groovy.md b/docs/generators/groovy.md index ef327d98124..8a0bd7ad207 100644 --- a/docs/generators/groovy.md +++ b/docs/generators/groovy.md @@ -25,6 +25,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |apiPackage|package for generated api classes| |org.openapitools.api| |artifactId|artifactId in generated pom.xml. This also becomes part of the generated library's filename| |openapi-groovy| |artifactVersion|artifact version in generated pom.xml. This also becomes part of the generated library's filename| |1.0.0| +|autosetConstants|Automatically set Required Params having a Single enum value i.e. Constants in generated code| |false| |bigDecimalAsString|Treat BigDecimal values as Strings to avoid precision loss.| |false| |booleanGetterPrefix|Set booleanGetterPrefix| |get| |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| diff --git a/docs/generators/java-camel.md b/docs/generators/java-camel.md index 84a85a253a2..0f6a369f7af 100644 --- a/docs/generators/java-camel.md +++ b/docs/generators/java-camel.md @@ -30,6 +30,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |artifactUrl|artifact URL in generated pom.xml| |https://github.com/openapitools/openapi-generator| |artifactVersion|artifact version in generated pom.xml. This also becomes part of the generated library's filename| |1.0.0| |async|use async Callable controllers| |false| +|autosetConstants|Automatically set Required Params having a Single enum value i.e. Constants in generated code| |false| |basePackage|base package (invokerPackage) for generated code| |org.openapitools| |bigDecimalAsString|Treat BigDecimal values as Strings to avoid precision loss.| |false| |booleanGetterPrefix|Set booleanGetterPrefix| |get| diff --git a/docs/generators/java-helidon-client.md b/docs/generators/java-helidon-client.md index e7c4f63d0b5..79440feabcd 100644 --- a/docs/generators/java-helidon-client.md +++ b/docs/generators/java-helidon-client.md @@ -27,6 +27,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |artifactId|artifactId in generated pom.xml. This also becomes part of the generated library's filename| |openapi-java-client| |artifactUrl|artifact URL in generated pom.xml| |https://github.com/openapitools/openapi-generator| |artifactVersion|artifact version in generated pom.xml. This also becomes part of the generated library's filename| |1.0.0| +|autosetConstants|Automatically set Required Params having a Single enum value i.e. Constants in generated code| |false| |bigDecimalAsString|Treat BigDecimal values as Strings to avoid precision loss.| |false| |booleanGetterPrefix|Set booleanGetterPrefix| |get| |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| diff --git a/docs/generators/java-helidon-server.md b/docs/generators/java-helidon-server.md index a027e1cee38..0360cad75fe 100644 --- a/docs/generators/java-helidon-server.md +++ b/docs/generators/java-helidon-server.md @@ -27,6 +27,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |artifactId|artifactId in generated pom.xml. This also becomes part of the generated library's filename| |openapi-java-server| |artifactUrl|artifact URL in generated pom.xml| |https://github.com/openapitools/openapi-generator| |artifactVersion|artifact version in generated pom.xml. This also becomes part of the generated library's filename| |1.0.0| +|autosetConstants|Automatically set Required Params having a Single enum value i.e. Constants in generated code| |false| |bigDecimalAsString|Treat BigDecimal values as Strings to avoid precision loss.| |false| |booleanGetterPrefix|Set booleanGetterPrefix| |get| |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| diff --git a/docs/generators/java-inflector.md b/docs/generators/java-inflector.md index c91aa73e31b..68d8c1414ac 100644 --- a/docs/generators/java-inflector.md +++ b/docs/generators/java-inflector.md @@ -27,6 +27,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |artifactId|artifactId in generated pom.xml. This also becomes part of the generated library's filename| |openapi-inflector-server| |artifactUrl|artifact URL in generated pom.xml| |https://github.com/openapitools/openapi-generator| |artifactVersion|artifact version in generated pom.xml. This also becomes part of the generated library's filename| |1.0.0| +|autosetConstants|Automatically set Required Params having a Single enum value i.e. Constants in generated code| |false| |bigDecimalAsString|Treat BigDecimal values as Strings to avoid precision loss.| |false| |booleanGetterPrefix|Set booleanGetterPrefix| |get| |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| diff --git a/docs/generators/java-micronaut-client.md b/docs/generators/java-micronaut-client.md index 76e90328b3f..0395914cec5 100644 --- a/docs/generators/java-micronaut-client.md +++ b/docs/generators/java-micronaut-client.md @@ -30,6 +30,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |artifactUrl|artifact URL in generated pom.xml| |https://github.com/openapitools/openapi-generator| |artifactVersion|artifact version in generated pom.xml. This also becomes part of the generated library's filename| |1.0.0| |authorizationFilterPattern|Configure the authorization filter pattern for the client. Generally defined when generating clients from multiple specification files| |null| +|autosetConstants|Automatically set Required Params having a Single enum value i.e. Constants in generated code| |false| |basePathSeparator|Configure the separator to use between the application name and base path when referencing the property| |-| |bigDecimalAsString|Treat BigDecimal values as Strings to avoid precision loss.| |false| |booleanGetterPrefix|Set booleanGetterPrefix| |get| diff --git a/docs/generators/java-micronaut-server.md b/docs/generators/java-micronaut-server.md index 2366e962c65..057fb2da564 100644 --- a/docs/generators/java-micronaut-server.md +++ b/docs/generators/java-micronaut-server.md @@ -27,6 +27,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |artifactId|artifactId in generated pom.xml. This also becomes part of the generated library's filename| |openapi-micronaut| |artifactUrl|artifact URL in generated pom.xml| |https://github.com/openapitools/openapi-generator| |artifactVersion|artifact version in generated pom.xml. This also becomes part of the generated library's filename| |1.0.0| +|autosetConstants|Automatically set Required Params having a Single enum value i.e. Constants in generated code| |false| |bigDecimalAsString|Treat BigDecimal values as Strings to avoid precision loss.| |false| |booleanGetterPrefix|Set booleanGetterPrefix| |get| |build|Specify for which build tool to generate files|
**gradle**
Gradle configuration is generated for the project
**all**
Both Gradle and Maven configurations are generated
**maven**
Maven configuration is generated for the project
|all| diff --git a/docs/generators/java-msf4j.md b/docs/generators/java-msf4j.md index d656e20a81d..9daa84171f3 100644 --- a/docs/generators/java-msf4j.md +++ b/docs/generators/java-msf4j.md @@ -27,6 +27,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |artifactId|artifactId in generated pom.xml. This also becomes part of the generated library's filename| |openapi-jaxrs-server| |artifactUrl|artifact URL in generated pom.xml| |https://github.com/openapitools/openapi-generator| |artifactVersion|artifact version in generated pom.xml. This also becomes part of the generated library's filename| |1.0.0| +|autosetConstants|Automatically set Required Params having a Single enum value i.e. Constants in generated code| |false| |bigDecimalAsString|Treat BigDecimal values as Strings to avoid precision loss.| |false| |booleanGetterPrefix|Set booleanGetterPrefix| |get| |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| diff --git a/docs/generators/java-pkmst.md b/docs/generators/java-pkmst.md index 56f49ef7d2f..6ea10a27ac5 100644 --- a/docs/generators/java-pkmst.md +++ b/docs/generators/java-pkmst.md @@ -27,6 +27,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |artifactId|artifactId in generated pom.xml. This also becomes part of the generated library's filename| |pkmst-microservice| |artifactUrl|artifact URL in generated pom.xml| |https://github.com/openapitools/openapi-generator| |artifactVersion|artifact version in generated pom.xml. This also becomes part of the generated library's filename| |1.0.0| +|autosetConstants|Automatically set Required Params having a Single enum value i.e. Constants in generated code| |false| |basePackage|base package for java source code| |null| |bigDecimalAsString|Treat BigDecimal values as Strings to avoid precision loss.| |false| |booleanGetterPrefix|Set booleanGetterPrefix| |get| diff --git a/docs/generators/java-play-framework.md b/docs/generators/java-play-framework.md index b0205e0a4b3..86750639ddc 100644 --- a/docs/generators/java-play-framework.md +++ b/docs/generators/java-play-framework.md @@ -27,6 +27,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |artifactId|artifactId in generated pom.xml. This also becomes part of the generated library's filename| |openapi-java-playframework| |artifactUrl|artifact URL in generated pom.xml| |https://github.com/openapitools/openapi-generator| |artifactVersion|artifact version in generated pom.xml. This also becomes part of the generated library's filename| |1.0.0| +|autosetConstants|Automatically set Required Params having a Single enum value i.e. Constants in generated code| |false| |basePackage|base package for generated code| |org.openapitools| |bigDecimalAsString|Treat BigDecimal values as Strings to avoid precision loss.| |false| |booleanGetterPrefix|Set booleanGetterPrefix| |get| diff --git a/docs/generators/java-undertow-server.md b/docs/generators/java-undertow-server.md index 7342fd046e8..1aa234dd316 100644 --- a/docs/generators/java-undertow-server.md +++ b/docs/generators/java-undertow-server.md @@ -27,6 +27,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |artifactId|artifactId in generated pom.xml. This also becomes part of the generated library's filename| |openapi-undertow-server| |artifactUrl|artifact URL in generated pom.xml| |https://github.com/openapitools/openapi-generator| |artifactVersion|artifact version in generated pom.xml. This also becomes part of the generated library's filename| |1.0.0| +|autosetConstants|Automatically set Required Params having a Single enum value i.e. Constants in generated code| |false| |bigDecimalAsString|Treat BigDecimal values as Strings to avoid precision loss.| |false| |booleanGetterPrefix|Set booleanGetterPrefix| |get| |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| diff --git a/docs/generators/java-vertx-web.md b/docs/generators/java-vertx-web.md index 2057fefafc9..bee4c2e6330 100644 --- a/docs/generators/java-vertx-web.md +++ b/docs/generators/java-vertx-web.md @@ -27,6 +27,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |artifactId|artifactId in generated pom.xml. This also becomes part of the generated library's filename| |openapi-java-vertx-web-server| |artifactUrl|artifact URL in generated pom.xml| |https://github.com/openapitools/openapi-generator| |artifactVersion|artifact version in generated pom.xml. This also becomes part of the generated library's filename| |1.0.0-SNAPSHOT| +|autosetConstants|Automatically set Required Params having a Single enum value i.e. Constants in generated code| |false| |bigDecimalAsString|Treat BigDecimal values as Strings to avoid precision loss.| |false| |booleanGetterPrefix|Set booleanGetterPrefix| |get| |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| diff --git a/docs/generators/java-vertx.md b/docs/generators/java-vertx.md index 57b3b487f73..fef6af1b644 100644 --- a/docs/generators/java-vertx.md +++ b/docs/generators/java-vertx.md @@ -27,6 +27,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |artifactId|artifactId in generated pom.xml. This also becomes part of the generated library's filename| |openapi-java-vertx-server| |artifactUrl|artifact URL in generated pom.xml| |https://github.com/openapitools/openapi-generator| |artifactVersion|artifact version in generated pom.xml. This also becomes part of the generated library's filename| |1.0.0-SNAPSHOT| +|autosetConstants|Automatically set Required Params having a Single enum value i.e. Constants in generated code| |false| |bigDecimalAsString|Treat BigDecimal values as Strings to avoid precision loss.| |false| |booleanGetterPrefix|Set booleanGetterPrefix| |get| |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| diff --git a/docs/generators/java.md b/docs/generators/java.md index 0eb95e0ef8f..ea5310688bc 100644 --- a/docs/generators/java.md +++ b/docs/generators/java.md @@ -29,6 +29,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |artifactUrl|artifact URL in generated pom.xml| |https://github.com/openapitools/openapi-generator| |artifactVersion|artifact version in generated pom.xml. This also becomes part of the generated library's filename| |1.0.0| |asyncNative|If true, async handlers will be used, instead of the sync version| |false| +|autosetConstants|Automatically set Required Params having a Single enum value i.e. Constants in generated code| |false| |bigDecimalAsString|Treat BigDecimal values as Strings to avoid precision loss.| |false| |booleanGetterPrefix|Set booleanGetterPrefix| |get| |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| diff --git a/docs/generators/jaxrs-cxf-cdi.md b/docs/generators/jaxrs-cxf-cdi.md index 3c470946b30..b7d670e8dbb 100644 --- a/docs/generators/jaxrs-cxf-cdi.md +++ b/docs/generators/jaxrs-cxf-cdi.md @@ -27,6 +27,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |artifactId|artifactId in generated pom.xml. This also becomes part of the generated library's filename| |openapi-jaxrs-cxf-cdi-server| |artifactUrl|artifact URL in generated pom.xml| |https://github.com/openapitools/openapi-generator| |artifactVersion|artifact version in generated pom.xml. This also becomes part of the generated library's filename| |1.0.0| +|autosetConstants|Automatically set Required Params having a Single enum value i.e. Constants in generated code| |false| |bigDecimalAsString|Treat BigDecimal values as Strings to avoid precision loss.| |false| |booleanGetterPrefix|Set booleanGetterPrefix| |get| |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| diff --git a/docs/generators/jaxrs-cxf-client.md b/docs/generators/jaxrs-cxf-client.md index d2501c27ed7..bbbc265ebb7 100644 --- a/docs/generators/jaxrs-cxf-client.md +++ b/docs/generators/jaxrs-cxf-client.md @@ -27,6 +27,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |artifactId|artifactId in generated pom.xml. This also becomes part of the generated library's filename| |openapi-jaxrs-client| |artifactUrl|artifact URL in generated pom.xml| |https://github.com/openapitools/openapi-generator| |artifactVersion|artifact version in generated pom.xml. This also becomes part of the generated library's filename| |1.0.0| +|autosetConstants|Automatically set Required Params having a Single enum value i.e. Constants in generated code| |false| |bigDecimalAsString|Treat BigDecimal values as Strings to avoid precision loss.| |false| |booleanGetterPrefix|Set booleanGetterPrefix| |get| |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| diff --git a/docs/generators/jaxrs-cxf-extended.md b/docs/generators/jaxrs-cxf-extended.md index b5e40fddf86..bd16ea9cd02 100644 --- a/docs/generators/jaxrs-cxf-extended.md +++ b/docs/generators/jaxrs-cxf-extended.md @@ -28,6 +28,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |artifactId|artifactId in generated pom.xml. This also becomes part of the generated library's filename| |openapi-cxf-server| |artifactUrl|artifact URL in generated pom.xml| |https://github.com/openapitools/openapi-generator| |artifactVersion|artifact version in generated pom.xml. This also becomes part of the generated library's filename| |1.0.0| +|autosetConstants|Automatically set Required Params having a Single enum value i.e. Constants in generated code| |false| |bigDecimalAsString|Treat BigDecimal values as Strings to avoid precision loss.| |false| |booleanGetterPrefix|Set booleanGetterPrefix| |get| |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| diff --git a/docs/generators/jaxrs-cxf.md b/docs/generators/jaxrs-cxf.md index 19cbe9aaa0a..47a667c2e9c 100644 --- a/docs/generators/jaxrs-cxf.md +++ b/docs/generators/jaxrs-cxf.md @@ -28,6 +28,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |artifactId|artifactId in generated pom.xml. This also becomes part of the generated library's filename| |openapi-cxf-server| |artifactUrl|artifact URL in generated pom.xml| |https://github.com/openapitools/openapi-generator| |artifactVersion|artifact version in generated pom.xml. This also becomes part of the generated library's filename| |1.0.0| +|autosetConstants|Automatically set Required Params having a Single enum value i.e. Constants in generated code| |false| |bigDecimalAsString|Treat BigDecimal values as Strings to avoid precision loss.| |false| |booleanGetterPrefix|Set booleanGetterPrefix| |get| |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| diff --git a/docs/generators/jaxrs-jersey.md b/docs/generators/jaxrs-jersey.md index e25a01acaf0..2e79c39409f 100644 --- a/docs/generators/jaxrs-jersey.md +++ b/docs/generators/jaxrs-jersey.md @@ -27,6 +27,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |artifactId|artifactId in generated pom.xml. This also becomes part of the generated library's filename| |openapi-jaxrs-server| |artifactUrl|artifact URL in generated pom.xml| |https://github.com/openapitools/openapi-generator| |artifactVersion|artifact version in generated pom.xml. This also becomes part of the generated library's filename| |1.0.0| +|autosetConstants|Automatically set Required Params having a Single enum value i.e. Constants in generated code| |false| |bigDecimalAsString|Treat BigDecimal values as Strings to avoid precision loss.| |false| |booleanGetterPrefix|Set booleanGetterPrefix| |get| |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| diff --git a/docs/generators/jaxrs-resteasy-eap.md b/docs/generators/jaxrs-resteasy-eap.md index f78b6796302..bf198db901f 100644 --- a/docs/generators/jaxrs-resteasy-eap.md +++ b/docs/generators/jaxrs-resteasy-eap.md @@ -27,6 +27,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |artifactId|artifactId in generated pom.xml. This also becomes part of the generated library's filename| |openapi-jaxrs-resteasy-eap-server| |artifactUrl|artifact URL in generated pom.xml| |https://github.com/openapitools/openapi-generator| |artifactVersion|artifact version in generated pom.xml. This also becomes part of the generated library's filename| |1.0.0| +|autosetConstants|Automatically set Required Params having a Single enum value i.e. Constants in generated code| |false| |bigDecimalAsString|Treat BigDecimal values as Strings to avoid precision loss.| |false| |booleanGetterPrefix|Set booleanGetterPrefix| |get| |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| diff --git a/docs/generators/jaxrs-resteasy.md b/docs/generators/jaxrs-resteasy.md index 55bb4e75cef..59c2f3f3516 100644 --- a/docs/generators/jaxrs-resteasy.md +++ b/docs/generators/jaxrs-resteasy.md @@ -27,6 +27,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |artifactId|artifactId in generated pom.xml. This also becomes part of the generated library's filename| |openapi-jaxrs-resteasy-server| |artifactUrl|artifact URL in generated pom.xml| |https://github.com/openapitools/openapi-generator| |artifactVersion|artifact version in generated pom.xml. This also becomes part of the generated library's filename| |1.0.0| +|autosetConstants|Automatically set Required Params having a Single enum value i.e. Constants in generated code| |false| |bigDecimalAsString|Treat BigDecimal values as Strings to avoid precision loss.| |false| |booleanGetterPrefix|Set booleanGetterPrefix| |get| |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| diff --git a/docs/generators/jaxrs-spec.md b/docs/generators/jaxrs-spec.md index 8c5c3e899c8..85477ef8785 100644 --- a/docs/generators/jaxrs-spec.md +++ b/docs/generators/jaxrs-spec.md @@ -27,6 +27,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |artifactId|artifactId in generated pom.xml. This also becomes part of the generated library's filename| |openapi-jaxrs-server| |artifactUrl|artifact URL in generated pom.xml| |https://github.com/openapitools/openapi-generator| |artifactVersion|artifact version in generated pom.xml. This also becomes part of the generated library's filename| |1.0.0| +|autosetConstants|Automatically set Required Params having a Single enum value i.e. Constants in generated code| |false| |bigDecimalAsString|Treat BigDecimal values as Strings to avoid precision loss.| |false| |booleanGetterPrefix|Set booleanGetterPrefix| |get| |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| diff --git a/docs/generators/spring.md b/docs/generators/spring.md index 3b5f5f5f4d0..cbf36af54e2 100644 --- a/docs/generators/spring.md +++ b/docs/generators/spring.md @@ -30,6 +30,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |artifactUrl|artifact URL in generated pom.xml| |https://github.com/openapitools/openapi-generator| |artifactVersion|artifact version in generated pom.xml. This also becomes part of the generated library's filename| |1.0.0| |async|use async Callable controllers| |false| +|autosetConstants|Automatically set Required Params having a Single enum value i.e. Constants in generated code| |false| |basePackage|base package (invokerPackage) for generated code| |org.openapitools| |bigDecimalAsString|Treat BigDecimal values as Strings to avoid precision loss.| |false| |booleanGetterPrefix|Set booleanGetterPrefix| |get| diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java index d928016ce94..ab938291187 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java @@ -30,7 +30,7 @@ public class CodegenOperation { hasVersionHeaders = false, hasVersionQueryParams = false, isResponseBinary = false, isResponseFile = false, isResponseOptional = false, hasReference = false, defaultReturnType = false, isRestfulIndex, isRestfulShow, isRestfulCreate, isRestfulUpdate, isRestfulDestroy, - isRestful, isDeprecated, isCallbackRequest, uniqueItems, hasDefaultResponse = false, + isRestful, isDeprecated, isCallbackRequest, uniqueItems, hasDefaultResponse = false, hasConstantParams = false, hasErrorResponseObject; // if 4xx, 5xx responses have at least one error object defined public CodegenProperty returnProperty; public String path, operationId, returnType, returnFormat, httpMethod, returnBaseType, @@ -45,6 +45,7 @@ public class CodegenOperation { public List queryParams = new ArrayList(); public List headerParams = new ArrayList(); public List implicitHeadersParams = new ArrayList(); + public List constantParams = new ArrayList(); public List formParams = new ArrayList(); public List cookieParams = new ArrayList(); public List requiredParams = new ArrayList(); @@ -392,6 +393,7 @@ public class CodegenOperation { sb.append(", operationIdLowerCase='").append(operationIdLowerCase).append('\''); sb.append(", operationIdCamelCase='").append(operationIdCamelCase).append('\''); sb.append(", operationIdSnakeCase='").append(operationIdSnakeCase).append('\''); + sb.append(", constantParams='").append(constantParams).append('\''); sb.append('}'); return sb.toString(); } @@ -472,7 +474,8 @@ public class CodegenOperation { Objects.equals(operationIdOriginal, that.operationIdOriginal) && Objects.equals(operationIdLowerCase, that.operationIdLowerCase) && Objects.equals(operationIdCamelCase, that.operationIdCamelCase) && - Objects.equals(operationIdSnakeCase, that.operationIdSnakeCase); + Objects.equals(operationIdSnakeCase, that.operationIdSnakeCase) && + Objects.equals(constantParams, that.constantParams); } @Override @@ -488,6 +491,6 @@ public class CodegenOperation { pathParams, queryParams, headerParams, formParams, cookieParams, requiredParams, returnProperty, optionalParams, authMethods, tags, responses, callbacks, imports, examples, requestBodyExamples, externalDocs, vendorExtensions, nickname, operationIdOriginal, operationIdLowerCase, operationIdCamelCase, - operationIdSnakeCase, hasErrorResponseObject, requiredAndNotNullableParams, notNullableParams); + operationIdSnakeCase, hasErrorResponseObject, requiredAndNotNullableParams, notNullableParams, constantParams); } } 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 bd4007d1b3f..4d74bb3cdad 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 @@ -83,6 +83,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code public static final String TEST_OUTPUT = "testOutput"; public static final String IMPLICIT_HEADERS = "implicitHeaders"; public static final String IMPLICIT_HEADERS_REGEX = "implicitHeadersRegex"; + public static final String AUTOSET_CONSTANTS = "autosetConstants"; public static final String JAVAX_PACKAGE = "javaxPackage"; public static final String USE_JAKARTA_EE = "useJakartaEe"; public static final String CONTAINER_DEFAULT_TO_NULL = "containerDefaultToNull"; @@ -137,6 +138,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code protected AnnotationLibrary annotationLibrary; protected boolean implicitHeaders = false; protected String implicitHeadersRegex = null; + protected boolean autosetConstants = false; protected boolean camelCaseDollarSign = false; protected boolean useJakartaEe = false; protected boolean containerDefaultToNull = false; @@ -277,6 +279,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code cliOptions.add(CliOption.newBoolean(OPENAPI_NULLABLE, "Enable OpenAPI Jackson Nullable library", this.openApiNullable)); cliOptions.add(CliOption.newBoolean(IMPLICIT_HEADERS, "Skip header parameters in the generated API methods using @ApiImplicitParams annotation.", implicitHeaders)); cliOptions.add(CliOption.newString(IMPLICIT_HEADERS_REGEX, "Skip header parameters that matches given regex in the generated API methods using @ApiImplicitParams annotation. Note: this parameter is ignored when implicitHeaders=true")); + cliOptions.add(CliOption.newBoolean(AUTOSET_CONSTANTS, "Automatically set Required Params having a Single enum value i.e. Constants in generated code", autosetConstants)); cliOptions.add(CliOption.newBoolean(CAMEL_CASE_DOLLAR_SIGN, "Fix camelCase when starting with $ sign. when true : $Value when false : $value")); cliOptions.add(CliOption.newBoolean(USE_JAKARTA_EE, "whether to use Jakarta EE namespace instead of javax")); cliOptions.add(CliOption.newBoolean(CONTAINER_DEFAULT_TO_NULL, "Set containers (array, set, map) default to null")); @@ -563,6 +566,10 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code this.setImplicitHeadersRegex(additionalProperties.get(IMPLICIT_HEADERS_REGEX).toString()); } + if (additionalProperties.containsKey(AUTOSET_CONSTANTS)) { + this.setAutosetConstants(Boolean.parseBoolean(additionalProperties.get(AUTOSET_CONSTANTS).toString())); + } + if (additionalProperties.containsKey(CAMEL_CASE_DOLLAR_SIGN)) { this.setCamelCaseDollarSign(Boolean.parseBoolean(additionalProperties.get(CAMEL_CASE_DOLLAR_SIGN).toString())); } @@ -1578,6 +1585,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code op.vendorExtensions.put("x-java-import", operationImports); handleImplicitHeaders(op); + handleConstantParams(op); } return objs; @@ -2052,6 +2060,10 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code this.implicitHeadersRegex = implicitHeadersRegex; } + public void setAutosetConstants(boolean autosetConstants) { + this.autosetConstants = autosetConstants; + } + public void setCamelCaseDollarSign(boolean camelCaseDollarSign) { this.camelCaseDollarSign = camelCaseDollarSign; } @@ -2294,6 +2306,45 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code operation.hasParams = !operation.allParams.isEmpty(); } + /** + * This method removes all constant Query, Header and Cookie Params from allParams and sets them as constantParams in the CodegenOperation. + * The definition of constant is single valued required enum params. + * The constantParams in the the generated code should be hardcoded to the constantValue if autosetConstants feature is enabled. + * + * @param operation - operation to be processed + */ + protected void handleConstantParams(CodegenOperation operation) { + if (!autosetConstants || operation.allParams.isEmpty()) { + return; + } + final ArrayList copy = new ArrayList<>(operation.allParams); + // Remove all params from Params, Non constant params will be added back later. + operation.allParams.clear(); + + // Finds all constant params, removes them from allParams and adds them to constant params. + // Also, adds back non constant params to allParams. + for (CodegenParameter p : copy) { + if (p.isEnum && p.required && p._enum != null && p._enum.size() == 1) { + // Add to constantParams for use in the code generation templates. + operation.constantParams.add(p); + if(p.isQueryParam) { + operation.queryParams.removeIf(param -> param.baseName.equals(p.baseName)); + } + if(p.isHeaderParam) { + operation.headerParams.removeIf(param -> param.baseName.equals(p.baseName)); + } + if(p.isCookieParam) { + operation.cookieParams.removeIf(param -> param.baseName.equals(p.baseName)); + } + LOGGER.info("Update operation [{}]. Remove parameter [{}] because it can only have a fixed value of [{}]", operation.operationId, p.baseName, p._enum.get(0)); + } else { + // Add back to allParams as the param is not a constant. + operation.allParams.add(p); + } + } + operation.hasParams = !operation.allParams.isEmpty(); + } + private boolean shouldBeImplicitHeader(CodegenParameter parameter) { return StringUtils.isNotBlank(implicitHeadersRegex) && parameter.baseName.matches(implicitHeadersRegex); } diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/api.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/api.mustache index ad8af005c15..b52a1cbd5cb 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/api.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/api.mustache @@ -172,18 +172,39 @@ public class {{classname}} { } {{/queryParams}} + {{#constantParams}} + {{#isQueryParam}} + // Set client side default value of Query Param "{{baseName}}". + localVarCollectionQueryParams.add(new Pair("{{baseName}}", {{#_enum}}"{{{.}}}"{{/_enum}})); + + {{/isQueryParam}} + {{/constantParams}} {{#headerParams}} if ({{paramName}} != null) { localVarHeaderParams.put("{{baseName}}", localVarApiClient.parameterToString({{paramName}})); } {{/headerParams}} + {{#constantParams}} + {{#isHeaderParam}} + // Set client side default value of Header Param "{{baseName}}". + localVarHeaderParams.put("{{baseName}}", {{#_enum}}"{{{.}}}"{{/_enum}}); + + {{/isHeaderParam}} + {{/constantParams}} {{#cookieParams}} if ({{paramName}} != null) { localVarCookieParams.put("{{baseName}}", localVarApiClient.parameterToString({{paramName}})); } {{/cookieParams}} + {{#constantParams}} + {{#isCookieParam}} + // Set client side default value of Cookie Param "{{baseName}}". + localVarCookieParams.put("{{baseName}}", {{#_enum}}"{{{.}}}"{{/_enum}}); + + {{/isCookieParam}} + {{/constantParams}} {{/dynamicOperations}} {{#dynamicOperations}} localVarPath = localVarApiClient.fillParametersFromOperation(operation, paramMap, localVarPath, localVarQueryParams, localVarCollectionQueryParams, localVarHeaderParams, localVarCookieParams); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java index f5519605bad..ba56a03eefd 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java @@ -17,6 +17,15 @@ package org.openapitools.codegen.java; +import static org.junit.Assert.assertNotNull; +import static org.openapitools.codegen.TestUtils.assertFileContains; +import static org.openapitools.codegen.TestUtils.assertFileNotContains; +import static org.openapitools.codegen.TestUtils.validateJavaSourceFiles; +import static org.openapitools.codegen.languages.JavaClientCodegen.USE_ENUM_CASE_INSENSITIVE; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; + import com.google.common.collect.ImmutableMap; import io.swagger.parser.OpenAPIParser; import io.swagger.v3.oas.models.OpenAPI; @@ -33,6 +42,27 @@ import io.swagger.v3.oas.models.parameters.RequestBody; import io.swagger.v3.oas.models.responses.ApiResponse; import io.swagger.v3.parser.core.models.ParseOptions; import io.swagger.v3.parser.util.SchemaTypeUtil; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; import lombok.SneakyThrows; import org.openapitools.codegen.ClientOptInput; import org.openapitools.codegen.CodegenConstants; @@ -58,36 +88,6 @@ import org.testng.annotations.DataProvider; import org.testng.annotations.Ignore; import org.testng.annotations.Test; -import java.io.File; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Optional; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - -import static org.openapitools.codegen.TestUtils.assertFileContains; -import static org.openapitools.codegen.TestUtils.assertFileNotContains; -import static org.openapitools.codegen.TestUtils.validateJavaSourceFiles; -import static org.openapitools.codegen.languages.JavaClientCodegen.USE_ENUM_CASE_INSENSITIVE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - public class JavaClientCodegenTest { @Test @@ -98,7 +98,11 @@ public class JavaClientCodegenTest { RequestBody body1 = new RequestBody(); body1.setDescription("A list of ids"); - body1.setContent(new Content().addMediaType("application/json", new MediaType().schema(new ArraySchema().items(new StringSchema())))); + body1.setContent( + new Content() + .addMediaType( + "application/json", + new MediaType().schema(new ArraySchema().items(new StringSchema())))); CodegenParameter codegenParameter1 = codegen.fromRequestBody(body1, new HashSet(), null); Assert.assertEquals(codegenParameter1.description, "A list of ids"); Assert.assertEquals(codegenParameter1.dataType, "List"); @@ -106,7 +110,13 @@ public class JavaClientCodegenTest { RequestBody body2 = new RequestBody(); body2.setDescription("A list of list of values"); - body2.setContent(new Content().addMediaType("application/json", new MediaType().schema(new ArraySchema().items(new ArraySchema().items(new IntegerSchema()))))); + body2.setContent( + new Content() + .addMediaType( + "application/json", + new MediaType() + .schema( + new ArraySchema().items(new ArraySchema().items(new IntegerSchema()))))); CodegenParameter codegenParameter2 = codegen.fromRequestBody(body2, new HashSet(), null); Assert.assertEquals(codegenParameter2.description, "A list of list of values"); Assert.assertEquals(codegenParameter2.dataType, "List>"); @@ -114,7 +124,14 @@ public class JavaClientCodegenTest { RequestBody body3 = new RequestBody(); body3.setDescription("A list of points"); - body3.setContent(new Content().addMediaType("application/json", new MediaType().schema(new ArraySchema().items(new ObjectSchema().$ref("#/components/schemas/Point"))))); + body3.setContent( + new Content() + .addMediaType( + "application/json", + new MediaType() + .schema( + new ArraySchema() + .items(new ObjectSchema().$ref("#/components/schemas/Point"))))); ObjectSchema point = new ObjectSchema(); point.addProperty("message", new StringSchema()); point.addProperty("x", new IntegerSchema().format(SchemaTypeUtil.INTEGER32_FORMAT)); @@ -167,11 +184,17 @@ public class JavaClientCodegenTest { Assert.assertFalse(codegen.isHideGenerationTimestamp()); Assert.assertEquals(codegen.modelPackage(), "org.openapitools.client.model"); - Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "org.openapitools.client.model"); + Assert.assertEquals( + codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), + "org.openapitools.client.model"); Assert.assertEquals(codegen.apiPackage(), "org.openapitools.client.api"); - Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), "org.openapitools.client.api"); + Assert.assertEquals( + codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), + "org.openapitools.client.api"); Assert.assertEquals(codegen.getInvokerPackage(), "org.openapitools.client"); - Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), "org.openapitools.client"); + Assert.assertEquals( + codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), + "org.openapitools.client"); Assert.assertEquals(codegen.getSerializationLibrary(), JavaClientCodegen.SERIALIZATION_LIBRARY_GSON); } @@ -188,11 +211,16 @@ public class JavaClientCodegenTest { Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); Assert.assertTrue(codegen.isHideGenerationTimestamp()); Assert.assertEquals(codegen.modelPackage(), "xyz.yyyyy.zzzzzzz.model"); - Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "xyz.yyyyy.zzzzzzz.model"); + Assert.assertEquals( + codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), + "xyz.yyyyy.zzzzzzz.model"); Assert.assertEquals(codegen.apiPackage(), "xyz.yyyyy.zzzzzzz.api"); - Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), "xyz.yyyyy.zzzzzzz.api"); + Assert.assertEquals( + codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), "xyz.yyyyy.zzzzzzz.api"); Assert.assertEquals(codegen.getInvokerPackage(), "xyz.yyyyy.zzzzzzz.invoker"); - Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), "xyz.yyyyy.zzzzzzz.invoker"); + Assert.assertEquals( + codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), + "xyz.yyyyy.zzzzzzz.invoker"); Assert.assertEquals(codegen.getSerializationLibrary(), JavaClientCodegen.SERIALIZATION_LIBRARY_GSON); // the library JavaClientCodegen.OKHTTP_GSON only supports GSON } @@ -200,9 +228,13 @@ public class JavaClientCodegenTest { public void testAdditionalPropertiesPutForConfigValues() throws Exception { final JavaClientCodegen codegen = new JavaClientCodegen(); codegen.additionalProperties().put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true"); - codegen.additionalProperties().put(CodegenConstants.MODEL_PACKAGE, "xyz.yyyyy.zzzzzzz.mmmmm.model"); - codegen.additionalProperties().put(CodegenConstants.API_PACKAGE, "xyz.yyyyy.zzzzzzz.aaaaa.api"); - codegen.additionalProperties().put(CodegenConstants.INVOKER_PACKAGE, "xyz.yyyyy.zzzzzzz.iiii.invoker"); + codegen + .additionalProperties() + .put(CodegenConstants.MODEL_PACKAGE, "xyz.yyyyy.zzzzzzz.mmmmm.model"); + codegen.additionalProperties().put(CodegenConstants.API_PACKAGE, "xyz.yyyyy.zzzzzzz.aaaaa.api"); + codegen + .additionalProperties() + .put(CodegenConstants.INVOKER_PACKAGE, "xyz.yyyyy.zzzzzzz.iiii.invoker"); codegen.additionalProperties().put(CodegenConstants.SERIALIZATION_LIBRARY, "JACKSON"); codegen.additionalProperties().put(CodegenConstants.LIBRARY, JavaClientCodegen.JERSEY2); codegen.processOpts(); @@ -210,11 +242,17 @@ public class JavaClientCodegenTest { Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); Assert.assertTrue(codegen.isHideGenerationTimestamp()); Assert.assertEquals(codegen.modelPackage(), "xyz.yyyyy.zzzzzzz.mmmmm.model"); - Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "xyz.yyyyy.zzzzzzz.mmmmm.model"); + Assert.assertEquals( + codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), + "xyz.yyyyy.zzzzzzz.mmmmm.model"); Assert.assertEquals(codegen.apiPackage(), "xyz.yyyyy.zzzzzzz.aaaaa.api"); - Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), "xyz.yyyyy.zzzzzzz.aaaaa.api"); + Assert.assertEquals( + codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), + "xyz.yyyyy.zzzzzzz.aaaaa.api"); Assert.assertEquals(codegen.getInvokerPackage(), "xyz.yyyyy.zzzzzzz.iiii.invoker"); - Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), "xyz.yyyyy.zzzzzzz.iiii.invoker"); + Assert.assertEquals( + codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), + "xyz.yyyyy.zzzzzzz.iiii.invoker"); Assert.assertEquals(codegen.getSerializationLibrary(), JavaClientCodegen.SERIALIZATION_LIBRARY_JACKSON); } @@ -225,12 +263,14 @@ public class JavaClientCodegenTest { File output = Files.createTempDirectory("test").toFile(); - final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.JERSEY3) - .setAdditionalProperties(properties) - .setInputSpec("src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + final CodegenConfigurator configurator = + new CodegenConfigurator() + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.JERSEY3) + .setAdditionalProperties(properties) + .setInputSpec( + "src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml") + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); final ClientOptInput clientOptInput = configurator.toClientOptInput(); @@ -238,11 +278,14 @@ public class JavaClientCodegenTest { List files = generator.opts(clientOptInput).generate(); - TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/auth/ApiKeyAuth.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/auth/Authentication.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/auth/HttpBasicAuth.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/auth/HttpBearerAuth.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/auth/HttpSignatureAuth.java"); + TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/auth/ApiKeyAuth.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/xyz/abcdef/auth/Authentication.java"); + TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/auth/HttpBasicAuth.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/xyz/abcdef/auth/HttpBearerAuth.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/xyz/abcdef/auth/HttpSignatureAuth.java"); } @Test @@ -262,7 +305,9 @@ public class JavaClientCodegenTest { List files = generator.opts(clientOptInput).generate(); - TestUtils.assertFileContains(Paths.get(output + "/src/main/java/org/openapitools/client/api/QueryApi.java"), "import java.time.Instant;"); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/org/openapitools/client/api/QueryApi.java"), + "import java.time.Instant;"); } @Test @@ -277,35 +322,52 @@ public class JavaClientCodegenTest { @Test public void testPackageNamesSetInvokerDerivedFromApi() { final JavaClientCodegen codegen = new JavaClientCodegen(); - codegen.additionalProperties().put(CodegenConstants.MODEL_PACKAGE, "xyz.yyyyy.zzzzzzz.mmmmm.model"); - codegen.additionalProperties().put(CodegenConstants.API_PACKAGE, "xyz.yyyyy.zzzzzzz.aaaaa.api"); + codegen + .additionalProperties() + .put(CodegenConstants.MODEL_PACKAGE, "xyz.yyyyy.zzzzzzz.mmmmm.model"); + codegen.additionalProperties().put(CodegenConstants.API_PACKAGE, "xyz.yyyyy.zzzzzzz.aaaaa.api"); codegen.processOpts(); Assert.assertEquals(codegen.modelPackage(), "xyz.yyyyy.zzzzzzz.mmmmm.model"); - Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "xyz.yyyyy.zzzzzzz.mmmmm.model"); + Assert.assertEquals( + codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), + "xyz.yyyyy.zzzzzzz.mmmmm.model"); Assert.assertEquals(codegen.apiPackage(), "xyz.yyyyy.zzzzzzz.aaaaa.api"); - Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), "xyz.yyyyy.zzzzzzz.aaaaa.api"); + Assert.assertEquals( + codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), + "xyz.yyyyy.zzzzzzz.aaaaa.api"); Assert.assertEquals(codegen.getInvokerPackage(), "xyz.yyyyy.zzzzzzz.aaaaa"); - Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), "xyz.yyyyy.zzzzzzz.aaaaa"); + Assert.assertEquals( + codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), + "xyz.yyyyy.zzzzzzz.aaaaa"); } @Test public void testPackageNamesSetInvokerDerivedFromModel() { final JavaClientCodegen codegen = new JavaClientCodegen(); - codegen.additionalProperties().put(CodegenConstants.MODEL_PACKAGE, "xyz.yyyyy.zzzzzzz.mmmmm.model"); + codegen + .additionalProperties() + .put(CodegenConstants.MODEL_PACKAGE, "xyz.yyyyy.zzzzzzz.mmmmm.model"); codegen.processOpts(); Assert.assertEquals(codegen.modelPackage(), "xyz.yyyyy.zzzzzzz.mmmmm.model"); - Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "xyz.yyyyy.zzzzzzz.mmmmm.model"); + Assert.assertEquals( + codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), + "xyz.yyyyy.zzzzzzz.mmmmm.model"); Assert.assertEquals(codegen.apiPackage(), "org.openapitools.client.api"); - Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), "org.openapitools.client.api"); + Assert.assertEquals( + codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), + "org.openapitools.client.api"); Assert.assertEquals(codegen.getInvokerPackage(), "xyz.yyyyy.zzzzzzz.mmmmm"); - Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), "xyz.yyyyy.zzzzzzz.mmmmm"); + Assert.assertEquals( + codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), + "xyz.yyyyy.zzzzzzz.mmmmm"); } @Test public void testGetSchemaTypeWithComposedSchemaWithAllOf() { - final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/2_0/composed-allof.yaml"); + final OpenAPI openAPI = + TestUtils.parseFlattenSpec("src/test/resources/2_0/composed-allof.yaml"); final JavaClientCodegen codegen = new JavaClientCodegen(); Operation operation = openAPI.getPaths().get("/ping").getPost(); @@ -321,7 +383,8 @@ public class JavaClientCodegenTest { codegen.updateCodegenPropertyEnum(array); - List> enumVars = (List>) array.getItems().getAllowableValues().get("enumVars"); + List> enumVars = + (List>) array.getItems().getAllowableValues().get("enumVars"); Assert.assertNotNull(enumVars); Map testedEnumVar = enumVars.get(0); Assert.assertNotNull(testedEnumVar); @@ -333,11 +396,15 @@ public class JavaClientCodegenTest { public void updateCodegenPropertyEnumWithCustomNames() { final JavaClientCodegen codegen = new JavaClientCodegen(); CodegenProperty array = codegenPropertyWithArrayOfIntegerValues(); - array.getItems().setVendorExtensions(Collections.singletonMap("x-enum-varnames", Collections.singletonList("ONE"))); + array + .getItems() + .setVendorExtensions( + Collections.singletonMap("x-enum-varnames", Collections.singletonList("ONE"))); codegen.updateCodegenPropertyEnum(array); - List> enumVars = (List>) array.getItems().getAllowableValues().get("enumVars"); + List> enumVars = + (List>) array.getItems().getAllowableValues().get("enumVars"); Assert.assertNotNull(enumVars); Map testedEnumVar = enumVars.get(0); Assert.assertNotNull(testedEnumVar); @@ -388,24 +455,32 @@ public class JavaClientCodegenTest { TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/ApiClient.java"); TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/ApiException.java"); TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/ApiResponse.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/ServerConfiguration.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/xyz/abcdef/ServerConfiguration.java"); TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/ServerVariable.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/auth/ApiKeyAuth.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/auth/Authentication.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/auth/HttpBasicAuth.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/auth/HttpBearerAuth.java"); + TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/auth/ApiKeyAuth.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/xyz/abcdef/auth/Authentication.java"); + TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/auth/HttpBasicAuth.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/xyz/abcdef/auth/HttpBearerAuth.java"); TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/Configuration.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/GzipRequestInterceptor.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/xyz/abcdef/GzipRequestInterceptor.java"); TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/JSON.java"); TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/Pair.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/ProgressRequestBody.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/ProgressResponseBody.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/xyz/abcdef/ProgressRequestBody.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/xyz/abcdef/ProgressResponseBody.java"); TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/StringUtil.java"); - TestUtils.ensureContainsFile(files, output, "src/test/java/xyz/abcdef/api/DefaultApiTest.java"); + TestUtils.ensureContainsFile(files, output, "src/test/java/xyz/abcdef/api/DefaultApiTest.java"); validateJavaSourceFiles(files); - TestUtils.assertFileContains(Paths.get(output + "/src/main/java/xyz/abcdef/api/DefaultApi.java"), "public class DefaultApi"); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/xyz/abcdef/api/DefaultApi.java"), + "public class DefaultApi"); output.deleteOnExit(); } @@ -453,32 +528,49 @@ public class JavaClientCodegenTest { TestUtils.ensureContainsFile(files, output, "api/openapi.yaml"); TestUtils.ensureContainsFile(files, output, "src/main/AndroidManifest.xml"); TestUtils.ensureContainsFile(files, output, "src/main/java/zz/yyyy/api/xxxx/PingApi.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/zz/yyyy/invoker/xxxx/ApiCallback.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/zz/yyyy/invoker/xxxx/ApiClient.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/zz/yyyy/invoker/xxxx/ApiException.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/zz/yyyy/invoker/xxxx/ApiResponse.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/zz/yyyy/invoker/xxxx/ServerConfiguration.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/zz/yyyy/invoker/xxxx/ServerVariable.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/zz/yyyy/invoker/xxxx/auth/ApiKeyAuth.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/zz/yyyy/invoker/xxxx/auth/Authentication.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/zz/yyyy/invoker/xxxx/auth/HttpBasicAuth.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/zz/yyyy/invoker/xxxx/auth/HttpBearerAuth.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/zz/yyyy/invoker/xxxx/Configuration.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/zz/yyyy/invoker/xxxx/GzipRequestInterceptor.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/zz/yyyy/invoker/xxxx/ApiCallback.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/zz/yyyy/invoker/xxxx/ApiClient.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/zz/yyyy/invoker/xxxx/ApiException.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/zz/yyyy/invoker/xxxx/ApiResponse.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/zz/yyyy/invoker/xxxx/ServerConfiguration.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/zz/yyyy/invoker/xxxx/ServerVariable.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/zz/yyyy/invoker/xxxx/auth/ApiKeyAuth.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/zz/yyyy/invoker/xxxx/auth/Authentication.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/zz/yyyy/invoker/xxxx/auth/HttpBasicAuth.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/zz/yyyy/invoker/xxxx/auth/HttpBearerAuth.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/zz/yyyy/invoker/xxxx/Configuration.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/zz/yyyy/invoker/xxxx/GzipRequestInterceptor.java"); TestUtils.ensureContainsFile(files, output, "src/main/java/zz/yyyy/invoker/xxxx/JSON.java"); TestUtils.ensureContainsFile(files, output, "src/main/java/zz/yyyy/invoker/xxxx/Pair.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/zz/yyyy/invoker/xxxx/ProgressRequestBody.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/zz/yyyy/invoker/xxxx/ProgressResponseBody.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/zz/yyyy/invoker/xxxx/StringUtil.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/zz/yyyy/model/xxxx/SomeObj.java"); - TestUtils.ensureContainsFile(files, output, "src/test/java/zz/yyyy/api/xxxx/PingApiTest.java"); - TestUtils.ensureContainsFile(files, output, "src/test/java/zz/yyyy/model/xxxx/SomeObjTest.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/zz/yyyy/invoker/xxxx/ProgressRequestBody.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/zz/yyyy/invoker/xxxx/ProgressResponseBody.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/zz/yyyy/invoker/xxxx/StringUtil.java"); + TestUtils.ensureContainsFile(files, output, "src/main/java/zz/yyyy/model/xxxx/SomeObj.java"); + TestUtils.ensureContainsFile(files, output, "src/test/java/zz/yyyy/api/xxxx/PingApiTest.java"); + TestUtils.ensureContainsFile( + files, output, "src/test/java/zz/yyyy/model/xxxx/SomeObjTest.java"); validateJavaSourceFiles(files); - TestUtils.assertFileContains(Paths.get(output + "/src/main/java/zz/yyyy/model/xxxx/SomeObj.java"), - "public class SomeObj", - "Boolean isActive()"); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/zz/yyyy/model/xxxx/SomeObj.java"), + "public class SomeObj", + "Boolean isActive()"); output.deleteOnExit(); } @@ -505,11 +597,12 @@ public class JavaClientCodegenTest { Assert.assertEquals(files.size(), 32); validateJavaSourceFiles(files); - TestUtils.assertFileContains(Paths.get(output + "/src/main/java/xyz/abcdef/api/DefaultApi.java"), - "public class DefaultApi", - "import java.net.http.HttpClient;", - "import java.net.http.HttpRequest;", - "import java.net.http.HttpResponse;"); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/xyz/abcdef/api/DefaultApi.java"), + "public class DefaultApi", + "import java.net.http.HttpClient;", + "import java.net.http.HttpRequest;", + "import java.net.http.HttpResponse;"); TestUtils.assertFileContains(Paths.get(output + "/src/main/java/xyz/abcdef/ApiClient.java"), "public class ApiClient", @@ -527,12 +620,14 @@ public class JavaClientCodegenTest { File output = Files.createTempDirectory("test").toFile(); output.deleteOnExit(); - final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.NATIVE) - .setAdditionalProperties(properties) - .setInputSpec("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + final CodegenConfigurator configurator = + new CodegenConfigurator() + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.NATIVE) + .setAdditionalProperties(properties) + .setInputSpec( + "src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml") + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); final ClientOptInput clientOptInput = configurator.toClientOptInput(); DefaultGenerator generator = new DefaultGenerator(); @@ -611,17 +706,26 @@ public class JavaClientCodegenTest { clientOptInput.config(new JavaClientCodegen()); defaultGenerator.opts(clientOptInput); - final List codegenOperations = defaultGenerator.processPaths(openAPI.getPaths()).get("Pet"); + final List codegenOperations = + defaultGenerator.processPaths(openAPI.getPaths()).get("Pet"); - // Verify GET only has 'read' scope - final CodegenOperation getCodegenOperation = codegenOperations.stream().filter(it -> it.httpMethod.equals("GET")).collect(Collectors.toList()).get(0); + // Verify GET only has 'read' scope + final CodegenOperation getCodegenOperation = + codegenOperations.stream() + .filter(it -> it.httpMethod.equals("GET")) + .collect(Collectors.toList()) + .get(0); assertTrue(getCodegenOperation.hasAuthMethods); assertEquals(getCodegenOperation.authMethods.size(), 1); final List> getScopes = getCodegenOperation.authMethods.get(0).scopes; assertEquals(getScopes.size(), 1, "GET scopes don't match. actual::" + getScopes); - // POST operation should have both 'read' and 'write' scope on it - final CodegenOperation postCodegenOperation = codegenOperations.stream().filter(it -> it.httpMethod.equals("POST")).collect(Collectors.toList()).get(0); + // POST operation should have both 'read' and 'write' scope on it + final CodegenOperation postCodegenOperation = + codegenOperations.stream() + .filter(it -> it.httpMethod.equals("POST")) + .collect(Collectors.toList()) + .get(0); assertTrue(postCodegenOperation.hasAuthMethods); assertEquals(postCodegenOperation.authMethods.size(), 1); final List> postScopes = postCodegenOperation.authMethods.get(0).scopes; @@ -669,9 +773,14 @@ public class JavaClientCodegenTest { clientOptInput.config(new JavaClientCodegen()); defaultGenerator.opts(clientOptInput); - final List codegenOperations = defaultGenerator.processPaths(openAPI.getPaths()).get("Pet"); + final List codegenOperations = + defaultGenerator.processPaths(openAPI.getPaths()).get("Pet"); - final CodegenOperation getCodegenOperation = codegenOperations.stream().filter(it -> it.httpMethod.equals("GET")).collect(Collectors.toList()).get(0); + final CodegenOperation getCodegenOperation = + codegenOperations.stream() + .filter(it -> it.httpMethod.equals("GET")) + .collect(Collectors.toList()) + .get(0); assertTrue(getCodegenOperation.hasAuthMethods); assertEquals(getCodegenOperation.authMethods.size(), 2); } @@ -734,7 +843,8 @@ public class JavaClientCodegenTest { .setOutputDir(output.getAbsolutePath().replace("\\", "/")); final ClientOptInput clientOptInput = configurator.toClientOptInput(); - Assert.assertEquals(clientOptInput.getConfig().schemaMapping().get("TypeAlias"), "foo.bar.TypeAlias"); + Assert.assertEquals( + clientOptInput.getConfig().schemaMapping().get("TypeAlias"), "foo.bar.TypeAlias"); DefaultGenerator generator = new DefaultGenerator(); generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true"); @@ -749,17 +859,19 @@ public class JavaClientCodegenTest { validateJavaSourceFiles(files); Assert.assertEquals(files.size(), 1); - TestUtils.ensureContainsFile(files, output, "src/main/java/org/openapitools/client/model/ParentType.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/org/openapitools/client/model/ParentType.java"); String parentTypeContents = ""; try { - File file = files.stream().filter(f -> f.getName().endsWith("ParentType.java")).findFirst().get(); + File file = + files.stream().filter(f -> f.getName().endsWith("ParentType.java")).findFirst().get(); parentTypeContents = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8); } catch (IOException ignored) { } - final Pattern FIELD_PATTERN = Pattern.compile(".* private (.*?) typeAlias;.*", Pattern.DOTALL); + final Pattern FIELD_PATTERN = Pattern.compile(".* private (.*?) typeAlias;.*", Pattern.DOTALL); Matcher fieldMatcher = FIELD_PATTERN.matcher(parentTypeContents); Assert.assertTrue(fieldMatcher.matches()); @@ -770,7 +882,8 @@ public class JavaClientCodegenTest { @Test public void testBearerAuth() { - final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/pingBearerAuth.yaml"); + final OpenAPI openAPI = + TestUtils.parseFlattenSpec("src/test/resources/3_0/pingBearerAuth.yaml"); JavaClientCodegen codegen = new JavaClientCodegen(); List security = codegen.fromSecurity(openAPI.getComponents().getSecuritySchemes()); @@ -994,19 +1107,20 @@ public class JavaClientCodegenTest { validateJavaSourceFiles(files); Path defaultApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/MultipartApi.java"); - TestUtils.assertFileContains(defaultApi, - //multiple files - "multipartArrayWithHttpInfo(List files)", - "formParams.addAll(\"files\", files.stream().map(FileSystemResource::new).collect(Collectors.toList()));", + TestUtils.assertFileContains( + defaultApi, + // multiple files + "multipartArrayWithHttpInfo(List files)", + "formParams.addAll(\"files\"," + + " files.stream().map(FileSystemResource::new).collect(Collectors.toList()));", - //mixed - "multipartMixedWithHttpInfo(File file, MultipartMixedMarker marker)", - "formParams.add(\"file\", new FileSystemResource(file));", + // mixed + "multipartMixedWithHttpInfo(File file, MultipartMixedMarker marker)", + "formParams.add(\"file\", new FileSystemResource(file));", - //single file - "multipartSingleWithHttpInfo(File file)", - "formParams.add(\"file\", new FileSystemResource(file));" - ); + // single file + "multipartSingleWithHttpInfo(File file)", + "formParams.add(\"file\", new FileSystemResource(file));"); } /** @@ -1042,19 +1156,20 @@ public class JavaClientCodegenTest { validateJavaSourceFiles(files); Path defaultApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/MultipartApi.java"); - TestUtils.assertFileContains(defaultApi, - //multiple files - "multipartArray(List files)", - "formParams.addAll(\"files\", files.stream().map(FileSystemResource::new).collect(Collectors.toList()));", + TestUtils.assertFileContains( + defaultApi, + // multiple files + "multipartArray(List files)", + "formParams.addAll(\"files\"," + + " files.stream().map(FileSystemResource::new).collect(Collectors.toList()));", - //mixed - "multipartMixed(File file, MultipartMixedMarker marker)", - "formParams.add(\"file\", new FileSystemResource(file));", + // mixed + "multipartMixed(File file, MultipartMixedMarker marker)", + "formParams.add(\"file\", new FileSystemResource(file));", - //single file - "multipartSingle(File file)", - "formParams.add(\"file\", new FileSystemResource(file));" - ); + // single file + "multipartSingle(File file)", + "formParams.add(\"file\", new FileSystemResource(file));"); } @Test @@ -1066,24 +1181,32 @@ public class JavaClientCodegenTest { File output = Files.createTempDirectory("test").toFile(); output.deleteOnExit(); - final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.WEBCLIENT) - .setAdditionalProperties(properties) - .setInputSpec("src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + final CodegenConfigurator configurator = + new CodegenConfigurator() + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.WEBCLIENT) + .setAdditionalProperties(properties) + .setInputSpec( + "src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml") + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); DefaultGenerator generator = new DefaultGenerator(); Map files = generator.opts(configurator.toClientOptInput()).generate().stream() .collect(Collectors.toMap(File::getName, Function.identity())); - JavaFileAssert.assertThat(files.get("StoreApi.java")) - .assertMethod("getInventory").hasReturnType("Mono>") //explicit 'x-webclient-blocking: false' which overrides global config - .toFileAssert() - .assertMethod("placeOrder").hasReturnType("Order"); // use global config + JavaFileAssert.assertThat(files.get("StoreApi.java")) + .assertMethod("getInventory") + .hasReturnType( + "Mono>") // explicit 'x-webclient-blocking: false' which overrides + // global config + .toFileAssert() + .assertMethod("placeOrder") + .hasReturnType("Order"); // use global config - JavaFileAssert.assertThat(files.get("PetApi.java")) - .assertMethod("findPetsByStatus").hasReturnType("List"); // explicit 'x-webclient-blocking: true' which overrides global config + JavaFileAssert.assertThat(files.get("PetApi.java")) + .assertMethod("findPetsByStatus") + .hasReturnType( + "List"); // explicit 'x-webclient-blocking: true' which overrides global config } @Test @@ -1101,16 +1224,20 @@ public class JavaClientCodegenTest { List files = generator.opts(clientOptInput).generate(); Assert.assertEquals(files.size(), 49); - TestUtils.ensureContainsFile(files, output, "src/main/java/org/openapitools/client/model/RealCommand.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/org/openapitools/client/model/Command.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/org/openapitools/client/model/RealCommand.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/org/openapitools/client/model/Command.java"); validateJavaSourceFiles(files); - TestUtils.assertFileContains(Paths.get(output + "/src/main/java/org/openapitools/client/model/RealCommand.java"), - "class RealCommand {"); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/org/openapitools/client/model/RealCommand.java"), + "class RealCommand {"); - TestUtils.assertFileContains(Paths.get(output + "/src/main/java/org/openapitools/client/model/Command.java"), - "class Command {"); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/org/openapitools/client/model/Command.java"), + "class Command {"); output.deleteOnExit(); } @@ -1149,27 +1276,29 @@ public class JavaClientCodegenTest { validateJavaSourceFiles(files); Path defaultApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/MultipartApi.java"); - TestUtils.assertFileContains(defaultApi, - //multiple files - "multipartArray(java.util.Collection files)", - "multipartArrayWithHttpInfo(java.util.Collection files)", - "formParams.addAll(\"files\", files.stream().collect(Collectors.toList()));", + TestUtils.assertFileContains( + defaultApi, + // multiple files + "multipartArray(java.util.Collection files)", + "multipartArrayWithHttpInfo(java.util.Collection" + + " files)", + "formParams.addAll(\"files\", files.stream().collect(Collectors.toList()));", - //mixed - "multipartMixed(org.springframework.core.io.Resource file, MultipartMixedMarker marker)", - "multipartMixedWithHttpInfo(org.springframework.core.io.Resource file, MultipartMixedMarker marker)", - "formParams.add(\"file\", file);", + // mixed + "multipartMixed(org.springframework.core.io.Resource file, MultipartMixedMarker marker)", + "multipartMixedWithHttpInfo(org.springframework.core.io.Resource file, MultipartMixedMarker" + + " marker)", + "formParams.add(\"file\", file);", - //single file - "multipartSingle(org.springframework.core.io.Resource file)", - "multipartSingleWithHttpInfo(org.springframework.core.io.Resource file)", - "formParams.add(\"file\", file);" - ); + // single file + "multipartSingle(org.springframework.core.io.Resource file)", + "multipartSingleWithHttpInfo(org.springframework.core.io.Resource file)", + "formParams.add(\"file\", file);"); } @Test void testNotDuplicateOauth2FlowsScopes() { - final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/issue_7614.yaml"); + final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/issue_7614.yaml"); final ClientOptInput clientOptInput = new ClientOptInput() .openAPI(openAPI) @@ -1181,7 +1310,8 @@ public class JavaClientCodegenTest { final Map> paths = defaultGenerator.processPaths(openAPI.getPaths()); final List codegenOperations = paths.values().stream().flatMap(Collection::stream).collect(Collectors.toList()); - final CodegenOperation getWithBasicAuthAndOauth = getByOperationId(codegenOperations, "getWithBasicAuthAndOauth"); + final CodegenOperation getWithBasicAuthAndOauth = + getByOperationId(codegenOperations, "getWithBasicAuthAndOauth"); assertEquals(getWithBasicAuthAndOauth.authMethods.size(), 3); assertEquals(getWithBasicAuthAndOauth.authMethods.get(0).name, "basic_auth"); final Map passwordFlowScope = getWithBasicAuthAndOauth.authMethods.get(1).scopes.get(0); @@ -1189,9 +1319,10 @@ public class JavaClientCodegenTest { assertEquals(passwordFlowScope.get("description"), "create from password flow"); final Map clientCredentialsFlow = getWithBasicAuthAndOauth.authMethods.get(2).scopes.get(0); assertEquals(clientCredentialsFlow.get("scope"), "something:create"); - assertEquals(clientCredentialsFlow.get("description"), "create from client credentials flow"); + assertEquals(clientCredentialsFlow.get("description"), "create from client credentials flow"); - final CodegenOperation getWithOauthAuth = getByOperationId(codegenOperations, "getWithOauthAuth"); + final CodegenOperation getWithOauthAuth = + getByOperationId(codegenOperations, "getWithOauthAuth"); assertEquals(getWithOauthAuth.authMethods.size(), 2); final Map passwordFlow = getWithOauthAuth.authMethods.get(0).scopes.get(0); assertEquals(passwordFlow.get("scope"), "something:create"); @@ -1199,16 +1330,22 @@ public class JavaClientCodegenTest { final Map clientCredentialsCreateFlow = getWithOauthAuth.authMethods.get(1).scopes.get(0); assertEquals(clientCredentialsCreateFlow.get("scope"), "something:create"); - assertEquals(clientCredentialsCreateFlow.get("description"), "create from client credentials flow"); + assertEquals( + clientCredentialsCreateFlow.get("description"), "create from client credentials flow"); final Map clientCredentialsProcessFlow = getWithOauthAuth.authMethods.get(1).scopes.get(1); assertEquals(clientCredentialsProcessFlow.get("scope"), "something:process"); - assertEquals(clientCredentialsProcessFlow.get("description"), "process from client credentials flow"); + assertEquals( + clientCredentialsProcessFlow.get("description"), "process from client credentials flow"); } private CodegenOperation getByOperationId(List codegenOperations, String operationId) { - return getByCriteria(codegenOperations, (co) -> co.operationId.equals(operationId)) - .orElseThrow(() -> new IllegalStateException(String.format(Locale.ROOT, "Operation with id [%s] does not exist", operationId))); + return getByCriteria(codegenOperations, (co) -> co.operationId.equals(operationId)) + .orElseThrow( + () -> + new IllegalStateException( + String.format( + Locale.ROOT, "Operation with id [%s] does not exist", operationId))); } private Optional getByCriteria(List codegenOperations, Predicate filter) { @@ -1232,18 +1369,22 @@ public class JavaClientCodegenTest { DefaultGenerator generator = new DefaultGenerator(); List files = generator.opts(clientOptInput).generate(); - TestUtils.ensureContainsFile(files, output, "src/main/java/org/openapitools/client/api/DefaultApi.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/org/openapitools/client/api/DefaultApi.java"); validateJavaSourceFiles(files); - TestUtils.assertFileContains(Paths.get(output + "/src/main/java/org/openapitools/client/api/DefaultApi.java"), - "@RequestLine(\"POST /events/{eventId}:undelete\")"); - TestUtils.assertFileNotContains(Paths.get(output + "/src/main/java/org/openapitools/client/api/DefaultApi.java"), - "event_id"); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/org/openapitools/client/api/DefaultApi.java"), + "@RequestLine(\"POST /events/{eventId}:undelete\")"); + TestUtils.assertFileNotContains( + Paths.get(output + "/src/main/java/org/openapitools/client/api/DefaultApi.java"), + "event_id"); - // baseName is kept for form parameters - TestUtils.assertFileContains(Paths.get(output + "/src/main/java/org/openapitools/client/api/DefaultApi.java"), - "@Param(\"some_file\") File someFile"); + // baseName is kept for form parameters + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/org/openapitools/client/api/DefaultApi.java"), + "@Param(\"some_file\") File someFile"); output.deleteOnExit(); } @@ -1281,19 +1422,20 @@ public class JavaClientCodegenTest { validateJavaSourceFiles(files); Path defaultApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/MultipartApi.java"); - TestUtils.assertFileContains(defaultApi, - //multiple files - "multipartArray(java.util.Collection files)", - "formParams.addAll(\"files\", files.stream().collect(Collectors.toList()));", + TestUtils.assertFileContains( + defaultApi, + // multiple files + "multipartArray(java.util.Collection files)", + "formParams.addAll(\"files\", files.stream().collect(Collectors.toList()));", - //mixed - "multipartMixed(org.springframework.core.io.AbstractResource file, MultipartMixedMarker marker)", - "formParams.add(\"file\", file);", + // mixed + "multipartMixed(org.springframework.core.io.AbstractResource file, MultipartMixedMarker" + + " marker)", + "formParams.add(\"file\", file);", - //single file - "multipartSingle(org.springframework.core.io.AbstractResource file)", - "formParams.add(\"file\", file);" - ); + // single file + "multipartSingle(org.springframework.core.io.AbstractResource file)", + "formParams.add(\"file\", file);"); } /** @@ -1379,8 +1521,10 @@ public class JavaClientCodegenTest { Assert.assertEquals(files.size(), 35); validateJavaSourceFiles(files); - TestUtils.assertFileContains(Paths.get(output + "/src/main/java/xyz/abcdef/ApiClient.java"), - "public static String urlEncode(String s) { return URLEncoder.encode(s, UTF_8).replaceAll(\"\\\\+\", \"%20\"); }"); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/xyz/abcdef/ApiClient.java"), + "public static String urlEncode(String s) { return URLEncoder.encode(s," + + " UTF_8).replaceAll(\"\\\\+\", \"%20\"); }"); } /** @@ -1408,12 +1552,16 @@ public class JavaClientCodegenTest { Assert.assertEquals(files.size(), 38); validateJavaSourceFiles(files); - TestUtils.assertFileContains(Paths.get(output + "/src/main/java/xyz/abcdef/api/DefaultApi.java"), - "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"since\", queryObject.getSince()));", - "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"sinceBuild\", queryObject.getSinceBuild()));", - "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"maxBuilds\", queryObject.getMaxBuilds()));", - "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"maxWaitSecs\", queryObject.getMaxWaitSecs()));" - ); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/xyz/abcdef/api/DefaultApi.java"), + "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"since\"," + + " queryObject.getSince()));", + "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"sinceBuild\"," + + " queryObject.getSinceBuild()));", + "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"maxBuilds\"," + + " queryObject.getMaxBuilds()));", + "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"maxWaitSecs\"," + + " queryObject.getMaxWaitSecs()));"); } @Test @@ -1515,8 +1663,9 @@ public class JavaClientCodegenTest { "1.2.1"); TestUtils.assertFileContains(Paths.get(output + "/pom.xml"), "1.8"); - TestUtils.assertFileContains(Paths.get(output + "/src/main/java/org/openapitools/client/api/PetApi.java"), - "import javax."); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/org/openapitools/client/api/PetApi.java"), + "import javax."); output.deleteOnExit(); } @@ -1543,20 +1692,26 @@ public class JavaClientCodegenTest { validateJavaSourceFiles(files); - TestUtils.assertFileContains(Paths.get(output + "/pom.xml"), - "1.4.1"); + TestUtils.assertFileContains( + Paths.get(output + "/pom.xml"), + "1.4.1"); TestUtils.assertFileContains(Paths.get(output + "/pom.xml"), "1.2.1"); TestUtils.assertFileContains(Paths.get(output + "/pom.xml"), "1.8"); - TestUtils.assertFileContains(Paths.get(output + "/src/main/java/org/openapitools/client/api/PetApi.java"), - "import javax."); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/org/openapitools/client/api/PetApi.java"), + "import javax."); output.deleteOnExit(); } - @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Version incorrectVersion of MicroProfile Rest Client is not supported or incorrect. Supported versions are 1.4.1, 2.0, 3.0") - public void testMicroprofileRestClientIncorrectVersion() throws Exception { + @Test( + expectedExceptions = IllegalArgumentException.class, + expectedExceptionsMessageRegExp = + "Version incorrectVersion of MicroProfile Rest Client is not supported or incorrect." + + " Supported versions are 1.4.1, 2.0, 3.0") + public void testMicroprofileRestClientIncorrectVersion() throws Exception { Map properties = new HashMap<>(); properties.put(JavaClientCodegen.MICROPROFILE_REST_CLIENT_VERSION, "incorrectVersion"); @@ -1604,8 +1759,9 @@ public class JavaClientCodegenTest { "3.0.4"); TestUtils.assertFileContains(Paths.get(output + "/pom.xml"), "11"); - TestUtils.assertFileContains(Paths.get(output + "/src/main/java/org/openapitools/client/api/PetApi.java"), - "import jakarta."); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/org/openapitools/client/api/PetApi.java"), + "import jakarta."); output.deleteOnExit(); } @@ -1630,15 +1786,17 @@ public class JavaClientCodegenTest { Map files = generator.opts(clientOptInput).generate().stream() .collect(Collectors.toMap(File::getName, Function.identity())); - JavaFileAssert.assertThat(files.get("Foo.java")) - .assertConstructor("String", "Integer") - .hasParameter("b") - .assertParameterAnnotations() - .containsWithNameAndAttributes("JsonbProperty", ImmutableMap.of("value", "\"b\"", "nillable", "true")) - .toParameter().toConstructor() - .hasParameter("c") - .assertParameterAnnotations() - .containsWithNameAndAttributes("JsonbProperty", ImmutableMap.of("value", "\"c\"")); + JavaFileAssert.assertThat(files.get("Foo.java")) + .assertConstructor("String", "Integer") + .hasParameter("b") + .assertParameterAnnotations() + .containsWithNameAndAttributes( + "JsonbProperty", ImmutableMap.of("value", "\"b\"", "nillable", "true")) + .toParameter() + .toConstructor() + .hasParameter("c") + .assertParameterAnnotations() + .containsWithNameAndAttributes("JsonbProperty", ImmutableMap.of("value", "\"c\"")); } @Test @@ -1649,12 +1807,14 @@ public class JavaClientCodegenTest { File output = Files.createTempDirectory("test").toFile(); output.deleteOnExit(); - final CodegenConfigurator configurator = new CodegenConfigurator() - .setAdditionalProperties(properties) - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.WEBCLIENT) - .setInputSpec("src/test/resources/bugs/java-codegen-empty-array-as-default-value/issue_wrong-default.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + final CodegenConfigurator configurator = + new CodegenConfigurator() + .setAdditionalProperties(properties) + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.WEBCLIENT) + .setInputSpec( + "src/test/resources/bugs/java-codegen-empty-array-as-default-value/issue_wrong-default.yaml") + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); final ClientOptInput clientOptInput = configurator.toClientOptInput(); DefaultGenerator generator = new DefaultGenerator(); @@ -1692,13 +1852,13 @@ public class JavaClientCodegenTest { Map files = generator.opts(clientOptInput).generate().stream() .collect(Collectors.toMap(File::getName, Function.identity())); - JavaFileAssert.assertThat(files.get("TestObject.java")) - .printFileContent() - .assertConstructor("String", "String") - .bodyContainsLines( - "this.nullableProperty = nullableProperty == null ? JsonNullable.undefined() : JsonNullable.of(nullableProperty);", - "this.notNullableProperty = notNullableProperty;" - ); + JavaFileAssert.assertThat(files.get("TestObject.java")) + .printFileContent() + .assertConstructor("String", "String") + .bodyContainsLines( + "this.nullableProperty = nullableProperty == null ? JsonNullable.undefined() :" + + " JsonNullable.of(nullableProperty);", + "this.notNullableProperty = notNullableProperty;"); } @Test @@ -1726,11 +1886,12 @@ public class JavaClientCodegenTest { validateJavaSourceFiles(files); Path defaultApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/ResourceApi.java"); - TestUtils.assertFileContains(defaultApi, - "org.springframework.core.io.Resource resourceInResponse()", - "ResponseEntity resourceInResponseWithHttpInfo()", - "ParameterizedTypeReference localReturnType = new ParameterizedTypeReference()" - ); + TestUtils.assertFileContains( + defaultApi, + "org.springframework.core.io.Resource resourceInResponse()", + "ResponseEntity resourceInResponseWithHttpInfo()", + "ParameterizedTypeReference localReturnType = new" + + " ParameterizedTypeReference()"); } public void testExtraAnnotations(String library) throws IOException { @@ -1758,8 +1919,8 @@ public class JavaClientCodegenTest { generator.setGeneratorPropertyDefault(CodegenConstants.SUPPORTING_FILES, "false"); generator.opts(clientOptInput).generate(); - TestUtils.assertExtraAnnotationFiles(outputPath + "/src/main/java/org/openapitools/client/model"); - + TestUtils.assertExtraAnnotationFiles( + outputPath + "/src/main/java/org/openapitools/client/model"); } /** @@ -1810,10 +1971,9 @@ public class JavaClientCodegenTest { DefaultGenerator generator = new DefaultGenerator(); generator.opts(clientOptInput).generate(); - TestUtils.assertFileContains(Paths.get(output + "/src/main/java/org/openapitools/client/api/DefaultApi.java"), - "import java.util.Stack;" - ); - + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/org/openapitools/client/api/DefaultApi.java"), + "import java.util.Stack;"); } @Test @@ -1835,9 +1995,10 @@ public class JavaClientCodegenTest { DefaultGenerator generator = new DefaultGenerator(); generator.opts(clientOptInput).generate(); - TestUtils.assertFileContains(Paths.get(output + "/src/main/java/xyz/abcdef/api/DefaultApi.java"), - "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"multi\", \"values\", queryObject.getValues()));" - ); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/xyz/abcdef/api/DefaultApi.java"), + "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"multi\", \"values\"," + + " queryObject.getValues()));"); } @Test @@ -1867,12 +2028,15 @@ public class JavaClientCodegenTest { Assert.assertEquals(files.size(), 24); validateJavaSourceFiles(files); - TestUtils.assertFileContains(Paths.get(output + "/src/main/java/xyz/abcdef/model/Child.java"), - "public class Child extends Person {"); - TestUtils.assertFileContains(Paths.get(output + "/src/main/java/xyz/abcdef/model/Adult.java"), - "public class Adult extends Person {"); - TestUtils.assertFileContains(Paths.get(output + "/src/main/java/xyz/abcdef/model/AnotherChild.java"), - "public class AnotherChild {"); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/xyz/abcdef/model/Child.java"), + "public class Child extends Person {"); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/xyz/abcdef/model/Adult.java"), + "public class Adult extends Person {"); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/xyz/abcdef/model/AnotherChild.java"), + "public class AnotherChild {"); } @Test @@ -1880,8 +2044,10 @@ public class JavaClientCodegenTest { File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); output.deleteOnExit(); String outputPath = output.getAbsolutePath().replace('\\', '/'); - OpenAPI openAPI = new OpenAPIParser() - .readLocation("src/test/resources/bugs/issue_14731.yaml", null, new ParseOptions()).getOpenAPI(); + OpenAPI openAPI = + new OpenAPIParser() + .readLocation("src/test/resources/bugs/issue_14731.yaml", null, new ParseOptions()) + .getOpenAPI(); JavaClientCodegen codegen = new JavaClientCodegen(); codegen.setOutputDir(output.getAbsolutePath()); @@ -1894,8 +2060,7 @@ public class JavaClientCodegenTest { DefaultGenerator generator = new DefaultGenerator(); generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true"); - generator.setGeneratorPropertyDefault(CodegenConstants.LEGACY_DISCRIMINATOR_BEHAVIOR, "false"); - + generator.setGeneratorPropertyDefault(CodegenConstants.LEGACY_DISCRIMINATOR_BEHAVIOR, "false"); codegen.setUseOneOfInterfaces(true); codegen.setLegacyDiscriminatorBehavior(false); @@ -1909,8 +2074,14 @@ public class JavaClientCodegenTest { generator.opts(input).generate(); - assertFileNotContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/ChildWithMappingADTO.java"), "@JsonTypeName"); - assertFileNotContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/ChildWithMappingBDTO.java"), "@JsonTypeName"); + assertFileNotContains( + Paths.get( + outputPath + "/src/main/java/org/openapitools/client/model/ChildWithMappingADTO.java"), + "@JsonTypeName"); + assertFileNotContains( + Paths.get( + outputPath + "/src/main/java/org/openapitools/client/model/ChildWithMappingBDTO.java"), + "@JsonTypeName"); } @Test @@ -1918,8 +2089,10 @@ public class JavaClientCodegenTest { File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); output.deleteOnExit(); String outputPath = output.getAbsolutePath().replace('\\', '/'); - OpenAPI openAPI = new OpenAPIParser() - .readLocation("src/test/resources/bugs/issue_14731.yaml", null, new ParseOptions()).getOpenAPI(); + OpenAPI openAPI = + new OpenAPIParser() + .readLocation("src/test/resources/bugs/issue_14731.yaml", null, new ParseOptions()) + .getOpenAPI(); JavaClientCodegen codegen = new JavaClientCodegen(); codegen.setOutputDir(output.getAbsolutePath()); @@ -1932,8 +2105,7 @@ public class JavaClientCodegenTest { DefaultGenerator generator = new DefaultGenerator(); generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true"); - generator.setGeneratorPropertyDefault(CodegenConstants.LEGACY_DISCRIMINATOR_BEHAVIOR, "false"); - + generator.setGeneratorPropertyDefault(CodegenConstants.LEGACY_DISCRIMINATOR_BEHAVIOR, "false"); codegen.setUseOneOfInterfaces(true); codegen.setLegacyDiscriminatorBehavior(false); @@ -1949,8 +2121,16 @@ public class JavaClientCodegenTest { generator.opts(input).generate(); - assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/ChildWithoutMappingADTO.java"), "@JsonTypeName"); - assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/ChildWithoutMappingBDTO.java"), "@JsonTypeName"); + assertFileContains( + Paths.get( + outputPath + + "/src/main/java/org/openapitools/client/model/ChildWithoutMappingADTO.java"), + "@JsonTypeName"); + assertFileContains( + Paths.get( + outputPath + + "/src/main/java/org/openapitools/client/model/ChildWithoutMappingBDTO.java"), + "@JsonTypeName"); } @Test @@ -1958,8 +2138,10 @@ public class JavaClientCodegenTest { File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); output.deleteOnExit(); String outputPath = output.getAbsolutePath().replace('\\', '/'); - OpenAPI openAPI = new OpenAPIParser() - .readLocation("src/test/resources/bugs/issue_14917.yaml", null, new ParseOptions()).getOpenAPI(); + OpenAPI openAPI = + new OpenAPIParser() + .readLocation("src/test/resources/bugs/issue_14917.yaml", null, new ParseOptions()) + .getOpenAPI(); JavaClientCodegen codegen = new JavaClientCodegen(); codegen.setOutputDir(output.getAbsolutePath()); @@ -1973,23 +2155,53 @@ public class JavaClientCodegenTest { generator.opts(input).generate(); - assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), "mappings.put(\"Cat\", Cat.class)"); - assertFileNotContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), "@JsonSubTypes"); - assertFileNotContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), "mappings.put(\"cat\", Cat.class);"); - assertFileNotContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), "mappings.put(\"dog\", Dog.class);"); - assertFileNotContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), "mappings.put(\"lizard\", Lizard.class);"); + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), + "mappings.put(\"Cat\", Cat.class)"); + assertFileNotContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), + "@JsonSubTypes"); + assertFileNotContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), + "mappings.put(\"cat\", Cat.class);"); + assertFileNotContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), + "mappings.put(\"dog\", Dog.class);"); + assertFileNotContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), + "mappings.put(\"lizard\", Lizard.class);"); - assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), "@JsonSubTypes.Type(value = Cat.class, name = \"cat\")"); - assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), "@JsonSubTypes.Type(value = Dog.class, name = \"dog\")"); - assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), "@JsonSubTypes.Type(value = Lizard.class, name = \"lizard\")"); - assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), "mappings.put(\"cat\", Cat.class)"); - assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), "mappings.put(\"dog\", Dog.class)"); - assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), "mappings.put(\"lizard\", Lizard.class)"); - assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), "mappings.put(\"Pet\", Pet.class)"); + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "@JsonSubTypes.Type(value = Cat.class, name = \"cat\")"); + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "@JsonSubTypes.Type(value = Dog.class, name = \"dog\")"); + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "@JsonSubTypes.Type(value = Lizard.class, name = \"lizard\")"); + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "mappings.put(\"cat\", Cat.class)"); + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "mappings.put(\"dog\", Dog.class)"); + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "mappings.put(\"lizard\", Lizard.class)"); + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "mappings.put(\"Pet\", Pet.class)"); - assertFileNotContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), "@JsonSubTypes.Type(value = Cat.class, name = \"Cat\")"); - assertFileNotContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), "@JsonSubTypes.Type(value = Dog.class, name = \"Dog\")"); - assertFileNotContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), "@JsonSubTypes.Type(value = Lizard.class, name = \"Lizard\")"); + assertFileNotContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "@JsonSubTypes.Type(value = Cat.class, name = \"Cat\")"); + assertFileNotContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "@JsonSubTypes.Type(value = Dog.class, name = \"Dog\")"); + assertFileNotContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "@JsonSubTypes.Type(value = Lizard.class, name = \"Lizard\")"); } @Test @@ -2000,14 +2212,21 @@ public class JavaClientCodegenTest { JavaClientCodegen.RESTTEMPLATE ); - JavaFileAssert.assertThat(files.get("DefaultApi.java")) - .printFileContent() - .assertMethod("searchWithHttpInfo") - .bodyContainsLines("localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, \"regular-param\", regularParam));") - .bodyContainsLines("localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, \"someString\", objectParam.getSomeString()));") - .bodyContainsLines("localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, \"someBoolean\", objectParam.getSomeBoolean()));") - .bodyContainsLines("localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, \"someInteger\", objectParam.getSomeInteger()));") - ; + JavaFileAssert.assertThat(files.get("DefaultApi.java")) + .printFileContent() + .assertMethod("searchWithHttpInfo") + .bodyContainsLines( + "localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, \"regular-param\"," + + " regularParam));") + .bodyContainsLines( + "localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, \"someString\"," + + " objectParam.getSomeString()));") + .bodyContainsLines( + "localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, \"someBoolean\"," + + " objectParam.getSomeBoolean()));") + .bodyContainsLines( + "localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, \"someInteger\"," + + " objectParam.getSomeInteger()));"); } private static Map generateFromContract(final String pathToSpecification, final String library) { @@ -2041,8 +2260,10 @@ public class JavaClientCodegenTest { File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); output.deleteOnExit(); String outputPath = output.getAbsolutePath().replace('\\', '/'); - OpenAPI openAPI = new OpenAPIParser() - .readLocation("src/test/resources/bugs/issue_14917.yaml", null, new ParseOptions()).getOpenAPI(); + OpenAPI openAPI = + new OpenAPIParser() + .readLocation("src/test/resources/bugs/issue_14917.yaml", null, new ParseOptions()) + .getOpenAPI(); JavaClientCodegen codegen = new JavaClientCodegen(); codegen.setOutputDir(output.getAbsolutePath()); @@ -2056,24 +2277,51 @@ public class JavaClientCodegenTest { generator.opts(input).generate(); - assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), "@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = \"petType\", visible = true)"); - assertFileNotContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), "mappings.put"); - assertFileNotContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), "@JsonSubTypes.Type(value = Cat.class, name = \"cat\")"); - assertFileNotContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), "@JsonSubTypes.Type(value = Dog.class, name = \"dog\")"); - assertFileNotContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), "@JsonSubTypes.Type(value = Lizard.class, name = \"lizard\")"); + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), + "@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property =" + + " \"petType\", visible = true)"); + assertFileNotContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), + "mappings.put"); + assertFileNotContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), + "@JsonSubTypes.Type(value = Cat.class, name = \"cat\")"); + assertFileNotContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), + "@JsonSubTypes.Type(value = Dog.class, name = \"dog\")"); + assertFileNotContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), + "@JsonSubTypes.Type(value = Lizard.class, name = \"lizard\")"); - assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), "@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = \"petType\", visible = true)"); - assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), "@JsonSubTypes.Type(value = Cat.class, name = \"cat\")"); - assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), "@JsonSubTypes.Type(value = Dog.class, name = \"dog\")"); - assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), "@JsonSubTypes.Type(value = Lizard.class, name = \"lizard\")"); - assertFileNotContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), "@JsonSubTypes.Type(value = Cat.class, name = \"Cat\")"); - assertFileNotContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), "@JsonSubTypes.Type(value = Dog.class, name = \"Dog\")"); - assertFileNotContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), "@JsonSubTypes.Type(value = Lizard.class, name = \"Lizard\")"); + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property =" + + " \"petType\", visible = true)"); + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "@JsonSubTypes.Type(value = Cat.class, name = \"cat\")"); + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "@JsonSubTypes.Type(value = Dog.class, name = \"dog\")"); + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "@JsonSubTypes.Type(value = Lizard.class, name = \"lizard\")"); + assertFileNotContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "@JsonSubTypes.Type(value = Cat.class, name = \"Cat\")"); + assertFileNotContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "@JsonSubTypes.Type(value = Dog.class, name = \"Dog\")"); + assertFileNotContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "@JsonSubTypes.Type(value = Lizard.class, name = \"Lizard\")"); } @Test public void testIsOverriddenProperty() { - final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/allOf_composition_discriminator.yaml"); + final OpenAPI openAPI = + TestUtils.parseFlattenSpec("src/test/resources/3_0/allOf_composition_discriminator.yaml"); JavaClientCodegen codegen = new JavaClientCodegen(); Schema test1 = openAPI.getComponents().getSchemas().get("Cat"); @@ -2094,8 +2342,13 @@ public class JavaClientCodegenTest { File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); output.deleteOnExit(); String outputPath = output.getAbsolutePath().replace('\\', '/'); - OpenAPI openAPI = new OpenAPIParser() - .readLocation("src/test/resources/3_0/allOf_composition_discriminator.yaml", null, new ParseOptions()).getOpenAPI(); + OpenAPI openAPI = + new OpenAPIParser() + .readLocation( + "src/test/resources/3_0/allOf_composition_discriminator.yaml", + null, + new ParseOptions()) + .getOpenAPI(); JavaClientCodegen codegen = new JavaClientCodegen(); codegen.setOutputDir(output.getAbsolutePath()); @@ -2109,12 +2362,12 @@ public class JavaClientCodegenTest { generator.opts(input).generate(); - assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), " @Override\n" + - " public Cat petType(String petType) {"); - assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), " }\n" + - "\n" + - " public Pet petType(String petType) {\n"); - + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), + " @Override\n" + " public Cat petType(String petType) {"); + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + " }\n" + "\n" + " public Pet petType(String petType) {\n"); } @Test @@ -2122,8 +2375,13 @@ public class JavaClientCodegenTest { File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); output.deleteOnExit(); String outputPath = output.getAbsolutePath().replace('\\', '/'); - OpenAPI openAPI = new OpenAPIParser() - .readLocation("src/test/resources/3_0/allOf_composition_discriminator.yaml", null, new ParseOptions()).getOpenAPI(); + OpenAPI openAPI = + new OpenAPIParser() + .readLocation( + "src/test/resources/3_0/allOf_composition_discriminator.yaml", + null, + new ParseOptions()) + .getOpenAPI(); JavaClientCodegen codegen = new JavaClientCodegen(); codegen.setOutputDir(output.getAbsolutePath()); @@ -2137,12 +2395,12 @@ public class JavaClientCodegenTest { generator.opts(input).generate(); - assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), " @Override\n" + - " public Cat petType(String petType) {"); - assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), " }\n" + - "\n" + - " public Pet petType(String petType) {\n"); - + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), + " @Override\n" + " public Cat petType(String petType) {"); + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + " }\n" + "\n" + " public Pet petType(String petType) {\n"); } @Test @@ -2161,22 +2419,22 @@ public class JavaClientCodegenTest { validateJavaSourceFiles(files); - // deprecated builder method - TestUtils.assertFileContains(Paths.get(output + "/src/main/java/org/openapitools/client/model/BigDog.java"), - "@Deprecated\n" + - " public BigDog declawed(Boolean declawed) {"); - - // deprecated getter - TestUtils.assertFileContains(Paths.get(output + "/src/main/java/org/openapitools/client/model/BigDog.java"), - "@Deprecated\n" + - " @javax.annotation.Nullable\n" + - "\n" + - " public Boolean getDeclawed() {"); - // deprecated setter - TestUtils.assertFileContains(Paths.get(output + "/src/main/java/org/openapitools/client/model/BigDog.java"), - "@Deprecated\n" + - " public void setDeclawed(Boolean declawed) {"); + // deprecated builder method + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/org/openapitools/client/model/BigDog.java"), + "@Deprecated\n" + " public BigDog declawed(Boolean declawed) {"); + // deprecated getter + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/org/openapitools/client/model/BigDog.java"), + "@Deprecated\n" + + " @javax.annotation.Nullable\n" + + "\n" + + " public Boolean getDeclawed() {"); + // deprecated setter + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/org/openapitools/client/model/BigDog.java"), + "@Deprecated\n" + " public void setDeclawed(Boolean declawed) {"); output.deleteOnExit(); } @@ -2191,10 +2449,12 @@ public class JavaClientCodegenTest { File output = Files.createTempDirectory("test").toFile(); output.deleteOnExit(); - final CodegenConfigurator configurator = new CodegenConfigurator() + final CodegenConfigurator configurator = + new CodegenConfigurator() .setGeneratorName("java") .setLibrary(library) - .addAdditionalProperty(AbstractJavaCodegen.ADDITIONAL_MODEL_TYPE_ANNOTATIONS, "@annotation1;@annotation2") + .addAdditionalProperty( + AbstractJavaCodegen.ADDITIONAL_MODEL_TYPE_ANNOTATIONS, "@annotation1;@annotation2") .setInputSpec("src/test/resources/3_0/deprecated-properties.yaml") .setOutputDir(output.getAbsolutePath().replace("\\", "/")); @@ -2322,14 +2582,16 @@ public class JavaClientCodegenTest { validateJavaSourceFiles(files); Path userApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/UsersApi.java"); - TestUtils.assertFileContains(userApi, - // set of string - "ParameterizedTypeReference> localVarReturnType = new ParameterizedTypeReference>() {};", - "getUserIdSetRequestCreation().toEntity(localVarReturnType)", - // list of string - "ParameterizedTypeReference> localVarReturnType = new ParameterizedTypeReference>() {};", - "getUserIdListRequestCreation().toEntity(localVarReturnType)" - ); + TestUtils.assertFileContains( + userApi, + // set of string + "ParameterizedTypeReference> localVarReturnType = new" + + " ParameterizedTypeReference>() {};", + "getUserIdSetRequestCreation().toEntity(localVarReturnType)", + // list of string + "ParameterizedTypeReference> localVarReturnType = new" + + " ParameterizedTypeReference>() {};", + "getUserIdListRequestCreation().toEntity(localVarReturnType)"); } @Test @@ -2384,4 +2646,31 @@ public class JavaClientCodegenTest { .bodyContainsLines("if (b.value.equals(value)) {"); } + @Test + public void testHandleConstantParams() throws IOException { + File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); + output.deleteOnExit(); + final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/java/autoset_constant.yaml"); + final DefaultGenerator defaultGenerator = new DefaultGenerator(); + final ClientOptInput clientOptInput = new ClientOptInput(); + clientOptInput.openAPI(openAPI); + JavaClientCodegen javaClientCodegen = new JavaClientCodegen(); + javaClientCodegen.setOutputDir(output.getAbsolutePath()); + javaClientCodegen.additionalProperties().put(JavaClientCodegen.AUTOSET_CONSTANTS, "true"); + javaClientCodegen.setAutosetConstants(true); + clientOptInput.config(javaClientCodegen); + defaultGenerator.opts(clientOptInput); + + Map files = defaultGenerator.generate().stream() + .collect(Collectors.toMap(File::getName, Function.identity())); + + File apiFile = files.get("HelloExampleApi.java"); + + assertNotNull(apiFile); + JavaFileAssert.assertThat(apiFile) + .assertMethod("helloCall", "String", "ApiCallback") + .bodyContainsLines( + "localVarHeaderParams.put(\"X-CUSTOM_CONSTANT_HEADER\", \"CONSTANT_VALUE\")"); + } + } diff --git a/modules/openapi-generator/src/test/resources/3_0/java/autoset_constant.yaml b/modules/openapi-generator/src/test/resources/3_0/java/autoset_constant.yaml new file mode 100644 index 00000000000..d8248a85695 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/java/autoset_constant.yaml @@ -0,0 +1,42 @@ +openapi: 3.0.3 +info: + title: Example Hello API + description: '' + version: v1 +servers: + - url: http://localhost + description: Global Endpoint +paths: + /v1/hello/{name}: + get: + tags: + - hello_example + operationId: Hello + description: Say Hello + parameters: + - name: X-CUSTOM_CONSTANT_HEADER + in: header + required: true + schema: + type: string + enum: + - CONSTANT_VALUE + - name: name + in: path + required: true + schema: + type: string + responses: + default: + description: Successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/HelloResponse' +components: + schemas: + HelloResponse: + type: object + properties: + message: + type: string \ No newline at end of file