diff --git a/docs/generators/csharp-dotnet2.md b/docs/generators/csharp-dotnet2.md
index 4ce8ee5b14b..fa97c717000 100644
--- a/docs/generators/csharp-dotnet2.md
+++ b/docs/generators/csharp-dotnet2.md
@@ -68,6 +68,8 @@ These options may be applied as additional-properties (cli) or configOptions (pl
Client
+
Configuration
+
Version
abstract
as
base
diff --git a/docs/generators/csharp-netcore.md b/docs/generators/csharp-netcore.md
index 8999e7a3a61..7a30e18f899 100644
--- a/docs/generators/csharp-netcore.md
+++ b/docs/generators/csharp-netcore.md
@@ -94,6 +94,8 @@ These options may be applied as additional-properties (cli) or configOptions (pl
Client
+
Configuration
+
Version
abstract
as
base
diff --git a/docs/generators/csharp.md b/docs/generators/csharp.md
index 0b3185606ec..b572a6c3710 100644
--- a/docs/generators/csharp.md
+++ b/docs/generators/csharp.md
@@ -88,6 +88,8 @@ These options may be applied as additional-properties (cli) or configOptions (pl
Client
+
Configuration
+
Version
abstract
as
base
diff --git a/docs/generators/java-micronaut-client.md b/docs/generators/java-micronaut-client.md
new file mode 100644
index 00000000000..ab0333b9bf1
--- /dev/null
+++ b/docs/generators/java-micronaut-client.md
@@ -0,0 +1,297 @@
+---
+title: Config Options for java-micronaut-client
+sidebar_label: java-micronaut-client
+---
+
+These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details.
+
+| Option | Description | Values | Default |
+| ------ | ----------- | ------ | ------- |
+|additionalEnumTypeAnnotations|Additional annotations for enum type(class level annotations)| |null|
+|additionalModelTypeAnnotations|Additional annotations for model type(class level annotations)| |null|
+|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false|
+|apiPackage|package for generated api classes| |org.openapitools.api|
+|artifactDescription|artifact description in generated pom.xml| |OpenAPI Java|
+|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|
+|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|
+|configPackage|Configuration package for generated code| |org.openapitools.configuration|
+|configureAuth|Configure all the authorization methods as specified in the file| |false|
+|developerEmail|developer email in generated pom.xml| |team@openapitools.org|
+|developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors|
+|developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org|
+|developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org|
+|disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false|
+|disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
**false**
The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
**true**
Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
|true|
+|discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true|
+|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
+|fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false|
+|groupId|groupId in generated pom.xml| |org.openapitools|
+|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
+|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
+|invokerPackage|root package for generated code| |org.openapitools|
+|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|
**true**
Use Java 8 classes such as Base64
**false**
Various third party libraries as needed
|true|
+|legacyDiscriminatorBehavior|Set to false for generators with better support for discriminators. (Python, Java, Go, PowerShell, C#have this enabled by default).|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true|
+|licenseName|The name of the license| |Unlicense|
+|licenseUrl|The URL of the license| |http://unlicense.org|
+|modelPackage|package for generated models| |org.openapitools.model|
+|openApiNullable|Enable OpenAPI Jackson Nullable library| |true|
+|parentArtifactId|parent artifactId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
+|parentGroupId|parent groupId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
+|parentVersion|parent version in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
+|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
+|scmConnection|SCM connection in generated pom.xml| |scm:git:git@github.com:openapitools/openapi-generator.git|
+|scmDeveloperConnection|SCM developer connection in generated pom.xml| |scm:git:git@github.com:openapitools/openapi-generator.git|
+|scmUrl|SCM URL in generated pom.xml| |https://github.com/openapitools/openapi-generator|
+|serializableModel|boolean - toggle "implements Serializable" for generated models| |false|
+|snapshotVersion|Uses a SNAPSHOT version.|
**true**
Use a SnapShot Version
**false**
Use a Release Version
|null|
+|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true|
+|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
+|sourceFolder|source folder for generated code| |src/main/java|
+|test|Specify which test tool to generate files for|
**junit**
Use JUnit as test tool
**spock**
Use Spock as test tool
|junit|
+|title|Client service name| |OpenAPI Micronaut Client|
+|useBeanValidation|Use BeanValidation API annotations| |true|
+|withXml|whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)| |false|
+
+## IMPORT MAPPING
+
+| Type/Alias | Imports |
+| ---------- | ------- |
+|Array|java.util.List|
+|ArrayList|java.util.ArrayList|
+|BigDecimal|java.math.BigDecimal|
+|Date|java.util.Date|
+|DateTime|org.joda.time.*|
+|File|java.io.File|
+|HashMap|java.util.HashMap|
+|LinkedHashSet|java.util.LinkedHashSet|
+|List|java.util.*|
+|LocalDate|org.joda.time.*|
+|LocalDateTime|org.joda.time.*|
+|LocalTime|org.joda.time.*|
+|Map|java.util.Map|
+|Set|java.util.*|
+|Timestamp|java.sql.Timestamp|
+|URI|java.net.URI|
+|UUID|java.util.UUID|
+
+
+## INSTANTIATION TYPES
+
+| Type/Alias | Instantiated By |
+| ---------- | --------------- |
+|array|ArrayList|
+|map|HashMap|
+|set|LinkedHashSet|
+
+
+## LANGUAGE PRIMITIVES
+
+
+
Boolean
+
Double
+
Float
+
Integer
+
Long
+
Object
+
String
+
boolean
+
byte[]
+
+
+## RESERVED WORDS
+
+
+
abstract
+
apiclient
+
apiexception
+
apiresponse
+
application
+
assert
+
authorization
+
body
+
boolean
+
break
+
byte
+
case
+
catch
+
char
+
class
+
client
+
configuration
+
const
+
continue
+
cookie
+
default
+
do
+
double
+
else
+
enum
+
extends
+
final
+
finally
+
float
+
for
+
format
+
goto
+
header
+
if
+
implements
+
import
+
instanceof
+
int
+
interface
+
localreturntype
+
localvaraccept
+
localvaraccepts
+
localvarauthnames
+
localvarcollectionqueryparams
+
localvarcontenttype
+
localvarcontenttypes
+
localvarcookieparams
+
localvarformparams
+
localvarheaderparams
+
localvarpath
+
localvarpostbody
+
localvarqueryparams
+
long
+
native
+
new
+
null
+
object
+
package
+
pathvariable
+
private
+
protected
+
public
+
queryparam
+
queryvalue
+
return
+
short
+
static
+
strictfp
+
stringutil
+
super
+
switch
+
synchronized
+
this
+
throw
+
throws
+
transient
+
try
+
void
+
volatile
+
while
+
+
+## FEATURE SET
+
+
+### Client Modification Feature
+| Name | Supported | Defined By |
+| ---- | --------- | ---------- |
+|BasePath|✓|ToolingExtension
+|Authorizations|✗|ToolingExtension
+|UserAgent|✗|ToolingExtension
+|MockServer|✗|ToolingExtension
+
+### Data Type Feature
+| Name | Supported | Defined By |
+| ---- | --------- | ---------- |
+|Custom|✗|OAS2,OAS3
+|Int32|✓|OAS2,OAS3
+|Int64|✓|OAS2,OAS3
+|Float|✓|OAS2,OAS3
+|Double|✓|OAS2,OAS3
+|Decimal|✓|ToolingExtension
+|String|✓|OAS2,OAS3
+|Byte|✓|OAS2,OAS3
+|Binary|✓|OAS2,OAS3
+|Boolean|✓|OAS2,OAS3
+|Date|✓|OAS2,OAS3
+|DateTime|✓|OAS2,OAS3
+|Password|✓|OAS2,OAS3
+|File|✓|OAS2
+|Array|✓|OAS2,OAS3
+|Maps|✓|ToolingExtension
+|CollectionFormat|✓|OAS2
+|CollectionFormatMulti|✓|OAS2
+|Enum|✓|OAS2,OAS3
+|ArrayOfEnum|✓|ToolingExtension
+|ArrayOfModel|✓|ToolingExtension
+|ArrayOfCollectionOfPrimitives|✓|ToolingExtension
+|ArrayOfCollectionOfModel|✓|ToolingExtension
+|ArrayOfCollectionOfEnum|✓|ToolingExtension
+|MapOfEnum|✓|ToolingExtension
+|MapOfModel|✓|ToolingExtension
+|MapOfCollectionOfPrimitives|✓|ToolingExtension
+|MapOfCollectionOfModel|✓|ToolingExtension
+|MapOfCollectionOfEnum|✓|ToolingExtension
+
+### Documentation Feature
+| Name | Supported | Defined By |
+| ---- | --------- | ---------- |
+|Readme|✓|ToolingExtension
+|Model|✓|ToolingExtension
+|Api|✓|ToolingExtension
+
+### Global Feature
+| Name | Supported | Defined By |
+| ---- | --------- | ---------- |
+|Host|✓|OAS2,OAS3
+|BasePath|✓|OAS2,OAS3
+|Info|✓|OAS2,OAS3
+|Schemes|✗|OAS2,OAS3
+|PartialSchemes|✓|OAS2,OAS3
+|Consumes|✓|OAS2
+|Produces|✓|OAS2
+|ExternalDocumentation|✓|OAS2,OAS3
+|Examples|✓|OAS2,OAS3
+|XMLStructureDefinitions|✗|OAS2,OAS3
+|MultiServer|✗|OAS3
+|ParameterizedServer|✗|OAS3
+|ParameterStyling|✗|OAS3
+|Callbacks|✗|OAS3
+|LinkObjects|✗|OAS3
+
+### Parameter Feature
+| Name | Supported | Defined By |
+| ---- | --------- | ---------- |
+|Path|✓|OAS2,OAS3
+|Query|✓|OAS2,OAS3
+|Header|✓|OAS2,OAS3
+|Body|✓|OAS2
+|FormUnencoded|✓|OAS2
+|FormMultipart|✓|OAS2
+|Cookie|✓|OAS3
+
+### Schema Support Feature
+| Name | Supported | Defined By |
+| ---- | --------- | ---------- |
+|Simple|✓|OAS2,OAS3
+|Composite|✓|OAS2,OAS3
+|Polymorphism|✗|OAS2,OAS3
+|Union|✗|OAS3
+
+### Security Feature
+| Name | Supported | Defined By |
+| ---- | --------- | ---------- |
+|BasicAuth|✓|OAS2,OAS3
+|ApiKey|✓|OAS2,OAS3
+|OpenIDConnect|✓|OAS3
+|BearerToken|✗|OAS3
+|OAuth2_Implicit|✓|OAS2,OAS3
+|OAuth2_Password|✓|OAS2,OAS3
+|OAuth2_ClientCredentials|✓|OAS2,OAS3
+|OAuth2_AuthorizationCode|✓|OAS2,OAS3
+
+### Wire Format Feature
+| Name | Supported | Defined By |
+| ---- | --------- | ---------- |
+|JSON|✓|OAS2,OAS3
+|XML|✓|OAS2,OAS3
+|PROTOBUF|✗|ToolingExtension
+|Custom|✗|OAS2,OAS3
diff --git a/docs/generators/kotlin-server-deprecated.md b/docs/generators/kotlin-server-deprecated.md
index 778b13ee7b3..2287e954abf 100644
--- a/docs/generators/kotlin-server-deprecated.md
+++ b/docs/generators/kotlin-server-deprecated.md
@@ -74,28 +74,64 @@ These options may be applied as additional-properties (cli) or configOptions (pl
## RESERVED WORDS
+
abstract
+
actual
+
annotation
as
break
class
+
companion
+
const
+
constructor
continue
+
crossinline
+
data
+
delegate
do
+
dynamic
else
+
enum
+
expect
external
false
+
field
+
final
+
finally
for
fun
if
+
import
in
+
infix
+
init
+
inline
+
inner
interface
internal
is
+
it
+
lateinit
+
noinline
null
object
open
+
operator
+
out
+
override
package
+
param
private
+
property
+
protected
+
public
+
receiver
+
reified
return
+
sealed
+
setparam
super
+
suspend
+
tailrec
this
throw
true
@@ -103,8 +139,11 @@ These options may be applied as additional-properties (cli) or configOptions (pl
typealias
typeof
val
+
value
var
+
vararg
when
+
where
while
diff --git a/docs/generators/kotlin-server.md b/docs/generators/kotlin-server.md
index f6e6c260343..81f75ca5785 100644
--- a/docs/generators/kotlin-server.md
+++ b/docs/generators/kotlin-server.md
@@ -76,28 +76,64 @@ These options may be applied as additional-properties (cli) or configOptions (pl
## RESERVED WORDS
+
abstract
+
actual
+
annotation
as
break
class
+
companion
+
const
+
constructor
continue
+
crossinline
+
data
+
delegate
do
+
dynamic
else
+
enum
+
expect
external
false
+
field
+
final
+
finally
for
fun
if
+
import
in
+
infix
+
init
+
inline
+
inner
interface
internal
is
+
it
+
lateinit
+
noinline
null
object
open
+
operator
+
out
+
override
package
+
param
private
+
property
+
protected
+
public
+
receiver
+
reified
return
+
sealed
+
setparam
super
+
suspend
+
tailrec
this
throw
true
@@ -105,8 +141,11 @@ These options may be applied as additional-properties (cli) or configOptions (pl
typealias
typeof
val
+
value
var
+
vararg
when
+
where
while
diff --git a/docs/generators/kotlin-spring.md b/docs/generators/kotlin-spring.md
index 58152432964..5cd67ff64aa 100644
--- a/docs/generators/kotlin-spring.md
+++ b/docs/generators/kotlin-spring.md
@@ -87,28 +87,64 @@ These options may be applied as additional-properties (cli) or configOptions (pl
ApiClient
ApiException
ApiResponse
+
abstract
+
actual
+
annotation
as
break
class
+
companion
+
const
+
constructor
continue
+
crossinline
+
data
+
delegate
do
+
dynamic
else
+
enum
+
expect
external
false
+
field
+
final
+
finally
for
fun
if
+
import
in
+
infix
+
init
+
inline
+
inner
interface
internal
is
+
it
+
lateinit
+
noinline
null
object
open
+
operator
+
out
+
override
package
+
param
private
+
property
+
protected
+
public
+
receiver
+
reified
return
+
sealed
+
setparam
super
+
suspend
+
tailrec
this
throw
true
@@ -116,8 +152,11 @@ These options may be applied as additional-properties (cli) or configOptions (pl
typealias
typeof
val
+
value
var
+
vararg
when
+
where
while
diff --git a/docs/generators/kotlin-vertx.md b/docs/generators/kotlin-vertx.md
index 246ffa62a64..90afde4de81 100644
--- a/docs/generators/kotlin-vertx.md
+++ b/docs/generators/kotlin-vertx.md
@@ -68,28 +68,64 @@ These options may be applied as additional-properties (cli) or configOptions (pl
## RESERVED WORDS
+
abstract
+
actual
+
annotation
as
break
class
+
companion
+
const
+
constructor
continue
+
crossinline
+
data
+
delegate
do
+
dynamic
else
+
enum
+
expect
external
false
+
field
+
final
+
finally
for
fun
if
+
import
in
+
infix
+
init
+
inline
+
inner
interface
internal
is
+
it
+
lateinit
+
noinline
null
object
open
+
operator
+
out
+
override
package
+
param
private
+
property
+
protected
+
public
+
receiver
+
reified
return
+
sealed
+
setparam
super
+
suspend
+
tailrec
this
throw
true
@@ -97,8 +133,11 @@ These options may be applied as additional-properties (cli) or configOptions (pl
typealias
typeof
val
+
value
var
+
vararg
when
+
where
while
diff --git a/docs/generators/kotlin.md b/docs/generators/kotlin.md
index 8f853b41cac..a8a1d0be869 100644
--- a/docs/generators/kotlin.md
+++ b/docs/generators/kotlin.md
@@ -27,8 +27,8 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|sourceFolder|source folder for generated code| |src/main/kotlin|
|supportAndroidApiLevel25AndBelow|[WARNING] This flag will generate code that has a known security vulnerability. It uses `kotlin.io.createTempFile` instead of `java.nio.file.Files.createTempFile` in oder to support Android API level 25 and bellow. For more info, please check the following links https://github.com/OpenAPITools/openapi-generator/security/advisories/GHSA-23x4-m842-fmwf, https://github.com/OpenAPITools/openapi-generator/pull/9284| |false|
|useCoroutines|Whether to use the Coroutines adapter with the retrofit2 library.| |false|
-|useRxJava|Whether to use the RxJava adapter with the retrofit2 library.| |false|
-|useRxJava2|Whether to use the RxJava2 adapter with the retrofit2 library.| |false|
+|useRxJava|Whether to use the RxJava adapter with the retrofit2 library. IMPORTANT: this option has been deprecated. Please use `useRxJava3` instead.| |false|
+|useRxJava2|Whether to use the RxJava2 adapter with the retrofit2 library. IMPORTANT: this option has been deprecated. Please use `useRxJava3` instead.| |false|
|useRxJava3|Whether to use the RxJava3 adapter with the retrofit2 library.| |false|
## IMPORT MAPPING
@@ -78,28 +78,64 @@ These options may be applied as additional-properties (cli) or configOptions (pl
## RESERVED WORDS
+
abstract
+
actual
+
annotation
as
break
class
+
companion
+
const
+
constructor
continue
+
crossinline
+
data
+
delegate
do
+
dynamic
else
+
enum
+
expect
external
false
+
field
+
final
+
finally
for
fun
if
+
import
in
+
infix
+
init
+
inline
+
inner
interface
internal
is
+
it
+
lateinit
+
noinline
null
object
open
+
operator
+
out
+
override
package
+
param
private
+
property
+
protected
+
public
+
receiver
+
reified
return
+
sealed
+
setparam
super
+
suspend
+
tailrec
this
throw
true
@@ -107,8 +143,11 @@ These options may be applied as additional-properties (cli) or configOptions (pl
typealias
typeof
val
+
value
var
+
vararg
when
+
where
while
diff --git a/docs/generators/php-dt.md b/docs/generators/php-dt.md
new file mode 100644
index 00000000000..a61f3cd351c
--- /dev/null
+++ b/docs/generators/php-dt.md
@@ -0,0 +1,243 @@
+---
+title: Config Options for php-dt
+sidebar_label: php-dt
+---
+
+These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details.
+
+| Option | Description | Values | Default |
+| ------ | ----------- | ------ | ------- |
+|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false|
+|apiPackage|package for generated api classes| |null|
+|artifactVersion|The version to use in the composer package version field. e.g. 1.2.3| |null|
+|disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
**false**
The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
**true**
Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
|true|
+|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
+|invokerPackage|The main namespace to use for all classes. e.g. Yay\Pets| |null|
+|legacyDiscriminatorBehavior|Set to false for generators with better support for discriminators. (Python, Java, Go, PowerShell, C#have this enabled by default).|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true|
+|modelPackage|package for generated models| |null|
+|modern|use modern language features (generated code will require PHP 8.0)| |false|
+|packageName|The main package name for classes. e.g. GeneratedPetstore| |null|
+|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
+|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true|
+|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
+|srcBasePath|The directory to serve as source root.| |null|
+|variableNamingConvention|naming convention of variable name, e.g. camelCase.| |snake_case|
+
+## IMPORT MAPPING
+
+| Type/Alias | Imports |
+| ---------- | ------- |
+
+
+## INSTANTIATION TYPES
+
+| Type/Alias | Instantiated By |
+| ---------- | --------------- |
+|array|array|
+|map|array|
+
+
+## LANGUAGE PRIMITIVES
+
+
+
DateTime
+
array
+
bool
+
boolean
+
byte
+
double
+
float
+
int
+
integer
+
mixed
+
number
+
object
+
string
+
void
+
+
+## RESERVED WORDS
+
+
+
__halt_compiler
+
_header_accept
+
_tempbody
+
abstract
+
and
+
array
+
as
+
break
+
callable
+
case
+
catch
+
class
+
clone
+
const
+
continue
+
declare
+
default
+
die
+
do
+
echo
+
else
+
elseif
+
empty
+
enddeclare
+
endfor
+
endforeach
+
endif
+
endswitch
+
endwhile
+
eval
+
exit
+
extends
+
final
+
for
+
foreach
+
formparams
+
function
+
global
+
goto
+
headerparams
+
httpbody
+
if
+
implements
+
include
+
include_once
+
instanceof
+
insteadof
+
interface
+
isset
+
list
+
namespace
+
new
+
or
+
print
+
private
+
protected
+
public
+
queryparams
+
require
+
require_once
+
resourcepath
+
return
+
static
+
switch
+
throw
+
trait
+
try
+
unset
+
use
+
var
+
while
+
xor
+
+
+## FEATURE SET
+
+
+### Client Modification Feature
+| Name | Supported | Defined By |
+| ---- | --------- | ---------- |
+|BasePath|✗|ToolingExtension
+|Authorizations|✗|ToolingExtension
+|UserAgent|✗|ToolingExtension
+|MockServer|✗|ToolingExtension
+
+### Data Type Feature
+| Name | Supported | Defined By |
+| ---- | --------- | ---------- |
+|Custom|✗|OAS2,OAS3
+|Int32|✓|OAS2,OAS3
+|Int64|✓|OAS2,OAS3
+|Float|✓|OAS2,OAS3
+|Double|✓|OAS2,OAS3
+|Decimal|✓|ToolingExtension
+|String|✓|OAS2,OAS3
+|Byte|✓|OAS2,OAS3
+|Binary|✓|OAS2,OAS3
+|Boolean|✓|OAS2,OAS3
+|Date|✓|OAS2,OAS3
+|DateTime|✓|OAS2,OAS3
+|Password|✓|OAS2,OAS3
+|File|✓|OAS2
+|Array|✓|OAS2,OAS3
+|Maps|✓|ToolingExtension
+|CollectionFormat|✓|OAS2
+|CollectionFormatMulti|✓|OAS2
+|Enum|✓|OAS2,OAS3
+|ArrayOfEnum|✓|ToolingExtension
+|ArrayOfModel|✓|ToolingExtension
+|ArrayOfCollectionOfPrimitives|✓|ToolingExtension
+|ArrayOfCollectionOfModel|✓|ToolingExtension
+|ArrayOfCollectionOfEnum|✓|ToolingExtension
+|MapOfEnum|✓|ToolingExtension
+|MapOfModel|✓|ToolingExtension
+|MapOfCollectionOfPrimitives|✓|ToolingExtension
+|MapOfCollectionOfModel|✓|ToolingExtension
+|MapOfCollectionOfEnum|✓|ToolingExtension
+
+### Documentation Feature
+| Name | Supported | Defined By |
+| ---- | --------- | ---------- |
+|Readme|✓|ToolingExtension
+|Model|✓|ToolingExtension
+|Api|✓|ToolingExtension
+
+### Global Feature
+| Name | Supported | Defined By |
+| ---- | --------- | ---------- |
+|Host|✓|OAS2,OAS3
+|BasePath|✓|OAS2,OAS3
+|Info|✓|OAS2,OAS3
+|Schemes|✗|OAS2,OAS3
+|PartialSchemes|✓|OAS2,OAS3
+|Consumes|✓|OAS2
+|Produces|✓|OAS2
+|ExternalDocumentation|✓|OAS2,OAS3
+|Examples|✓|OAS2,OAS3
+|XMLStructureDefinitions|✗|OAS2,OAS3
+|MultiServer|✗|OAS3
+|ParameterizedServer|✗|OAS3
+|ParameterStyling|✗|OAS3
+|Callbacks|✗|OAS3
+|LinkObjects|✗|OAS3
+
+### Parameter Feature
+| Name | Supported | Defined By |
+| ---- | --------- | ---------- |
+|Path|✓|OAS2,OAS3
+|Query|✓|OAS2,OAS3
+|Header|✓|OAS2,OAS3
+|Body|✓|OAS2
+|FormUnencoded|✓|OAS2
+|FormMultipart|✓|OAS2
+|Cookie|✓|OAS3
+
+### Schema Support Feature
+| Name | Supported | Defined By |
+| ---- | --------- | ---------- |
+|Simple|✓|OAS2,OAS3
+|Composite|✓|OAS2,OAS3
+|Polymorphism|✗|OAS2,OAS3
+|Union|✗|OAS3
+
+### Security Feature
+| Name | Supported | Defined By |
+| ---- | --------- | ---------- |
+|BasicAuth|✗|OAS2,OAS3
+|ApiKey|✗|OAS2,OAS3
+|OpenIDConnect|✗|OAS3
+|BearerToken|✗|OAS3
+|OAuth2_Implicit|✗|OAS2,OAS3
+|OAuth2_Password|✗|OAS2,OAS3
+|OAuth2_ClientCredentials|✗|OAS2,OAS3
+|OAuth2_AuthorizationCode|✗|OAS2,OAS3
+
+### Wire Format Feature
+| Name | Supported | Defined By |
+| ---- | --------- | ---------- |
+|JSON|✓|OAS2,OAS3
+|XML|✗|OAS2,OAS3
+|PROTOBUF|✗|ToolingExtension
+|Custom|✗|OAS2,OAS3
diff --git a/docs/generators/php-laravel.md b/docs/generators/php-laravel.md
index 9c8665cc52e..b28504c1d02 100644
--- a/docs/generators/php-laravel.md
+++ b/docs/generators/php-laravel.md
@@ -40,6 +40,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
DateTime
+
array
bool
boolean
byte
diff --git a/docs/generators/php-lumen.md b/docs/generators/php-lumen.md
index 9242d70ae45..28f4810873d 100644
--- a/docs/generators/php-lumen.md
+++ b/docs/generators/php-lumen.md
@@ -40,6 +40,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
DateTime
+
array
bool
boolean
byte
diff --git a/docs/generators/php-mezzio-ph.md b/docs/generators/php-mezzio-ph.md
index 93f31d7fbca..8460e439084 100644
--- a/docs/generators/php-mezzio-ph.md
+++ b/docs/generators/php-mezzio-ph.md
@@ -41,6 +41,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
DateTime
+
array
bool
boolean
byte
diff --git a/docs/generators/php-slim-deprecated.md b/docs/generators/php-slim-deprecated.md
index 016ccd242e2..838b14ab7c3 100644
--- a/docs/generators/php-slim-deprecated.md
+++ b/docs/generators/php-slim-deprecated.md
@@ -40,6 +40,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
DateTime
+
array
bool
boolean
byte
diff --git a/docs/generators/php-slim4.md b/docs/generators/php-slim4.md
index cadaf51e5ff..5e0ec649254 100644
--- a/docs/generators/php-slim4.md
+++ b/docs/generators/php-slim4.md
@@ -41,6 +41,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
DateTime
+
array
bool
boolean
byte
diff --git a/docs/generators/php.md b/docs/generators/php.md
index ab4045d604d..8a99d592df2 100644
--- a/docs/generators/php.md
+++ b/docs/generators/php.md
@@ -41,6 +41,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
DateTime
+
array
bool
boolean
byte
diff --git a/modules/openapi-generator-gradle-plugin/samples/local-spec/gradle.properties b/modules/openapi-generator-gradle-plugin/samples/local-spec/gradle.properties
index 8b65b3b4572..abf7b9c5626 100644
--- a/modules/openapi-generator-gradle-plugin/samples/local-spec/gradle.properties
+++ b/modules/openapi-generator-gradle-plugin/samples/local-spec/gradle.properties
@@ -1,3 +1,3 @@
# RELEASE_VERSION
-openApiGeneratorVersion=5.2.0-SNAPSHOT
+openApiGeneratorVersion=5.2.1-SNAPSHOT
# /RELEASE_VERSION
diff --git a/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java b/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java
index 8949156f4d8..1f1dbd946f5 100644
--- a/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java
+++ b/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java
@@ -458,7 +458,7 @@ public class CodeGenMojo extends AbstractMojo {
}
}
- if (Boolean.TRUE.equals(skipIfSpecIsUnchanged) && inputSpecFile.exists()) {
+ if (Boolean.TRUE.equals(skipIfSpecIsUnchanged)) {
File storedInputSpecHashFile = getHashFile(inputSpecFile);
if (storedInputSpecHashFile.exists()) {
String inputSpecHash = null;
diff --git a/modules/openapi-generator-maven-plugin/src/test/java/org/openapitools/codegen/plugin/CodeGenMojoTest.java b/modules/openapi-generator-maven-plugin/src/test/java/org/openapitools/codegen/plugin/CodeGenMojoTest.java
index ad69be7e720..dd2083d017e 100644
--- a/modules/openapi-generator-maven-plugin/src/test/java/org/openapitools/codegen/plugin/CodeGenMojoTest.java
+++ b/modules/openapi-generator-maven-plugin/src/test/java/org/openapitools/codegen/plugin/CodeGenMojoTest.java
@@ -16,6 +16,13 @@
package org.openapitools.codegen.plugin;
+import java.io.File;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.Map;
+
import org.apache.commons.io.FileUtils;
import org.apache.maven.execution.DefaultMavenExecutionRequest;
import org.apache.maven.execution.MavenExecutionRequest;
@@ -25,12 +32,6 @@ import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectBuilder;
import org.apache.maven.project.ProjectBuildingRequest;
import org.eclipse.aether.DefaultRepositorySystemSession;
-import org.openapitools.codegen.plugin.stubs.StubUtility;
-
-import java.io.File;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.Map;
public class CodeGenMojoTest extends BaseTestCase {
@Override
@@ -67,6 +68,87 @@ public class CodeGenMojoTest extends BaseTestCase {
assertTrue(hashFolder.resolve("petstore.yaml-executionId.sha256").toFile().exists());
}
+ /**
+ * For a Pom file which refers to a input file which will be on the classpath, as opposed to a file path,
+ * test that the spec is not regenerated when the hash has not changed.
+ *
+ * @throws Exception
+ */
+ public void testSkipRegenerationForClasspathSpecFileNoChange() throws Exception {
+
+ //GIVEN
+ /* Setup the mojo */
+ final Path folder = Files.createTempDirectory("test-classpath");
+ final CodeGenMojo mojo = loadMojo(folder.toFile(), "src/test/resources/classpath", "executionId");
+
+ /* Perform an initial generation */
+ mojo.execute();
+
+ /* Check the hash file was created */
+ final Path hashFolder = folder.resolve("target/generated-sources/common-maven/remote-openapi/.openapi-generator");
+ assertTrue(hashFolder.resolve("petstore-on-classpath.yaml-executionId.sha256").toFile().exists());
+
+ /* Remove the generated source */
+ Files.walk(folder.resolve("target/generated-sources/common-maven/remote-openapi/src"))
+ .sorted(Comparator.reverseOrder())
+ .map(Path::toFile)
+ .forEach(File::delete);
+
+
+ // WHEN
+ /* Execute the mojo again */
+ mojo.execute();
+
+ // THEN
+ /* Verify that the source directory has not been repopulated. If it has then we generated code again */
+ assertFalse("src directory should not have been regenerated",
+ folder.resolve("target/generated-sources/common-maven/remote-openapi/src").toFile().exists());
+
+ }
+
+ /**
+ * For a Pom file which refers to a input file which will be on the classpath, as opposed to a file path,
+ * test that the generated source is regenerated when the hash has changed.
+ *
+ * @throws Exception
+ */
+ public void testSkipRegenerationForClasspathSpecFileWithChange() throws Exception {
+
+ //GIVEN
+ /* Setup the mojo */
+ final Path folder = Files.createTempDirectory("test-classpath");
+ final CodeGenMojo mojo = loadMojo(folder.toFile(), "src/test/resources/classpath", "executionId");
+
+ /* Perform an initial generation */
+ mojo.execute();
+
+ /* Check the hash file was created, proving a generation occurred */
+ final Path hashFolder = folder.resolve("target/generated-sources/common-maven/remote-openapi/.openapi-generator");
+ assertTrue(hashFolder.resolve("petstore-on-classpath.yaml-executionId.sha256").toFile().exists());
+
+ /* Update the hash contents to be a different value, simulating a spec change */
+ Files.write(
+ hashFolder.resolve("petstore-on-classpath.yaml-executionId.sha256"),
+ Arrays.asList("bd1bf4a953c858f9d47b67ed6029daacf1707e5cbd3d2e4b01383ba30363366f"));
+
+ /* Remove the generated source */
+ Files.walk(folder.resolve("target/generated-sources/common-maven/remote-openapi/src"))
+ .sorted(Comparator.reverseOrder())
+ .map(Path::toFile)
+ .forEach(File::delete);
+
+
+ // WHEN
+ /* Execute the mojo again */
+ mojo.execute();
+
+ // THEN
+ /* Verify that the source directory has not been repopulated. If it has then we generated code again */
+ assertTrue("src directory should have been regenerated",
+ folder.resolve("target/generated-sources/common-maven/remote-openapi/src").toFile().exists());
+
+ }
+
protected CodeGenMojo loadMojo(File temporaryFolder, String projectRoot) throws Exception {
return loadMojo(temporaryFolder, projectRoot, "default");
}
diff --git a/modules/openapi-generator-maven-plugin/src/test/resources/classpath/pom.xml b/modules/openapi-generator-maven-plugin/src/test/resources/classpath/pom.xml
new file mode 100644
index 00000000000..6a841479f9d
--- /dev/null
+++ b/modules/openapi-generator-maven-plugin/src/test/resources/classpath/pom.xml
@@ -0,0 +1,59 @@
+
+
+
+ 4.0.0
+ common.maven
+ common-maven
+ jar
+ 1.0.0-SNAPSHOT
+ OpenAPI Generator Configuration Test
+ https://openapi-generator.tech/
+
+ common-maven
+
+
+ org.openapitools
+ openapi-generator-maven-plugin
+
+
+ petstore-on-classpath.yaml
+ java
+
+ true
+
+
+ joda
+
+ jersey2
+
+ remote.org.openapitools.client.api
+ remote.org.openapitools.client.model
+ remote.org.openapitools.client
+
+
+
+ executionId
+ generate-sources
+
+ generate
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/modules/openapi-generator-maven-plugin/src/test/resources/petstore-on-classpath.yaml b/modules/openapi-generator-maven-plugin/src/test/resources/petstore-on-classpath.yaml
new file mode 100644
index 00000000000..f5e98eec38d
--- /dev/null
+++ b/modules/openapi-generator-maven-plugin/src/test/resources/petstore-on-classpath.yaml
@@ -0,0 +1,736 @@
+openapi: 3.0.0
+servers:
+ - url: 'http://petstore.swagger.io/v2'
+info:
+ description: >-
+ This is a sample server Petstore server. For this sample, you can use the api key
+ `special-key` to test the authorization filters.
+ version: 1.0.0
+ title: OpenAPI Petstore
+ license:
+ name: Apache-2.0
+ url: 'https://www.apache.org/licenses/LICENSE-2.0.html'
+tags:
+ - name: pet
+ description: Everything about your Pets
+ - name: store
+ description: Access to Petstore orders
+ - name: user
+ description: Operations about user
+paths:
+ /pet:
+ post:
+ tags:
+ - pet
+ summary: Add a new pet to the store
+ description: ''
+ operationId: addPet
+ responses:
+ '200':
+ description: successful operation
+ content:
+ application/xml:
+ schema:
+ $ref: '#/components/schemas/Pet'
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Pet'
+ '405':
+ description: Invalid input
+ security:
+ - petstore_auth:
+ - 'write:pets'
+ - 'read:pets'
+ requestBody:
+ $ref: '#/components/requestBodies/Pet'
+ put:
+ tags:
+ - pet
+ summary: Update an existing pet
+ description: ''
+ operationId: updatePet
+ responses:
+ '200':
+ description: successful operation
+ content:
+ application/xml:
+ schema:
+ $ref: '#/components/schemas/Pet'
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Pet'
+ '400':
+ description: Invalid ID supplied
+ '404':
+ description: Pet not found
+ '405':
+ description: Validation exception
+ security:
+ - petstore_auth:
+ - 'write:pets'
+ - 'read:pets'
+ requestBody:
+ $ref: '#/components/requestBodies/Pet'
+ /pet/findByStatus:
+ get:
+ tags:
+ - pet
+ summary: Finds Pets by status
+ description: Multiple status values can be provided with comma separated strings
+ operationId: findPetsByStatus
+ parameters:
+ - name: status
+ in: query
+ description: Status values that need to be considered for filter
+ required: true
+ style: form
+ explode: false
+ schema:
+ type: array
+ items:
+ type: string
+ enum:
+ - available
+ - pending
+ - sold
+ default: available
+ responses:
+ '200':
+ description: successful operation
+ content:
+ application/xml:
+ schema:
+ type: array
+ items:
+ $ref: '#/components/schemas/Pet'
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: '#/components/schemas/Pet'
+ '400':
+ description: Invalid status value
+ security:
+ - petstore_auth:
+ - 'read:pets'
+ /pet/findByTags:
+ get:
+ tags:
+ - pet
+ summary: Finds Pets by tags
+ description: >-
+ Multiple tags can be provided with comma separated strings. Use tag1,
+ tag2, tag3 for testing.
+ operationId: findPetsByTags
+ parameters:
+ - name: tags
+ in: query
+ description: Tags to filter by
+ required: true
+ style: form
+ explode: false
+ schema:
+ type: array
+ items:
+ type: string
+ responses:
+ '200':
+ description: successful operation
+ content:
+ application/xml:
+ schema:
+ type: array
+ items:
+ $ref: '#/components/schemas/Pet'
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: '#/components/schemas/Pet'
+ '400':
+ description: Invalid tag value
+ security:
+ - petstore_auth:
+ - 'read:pets'
+ deprecated: true
+ '/pet/{petId}':
+ get:
+ tags:
+ - pet
+ summary: Find pet by ID
+ description: Returns a single pet
+ operationId: getPetById
+ parameters:
+ - name: petId
+ in: path
+ description: ID of pet to return
+ required: true
+ schema:
+ type: integer
+ format: int64
+ responses:
+ '200':
+ description: successful operation
+ content:
+ application/xml:
+ schema:
+ $ref: '#/components/schemas/Pet'
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Pet'
+ '400':
+ description: Invalid ID supplied
+ '404':
+ description: Pet not found
+ security:
+ - api_key: []
+ post:
+ tags:
+ - pet
+ summary: Updates a pet in the store with form data
+ description: ''
+ operationId: updatePetWithForm
+ parameters:
+ - name: petId
+ in: path
+ description: ID of pet that needs to be updated
+ required: true
+ schema:
+ type: integer
+ format: int64
+ responses:
+ '405':
+ description: Invalid input
+ security:
+ - petstore_auth:
+ - 'write:pets'
+ - 'read:pets'
+ requestBody:
+ content:
+ application/x-www-form-urlencoded:
+ schema:
+ type: object
+ properties:
+ name:
+ description: Updated name of the pet
+ type: string
+ status:
+ description: Updated status of the pet
+ type: string
+ delete:
+ tags:
+ - pet
+ summary: Deletes a pet
+ description: ''
+ operationId: deletePet
+ parameters:
+ - name: api_key
+ in: header
+ required: false
+ schema:
+ type: string
+ - name: petId
+ in: path
+ description: Pet id to delete
+ required: true
+ schema:
+ type: integer
+ format: int64
+ responses:
+ '400':
+ description: Invalid pet value
+ security:
+ - petstore_auth:
+ - 'write:pets'
+ - 'read:pets'
+ '/pet/{petId}/uploadImage':
+ post:
+ tags:
+ - pet
+ summary: uploads an image
+ description: ''
+ operationId: uploadFile
+ parameters:
+ - name: petId
+ in: path
+ description: ID of pet to update
+ required: true
+ schema:
+ type: integer
+ format: int64
+ responses:
+ '200':
+ description: successful operation
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ApiResponse'
+ security:
+ - petstore_auth:
+ - 'write:pets'
+ - 'read:pets'
+ requestBody:
+ content:
+ multipart/form-data:
+ schema:
+ type: object
+ properties:
+ additionalMetadata:
+ description: Additional data to pass to server
+ type: string
+ file:
+ description: file to upload
+ type: string
+ format: binary
+ /store/inventory:
+ get:
+ tags:
+ - store
+ summary: Returns pet inventories by status
+ description: Returns a map of status codes to quantities
+ operationId: getInventory
+ responses:
+ '200':
+ description: successful operation
+ content:
+ application/json:
+ schema:
+ type: object
+ additionalProperties:
+ type: integer
+ format: int32
+ security:
+ - api_key: []
+ /store/order:
+ post:
+ tags:
+ - store
+ summary: Place an order for a pet
+ description: ''
+ operationId: placeOrder
+ responses:
+ '200':
+ description: successful operation
+ content:
+ application/xml:
+ schema:
+ $ref: '#/components/schemas/Order'
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Order'
+ '400':
+ description: Invalid Order
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Order'
+ description: order placed for purchasing the pet
+ required: true
+ '/store/order/{orderId}':
+ get:
+ tags:
+ - store
+ summary: Find purchase order by ID
+ description: >-
+ For valid response try integer IDs with value <= 5 or > 10. Other values
+ will generated exceptions
+ operationId: getOrderById
+ parameters:
+ - name: orderId
+ in: path
+ description: ID of pet that needs to be fetched
+ required: true
+ schema:
+ type: integer
+ format: int64
+ minimum: 1
+ maximum: 5
+ responses:
+ '200':
+ description: successful operation
+ content:
+ application/xml:
+ schema:
+ $ref: '#/components/schemas/Order'
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Order'
+ '400':
+ description: Invalid ID supplied
+ '404':
+ description: Order not found
+ delete:
+ tags:
+ - store
+ summary: Delete purchase order by ID
+ description: >-
+ For valid response try integer IDs with value < 1000. Anything above
+ 1000 or nonintegers will generate API errors
+ operationId: deleteOrder
+ parameters:
+ - name: orderId
+ in: path
+ description: ID of the order that needs to be deleted
+ required: true
+ schema:
+ type: string
+ responses:
+ '400':
+ description: Invalid ID supplied
+ '404':
+ description: Order not found
+ /user:
+ post:
+ tags:
+ - user
+ summary: Create user
+ description: This can only be done by the logged in user.
+ operationId: createUser
+ responses:
+ default:
+ description: successful operation
+ security:
+ - api_key: []
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/User'
+ description: Created user object
+ required: true
+ /user/createWithArray:
+ post:
+ tags:
+ - user
+ summary: Creates list of users with given input array
+ description: ''
+ operationId: createUsersWithArrayInput
+ responses:
+ default:
+ description: successful operation
+ security:
+ - api_key: []
+ requestBody:
+ $ref: '#/components/requestBodies/UserArray'
+ /user/createWithList:
+ post:
+ tags:
+ - user
+ summary: Creates list of users with given input array
+ description: ''
+ operationId: createUsersWithListInput
+ responses:
+ default:
+ description: successful operation
+ security:
+ - api_key: []
+ requestBody:
+ $ref: '#/components/requestBodies/UserArray'
+ /user/login:
+ get:
+ tags:
+ - user
+ summary: Logs user into the system
+ description: ''
+ operationId: loginUser
+ parameters:
+ - name: username
+ in: query
+ description: The user name for login
+ required: true
+ schema:
+ type: string
+ pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$'
+ - name: password
+ in: query
+ description: The password for login in clear text
+ required: true
+ schema:
+ type: string
+ responses:
+ '200':
+ description: successful operation
+ headers:
+ Set-Cookie:
+ description: >-
+ Cookie authentication key for use with the `api_key`
+ apiKey authentication.
+ schema:
+ type: string
+ example: AUTH_KEY=abcde12345; Path=/; HttpOnly
+ X-Rate-Limit:
+ description: calls per hour allowed by the user
+ schema:
+ type: integer
+ format: int32
+ X-Expires-After:
+ description: date in UTC when toekn expires
+ schema:
+ type: string
+ format: date-time
+ content:
+ application/xml:
+ schema:
+ type: string
+ application/json:
+ schema:
+ type: string
+ '400':
+ description: Invalid username/password supplied
+ /user/logout:
+ get:
+ tags:
+ - user
+ summary: Logs out current logged in user session
+ description: ''
+ operationId: logoutUser
+ responses:
+ default:
+ description: successful operation
+ security:
+ - api_key: []
+ '/user/{username}':
+ get:
+ tags:
+ - user
+ summary: Get user by user name
+ description: ''
+ operationId: getUserByName
+ parameters:
+ - name: username
+ in: path
+ description: The name that needs to be fetched. Use user1 for testing.
+ required: true
+ schema:
+ type: string
+ responses:
+ '200':
+ description: successful operation
+ content:
+ application/xml:
+ schema:
+ $ref: '#/components/schemas/User'
+ application/json:
+ schema:
+ $ref: '#/components/schemas/User'
+ '400':
+ description: Invalid username supplied
+ '404':
+ description: User not found
+ put:
+ tags:
+ - user
+ summary: Updated user
+ description: This can only be done by the logged in user.
+ operationId: updateUser
+ parameters:
+ - name: username
+ in: path
+ description: name that need to be deleted
+ required: true
+ schema:
+ type: string
+ responses:
+ '400':
+ description: Invalid user supplied
+ '404':
+ description: User not found
+ security:
+ - api_key: []
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/User'
+ description: Updated user object
+ required: true
+ delete:
+ tags:
+ - user
+ summary: Delete user
+ description: This can only be done by the logged in user.
+ operationId: deleteUser
+ parameters:
+ - name: username
+ in: path
+ description: The name that needs to be deleted
+ required: true
+ schema:
+ type: string
+ responses:
+ '400':
+ description: Invalid username supplied
+ '404':
+ description: User not found
+ security:
+ - api_key: []
+externalDocs:
+ description: Find out more about Swagger
+ url: 'http://swagger.io'
+components:
+ requestBodies:
+ UserArray:
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: '#/components/schemas/User'
+ description: List of user object
+ required: true
+ Pet:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Pet'
+ application/xml:
+ schema:
+ $ref: '#/components/schemas/Pet'
+ description: Pet object that needs to be added to the store
+ required: true
+ securitySchemes:
+ petstore_auth:
+ type: oauth2
+ flows:
+ implicit:
+ authorizationUrl: 'http://petstore.swagger.io/api/oauth/dialog'
+ scopes:
+ 'write:pets': modify pets in your account
+ 'read:pets': read your pets
+ api_key:
+ type: apiKey
+ name: api_key
+ in: header
+ schemas:
+ Order:
+ title: Pet Order
+ description: An order for a pets from the pet store
+ type: object
+ properties:
+ id:
+ type: integer
+ format: int64
+ petId:
+ type: integer
+ format: int64
+ quantity:
+ type: integer
+ format: int32
+ shipDate:
+ type: string
+ format: date-time
+ status:
+ type: string
+ description: Order Status
+ enum:
+ - placed
+ - approved
+ - delivered
+ complete:
+ type: boolean
+ default: false
+ xml:
+ name: Order
+ Category:
+ title: Pet category
+ description: A category for a pet
+ type: object
+ properties:
+ id:
+ type: integer
+ format: int64
+ name:
+ type: string
+ pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$'
+ xml:
+ name: Category
+ User:
+ title: a User
+ description: A User who is purchasing from the pet store
+ type: object
+ properties:
+ id:
+ type: integer
+ format: int64
+ username:
+ type: string
+ firstName:
+ type: string
+ lastName:
+ type: string
+ email:
+ type: string
+ password:
+ type: string
+ phone:
+ type: string
+ userStatus:
+ type: integer
+ format: int32
+ description: User Status
+ xml:
+ name: User
+ Tag:
+ title: Pet Tag
+ description: A tag for a pet
+ type: object
+ properties:
+ id:
+ type: integer
+ format: int64
+ name:
+ type: string
+ xml:
+ name: Tag
+ Pet:
+ title: a Pet
+ description: A pet for sale in the pet store
+ type: object
+ required:
+ - name
+ - photoUrls
+ properties:
+ id:
+ type: integer
+ format: int64
+ category:
+ $ref: '#/components/schemas/Category'
+ name:
+ type: string
+ example: doggie
+ photoUrls:
+ type: array
+ xml:
+ name: photoUrl
+ wrapped: true
+ items:
+ type: string
+ tags:
+ type: array
+ xml:
+ name: tag
+ wrapped: true
+ items:
+ $ref: '#/components/schemas/Tag'
+ status:
+ type: string
+ description: pet status in the store
+ enum:
+ - available
+ - pending
+ - sold
+ xml:
+ name: Pet
+ ApiResponse:
+ title: An uploaded response
+ description: Describes the result of uploading an image resource
+ type: object
+ properties:
+ code:
+ type: integer
+ format: int32
+ type:
+ type: string
+ message:
+ type: string
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java
index a441659434a..8d825dc545a 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java
@@ -155,6 +155,7 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
private CodegenProperty additionalProperties;
private boolean isModel;
private boolean hasRequiredVars;
+ private boolean hasDiscriminatorWithNonEmptyMapping;
public String getAdditionalPropertiesType() {
return additionalPropertiesType;
@@ -316,6 +317,9 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
public void setDiscriminator(CodegenDiscriminator discriminator) {
this.discriminator = discriminator;
+ if (discriminator instanceof CodegenDiscriminator && !discriminator.getMappedModels().isEmpty()) {
+ this.hasDiscriminatorWithNonEmptyMapping = true;
+ }
}
/**
@@ -768,6 +772,14 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
this.hasRequired = hasRequired;
}
+ @Override
+ public boolean getHasDiscriminatorWithNonEmptyMapping() { return hasDiscriminatorWithNonEmptyMapping; };
+
+ @Override
+ public void setHasDiscriminatorWithNonEmptyMapping(boolean hasDiscriminatorWithNonEmptyMapping) {
+ this.hasDiscriminatorWithNonEmptyMapping = hasDiscriminatorWithNonEmptyMapping;
+ }
+
@Override
public boolean equals(Object o) {
if (this == o) return true;
@@ -801,6 +813,7 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
hasOnlyReadOnly == that.hasOnlyReadOnly &&
isNull == that.isNull &&
hasValidation == that.hasValidation &&
+ hasDiscriminatorWithNonEmptyMapping == that.getHasDiscriminatorWithNonEmptyMapping() &&
getAdditionalPropertiesIsAnyType() == that.getAdditionalPropertiesIsAnyType() &&
getUniqueItems() == that.getUniqueItems() &&
getExclusiveMinimum() == that.getExclusiveMinimum() &&
@@ -874,7 +887,7 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
getAdditionalPropertiesType(), getMaxProperties(), getMinProperties(), getUniqueItems(), getMaxItems(),
getMinItems(), getMaxLength(), getMinLength(), getExclusiveMinimum(), getExclusiveMaximum(), getMinimum(),
getMaximum(), getPattern(), getMultipleOf(), getItems(), getAdditionalProperties(), getIsModel(),
- getAdditionalPropertiesIsAnyType());
+ getAdditionalPropertiesIsAnyType(), hasDiscriminatorWithNonEmptyMapping);
}
@Override
@@ -964,6 +977,7 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
sb.append(", isNull='").append(isNull);
sb.append(", hasValidation='").append(hasValidation);
sb.append(", getAdditionalPropertiesIsAnyType=").append(getAdditionalPropertiesIsAnyType());
+ sb.append(", getHasDiscriminatorWithNonEmptyMapping=").append(hasDiscriminatorWithNonEmptyMapping);
sb.append('}');
return sb.toString();
}
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java
index 874ac93d152..8f512e4cec7 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java
@@ -51,6 +51,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties {
public Map vendorExtensions = new HashMap();
public boolean hasValidation;
public boolean isNullable;
+ public boolean isDeprecated;
/**
* Determines whether this parameter is mandatory. If the parameter is in "path",
* this property is required and its value MUST be true. Otherwise, the property
@@ -105,6 +106,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties {
private Integer minProperties;
public boolean isNull;
private boolean hasRequired;
+ private boolean hasDiscriminatorWithNonEmptyMapping;
public CodegenParameter copy() {
CodegenParameter output = new CodegenParameter();
@@ -155,6 +157,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties {
output.setAdditionalPropertiesIsAnyType(this.getAdditionalPropertiesIsAnyType());
output.setHasVars(this.hasVars);
output.setHasRequired(this.hasRequired);
+ output.setHasDiscriminatorWithNonEmptyMapping(this.hasDiscriminatorWithNonEmptyMapping);
if (this._enum != null) {
output._enum = new ArrayList(this._enum);
@@ -179,6 +182,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties {
}
output.hasValidation = this.hasValidation;
output.isNullable = this.isNullable;
+ output.isDeprecated = this.isDeprecated;
output.isBinary = this.isBinary;
output.isByteArray = this.isByteArray;
output.isString = this.isString;
@@ -211,7 +215,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties {
@Override
public int hashCode() {
- return Objects.hash(isFormParam, isQueryParam, isPathParam, isHeaderParam, isCookieParam, isBodyParam, isContainer, isCollectionFormatMulti, isPrimitiveType, isModel, isExplode, baseName, paramName, dataType, datatypeWithEnum, dataFormat, collectionFormat, description, unescapedDescription, baseType, defaultValue, enumName, style, isDeepObject, example, jsonSchema, isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isDecimal, isByteArray, isBinary, isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isFreeFormObject, isAnyType, isArray, isMap, isFile, isEnum, _enum, allowableValues, items, mostInnerItems, additionalProperties, vars, requiredVars, vendorExtensions, hasValidation, getMaxProperties(), getMinProperties(), isNullable, required, getMaximum(), getExclusiveMaximum(), getMinimum(), getExclusiveMinimum(), getMaxLength(), getMinLength(), getPattern(), getMaxItems(), getMinItems(), getUniqueItems(), contentType, multipleOf, isNull, additionalPropertiesIsAnyType, hasVars, hasRequired, isShort, isUnboundedInteger);
+ return Objects.hash(isFormParam, isQueryParam, isPathParam, isHeaderParam, isCookieParam, isBodyParam, isContainer, isCollectionFormatMulti, isPrimitiveType, isModel, isExplode, baseName, paramName, dataType, datatypeWithEnum, dataFormat, collectionFormat, description, unescapedDescription, baseType, defaultValue, enumName, style, isDeepObject, example, jsonSchema, isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isDecimal, isByteArray, isBinary, isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isFreeFormObject, isAnyType, isArray, isMap, isFile, isEnum, _enum, allowableValues, items, mostInnerItems, additionalProperties, vars, requiredVars, vendorExtensions, hasValidation, getMaxProperties(), getMinProperties(), isNullable, isDeprecated, required, getMaximum(), getExclusiveMaximum(), getMinimum(), getExclusiveMinimum(), getMaxLength(), getMinLength(), getPattern(), getMaxItems(), getMinItems(), getUniqueItems(), contentType, multipleOf, isNull, additionalPropertiesIsAnyType, hasVars, hasRequired, isShort, isUnboundedInteger, hasDiscriminatorWithNonEmptyMapping);
}
@Override
@@ -256,8 +260,10 @@ public class CodegenParameter implements IJsonSchemaValidationProperties {
isEnum == that.isEnum &&
hasValidation == that.hasValidation &&
isNullable == that.isNullable &&
+ isDeprecated == that.isDeprecated &&
required == that.required &&
isNull == that.isNull &&
+ hasDiscriminatorWithNonEmptyMapping && that.getHasDiscriminatorWithNonEmptyMapping() &&
getAdditionalPropertiesIsAnyType() == that.getAdditionalPropertiesIsAnyType() &&
getHasVars() == that.getHasVars() &&
getHasRequired() == that.getHasRequired() &&
@@ -365,6 +371,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties {
sb.append(", maxProperties=").append(maxProperties);
sb.append(", minProperties=").append(minProperties);
sb.append(", isNullable=").append(isNullable);
+ sb.append(", isDeprecated=").append(isDeprecated);
sb.append(", required=").append(required);
sb.append(", maximum='").append(maximum).append('\'');
sb.append(", exclusiveMaximum=").append(exclusiveMaximum);
@@ -382,6 +389,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties {
sb.append(", getAdditionalPropertiesIsAnyType=").append(additionalPropertiesIsAnyType);
sb.append(", getHasVars=").append(hasVars);
sb.append(", getHasRequired=").append(hasRequired);
+ sb.append(", getHasDiscriminatorWithNonEmptyMapping=").append(hasDiscriminatorWithNonEmptyMapping);
sb.append('}');
return sb.toString();
}
@@ -663,5 +671,13 @@ public class CodegenParameter implements IJsonSchemaValidationProperties {
public void setHasRequired(boolean hasRequired) {
this.hasRequired = hasRequired;
}
+
+ @Override
+ public boolean getHasDiscriminatorWithNonEmptyMapping() { return hasDiscriminatorWithNonEmptyMapping; };
+
+ @Override
+ public void setHasDiscriminatorWithNonEmptyMapping(boolean hasDiscriminatorWithNonEmptyMapping) {
+ this.hasDiscriminatorWithNonEmptyMapping = hasDiscriminatorWithNonEmptyMapping;
+ }
}
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java
index 4ccbb8c3a9d..8fe4c34ebb1 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java
@@ -190,6 +190,7 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti
private boolean additionalPropertiesIsAnyType;
private boolean hasVars;
private boolean hasRequired;
+ private boolean hasDiscriminatorWithNonEmptyMapping;
public String getBaseName() {
return baseName;
@@ -754,6 +755,14 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti
this.hasRequired = hasRequired;
}
+ @Override
+ public boolean getHasDiscriminatorWithNonEmptyMapping() { return hasDiscriminatorWithNonEmptyMapping; };
+
+ @Override
+ public void setHasDiscriminatorWithNonEmptyMapping(boolean hasDiscriminatorWithNonEmptyMapping) {
+ this.hasDiscriminatorWithNonEmptyMapping = hasDiscriminatorWithNonEmptyMapping;
+ }
+
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("CodegenProperty{");
@@ -848,6 +857,7 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti
sb.append(", getAdditionalPropertiesIsAnyType=").append(getAdditionalPropertiesIsAnyType());
sb.append(", getHasVars=").append(getHasVars());
sb.append(", getHasRequired=").append(getHasRequired());
+ sb.append(", getHasDiscriminatorWithNonEmptyMapping=").append(hasDiscriminatorWithNonEmptyMapping);
sb.append('}');
return sb.toString();
}
@@ -899,6 +909,7 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti
isXmlAttribute == that.isXmlAttribute &&
isXmlWrapped == that.isXmlWrapped &&
isNull == that.isNull &&
+ hasDiscriminatorWithNonEmptyMapping == that.hasDiscriminatorWithNonEmptyMapping &&
getAdditionalPropertiesIsAnyType() == that.getAdditionalPropertiesIsAnyType() &&
getHasVars() == that.getHasVars() &&
getHasRequired() ==that.getHasRequired() &&
@@ -963,6 +974,7 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti
items, mostInnerItems, additionalProperties, vars, requiredVars,
vendorExtensions, hasValidation, isInherited, discriminatorValue, nameInCamelCase,
nameInSnakeCase, enumName, maxItems, minItems, isXmlAttribute, xmlPrefix, xmlName,
- xmlNamespace, isXmlWrapped, isNull, additionalPropertiesIsAnyType, hasVars, hasRequired);
+ xmlNamespace, isXmlWrapped, isNull, additionalPropertiesIsAnyType, hasVars, hasRequired,
+ hasDiscriminatorWithNonEmptyMapping);
}
}
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java
index 22c85170bbb..022933ebe4c 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java
@@ -84,6 +84,7 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
private boolean additionalPropertiesIsAnyType;
private boolean hasVars;
private boolean hasRequired;
+ private boolean hasDiscriminatorWithNonEmptyMapping;
@Override
public int hashCode() {
@@ -94,7 +95,8 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
vars, requiredVars, isNull, hasValidation, isShort, isUnboundedInteger,
getMaxProperties(), getMinProperties(), uniqueItems, getMaxItems(), getMinItems(), getMaxLength(),
getMinLength(), exclusiveMinimum, exclusiveMaximum, getMinimum(), getMaximum(), getPattern(),
- is1xx, is2xx, is3xx, is4xx, is5xx, additionalPropertiesIsAnyType, hasVars, hasRequired);
+ is1xx, is2xx, is3xx, is4xx, is5xx, additionalPropertiesIsAnyType, hasVars, hasRequired,
+ hasDiscriminatorWithNonEmptyMapping);
}
@Override
@@ -138,6 +140,7 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
is3xx == that.is3xx &&
is4xx == that.is4xx &&
is5xx == that.is5xx &&
+ hasDiscriminatorWithNonEmptyMapping == that.getHasDiscriminatorWithNonEmptyMapping() &&
getAdditionalPropertiesIsAnyType() == that.getAdditionalPropertiesIsAnyType() &&
getHasVars() == that.getHasVars() &&
getHasRequired() == that.getHasRequired() &&
@@ -478,6 +481,7 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
sb.append(", getAdditionalPropertiesIsAnyType=").append(additionalPropertiesIsAnyType);
sb.append(", getHasVars=").append(hasVars);
sb.append(", getHasRequired=").append(hasRequired);
+ sb.append(", getHasDiscriminatorWithNonEmptyMapping=").append(hasDiscriminatorWithNonEmptyMapping);
sb.append('}');
return sb.toString();
}
@@ -534,4 +538,12 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
public void setHasVars(boolean hasVars) {
this.hasVars = hasVars;
}
+
+ @Override
+ public boolean getHasDiscriminatorWithNonEmptyMapping() { return hasDiscriminatorWithNonEmptyMapping; };
+
+ @Override
+ public void setHasDiscriminatorWithNonEmptyMapping(boolean hasDiscriminatorWithNonEmptyMapping) {
+ this.hasDiscriminatorWithNonEmptyMapping = hasDiscriminatorWithNonEmptyMapping;
+ }
}
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java
index b17b449893f..4d0b35007fa 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java
@@ -256,6 +256,9 @@ public class DefaultCodegen implements CodegenConfig {
// A cache to efficiently lookup a Schema instance based on the return value of `toModelName()`.
private Map modelNameToSchemaCache;
+ // A cache to efficiently lookup schema `toModelName()` based on the schema Key
+ private Map schemaKeyToModelNameCache = new HashMap<>();
+
@Override
public List cliOptions() {
return cliOptions;
@@ -2322,7 +2325,13 @@ public class DefaultCodegen implements CodegenConfig {
*/
@Override
public String toModelName(final String name) {
- return camelize(modelNamePrefix + "_" + name + "_" + modelNameSuffix);
+ if (schemaKeyToModelNameCache.containsKey(name)) {
+ return schemaKeyToModelNameCache.get(name);
+ }
+
+ String camelizedName = camelize(modelNamePrefix + "_" + name + "_" + modelNameSuffix);
+ schemaKeyToModelNameCache.put(name, camelizedName);
+ return camelizedName;
}
private static class NamedSchema {
@@ -2393,7 +2402,7 @@ public class DefaultCodegen implements CodegenConfig {
}
m.isAlias = (typeAliases.containsKey(name)
|| isAliasOfSimpleTypes(schema)); // check if the unaliased schema is an alias of simple OAS types
- m.discriminator = createDiscriminator(name, schema, this.openAPI);
+ m.setDiscriminator(createDiscriminator(name, schema, this.openAPI));
if (!this.getLegacyDiscriminatorBehavior()) {
m.addDiscriminatorMappedModelsImports();
}
@@ -2453,7 +2462,7 @@ public class DefaultCodegen implements CodegenConfig {
for (Schema innerSchema : composed.getAllOf()) { // TODO need to work with anyOf, oneOf as well
if (m.discriminator == null && innerSchema.getDiscriminator() != null) {
LOGGER.debug("discriminator is set to null (not correctly set earlier): {}", name);
- m.discriminator = createDiscriminator(name, innerSchema, this.openAPI);
+ m.setDiscriminator(createDiscriminator(name, innerSchema, this.openAPI));
if (!this.getLegacyDiscriminatorBehavior()) {
m.addDiscriminatorMappedModelsImports();
}
@@ -4334,6 +4343,9 @@ public class DefaultCodegen implements CodegenConfig {
if (parameter.getRequired() != null) {
codegenParameter.required = parameter.getRequired();
}
+ if (parameter.getDeprecated() != null) {
+ codegenParameter.isDeprecated = parameter.getDeprecated();
+ }
codegenParameter.jsonSchema = Json.pretty(parameter);
if (GlobalSettings.getProperty("debugParser") != null) {
@@ -6660,7 +6672,7 @@ public class DefaultCodegen implements CodegenConfig {
CodegenModel cm = new CodegenModel();
- cm.discriminator = createDiscriminator("", cs, openAPI);
+ cm.setDiscriminator(createDiscriminator("", cs, openAPI));
if (!this.getLegacyDiscriminatorBehavior()) {
cm.addDiscriminatorMappedModelsImports();
}
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java
index d2e1bb4500d..404c49fd0d2 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java
@@ -630,6 +630,8 @@ public class DefaultGenerator implements Generator {
allOperations.add(new HashMap<>(operation));
+ addAuthenticationSwitches(operation);
+
for (String templateName : config.apiTemplateFiles().keySet()) {
String filename = config.apiFilename(templateName, tag);
File written = processTemplateToFile(operation, templateName, filename, generateApis, CodegenConstants.APIS);
@@ -779,30 +781,10 @@ public class DefaultGenerator implements Generator {
bundle.put("models", allModels);
bundle.put("apiFolder", config.apiPackage().replace('.', File.separatorChar));
bundle.put("modelPackage", config.modelPackage());
+ bundle.put("library", config.getLibrary());
+ // todo verify support and operation bundles have access to the common variables
- Map securitySchemeMap = openAPI.getComponents() != null ? openAPI.getComponents().getSecuritySchemes() : null;
- List authMethods = config.fromSecurity(securitySchemeMap);
- if (authMethods != null && !authMethods.isEmpty()) {
- bundle.put("authMethods", authMethods);
- bundle.put("hasAuthMethods", true);
-
- if (ProcessUtils.hasOAuthMethods(authMethods)) {
- bundle.put("hasOAuthMethods", true);
- bundle.put("oauthMethods", ProcessUtils.getOAuthMethods(authMethods));
- }
- if (ProcessUtils.hasHttpBearerMethods(authMethods)) {
- bundle.put("hasHttpBearerMethods", true);
- }
- if (ProcessUtils.hasHttpSignatureMethods(authMethods)) {
- bundle.put("hasHttpSignatureMethods", true);
- }
- if (ProcessUtils.hasHttpBasicMethods(authMethods)) {
- bundle.put("hasHttpBasicMethods", true);
- }
- if (ProcessUtils.hasApiKeyMethods(authMethods)) {
- bundle.put("hasApiKeyMethods", true);
- }
- }
+ addAuthenticationSwitches(bundle);
List servers = config.fromServers(openAPI.getServers());
if (servers != null && !servers.isEmpty()) {
@@ -830,6 +812,48 @@ public class DefaultGenerator implements Generator {
return bundle;
}
+ /**
+ * Add authentication methods to the given map
+ * This adds a boolean and a collection for each authentication type to the map.
+ *
+ * Examples:
+ *
+ * boolean hasOAuthMethods
+ *
+ * List<CodegenSecurity> oauthMethods
+ *
+ * @param bundle the map which the booleans and collections will be added
+ */
+ void addAuthenticationSwitches(Map bundle){
+ Map securitySchemeMap = openAPI.getComponents() != null ? openAPI.getComponents().getSecuritySchemes() : null;
+ List authMethods = config.fromSecurity(securitySchemeMap);
+ if (authMethods != null && !authMethods.isEmpty()) {
+ bundle.put("authMethods", authMethods);
+ bundle.put("hasAuthMethods", true);
+
+ if (ProcessUtils.hasOAuthMethods(authMethods)) {
+ bundle.put("hasOAuthMethods", true);
+ bundle.put("oauthMethods", ProcessUtils.getOAuthMethods(authMethods));
+ }
+ if (ProcessUtils.hasHttpBearerMethods(authMethods)) {
+ bundle.put("hasHttpBearerMethods", true);
+ bundle.put("httpBearerMethods", ProcessUtils.getHttpBearerMethods(authMethods));
+ }
+ if (ProcessUtils.hasHttpSignatureMethods(authMethods)) {
+ bundle.put("hasHttpSignatureMethods", true);
+ bundle.put("httpSignatureMethods", ProcessUtils.getHttpSignatureMethods(authMethods));
+ }
+ if (ProcessUtils.hasHttpBasicMethods(authMethods)) {
+ bundle.put("hasHttpBasicMethods", true);
+ bundle.put("httpBasicMethods", ProcessUtils.getHttpBasicMethods(authMethods));
+ }
+ if (ProcessUtils.hasApiKeyMethods(authMethods)) {
+ bundle.put("hasApiKeyMethods", true);
+ bundle.put("apiKeyMethods", ProcessUtils.getApiKeyMethods(authMethods));
+ }
+ }
+ }
+
@Override
public List generate() {
if (openAPI == null) {
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/IJsonSchemaValidationProperties.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/IJsonSchemaValidationProperties.java
index bf078ab792d..ffb195c4a5b 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/IJsonSchemaValidationProperties.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/IJsonSchemaValidationProperties.java
@@ -122,4 +122,10 @@ public interface IJsonSchemaValidationProperties {
boolean getHasRequired();
void setHasRequired(boolean hasRequired);
-}
+
+ // discriminators are only supported in request bodies and response payloads per OpenApi
+ boolean getHasDiscriminatorWithNonEmptyMapping();
+
+ // discriminators are only supported in request bodies and response payloads per OpenApi
+ void setHasDiscriminatorWithNonEmptyMapping(boolean hasDiscriminatorWithNonEmptyMapping);
+}
\ No newline at end of file
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCSharpCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCSharpCodegen.java
index 1de6d2f1200..7093997f0b9 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCSharpCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCSharpCodegen.java
@@ -87,6 +87,12 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
private final Logger LOGGER = LoggerFactory.getLogger(AbstractCSharpCodegen.class);
+ // special property keywords not allowed as these are the function names in the model files
+ protected Set propertySpecialKeywords = new HashSet<>(Arrays.asList("ToString", "ToJson", "GetHashCode", "Equals", "ShouldSerializeToString"));
+
+ // A cache to efficiently lookup schema `toModelName()` based on the schema Key
+ private Map schemaKeyToModelNameCache = new HashMap<>();
+
public AbstractCSharpCodegen() {
super();
@@ -115,7 +121,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
// set "client" as a reserved word to avoid conflicts with Org.OpenAPITools.Client
// this is a workaround and can be removed if c# api client is updated to use
// fully qualified name
- "Client", "client", "parameter",
+ "Client", "client", "parameter", "Configuration", "Version",
// local variable names in API methods (endpoints)
"localVarPath", "localVarPathParams", "localVarQueryParams", "localVarHeaderParams",
"localVarFormParams", "localVarFileParams", "localVarStatusCode", "localVarResponse",
@@ -829,6 +835,10 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
name = escapeReservedWord(name);
}
+ if (propertySpecialKeywords.contains(name)) {
+ return camelize("property_" + name);
+ }
+
return name;
}
@@ -1028,6 +1038,13 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
if (importMapping.containsKey(name)) {
return importMapping.get(name);
}
+
+ // memoization
+ String origName = name;
+ if (schemaKeyToModelNameCache.containsKey(origName)) {
+ return schemaKeyToModelNameCache.get(origName);
+ }
+
if (!StringUtils.isEmpty(modelNamePrefix)) {
name = modelNamePrefix + "_" + name;
}
@@ -1051,9 +1068,12 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
name = "model_" + name; // e.g. 200Response => Model200Response (after camelize)
}
+ String camelizedName = camelize(name);
+ schemaKeyToModelNameCache.put(origName, camelizedName);
+
// camelize the model name
// phone_number => PhoneNumber
- return camelize(name);
+ return camelizedName;
}
@Override
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 aaa988a6109..a5d05d09cb6 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
@@ -1219,6 +1219,13 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
model.imports.add("ApiModelProperty");
model.imports.add("ApiModel");
}
+
+ if (openApiNullable) {
+ if (Boolean.FALSE.equals(property.required) && Boolean.TRUE.equals(property.isNullable)) {
+ model.imports.add("JsonNullable");
+ model.getVendorExtensions().put("x-jackson-optional-nullable-helpers", true);
+ }
+ }
}
@Override
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractKotlinCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractKotlinCodegen.java
index c44fa068aa1..1dd3780689c 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractKotlinCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractKotlinCodegen.java
@@ -23,12 +23,7 @@ import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
-import org.openapitools.codegen.CliOption;
-import org.openapitools.codegen.CodegenConfig;
-import org.openapitools.codegen.CodegenConstants;
-import org.openapitools.codegen.CodegenModel;
-import org.openapitools.codegen.CodegenProperty;
-import org.openapitools.codegen.DefaultCodegen;
+import org.openapitools.codegen.*;
import org.openapitools.codegen.utils.ModelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -73,6 +68,10 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
protected CodegenConstants.ENUM_PROPERTY_NAMING_TYPE enumPropertyNaming = CodegenConstants.ENUM_PROPERTY_NAMING_TYPE.camelCase;
protected SERIALIZATION_LIBRARY_TYPE serializationLibrary = SERIALIZATION_LIBRARY_TYPE.moshi;
+ // model classes cannot use the same property names defined in HashMap
+ // ref: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-hash-map/
+ protected Set propertyAdditionalKeywords = new HashSet<>(Arrays.asList("entries", "keys", "size", "values"));
+
public AbstractKotlinCodegen() {
super();
@@ -99,24 +98,64 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
// this includes hard reserved words defined by https://github.com/JetBrains/kotlin/blob/master/core/descriptors/src/org/jetbrains/kotlin/renderer/KeywordStringsGenerated.java
// as well as keywords from https://kotlinlang.org/docs/reference/keyword-reference.html
reservedWords = new HashSet(Arrays.asList(
+ "abstract",
+ "actual",
+ "annotation",
"as",
"break",
"class",
+ "companion",
+ "const",
+ "constructor",
"continue",
+ "crossinline",
+ "data",
+ "delegate",
"do",
+ "dynamic",
"else",
+ "enum",
+ "expect",
+ "external",
"false",
+ "field",
+ "final",
+ "finally",
"for",
"fun",
"if",
+ "import",
"in",
+ "infix",
+ "init",
+ "inline",
+ "inner",
"interface",
+ "internal",
"is",
+ "it",
+ "lateinit",
+ "noinline",
"null",
"object",
+ "open",
+ "operator",
+ "out",
+ "override",
"package",
+ "param",
+ "private",
+ "property",
+ "protected",
+ "public",
+ "receiver",
+ "reified",
"return",
+ "sealed",
+ "setparam",
"super",
+ "suspend",
+ "tailrec",
"this",
"throw",
"true",
@@ -124,13 +163,12 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
"typealias",
"typeof",
"val",
+ "value",
"var",
+ "vararg",
"when",
- "while",
- "private",
- "open",
- "external",
- "internal"
+ "where",
+ "while"
));
defaultIncludes = new HashSet(Arrays.asList(
@@ -170,6 +208,7 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
typeMapping.put("binary", "kotlin.ByteArray");
typeMapping.put("Date", "java.time.LocalDate");
typeMapping.put("DateTime", "java.time.OffsetDateTime");
+ typeMapping.put("AnyType", "kotlin.Any");
instantiationTypes.put("array", "kotlin.collections.ArrayList");
instantiationTypes.put("list", "kotlin.collections.ArrayList");
@@ -816,11 +855,20 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
}
// should be the same as variable name
- return toVarName(name);
+ return toVariableName(name);
}
@Override
public String toVarName(String name) {
+ name = toVariableName(name);
+ if (propertyAdditionalKeywords.contains(name)) {
+ return camelize("property_" + name, true);
+ } else {
+ return name;
+ }
+ }
+
+ protected String toVariableName(String name) {
// sanitize name
name = sanitizeName(name, "\\W-[\\$]");
name = sanitizeKotlinSpecificNames(name);
@@ -944,7 +992,7 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
itemsSchema.setDefault(element.asText());
defaultContent.append(toDefaultValue(itemsSchema)).append(",");
});
- defaultContent.deleteCharAt(defaultContent.length()-1); // remove trailing comma
+ defaultContent.deleteCharAt(defaultContent.length() - 1); // remove trailing comma
return arrInstantiationType + "Of(" + defaultContent + ")";
}
} else if (ModelUtils.isStringSchema(p)) {
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPhpCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPhpCodegen.java
index d8327a99401..779393af403 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPhpCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPhpCodegen.java
@@ -89,6 +89,7 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg
"float",
"string",
"object",
+ "array",
"DateTime",
"mixed",
"number",
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java
index 96c7c92f5ec..3e6a692ecec 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java
@@ -902,6 +902,11 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
name = escapeReservedWord(name);
}
+ // for function names in the model, escape with the "Property" prefix
+ if (propertySpecialKeywords.contains(name)) {
+ return camelize("property_" + name);
+ }
+
return name;
}
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java
index 18cfb324f9a..0aa6cb25685 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java
@@ -381,42 +381,79 @@ public class CppPistacheServerCodegen extends AbstractCppCodegen {
@Override
public String toDefaultValue(Schema p) {
- if (ModelUtils.isBooleanSchema(p)) {
- return "false";
+ if (ModelUtils.isStringSchema(p)) {
+ if (p.getDefault() != null) {
+ return "\"" + p.getDefault().toString() + "\"";
+ } else {
+ return "\"\"";
+ }
+ } else if (ModelUtils.isBooleanSchema(p)) {
+ if (p.getDefault() != null) {
+ return p.getDefault().toString();
+ } else {
+ return "false";
+ }
} else if (ModelUtils.isDateSchema(p)) {
- return "\"\"";
+ if (p.getDefault() != null) {
+ return "\"" + p.getDefault().toString() + "\"";
+ } else {
+ return "\"\"";
+ }
} else if (ModelUtils.isDateTimeSchema(p)) {
- return "\"\"";
+ if (p.getDefault() != null) {
+ return "\"" + p.getDefault().toString() + "\"";
+ } else {
+ return "\"\"";
+ }
} else if (ModelUtils.isNumberSchema(p)) {
- if (ModelUtils.isFloatSchema(p)) {
- return "0.0f";
+ if (ModelUtils.isFloatSchema(p)) { // float
+ if (p.getDefault() != null) {
+ return p.getDefault().toString() + "f";
+ } else {
+ return "0.0f";
+ }
+ } else { // double
+ if (p.getDefault() != null) {
+ return p.getDefault().toString();
+ } else {
+ return "0.0";
+ }
}
- return "0.0";
} else if (ModelUtils.isIntegerSchema(p)) {
- if (ModelUtils.isLongSchema(p)) {
- return "0L";
+ if (ModelUtils.isLongSchema(p)) { // long
+ if (p.getDefault() != null) {
+ return p.getDefault().toString() + "L";
+ } else {
+ return "0L";
+ }
+ } else { // integer
+ if (p.getDefault() != null) {
+ return p.getDefault().toString();
+ } else {
+ return "0";
+ }
}
- return "0";
} else if (ModelUtils.isByteArraySchema(p)) {
- return "\"\"";
+ if (p.getDefault() != null) {
+ return "\"" + p.getDefault().toString() + "\"";
+ } else {
+ return "\"\"";
+ }
} else if (ModelUtils.isMapSchema(p)) {
String inner = getSchemaType(getAdditionalProperties(p));
return "std::map()";
} else if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
String inner = getSchemaType(ap.getItems());
- return "std::vector<" + inner + ">()";
- } else if (!StringUtils.isEmpty(p.get$ref())) { // model
- return toModelName(ModelUtils.getSimpleRef(p.get$ref())) + "()";
- } else if (ModelUtils.isStringSchema(p)) {
- if (p.getDefault() == null) {
- return "\"\"";
- } else {
- return "\"" + p.getDefault().toString() + "\"";
+ if (!languageSpecificPrimitives.contains(inner)) {
+ inner = "std::shared_ptr<" + inner + ">";
}
+ return "std::vector<" + inner + ">()";
+ } else if (!StringUtils.isEmpty(p.get$ref())) {
+ return "std::make_shared<" + toModelName(ModelUtils.getSimpleRef(p.get$ref())) + ">()";
}
- return "";
+ return "nullptr";
}
/**
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioNextClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioNextClientCodegen.java
index cf93047eda2..895a5559e68 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioNextClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioNextClientCodegen.java
@@ -20,6 +20,7 @@ import com.google.common.collect.Sets;
import io.swagger.v3.oas.models.media.Schema;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.*;
+import org.openapitools.codegen.config.GlobalSettings;
import org.openapitools.codegen.meta.GeneratorMetadata;
import org.openapitools.codegen.meta.Stability;
import org.openapitools.codegen.meta.features.ClientModificationFeature;
@@ -317,13 +318,23 @@ public class DartDioNextClientCodegen extends AbstractDartCodegen {
for (CodegenOperation op : operationList) {
for (CodegenParameter param : op.allParams) {
if (((op.isMultipart && param.isFormParam) || param.isBodyParam) && (param.isBinary || param.isFile)) {
- param.baseType = "MultipartFile";
- param.dataType = "MultipartFile";
+ param.dataType = param.dataType.replace("Uint8List", "MultipartFile");
+ param.baseType = param.baseType.replace("Uint8List", "MultipartFile");
op.imports.add("MultipartFile");
+
+ if (SERIALIZATION_LIBRARY_BUILT_VALUE.equals(library)) {
+ boolean skipFormModel = Boolean.parseBoolean(GlobalSettings.getProperty(CodegenConstants.SKIP_FORM_MODEL, "true"));
+ if (param.isFormParam && param.isContainer && !skipFormModel) {
+ // Because of skipFormModel=false, there is a model class generated which has
+ // "BuiltList" as property and it requires the correct
+ // serializer imports to be added in order to compile.
+ addBuiltValueSerializerImport("Uint8List");
+ }
+ }
}
}
- // the MultipartFile handling above changes the type of some parameters from
+ // The MultipartFile handling above changes the type of some parameters from
// `UInt8List`, the default for files, to `MultipartFile`.
//
// The following block removes the required import for Uint8List if it is no
@@ -335,8 +346,10 @@ public class DartDioNextClientCodegen extends AbstractDartCodegen {
op.imports.remove("Uint8List");
}
- for (CodegenParameter param : op.bodyParams) {
- if (param.isContainer) {
+ for (CodegenParameter param : op.allParams) {
+ // Generate serializer factories for all container type parameters.
+ // But skip binary and file parameters, JSON serializers don't make sense there.
+ if (param.isContainer && !(param.isBinary || param.isFile )) {
final Map serializer = new HashMap<>();
serializer.put("isArray", param.isArray);
serializer.put("uniqueItems", param.uniqueItems);
@@ -351,7 +364,9 @@ public class DartDioNextClientCodegen extends AbstractDartCodegen {
resultImports.add("package:" + pubName + "/src/api_util.dart");
}
- if (op.returnContainer != null) {
+ // Generate serializer factories for response types.
+ // But skip binary and file response, JSON serializers don't make sense there.
+ if (op.returnContainer != null && !(op.isResponseBinary || op.isResponseFile)) {
final Map serializer = new HashMap<>();
serializer.put("isArray", Objects.equals("array", op.returnContainer) || Objects.equals("set", op.returnContainer));
serializer.put("uniqueItems", op.uniqueItems);
@@ -367,6 +382,14 @@ public class DartDioNextClientCodegen extends AbstractDartCodegen {
return objs;
}
+ private void addBuiltValueSerializerImport(String type) {
+ additionalProperties.compute("builtValueSerializerImports", (k, v) -> {
+ Set imports = v == null ? Sets.newHashSet() : ((Set) v);
+ imports.addAll(rewriteImports(Sets.newHashSet(type), true));
+ return imports;
+ });
+ }
+
private Set rewriteImports(Set originalImports, boolean isModel) {
Set resultImports = Sets.newHashSet();
for (String modelImport : originalImports) {
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoClientCodegen.java
index 11861b57924..60c0d9117db 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoClientCodegen.java
@@ -49,6 +49,9 @@ public class GoClientCodegen extends AbstractGoCodegen {
protected boolean isGoSubmodule = false;
protected boolean useOneOfDiscriminatorLookup = false; // use oneOf discriminator's mapping for model lookup
+ // A cache to efficiently lookup schema `toModelName()` based on the schema Key
+ private Map schemaKeyToModelNameCache = new HashMap<>();
+
public GoClientCodegen() {
super();
@@ -312,8 +315,14 @@ public class GoClientCodegen extends AbstractGoCodegen {
@Override
public String toModelName(String name) {
+ if (schemaKeyToModelNameCache.containsKey(name)) {
+ return schemaKeyToModelNameCache.get(name);
+ }
+
// underscoring would also lowercase the whole name, thus losing acronyms which are in capitals
- return camelize(toModel(name, false));
+ String camelizedName = camelize(toModel(name, false));
+ schemaKeyToModelNameCache.put(name, camelizedName);
+ return camelizedName;
}
public String escapeReservedWord(String name) {
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoServerCodegen.java
index 49ab62e2b68..5f9734460f8 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoServerCodegen.java
@@ -244,6 +244,7 @@ public class GoServerCodegen extends AbstractGoCodegen {
supportingFiles.add(new SupportingFile("impl.mustache",sourceFolder, "impl.go"));
supportingFiles.add(new SupportingFile("helpers.mustache", sourceFolder, "helpers.go"));
supportingFiles.add(new SupportingFile("api.mustache", sourceFolder, "api.go"));
+ supportingFiles.add(new SupportingFile("error.mustache", sourceFolder, "error.go"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")
.doNotOverwrite());
}
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaJerseyServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaJerseyServerCodegen.java
index 10e354d6f7f..57ad135e867 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaJerseyServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaJerseyServerCodegen.java
@@ -126,6 +126,9 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen {
supportingFiles.add(new SupportingFile("web.mustache", ("src/main/webapp/WEB-INF"), "web.xml")
.doNotOverwrite());
supportingFiles.add(new SupportingFile("StringUtil.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "StringUtil.java"));
+
+ // JsonNullable is not implemented for this generator
+ openApiNullable = false;
}
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaMicronautClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaMicronautClientCodegen.java
new file mode 100644
index 00000000000..df5073d8d92
--- /dev/null
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaMicronautClientCodegen.java
@@ -0,0 +1,339 @@
+package org.openapitools.codegen.languages;
+
+import org.openapitools.codegen.CliOption;
+import org.openapitools.codegen.CodegenConstants;
+import org.openapitools.codegen.CodegenType;
+import org.openapitools.codegen.SupportingFile;
+import org.openapitools.codegen.languages.features.BeanValidationFeatures;
+import org.openapitools.codegen.meta.GeneratorMetadata;
+import org.openapitools.codegen.meta.Stability;
+import org.openapitools.codegen.meta.features.DocumentationFeature;
+import org.openapitools.codegen.meta.features.SecurityFeature;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Arrays;
+import java.util.EnumSet;
+import java.util.HashMap;
+
+import static org.openapitools.codegen.CodegenConstants.INVOKER_PACKAGE;
+
+
+public class JavaMicronautClientCodegen extends AbstractJavaCodegen implements BeanValidationFeatures {
+
+ private final Logger LOGGER = LoggerFactory.getLogger(JavaClientCodegen.class);
+
+ public static final String OPT_TITLE = "title";
+ public static final String OPT_CONFIG_PACKAGE = "configPackage";
+ public static final String OPT_CONFIGURE_AUTH = "configureAuth";
+ public static final String OPT_BUILD = "build";
+ public static final String OPT_BUILD_GRADLE = "gradle";
+ public static final String OPT_BUILD_MAVEN = "maven";
+ public static final String OPT_BUILD_ALL = "all";
+ public static final String OPT_TEST = "test";
+ public static final String OPT_TEST_JUNIT = "junit";
+ public static final String OPT_TEST_SPOCK = "spock";
+
+ public static final String NAME = "java-micronaut-client";
+
+ protected String title;
+ protected String configPackage;
+ protected boolean useBeanValidation;
+ protected boolean configureAuthorization;
+ protected String buildTool;
+ protected String testTool;
+
+ public JavaMicronautClientCodegen() {
+ super();
+
+ title = "OpenAPI Micronaut Client";
+ invokerPackage = "org.openapitools";
+ configPackage = "org.openapitools.configuration";
+ useBeanValidation = true;
+ configureAuthorization = false;
+ buildTool = OPT_BUILD_ALL;
+ testTool = OPT_TEST_JUNIT;
+
+ modifyFeatureSet(features -> features
+ .includeDocumentationFeatures(
+ DocumentationFeature.Readme
+ )
+ .securityFeatures(EnumSet.of(
+ SecurityFeature.ApiKey,
+ SecurityFeature.BasicAuth,
+ SecurityFeature.OAuth2_Implicit,
+ SecurityFeature.OAuth2_AuthorizationCode,
+ SecurityFeature.OAuth2_ClientCredentials,
+ SecurityFeature.OAuth2_Password,
+ SecurityFeature.OpenIDConnect
+ ))
+ );
+
+ generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata)
+ .stability(Stability.BETA)
+ .build();
+
+ outputFolder = "generated-code/java-micronaut-client";
+ embeddedTemplateDir = templateDir = "java-micronaut-client";
+ apiPackage = "org.openapitools.api";
+ modelPackage = "org.openapitools.model";
+ invokerPackage = "org.openapitools";
+ artifactId = "openapi-micronaut";
+
+ updateOption(INVOKER_PACKAGE, this.getInvokerPackage());
+ updateOption(CodegenConstants.ARTIFACT_ID, this.getArtifactId());
+ updateOption(CodegenConstants.API_PACKAGE, apiPackage);
+ updateOption(CodegenConstants.MODEL_PACKAGE, modelPackage);
+
+ apiTestTemplateFiles.clear();
+
+ additionalProperties.put("jackson", "true");
+ additionalProperties.put("openbrace", "{");
+ additionalProperties.put("closebrace", "}");
+
+ cliOptions.add(new CliOption(OPT_TITLE, "Client service name").defaultValue(title));
+ cliOptions.add(new CliOption(OPT_CONFIG_PACKAGE, "Configuration package for generated code").defaultValue(configPackage));
+ cliOptions.add(CliOption.newBoolean(OPT_CONFIGURE_AUTH, "Configure all the authorization methods as specified in the file", configureAuthorization));
+ cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations", useBeanValidation));
+
+ CliOption buildToolOption = new CliOption(OPT_BUILD, "Specify for which build tool to generate files").defaultValue(buildTool);
+ buildToolOption.setEnum(new HashMap() {{
+ put(OPT_BUILD_GRADLE, "Gradle configuration is generated for the project");
+ put(OPT_BUILD_MAVEN, "Maven configuration is generated for the project");
+ put(OPT_BUILD_ALL, "Both Gradle and Maven configurations are generated");
+ }});
+ cliOptions.add(buildToolOption);
+
+ CliOption testToolOption = new CliOption(OPT_TEST, "Specify which test tool to generate files for").defaultValue(testTool);
+ testToolOption.setEnum(new HashMap() {{
+ put(OPT_TEST_JUNIT, "Use JUnit as test tool");
+ put(OPT_TEST_SPOCK, "Use Spock as test tool");
+ }});
+ cliOptions.add(testToolOption);
+
+ // Remove the date library option
+ cliOptions.stream().filter(o -> o.getOpt().equals("dateLibrary")).findFirst()
+ .ifPresent(v -> cliOptions.remove(v));
+
+ // Add reserved words
+ String[] reservedWordsArray = new String[]{
+ "client", "format", "queryvalue", "queryparam", "pathvariable", "header", "cookie",
+ "authorization", "body", "application"
+ };
+ reservedWords.addAll(Arrays.asList(reservedWordsArray));
+ }
+
+ @Override
+ public CodegenType getTag() {
+ return CodegenType.CLIENT;
+ }
+
+ @Override
+ public String getName() {
+ return NAME;
+ }
+
+ @Override
+ public String getHelp() {
+ return "Generates a Java Micronaut Client.";
+ }
+
+ @Override
+ public void processOpts() {
+ super.processOpts();
+
+ // Get properties
+ if (additionalProperties.containsKey(OPT_TITLE)) {
+ this.title = (String) additionalProperties.get(OPT_TITLE);
+ }
+
+ if (additionalProperties.containsKey(OPT_CONFIG_PACKAGE)) {
+ configPackage = (String) additionalProperties.get(OPT_CONFIG_PACKAGE);
+ } else {
+ additionalProperties.put(OPT_CONFIG_PACKAGE, configPackage);
+ }
+
+ if (additionalProperties.containsKey(INVOKER_PACKAGE)) {
+ invokerPackage = (String) additionalProperties.get(INVOKER_PACKAGE);
+ } else {
+ additionalProperties.put(INVOKER_PACKAGE, invokerPackage);
+ }
+
+ // Get boolean properties
+ if (additionalProperties.containsKey(USE_BEANVALIDATION)) {
+ this.setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION));
+ }
+ writePropertyBack(USE_BEANVALIDATION, useBeanValidation);
+
+ if (additionalProperties.containsKey(OPT_CONFIGURE_AUTH)) {
+ this.configureAuthorization = convertPropertyToBoolean(OPT_CONFIGURE_AUTH);
+ }
+ writePropertyBack(OPT_CONFIGURE_AUTH, configureAuthorization);
+
+ // Get enum properties
+ if (additionalProperties.containsKey(OPT_BUILD)) {
+ switch ((String) additionalProperties.get(OPT_BUILD)) {
+ case OPT_BUILD_GRADLE:
+ case OPT_BUILD_MAVEN:
+ case OPT_BUILD_ALL:
+ this.buildTool = (String) additionalProperties.get(OPT_BUILD);
+ break;
+ default:
+ throw new RuntimeException("Build tool \"" + additionalProperties.get(OPT_BUILD) + "\" is not supported or misspelled.");
+ }
+ }
+ additionalProperties.put(OPT_BUILD, buildTool);
+
+ if (additionalProperties.containsKey(OPT_TEST)) {
+ switch ((String) additionalProperties.get(OPT_TEST)) {
+ case OPT_TEST_JUNIT:
+ case OPT_TEST_SPOCK:
+ this.testTool = (String) additionalProperties.get(OPT_TEST);
+ break;
+ default:
+ throw new RuntimeException("Test tool \"" + additionalProperties.get(OPT_TEST) + "\" is not supported or misspelled.");
+ }
+ }
+ additionalProperties.put(OPT_TEST, testTool);
+ if (testTool.equals(OPT_TEST_JUNIT)) {
+ additionalProperties.put("isTestJunit", true);
+ } else if (testTool.equals(OPT_TEST_SPOCK)) {
+ additionalProperties.put("isTestSpock", true);
+ }
+
+ final String invokerFolder = (sourceFolder + '/' + invokerPackage).replace(".", "/");
+ final String apiFolder = (sourceFolder + '/' + apiPackage).replace(".", "/");
+
+ // Add all the supporting files
+ String resourceFolder = projectFolder + "/resources";
+ supportingFiles.add(new SupportingFile("configuration/application.yml.mustache", resourceFolder, "application.yml").doNotOverwrite());
+
+ // Authorization files
+ if (configureAuthorization) {
+ final String authFolder = invokerFolder + "/auth";
+ supportingFiles.add(new SupportingFile("auth/Authorization.mustache", authFolder, "Authorization.java"));
+ supportingFiles.add(new SupportingFile("auth/AuthorizationBinder.mustache", authFolder, "AuthorizationBinder.java"));
+ supportingFiles.add(new SupportingFile("auth/Authorizations.mustache", authFolder, "Authorizations.java"));
+ supportingFiles.add(new SupportingFile("auth/AuthorizationFilter.mustache", authFolder, "AuthorizationFilter.java"));
+ final String authConfigurationFolder = authFolder + "/configuration";
+ supportingFiles.add(new SupportingFile("auth/configuration/ApiKeyAuthConfiguration.mustache", authConfigurationFolder, "ApiKeyAuthConfiguration.java"));
+ supportingFiles.add(new SupportingFile("auth/configuration/ConfigurableAuthorization.mustache", authConfigurationFolder, "ConfigurableAuthorization.java"));
+ supportingFiles.add(new SupportingFile("auth/configuration/HttpBasicAuthConfiguration.mustache", authConfigurationFolder, "HttpBasicAuthConfiguration.java"));
+ }
+
+ // Query files
+ final String queryFolder = invokerFolder + "/query";
+ supportingFiles.add(new SupportingFile("query/QueryParam.mustache", queryFolder, "QueryParam.java"));
+ supportingFiles.add(new SupportingFile("query/QueryParamBinder.mustache", queryFolder, "QueryParamBinder.java"));
+
+ if (buildTool.equals(OPT_BUILD_GRADLE) || buildTool.equals(OPT_BUILD_ALL)) {
+ // Gradle files
+ supportingFiles.add(new SupportingFile("configuration/gradle/build.gradle.mustache", "", "build.gradle").doNotOverwrite());
+ supportingFiles.add(new SupportingFile("configuration/gradle/settings.gradle.mustache", "", "settings.gradle").doNotOverwrite());
+ supportingFiles.add(new SupportingFile("configuration/gradle/gradle.properties.mustache", "", "gradle.properties").doNotOverwrite());
+
+ // Gradlew files
+ final String gradleWrapperFolder = "gradle/wrapper";
+ supportingFiles.add(new SupportingFile("configuration/gradlew/gradlew.mustache", "", "gradlew"));
+ supportingFiles.add(new SupportingFile("configuration/gradlew/gradlew.bat.mustache", "", "gradlew.bat"));
+ supportingFiles.add(new SupportingFile("configuration/gradlew/gradle-wrapper.properties.mustache", gradleWrapperFolder, "gradle-wrapper.properties"));
+ supportingFiles.add(new SupportingFile("configuration/gradlew/gradle-wrapper.jar", gradleWrapperFolder, "gradle-wrapper.jar"));
+ }
+
+ if (buildTool.equals(OPT_BUILD_MAVEN) || buildTool.equals(OPT_BUILD_ALL)) {
+ // Maven files
+ supportingFiles.add(new SupportingFile("configuration/pom.xml.mustache", "", "pom.xml").doNotOverwrite());
+
+ // Maven wrapper files
+ supportingFiles.add(new SupportingFile("configuration/mavenw/mvnw.mustache", "", "mvnw"));
+ supportingFiles.add(new SupportingFile("configuration/mavenw/mvnw.bat.mustache", "", "mvnw.bat"));
+ supportingFiles.add(new SupportingFile("configuration/mavenw/MavenWrapperDownloader.java.mustache", ".mvn/wrapper", "MavenWrapperDownloader.java"));
+ supportingFiles.add(new SupportingFile("configuration/mavenw/maven-wrapper.jar.mustache", ".mvn/wrapper", "maven-wrapper.jar"));
+ supportingFiles.add(new SupportingFile("configuration/mavenw/maven-wrapper.properties.mustache", ".mvn/wrapper", "maren-wrapper.properties"));
+ }
+
+ // Git files
+ supportingFiles.add(new SupportingFile("configuration/git/gitignore.mustache", "", ".gitignore").doNotOverwrite());
+
+ // Use the default java Date
+ typeMapping.put("date", "LocalDate");
+ typeMapping.put("DateTime", "LocalDateTime");
+ importMapping.put("LocalDate", "java.time.LocalDate");
+ importMapping.put("LocalDateTime", "java.time.LocalDateTime");
+
+ // Add documentation files
+ supportingFiles.add(new SupportingFile("doc/README.mustache", "", "README.md").doNotOverwrite());
+ supportingFiles.add(new SupportingFile("doc/auth.mustache", apiDocPath, "auth.md"));
+ modelDocTemplateFiles.put("doc/model_doc.mustache", ".md");
+ apiDocTemplateFiles.put("doc/api_doc.mustache", ".md");
+ modelDocTemplateFiles.remove("model_doc.mustache");
+ apiDocTemplateFiles.remove("api_doc.mustache");
+
+ // Add model files
+ modelTemplateFiles.remove("model.mustache");
+ modelTemplateFiles.put("model/model.mustache", ".java");
+
+ // Add test files
+ if (testTool.equals(OPT_TEST_JUNIT)) {
+ apiTestTemplateFiles.put("api_test.mustache", ".java");
+ modelTestTemplateFiles.put("model_test.mustache", ".java");
+ } else if (testTool.equals(OPT_TEST_SPOCK)) {
+ apiTestTemplateFiles.put("api_test.groovy.mustache", ".groovy");
+ modelTestTemplateFiles.put("model_test.groovy.mustache", ".groovy");
+ }
+ }
+
+ @Override
+ public String apiTestFileFolder() {
+ if (testTool.equals(OPT_TEST_SPOCK)) {
+ return getOutputDir() + "/src/test/groovy/" + getInvokerPackage().replaceAll("\\.", "/") + "/api";
+ }
+ return getOutputDir() + "/src/test/java/" + getInvokerPackage().replaceAll("\\.", "/") + "/api";
+ }
+
+ @Override
+ public String modelTestFileFolder() {
+ if (testTool.equals(OPT_TEST_SPOCK)) {
+ return getOutputDir() + "/src/test/groovy/" + getInvokerPackage().replaceAll("\\.", "/") + "/model";
+ }
+ return getOutputDir() + "/src/test/java/" + getInvokerPackage().replaceAll("\\.", "/") + "/model";
+ }
+
+ @Override
+ public String toApiTestFilename(String name) {
+ if (testTool.equals(OPT_TEST_SPOCK)) {
+ return toApiName(name) + "Spec";
+ }
+ return toApiName(name) + "Test";
+ }
+
+ @Override
+ public String toModelTestFilename(String name) {
+ if (testTool.equals(OPT_TEST_SPOCK)) {
+ return toModelName(name) + "Spec";
+ }
+ return toModelName(name) + "Test";
+ }
+
+ @Override
+ public void setUseBeanValidation(boolean useBeanValidation) {
+ this.useBeanValidation = useBeanValidation;
+ }
+
+ @Override
+ public String toApiVarName(String name) {
+ String apiVarName = super.toApiVarName(name);
+ if (reservedWords.contains(apiVarName)) {
+ apiVarName = escapeReservedWord(apiVarName);
+ }
+ return apiVarName;
+ }
+
+ public boolean isUseBeanValidation() {
+ return useBeanValidation;
+ }
+
+ public boolean isConfigureAuthorization() {
+ return configureAuthorization;
+ }
+}
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java
index 1b71f1a9e27..18609546f8f 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java
@@ -17,21 +17,12 @@
package org.openapitools.codegen.languages;
-import static java.util.Collections.sort;
-
import org.apache.commons.lang3.StringUtils;
-import org.openapitools.codegen.CliOption;
-import org.openapitools.codegen.CodegenConstants;
-import org.openapitools.codegen.CodegenModel;
-import org.openapitools.codegen.CodegenOperation;
-import org.openapitools.codegen.CodegenParameter;
-import org.openapitools.codegen.CodegenProperty;
-import org.openapitools.codegen.CodegenType;
-import org.openapitools.codegen.SupportingFile;
+import org.openapitools.codegen.*;
import org.openapitools.codegen.meta.features.*;
+import org.openapitools.codegen.utils.ProcessUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.openapitools.codegen.utils.ProcessUtils;
import java.io.File;
import java.util.HashMap;
@@ -40,6 +31,8 @@ import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
+import static java.util.Collections.sort;
+
public class KotlinClientCodegen extends AbstractKotlinCodegen {
private final Logger LOGGER = LoggerFactory.getLogger(KotlinClientCodegen.class);
@@ -204,8 +197,8 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen {
requestDateConverter.setDefault(this.requestDateConverter);
cliOptions.add(requestDateConverter);
- cliOptions.add(CliOption.newBoolean(USE_RX_JAVA, "Whether to use the RxJava adapter with the retrofit2 library."));
- cliOptions.add(CliOption.newBoolean(USE_RX_JAVA2, "Whether to use the RxJava2 adapter with the retrofit2 library."));
+ cliOptions.add(CliOption.newBoolean(USE_RX_JAVA, "Whether to use the RxJava adapter with the retrofit2 library. IMPORTANT: this option has been deprecated. Please use `useRxJava3` instead."));
+ cliOptions.add(CliOption.newBoolean(USE_RX_JAVA2, "Whether to use the RxJava2 adapter with the retrofit2 library. IMPORTANT: this option has been deprecated. Please use `useRxJava3` instead."));
cliOptions.add(CliOption.newBoolean(USE_RX_JAVA3, "Whether to use the RxJava3 adapter with the retrofit2 library."));
cliOptions.add(CliOption.newBoolean(USE_COROUTINES, "Whether to use the Coroutines adapter with the retrofit2 library."));
@@ -378,7 +371,7 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen {
additionalProperties.put("isList", true);
}
- if(usesRetrofit2Library()) {
+ if (usesRetrofit2Library()) {
if (ProcessUtils.hasOAuthMethods(openAPI)) {
supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.kt.mustache", authFolder, "ApiKeyAuth.kt"));
supportingFiles.add(new SupportingFile("auth/OAuth.kt.mustache", authFolder, "OAuth.kt"));
@@ -386,11 +379,11 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen {
supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.kt.mustache", authFolder, "OAuthOkHttpClient.kt"));
}
- if(ProcessUtils.hasHttpBearerMethods(openAPI)) {
+ if (ProcessUtils.hasHttpBearerMethods(openAPI)) {
supportingFiles.add(new SupportingFile("auth/HttpBearerAuth.kt.mustache", authFolder, "HttpBearerAuth.kt"));
}
- if(ProcessUtils.hasHttpBasicMethods(openAPI)) {
+ if (ProcessUtils.hasHttpBasicMethods(openAPI)) {
supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.kt.mustache", authFolder, "HttpBasicAuth.kt"));
}
}
@@ -591,7 +584,7 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen {
private void commonSupportingFiles() {
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
- if(getLibrary().equals(MULTIPLATFORM)) {
+ if (getLibrary().equals(MULTIPLATFORM)) {
supportingFiles.add(new SupportingFile("build.gradle.kts.mustache", "", "build.gradle.kts"));
supportingFiles.add(new SupportingFile("settings.gradle.kts.mustache", "", "settings.gradle.kts"));
} else {
@@ -677,7 +670,7 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen {
if (one.isPathParam && another.isQueryParam) {
return -1;
}
- if (one.isQueryParam && another.isPathParam){
+ if (one.isQueryParam && another.isPathParam) {
return 1;
}
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpDataTransferClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpDataTransferClientCodegen.java
new file mode 100644
index 00000000000..38fc3332ee1
--- /dev/null
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpDataTransferClientCodegen.java
@@ -0,0 +1,453 @@
+/*
+ * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
+ * Copyright 2018 SmartBear Software
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.openapitools.codegen.languages;
+
+import io.swagger.v3.oas.models.OpenAPI;
+import io.swagger.v3.oas.models.Operation;
+import io.swagger.v3.oas.models.PathItem;
+import io.swagger.v3.oas.models.PathItem.HttpMethod;
+import io.swagger.v3.oas.models.Paths;
+import io.swagger.v3.oas.models.media.*;
+import io.swagger.v3.oas.models.parameters.Parameter;
+import io.swagger.v3.oas.models.parameters.RequestBody;
+import io.swagger.v3.oas.models.responses.ApiResponse;
+import io.swagger.v3.oas.models.responses.ApiResponses;
+import org.openapitools.codegen.CodegenConstants;
+import org.openapitools.codegen.CodegenOperation;
+import org.openapitools.codegen.CodegenType;
+import org.openapitools.codegen.SupportingFile;
+import org.openapitools.codegen.meta.GeneratorMetadata;
+import org.openapitools.codegen.meta.Stability;
+import org.openapitools.codegen.meta.features.*;
+import org.openapitools.codegen.utils.ModelUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+import java.util.*;
+
+public class PhpDataTransferClientCodegen extends AbstractPhpCodegen {
+ private final Logger LOGGER = LoggerFactory.getLogger(PhpDataTransferClientCodegen.class);
+ // Custom generator option names
+ public static final String OPT_MODERN = "modern";
+ // Internal vendor extension names for extra template data that should not be set in specification
+ public static final String VEN_PARAMETER_LOCATION = "internal.parameterLocation";
+ public static final String VEN_FROM_PARAMETERS = "internal.fromParameters";
+ public static final String VEN_COLLECTION_FORMAT = "internal.collectionFormat";
+ public static final String VEN_PARAMETER_DATA_TYPE = "internal.parameterDataType";
+ public static final String VEN_HAS_PARAMETER_DATA = "internal.hasParameterData";
+ public static final String VEN_FROM_CONTAINER = "internal.fromContainer";
+ public static final String VEN_CONTAINER_DATA_TYPE = "internal.containerDataType";
+
+ private boolean useModernSyntax = false;
+
+ @Override
+ public CodegenType getTag() {
+ return CodegenType.CLIENT;
+ }
+
+ @Override
+ public String getName() {
+ return "php-dt";
+ }
+
+ @Override
+ public String getHelp() {
+ return "Generates a PHP client relying on Data Transfer ( https://github.com/Articus/DataTransfer ) and compliant with PSR-7, PSR-11, PSR-17 and PSR-18.";
+ }
+
+ public PhpDataTransferClientCodegen() {
+ super();
+ modifyFeatureSet(features -> features
+ .includeDocumentationFeatures(DocumentationFeature.Readme)
+ .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON))
+ .securityFeatures(EnumSet.noneOf(SecurityFeature.class))
+ .excludeGlobalFeatures(
+ GlobalFeature.XMLStructureDefinitions,
+ GlobalFeature.Callbacks,
+ GlobalFeature.LinkObjects,
+ GlobalFeature.ParameterStyling
+ )
+ .excludeSchemaSupportFeatures(
+ SchemaSupportFeature.Polymorphism
+ )
+ );
+
+ generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata)
+ .stability(Stability.BETA)
+ .build();
+
+ //no point to use double - http://php.net/manual/en/language.types.float.php , especially because of PHP 7+ float type declaration
+ typeMapping.put("double", "float");
+
+ apiTemplateFiles.clear();
+ apiTestTemplateFiles.clear();
+ apiDocTemplateFiles.clear();
+ modelTestTemplateFiles.clear();
+ modelDocTemplateFiles.clear();
+
+ additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, "1.0.0");
+ //Register custom CLI options
+ addSwitch(OPT_MODERN, "use modern language features (generated code will require PHP 8.0)", useModernSyntax);
+ }
+
+ @Override
+ public void processOpts() {
+ setSrcBasePath("src");
+ //Preserve and process options mangled in parent class
+ String rootNamespace = "App";
+ if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) {
+ rootNamespace = (String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE);
+ }
+ String modelNamespace = rootNamespace + "\\DTO";
+ if (additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) {
+ modelNamespace = (String) additionalProperties.get(CodegenConstants.MODEL_PACKAGE);
+ }
+ super.processOpts();
+ //Restore mangled options
+ setInvokerPackage(rootNamespace);
+ additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, rootNamespace);
+ setModelPackage(modelNamespace);
+ additionalProperties.put(CodegenConstants.MODEL_PACKAGE, modelNamespace);
+ //Process custom options
+ if (additionalProperties.containsKey(OPT_MODERN)) {
+ embeddedTemplateDir = templateDir = "php-dt-modern";
+ useModernSyntax = true;
+ } else {
+ embeddedTemplateDir = templateDir = "php-dt";
+ }
+
+ supportingFiles.add(new SupportingFile("composer.json.mustache", "", "composer.json"));
+ supportingFiles.add(new SupportingFile("ApiClient.php.mustache", toSrcPath(invokerPackage, srcBasePath), "ApiClient.php"));
+ supportingFiles.add(new SupportingFile("ApiClientFactory.php.mustache", toSrcPath(invokerPackage, srcBasePath), "ApiClientFactory.php"));
+ supportingFiles.add(new SupportingFile("README.md.mustache", "", "README.md"));
+ }
+
+ @Override
+ public String toSrcPath(String packageName, String basePath) {
+ return basePath + File.separator + packageName.replace("\\", File.separator);
+ }
+
+ @Override
+ public String toApiName(String name) {
+ return super.toApiName(toModelName(name));
+ }
+
+ @Override
+ public String getTypeDeclaration(Schema p) {
+ String result;
+ Map extensions = p.getExtensions();
+ if ((extensions != null) && extensions.containsKey(VEN_CONTAINER_DATA_TYPE)) {
+ result = (String) extensions.get(VEN_CONTAINER_DATA_TYPE);
+ } else if (useModernSyntax && (ModelUtils.isArraySchema(p) || ModelUtils.isMapSchema(p))) {
+ result = "array";
+ } else {
+ result = super.getTypeDeclaration(p);
+ }
+ return result;
+ }
+
+ @Override
+ public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) {
+ //Do not use tags for operation grouping
+ super.addOperationToGroup("", resourcePath, operation, co, operations);
+ }
+
+ @Override
+ protected String getContentType(RequestBody requestBody) {
+ //Awfully nasty workaround to skip formParams generation
+ return null;
+ }
+
+ @Override
+ public void preprocessOpenAPI(OpenAPI openAPI) {
+ super.preprocessOpenAPI(openAPI);
+
+ generateParameterSchemas(openAPI);
+ generateContainerSchemas(openAPI);
+ }
+
+ @Override
+ public void processOpenAPI(OpenAPI openAPI) {
+ super.processOpenAPI(openAPI);
+
+ quoteMediaTypes(openAPI);
+ }
+
+ /**
+ * Generate additional model definitions from query parameters
+ *
+ * @param openAPI OpenAPI object
+ */
+ protected void generateParameterSchemas(OpenAPI openAPI) {
+ Map paths = openAPI.getPaths();
+ if (paths != null) {
+ for (String pathname : paths.keySet()) {
+ PathItem path = paths.get(pathname);
+ Map operationMap = path.readOperationsMap();
+ if (operationMap != null) {
+ for (HttpMethod method : operationMap.keySet()) {
+ Operation operation = operationMap.get(method);
+ Map propertySchemas = new HashMap<>();
+ if (operation == null || operation.getParameters() == null) {
+ continue;
+ }
+
+ List requiredProperties = new ArrayList<>();
+ for (Parameter parameter : operation.getParameters()) {
+ Parameter referencedParameter = ModelUtils.getReferencedParameter(openAPI, parameter);
+ Schema propertySchema = convertParameterToSchema(openAPI, referencedParameter);
+ if (propertySchema != null) {
+ propertySchemas.put(propertySchema.getName(), propertySchema);
+ if (Boolean.TRUE.equals(referencedParameter.getRequired())) {
+ requiredProperties.add(propertySchema.getName());
+ }
+ }
+ }
+
+ if (!propertySchemas.isEmpty()) {
+ ObjectSchema schema = new ObjectSchema();
+ String operationId = getOrGenerateOperationId(operation, pathname, method.name());
+ schema.setDescription("Parameters for " + operationId);
+ schema.setProperties(propertySchemas);
+ schema.setRequired(requiredProperties);
+ addInternalExtensionToSchema(schema, VEN_FROM_PARAMETERS, Boolean.TRUE);
+ String schemaName = generateUniqueSchemaName(openAPI, operationId + "ParameterData");
+ openAPI.getComponents().addSchemas(schemaName, schema);
+ String schemaDataType = getTypeDeclaration(toModelName(schemaName));
+ addInternalExtensionToOperation(operation, VEN_PARAMETER_DATA_TYPE, schemaDataType);
+ addInternalExtensionToOperation(operation, VEN_HAS_PARAMETER_DATA, Boolean.TRUE);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ protected Schema convertParameterToSchema(OpenAPI openAPI, Parameter parameter) {
+ Schema property = null;
+
+ Schema parameterSchema = ModelUtils.getReferencedSchema(openAPI, parameter.getSchema());
+ // array
+ if (ModelUtils.isArraySchema(parameterSchema)) {
+ Schema itemSchema = ((ArraySchema) parameterSchema).getItems();
+ ArraySchema arraySchema = new ArraySchema();
+ arraySchema.setMinItems(parameterSchema.getMinItems());
+ arraySchema.setMaxItems(parameterSchema.getMaxItems());
+ arraySchema.setItems(itemSchema);
+ String collectionFormat = getCollectionFormat(parameter);
+ if (collectionFormat == null) {
+ collectionFormat = "csv";
+ }
+ addInternalExtensionToSchema(arraySchema, VEN_COLLECTION_FORMAT, collectionFormat);
+ property = arraySchema;
+ } else { // non-array e.g. string, integer
+ switch (parameterSchema.getType()) {
+ case "string":
+ StringSchema stringSchema = new StringSchema();
+ stringSchema.setMinLength(parameterSchema.getMinLength());
+ stringSchema.setMaxLength(parameterSchema.getMaxLength());
+ stringSchema.setPattern(parameterSchema.getPattern());
+ stringSchema.setEnum(parameterSchema.getEnum());
+ property = stringSchema;
+ break;
+ case "integer":
+ IntegerSchema integerSchema = new IntegerSchema();
+ integerSchema.setMinimum(parameterSchema.getMinimum());
+ integerSchema.setMaximum(parameterSchema.getMaximum());
+ property = integerSchema;
+ break;
+ case "number":
+ NumberSchema floatSchema = new NumberSchema();
+ floatSchema.setMinimum(parameterSchema.getMinimum());
+ floatSchema.setMaximum(parameterSchema.getMaximum());
+ property = floatSchema;
+ break;
+ case "boolean":
+ property = new BooleanSchema();
+ break;
+ case "date":
+ property = new DateSchema();
+ break;
+ case "date-time":
+ property = new DateTimeSchema();
+ break;
+ }
+ }
+
+ if (property != null) {
+ property.setName(parameter.getName());
+ property.setDescription(parameter.getDescription());
+ addInternalExtensionToSchema(property, VEN_PARAMETER_LOCATION, parameter.getIn());
+ }
+ return property;
+ }
+
+ protected void addInternalExtensionToSchema(Schema schema, String name, Object value) {
+ //Add internal extension directly, because addExtension filters extension names
+ if (schema.getExtensions() == null) {
+ schema.setExtensions(new HashMap<>());
+ }
+ schema.getExtensions().put(name, value);
+ }
+
+ protected void addInternalExtensionToOperation(Operation operation, String name, Object value) {
+ //Add internal extension directly, because addExtension filters extension names
+ if (operation.getExtensions() == null) {
+ operation.setExtensions(new HashMap<>());
+ }
+ operation.getExtensions().put(name, value);
+ }
+
+ protected String generateUniqueSchemaName(OpenAPI openAPI, String name) {
+ String result = name;
+ if (openAPI.getComponents().getSchemas() != null) {
+ int count = 1;
+ while (openAPI.getComponents().getSchemas().containsKey(result)) {
+ result = name + "_" + count;
+ count += 1;
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Generate additional model definitions for containers in whole specification
+ *
+ * @param openAPI OpenAPI object
+ */
+ protected void generateContainerSchemas(OpenAPI openAPI) {
+ Paths paths = openAPI.getPaths();
+ for (String pathName : paths.keySet()) {
+ for (Operation operation : paths.get(pathName).readOperations()) {
+ List parameters = operation.getParameters();
+ if (parameters != null) {
+ for (Parameter parameter : parameters) {
+ generateContainerSchemas(openAPI, ModelUtils.getReferencedParameter(openAPI, parameter).getSchema());
+ }
+ }
+ RequestBody requestBody = ModelUtils.getReferencedRequestBody(openAPI, operation.getRequestBody());
+ if (requestBody != null) {
+ Content requestBodyContent = requestBody.getContent();
+ if (requestBodyContent != null) {
+ for (String mediaTypeName : requestBodyContent.keySet()) {
+ generateContainerSchemas(openAPI, requestBodyContent.get(mediaTypeName).getSchema());
+ }
+ }
+ }
+ ApiResponses responses = operation.getResponses();
+ for (String responseCode : responses.keySet()) {
+ ApiResponse response = ModelUtils.getReferencedApiResponse(openAPI, responses.get(responseCode));
+ Content responseContent = response.getContent();
+ if (responseContent != null) {
+ for (String mediaTypeName : responseContent.keySet()) {
+ generateContainerSchemas(openAPI, responseContent.get(mediaTypeName).getSchema());
+ }
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Generate additional model definitions for containers in specified schema
+ *
+ * @param openAPI OpenAPI object
+ * @param schema OAS schema to process
+ */
+ protected void generateContainerSchemas(OpenAPI openAPI, Schema schema) {
+ if (schema != null) {
+ //Dereference schema
+ schema = ModelUtils.getReferencedSchema(openAPI, schema);
+ Boolean isContainer = Boolean.FALSE;
+
+ if (ModelUtils.isObjectSchema(schema)) {
+ //Recursively process all schemas of object properties
+ Map properties = schema.getProperties();
+ if (properties != null) {
+ for (String propertyName : properties.keySet()) {
+ generateContainerSchemas(openAPI, properties.get(propertyName));
+ }
+ }
+ } else if (ModelUtils.isArraySchema(schema)) {
+ //Recursively process schema of array items
+ generateContainerSchemas(openAPI, ((ArraySchema) schema).getItems());
+ isContainer = Boolean.TRUE;
+ } else if (ModelUtils.isMapSchema(schema)) {
+ //Recursively process schema of map items
+ Object itemSchema = schema.getAdditionalProperties();
+ if (itemSchema instanceof Schema) {
+ generateContainerSchemas(openAPI, (Schema) itemSchema);
+ }
+ isContainer = Boolean.TRUE;
+ }
+
+ if (isContainer) {
+ //Generate special component schema for container
+ String containerSchemaName = generateUniqueSchemaName(openAPI, "Collection");
+ Schema containerSchema = new ObjectSchema();
+ containerSchema.addProperties("inner", schema);
+ addInternalExtensionToSchema(containerSchema, VEN_FROM_CONTAINER, Boolean.TRUE);
+ openAPI.getComponents().addSchemas(containerSchemaName, containerSchema);
+ String containerDataType = getTypeDeclaration(toModelName(containerSchemaName));
+ addInternalExtensionToSchema(schema, VEN_CONTAINER_DATA_TYPE, containerDataType);
+ }
+ }
+ }
+
+ /**
+ * Awfully nasty workaround - add quotation marks for all media types to prevent special treatment of form media types
+ * in org/openapitools/codegen/DefaultGenerator.java:873
+ * TODO find a better way to prevent special form media type treatment
+ *
+ * @param openAPI OpenAPI object
+ */
+ protected void quoteMediaTypes(OpenAPI openAPI) {
+ Map paths = openAPI.getPaths();
+ if (paths != null) {
+ for (String pathname : paths.keySet()) {
+ PathItem path = paths.get(pathname);
+ List operations = path.readOperations();
+ if (operations != null) {
+ for (Operation operation : operations) {
+ RequestBody requestBody = ModelUtils.getReferencedRequestBody(openAPI, operation.getRequestBody());
+ if (requestBody != null) {
+ requestBody.setContent(copyWithQuotedMediaTypes(requestBody.getContent()));
+ }
+ ApiResponses responses = operation.getResponses();
+ for (String responseCode : responses.keySet()) {
+ ApiResponse response = ModelUtils.getReferencedApiResponse(openAPI, responses.get(responseCode));
+ response.setContent(copyWithQuotedMediaTypes(response.getContent()));
+ }
+ }
+ }
+ }
+ }
+ }
+
+ protected Content copyWithQuotedMediaTypes(Content content) {
+ Content result = null;
+ if (content != null) {
+ result = new Content();
+ for (String mediaType : content.keySet()) {
+ result.addMediaType("'" + mediaType + "'", content.get(mediaType));
+ }
+ }
+ return result;
+ }
+}
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSymfonyServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSymfonyServerCodegen.java
index f3324629b45..74490df3422 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSymfonyServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSymfonyServerCodegen.java
@@ -412,17 +412,17 @@ public class PhpSymfonyServerCodegen extends AbstractPhpCodegen implements Codeg
}
// Create a variable to display the correct data type in comments for interfaces
- param.vendorExtensions.put("x-comment-type", param.dataType);
+ param.vendorExtensions.put("x-comment-type", "\\" + param.dataType);
if (param.isContainer) {
- param.vendorExtensions.put("x-comment-type", param.dataType + "[]");
+ param.vendorExtensions.put("x-comment-type", "\\" + param.dataType + "[]");
}
}
// Create a variable to display the correct return type in comments for interfaces
if (op.returnType != null) {
- op.vendorExtensions.put("x-comment-type", op.returnType);
+ op.vendorExtensions.put("x-comment-type", "\\" + op.returnType);
if ("array".equals(op.returnContainer)) {
- op.vendorExtensions.put("x-comment-type", op.returnType + "[]");
+ op.vendorExtensions.put("x-comment-type", "\\" + op.returnType + "[]");
}
} else {
op.vendorExtensions.put("x-comment-type", "void");
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptClientCodegen.java
index 821d190f5eb..38c009f47b3 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptClientCodegen.java
@@ -17,6 +17,13 @@
package org.openapitools.codegen.languages;
+import com.google.common.collect.Sets;
+
+import io.swagger.v3.core.util.Json;
+import io.swagger.v3.oas.models.media.*;
+import io.swagger.v3.oas.models.media.MediaType;
+import io.swagger.v3.oas.models.parameters.RequestBody;
+import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.ComposedSchema;
@@ -24,13 +31,22 @@ import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.Parameter;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.*;
+import org.openapitools.codegen.CodegenDiscriminator.MappedModel;
import org.openapitools.codegen.meta.GeneratorMetadata;
import org.openapitools.codegen.meta.Stability;
import org.openapitools.codegen.utils.ModelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import com.github.curiousoddman.rgxgen.RgxGen;
+import com.github.curiousoddman.rgxgen.config.RgxGenOption;
+import com.github.curiousoddman.rgxgen.config.RgxGenProperties;
import java.io.File;
+import java.time.OffsetDateTime;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+import java.util.regex.Pattern;
+import java.util.regex.Matcher;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
@@ -38,6 +54,8 @@ import java.util.stream.Collectors;
import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
+import static org.openapitools.codegen.utils.OnceLogger.once;
+
public class TypeScriptClientCodegen extends DefaultCodegen implements CodegenConfig {
private final Logger LOGGER = LoggerFactory.getLogger(TypeScriptClientCodegen.class);
@@ -80,6 +98,9 @@ public class TypeScriptClientCodegen extends DefaultCodegen implements CodegenCo
protected String modelPropertyNaming = "camelCase";
protected HashSet languageGenericTypes;
+ private DateTimeFormatter iso8601Date = DateTimeFormatter.ISO_DATE;
+ private DateTimeFormatter iso8601DateTime = DateTimeFormatter.ISO_DATE_TIME;
+
public TypeScriptClientCodegen() {
super();
@@ -156,6 +177,7 @@ public class TypeScriptClientCodegen extends DefaultCodegen implements CodegenCo
typeMapping.put("ByteArray", "string");
typeMapping.put("UUID", "string");
typeMapping.put("Error", "Error");
+ typeMapping.put("AnyType", "any");
cliOptions.add(new CliOption(NPM_NAME, "The name under which you want to publish generated npm package." +
@@ -218,6 +240,7 @@ public class TypeScriptClientCodegen extends DefaultCodegen implements CodegenCo
supportingFiles.add(new SupportingFile("api" + File.separator + "middleware.mustache", "", "middleware.ts"));
supportingFiles.add(new SupportingFile("api" + File.separator + "baseapi.mustache", "apis", "baseapi.ts"));
apiTemplateFiles.put("api" + File.separator + "api.mustache", ".ts");
+ apiDocTemplateFiles.put("api_doc.mustache", ".md");
}
public String getNpmName() {
@@ -879,6 +902,616 @@ public class TypeScriptClientCodegen extends DefaultCodegen implements CodegenCo
addImport(codegenModel, codegenModel.additionalPropertiesType);
}
+ public String typescriptDate(Object dateValue) {
+ String strValue = null;
+ if (dateValue instanceof OffsetDateTime) {
+ OffsetDateTime date = null;
+ try {
+ date = (OffsetDateTime) dateValue;
+ } catch (ClassCastException e) {
+ LOGGER.warn("Invalid `date` format for value {}", dateValue);
+ date = ((Date) dateValue).toInstant().atOffset(ZoneOffset.UTC);
+ }
+ strValue = date.format(iso8601Date);
+ } else {
+ strValue = dateValue.toString();
+ }
+ return "new Date('" + strValue + "').toISOString().split('T')[0];";
+ }
+
+ public String typescriptDateTime(Object dateTimeValue) {
+ String strValue = null;
+ if (dateTimeValue instanceof OffsetDateTime) {
+ OffsetDateTime dateTime = null;
+ try {
+ dateTime = (OffsetDateTime) dateTimeValue;
+ } catch (ClassCastException e) {
+ LOGGER.warn("Invalid `date-time` format for value {}", dateTimeValue);
+ dateTime = ((Date) dateTimeValue).toInstant().atOffset(ZoneOffset.UTC);
+ }
+ strValue = dateTime.format(iso8601DateTime);
+ } else {
+ strValue = dateTimeValue.toString();
+ }
+ return "new Date('" + strValue + "')";
+ }
+
+ public String getModelName(Schema sc) {
+ if (sc.get$ref() != null) {
+ Schema unaliasedSchema = unaliasSchema(sc, importMapping);
+ if (unaliasedSchema.get$ref() != null) {
+ return toModelName(ModelUtils.getSimpleRef(sc.get$ref()));
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Gets an example if it exists
+ *
+ * @param sc input schema
+ * @return the example value
+ */
+ protected Object getObjectExample(Schema sc) {
+ Schema schema = sc;
+ String ref = sc.get$ref();
+ if (ref != null) {
+ schema = ModelUtils.getSchema(this.openAPI, ModelUtils.getSimpleRef(ref));
+ }
+ // TODO handle examples in object models in the future
+ Boolean objectModel = (ModelUtils.isObjectSchema(schema) || ModelUtils.isMapSchema(schema) || ModelUtils.isComposedSchema(schema));
+ if (objectModel) {
+ return null;
+ }
+ if (schema.getExample() != null) {
+ return schema.getExample();
+ }
+ if (schema.getDefault() != null) {
+ return schema.getDefault();
+ } else if (schema.getEnum() != null && !schema.getEnum().isEmpty()) {
+ return schema.getEnum().get(0);
+ }
+ return null;
+ }
+
+ /***
+ * Ensures that the string has a leading and trailing quote
+ *
+ * @param in input string
+ * @return quoted string
+ */
+ private String ensureQuotes(String in) {
+ Pattern pattern = Pattern.compile("\r\n|\r|\n");
+ Matcher matcher = pattern.matcher(in);
+ if (matcher.find()) {
+ // if a string has a new line in it add backticks to make it a typescript multiline string
+ return "`" + in + "`";
+ }
+ String strPattern = "^['\"].*?['\"]$";
+ if (in.matches(strPattern)) {
+ return in;
+ }
+ return "\"" + in + "\"";
+ }
+
+ @Override
+ public String toExampleValue(Schema schema) {
+ Object objExample = getObjectExample(schema);
+ return toExampleValue(schema, objExample);
+ }
+
+ public String toExampleValue(Schema schema, Object objExample) {
+ String modelName = getModelName(schema);
+ return toExampleValueRecursive(modelName, schema, objExample, 1, "", 0, Sets.newHashSet());
+ }
+
+ private Boolean simpleStringSchema(Schema schema) {
+ Schema sc = schema;
+ String ref = schema.get$ref();
+ if (ref != null) {
+ sc = ModelUtils.getSchema(this.openAPI, ModelUtils.getSimpleRef(ref));
+ }
+ return ModelUtils.isStringSchema(sc) && !ModelUtils.isDateSchema(sc) && !ModelUtils.isDateTimeSchema(sc) && !"Number".equalsIgnoreCase(sc.getFormat()) && !ModelUtils.isByteArraySchema(sc) && !ModelUtils.isBinarySchema(sc) && schema.getPattern() == null;
+ }
+
+ private MappedModel getDiscriminatorMappedModel(CodegenDiscriminator disc) {
+ for (MappedModel mm : disc.getMappedModels()) {
+ String modelName = mm.getModelName();
+ Schema modelSchema = getModelNameToSchemaCache().get(modelName);
+ if (ModelUtils.isObjectSchema(modelSchema)) {
+ return mm;
+ }
+ }
+ return null;
+ }
+
+ /***
+ * Recursively generates string examples for schemas
+ *
+ * @param modelName the string name of the refed model that will be generated for the schema or null
+ * @param schema the schema that we need an example for
+ * @param objExample the example that applies to this schema, for now only string example are used
+ * @param indentationLevel integer indentation level that we are currently at
+ * we assume the indentaion amount is 2 spaces times this integer
+ * @param prefix the string prefix that we will use when assigning an example for this line
+ * this is used when setting key: value, pairs "key: " is the prefix
+ * and this is used when setting properties like some_property='some_property_example'
+ * @param exampleLine this is the current line that we are generatign an example for, starts at 0
+ * we don't indentin the 0th line because using the example value looks like:
+ * prop = ModelName( line 0
+ * some_property='some_property_example' line 1
+ * ) line 2
+ * and our example value is:
+ * ModelName( line 0
+ * some_property='some_property_example' line 1
+ * ) line 2
+ * @param seenSchemas This set contains all the schemas passed into the recursive function. It is used to check
+ * if a schema was already passed into the function and breaks the infinite recursive loop. The
+ * only schemas that are not added are ones that contain $ref != null
+ * @return the string example
+ */
+ private String toExampleValueRecursive(String modelName, Schema schema, Object objExample, int indentationLevel, String prefix, Integer exampleLine, Set seenSchemas) {
+ final String indentionConst = " ";
+ String currentIndentation = "";
+ String closingIndentation = "";
+ for (int i = 0; i < indentationLevel; i++) currentIndentation += indentionConst;
+ if (exampleLine.equals(0)) {
+ closingIndentation = currentIndentation;
+ currentIndentation = "";
+ } else {
+ closingIndentation = currentIndentation;
+ }
+ String openChars = "";
+ String closeChars = "";
+ String fullPrefix = currentIndentation + prefix + openChars;
+
+ String example = null;
+ if (objExample != null) {
+ example = objExample.toString();
+ }
+ // checks if the current schema has already been passed in. If so, breaks the current recursive pass
+ if (seenSchemas.contains(schema)) {
+ if (modelName != null) {
+ return fullPrefix + closeChars;
+ } else {
+ // this is a recursive schema
+ // need to add a reasonable example to avoid
+ // infinite recursion
+ if (ModelUtils.isNullable(schema)) {
+ // if the schema is nullable, then 'null' is a valid value
+ return fullPrefix + "null" + closeChars;
+ } else if (ModelUtils.isArraySchema(schema)) {
+ // the schema is an array, add an empty array
+ return fullPrefix + "[]" + closeChars;
+ } else {
+ // the schema is an object, make an empty object
+ return fullPrefix + "{}" + closeChars;
+ }
+ }
+ }
+
+ if (null != schema.get$ref()) {
+ Map allDefinitions = ModelUtils.getSchemas(this.openAPI);
+ String ref = ModelUtils.getSimpleRef(schema.get$ref());
+ Schema refSchema = allDefinitions.get(ref);
+ if (null == refSchema) {
+ LOGGER.warn("Unable to find referenced schema " + schema.get$ref() + "\n");
+ return fullPrefix + "null" + closeChars;
+ }
+ String refModelName = getModelName(schema);
+ return toExampleValueRecursive(refModelName, refSchema, objExample, indentationLevel, prefix, exampleLine, seenSchemas);
+ } else if (ModelUtils.isNullType(schema) || isAnyTypeSchema(schema)) {
+ // The 'null' type is allowed in OAS 3.1 and above. It is not supported by OAS 3.0.x,
+ // though this tooling supports it.
+ return fullPrefix + "null" + closeChars;
+ } else if (ModelUtils.isBooleanSchema(schema)) {
+ if (objExample == null) {
+ example = "true";
+ } else {
+ if ("false".equalsIgnoreCase(objExample.toString())) {
+ example = "false";
+ } else {
+ example = "true";
+ }
+ }
+ return fullPrefix + example + closeChars;
+ } else if (ModelUtils.isDateSchema(schema)) {
+ if (objExample == null) {
+ example = typescriptDate("1970-01-01");
+ } else {
+ example = typescriptDate(objExample);
+ }
+ return fullPrefix + example + closeChars;
+ } else if (ModelUtils.isDateTimeSchema(schema)) {
+ if (objExample == null) {
+ example = typescriptDateTime("1970-01-01T00:00:00.00Z");
+ } else {
+ example = typescriptDateTime(objExample);
+ }
+ return fullPrefix + example + closeChars;
+ } else if (ModelUtils.isBinarySchema(schema)) {
+ if (objExample == null) {
+ example = "/path/to/file";
+ }
+ example = "{ data: Buffer.from(fs.readFileSync('" + example + "', 'utf-8')), name: '" + example + "' }";
+ return fullPrefix + example + closeChars;
+ } else if (ModelUtils.isByteArraySchema(schema)) {
+ if (objExample == null) {
+ example = "'YQ=='";
+ }
+ return fullPrefix + example + closeChars;
+ } else if (ModelUtils.isStringSchema(schema)) {
+ if (objExample == null) {
+ // a BigDecimal:
+ if ("Number".equalsIgnoreCase(schema.getFormat())) {
+ example = "2";
+ return fullPrefix + example + closeChars;
+ } else if (StringUtils.isNotBlank(schema.getPattern())) {
+ String pattern = schema.getPattern();
+ /*
+ RxGen does not support our ECMA dialect https://github.com/curious-odd-man/RgxGen/issues/56
+ So strip off the leading / and trailing / and turn on ignore case if we have it
+ */
+ Pattern valueExtractor = Pattern.compile("^/?(.+?)/?(.?)$");
+ Matcher m = valueExtractor.matcher(pattern);
+ RgxGen rgxGen = null;
+ if (m.find()) {
+ int groupCount = m.groupCount();
+ if (groupCount == 1) {
+ // only pattern found
+ String isolatedPattern = m.group(1);
+ rgxGen = new RgxGen(isolatedPattern);
+ } else if (groupCount == 2) {
+ // patterns and flag found
+ String isolatedPattern = m.group(1);
+ String flags = m.group(2);
+ if (flags.contains("i")) {
+ rgxGen = new RgxGen(isolatedPattern);
+ RgxGenProperties properties = new RgxGenProperties();
+ RgxGenOption.CASE_INSENSITIVE.setInProperties(properties, true);
+ rgxGen.setProperties(properties);
+ } else {
+ rgxGen = new RgxGen(isolatedPattern);
+ }
+ }
+ } else {
+ rgxGen = new RgxGen(pattern);
+ }
+
+ // this seed makes it so if we have [a-z] we pick a
+ Random random = new Random(18);
+ example = rgxGen.generate(random);
+ } else if (schema.getMinLength() != null) {
+ example = "";
+ int len = schema.getMinLength().intValue();
+ for (int i = 0; i < len; i++) example += "a";
+ } else if (ModelUtils.isUUIDSchema(schema)) {
+ example = "046b6c7f-0b8a-43b9-b35d-6489e6daee91";
+ } else {
+ example = "string_example";
+ }
+ }
+ return fullPrefix + ensureQuotes(example) + closeChars;
+ } else if (ModelUtils.isIntegerSchema(schema)) {
+ if (objExample == null) {
+ if (schema.getMinimum() != null) {
+ example = schema.getMinimum().toString();
+ } else {
+ example = "1";
+ }
+ }
+ return fullPrefix + example + closeChars;
+ } else if (ModelUtils.isNumberSchema(schema)) {
+ if (objExample == null) {
+ if (schema.getMinimum() != null) {
+ example = schema.getMinimum().toString();
+ } else {
+ example = "3.14";
+ }
+ }
+ return fullPrefix + example + closeChars;
+ } else if (ModelUtils.isArraySchema(schema)) {
+ ArraySchema arrayschema = (ArraySchema) schema;
+ Schema itemSchema = arrayschema.getItems();
+ String itemModelName = getModelName(itemSchema);
+ if (objExample instanceof Iterable && itemModelName == null) {
+ // If the example is already a list, return it directly instead of wrongly wrap it in another list
+ return fullPrefix + objExample.toString() + closeChars;
+ }
+ Set newSeenSchemas = new HashSet<>(seenSchemas);
+ newSeenSchemas.add(schema);
+ example = fullPrefix + "[" + "\n" + toExampleValueRecursive(itemModelName, itemSchema, objExample, indentationLevel + 1, "", exampleLine + 1, newSeenSchemas) + ",\n" + closingIndentation + "]" + closeChars;
+ return example;
+ } else if (ModelUtils.isMapSchema(schema)) {
+ if (modelName == null) {
+ fullPrefix += "{";
+ closeChars = "}";
+ }
+ Object addPropsObj = schema.getAdditionalProperties();
+ // TODO handle true case for additionalProperties
+ if (addPropsObj instanceof Schema) {
+ Schema addPropsSchema = (Schema) addPropsObj;
+ String key = "key";
+ Object addPropsExample = getObjectExample(addPropsSchema);
+ if (addPropsSchema.getEnum() != null && !addPropsSchema.getEnum().isEmpty()) {
+ key = addPropsSchema.getEnum().get(0).toString();
+ }
+ addPropsExample = exampleFromStringOrArraySchema(addPropsSchema, addPropsExample, key);
+ String addPropPrefix = key + ": ";
+ if (modelName == null) {
+ addPropPrefix = ensureQuotes(key) + ": ";
+ }
+ String addPropsModelName = "\"" + getModelName(addPropsSchema) + "\"";
+ Set newSeenSchemas = new HashSet<>(seenSchemas);
+ newSeenSchemas.add(schema);
+ example = fullPrefix + "\n" + toExampleValueRecursive(addPropsModelName, addPropsSchema, addPropsExample, indentationLevel + 1, addPropPrefix, exampleLine + 1, newSeenSchemas) + ",\n" + closingIndentation + closeChars;
+ } else {
+ example = fullPrefix + closeChars;
+ }
+ return example;
+ } else if (ModelUtils.isComposedSchema(schema)) {
+ ComposedSchema cm = (ComposedSchema) schema;
+ List ls = cm.getOneOf();
+ if (ls != null && !ls.isEmpty()) {
+ return fullPrefix + toExampleValue(ls.get(0)) + closeChars;
+ }
+ return fullPrefix + closeChars;
+ } else if (ModelUtils.isObjectSchema(schema)) {
+ fullPrefix += "{";
+ closeChars = "}";
+ CodegenDiscriminator disc = createDiscriminator(modelName, schema, openAPI);
+ if (disc != null) {
+ MappedModel mm = getDiscriminatorMappedModel(disc);
+ if (mm != null) {
+ String discPropNameValue = mm.getMappingName();
+ String chosenModelName = mm.getModelName();
+ // TODO handle this case in the future, this is when the discriminated
+ // schema allOf includes this schema, like Cat allOf includes Pet
+ // so this is the composed schema use case
+ } else {
+ return fullPrefix + closeChars;
+ }
+ }
+
+ Set newSeenSchemas = new HashSet<>(seenSchemas);
+ newSeenSchemas.add(schema);
+ String exampleForObjectModel = exampleForObjectModel(schema, fullPrefix, closeChars, null, indentationLevel, exampleLine, closingIndentation, newSeenSchemas);
+ return exampleForObjectModel;
+ } else {
+ LOGGER.warn("Type " + schema.getType() + " not handled properly in toExampleValue");
+ }
+
+ return example;
+ }
+
+ private String exampleForObjectModel(Schema schema, String fullPrefix, String closeChars, CodegenProperty discProp, int indentationLevel, int exampleLine, String closingIndentation, Set seenSchemas) {
+ Map requiredAndOptionalProps = schema.getProperties();
+ if (requiredAndOptionalProps == null || requiredAndOptionalProps.isEmpty()) {
+ return fullPrefix + closeChars;
+ }
+
+ String example = fullPrefix + "\n";
+ for (Map.Entry entry : requiredAndOptionalProps.entrySet()) {
+ String propName = entry.getKey();
+ Schema propSchema = entry.getValue();
+ boolean readOnly = false;
+ if (propSchema.getReadOnly() != null) {
+ readOnly = propSchema.getReadOnly();
+ }
+ if (readOnly) {
+ continue;
+ }
+ String ref = propSchema.get$ref();
+ if (ref != null) {
+ Schema refSchema = ModelUtils.getSchema(this.openAPI, ModelUtils.getSimpleRef(ref));
+ if (refSchema.getReadOnly() != null) {
+ readOnly = refSchema.getReadOnly();
+ }
+ if (readOnly) {
+ continue;
+ }
+ }
+ propName = toVarName(propName);
+ String propModelName = null;
+ Object propExample = null;
+ if (discProp != null && propName.equals(discProp.name)) {
+ propModelName = null;
+ propExample = discProp.example;
+ } else {
+ propModelName = getModelName(propSchema);
+ propExample = exampleFromStringOrArraySchema(propSchema, null, propName);
+ }
+ example += toExampleValueRecursive(propModelName, propSchema, propExample, indentationLevel + 1, propName + ": ", exampleLine + 1, seenSchemas) + ",\n";
+ }
+ // TODO handle additionalProperties also
+ example += closingIndentation + closeChars;
+ return example;
+ }
+
+ private Object exampleFromStringOrArraySchema(Schema sc, Object currentExample, String propName) {
+ if (currentExample != null) {
+ return currentExample;
+ }
+ Schema schema = sc;
+ String ref = sc.get$ref();
+ if (ref != null) {
+ schema = ModelUtils.getSchema(this.openAPI, ModelUtils.getSimpleRef(ref));
+ }
+ Object example = getObjectExample(schema);
+ if (example != null) {
+ return example;
+ } else if (simpleStringSchema(schema)) {
+ return propName + "_example";
+ } else if (ModelUtils.isArraySchema(schema)) {
+ ArraySchema arraySchema = (ArraySchema) schema;
+ Schema itemSchema = arraySchema.getItems();
+ example = getObjectExample(itemSchema);
+ if (example != null) {
+ return example;
+ } else if (simpleStringSchema(itemSchema)) {
+ return propName + "_example";
+ }
+ }
+ return null;
+ }
+
+ protected String setPropertyExampleValue(CodegenProperty p) {
+ String example;
+
+ if (p == null) {
+ return "null";
+ }
+
+ if (p.defaultValue == null) {
+ example = p.example;
+ } else {
+ example = p.defaultValue;
+ }
+
+ String type = p.baseType;
+ if (type == null) {
+ type = p.dataType;
+ }
+
+ if (Boolean.TRUE.equals(p.isInteger)) {
+ if (example == null) {
+ example = "56";
+ }
+ } else if (Boolean.TRUE.equals(p.isLong)) {
+ if (example == null) {
+ example = "789";
+ }
+ } else if (Boolean.TRUE.equals(p.isDouble)
+ || Boolean.TRUE.equals(p.isFloat)
+ || Boolean.TRUE.equals(p.isNumber)) {
+ if (example == null) {
+ example = "3.4";
+ }
+ } else if (Boolean.TRUE.equals(p.isBoolean)) {
+ if (example == null) {
+ example = "true";
+ }
+ } else if (Boolean.TRUE.equals(p.isFile) || Boolean.TRUE.equals(p.isBinary)) {
+ if (example == null) {
+ example = "/path/to/file";
+ }
+ example = "\"" + escapeText(example) + "\"";
+ } else if (Boolean.TRUE.equals(p.isDate)) {
+ if (example == null) {
+ example = "2013-10-20";
+ }
+ example = "new Date(\"" + escapeText(example) + "\")";
+ } else if (Boolean.TRUE.equals(p.isDateTime)) {
+ if (example == null) {
+ example = "2013-10-20T19:20:30+01:00";
+ }
+ example = "new Date(\"" + escapeText(example) + "\")";
+ } else if (Boolean.TRUE.equals(p.isString)) {
+ if (example == null) {
+ example = p.name + "_example";
+ }
+ example = "\"" + escapeText(example) + "\"";
+ } else if (!languageSpecificPrimitives.contains(type)) {
+ // type is a model class, e.g. User
+ example = "new " + "{{moduleName}}" + "." + type + "()";
+ }
+
+ return example;
+ }
+
+
+ /***
+ *
+ * Set the codegenParameter example value
+ * We have a custom version of this function so we can invoke toExampleValue
+ *
+ * @param codegenParameter the item we are setting the example on
+ * @param parameter the base parameter that came from the spec
+ */
+ @Override
+ public void setParameterExampleValue(CodegenParameter codegenParameter, Parameter parameter) {
+ Schema schema = parameter.getSchema();
+ if (schema == null) {
+ LOGGER.warn("CodegenParameter.example defaulting to null because parameter lacks a schema");
+ return;
+ }
+
+ Object example = null;
+ if (codegenParameter.vendorExtensions != null && codegenParameter.vendorExtensions.containsKey("x-example")) {
+ example = codegenParameter.vendorExtensions.get("x-example");
+ } else if (parameter.getExample() != null) {
+ example = parameter.getExample();
+ } else if (parameter.getExamples() != null && !parameter.getExamples().isEmpty() && parameter.getExamples().values().iterator().next().getValue() != null) {
+ example = parameter.getExamples().values().iterator().next().getValue();
+ } else {
+ example = getObjectExample(schema);
+ }
+ example = exampleFromStringOrArraySchema(schema, example, parameter.getName());
+ String finalExample = toExampleValue(schema, example);
+ codegenParameter.example = finalExample;
+ }
+
+ /**
+ * Return the example value of the parameter.
+ *
+ * @param codegenParameter Codegen parameter
+ * @param requestBody Request body
+ */
+ @Override
+ public void setParameterExampleValue(CodegenParameter codegenParameter, RequestBody requestBody) {
+ if (codegenParameter.vendorExtensions != null && codegenParameter.vendorExtensions.containsKey("x-example")) {
+ codegenParameter.example = Json.pretty(codegenParameter.vendorExtensions.get("x-example"));
+ }
+
+ Content content = requestBody.getContent();
+
+ if (content.size() > 1) {
+ // @see ModelUtils.getSchemaFromContent()
+ once(LOGGER).warn("Multiple MediaTypes found, using only the first one");
+ }
+
+ MediaType mediaType = content.values().iterator().next();
+ Schema schema = mediaType.getSchema();
+ if (schema == null) {
+ LOGGER.warn("CodegenParameter.example defaulting to null because requestBody content lacks a schema");
+ return;
+ }
+
+ Object example = null;
+ if (mediaType.getExample() != null) {
+ example = mediaType.getExample();
+ } else if (mediaType.getExamples() != null && !mediaType.getExamples().isEmpty() && mediaType.getExamples().values().iterator().next().getValue() != null) {
+ example = mediaType.getExamples().values().iterator().next().getValue();
+ } else {
+ example = getObjectExample(schema);
+ }
+ example = exampleFromStringOrArraySchema(schema, example, codegenParameter.paramName);
+ codegenParameter.example = toExampleValue(schema, example);
+ }
+
+ /**
+ * Create a CodegenParameter for a Form Property
+ * We have a custom version of this method so we can invoke
+ * setParameterExampleValue(codegenParameter, parameter)
+ * rather than setParameterExampleValue(codegenParameter)
+ * This ensures that all of our samples are generated in
+ * toExampleValueRecursive
+ *
+ * @param name the property name
+ * @param propertySchema the property schema
+ * @param imports our import set
+ * @return the resultant CodegenParameter
+ */
+ @Override
+ public CodegenParameter fromFormProperty(String name, Schema propertySchema, Set imports) {
+ CodegenParameter cp = super.fromFormProperty(name, propertySchema, imports);
+ Parameter p = new Parameter();
+ p.setSchema(propertySchema);
+ p.setName(cp.paramName);
+ setParameterExampleValue(cp, p);
+ return cp;
+ }
+
@Override
public String toAnyOfName(List names, ComposedSchema composedSchema) {
List types = getTypesFromSchemas(composedSchema.getAnyOf());
@@ -893,6 +1526,13 @@ public class TypeScriptClientCodegen extends DefaultCodegen implements CodegenCo
return String.join(" | ", types);
}
+ @Override
+ public String toAllOfName(List names, ComposedSchema composedSchema) {
+ List types = getTypesFromSchemas(composedSchema.getAllOf());
+
+ return String.join(" & ", types);
+ }
+
/**
* Extracts the list of type names from a list of schemas.
* Excludes `AnyType` if there are other valid types extracted.
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptInversifyClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptInversifyClientCodegen.java
index 6de4f086413..b4b05924917 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptInversifyClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptInversifyClientCodegen.java
@@ -188,6 +188,9 @@ public class TypeScriptInversifyClientCodegen extends AbstractTypeScriptClientCo
public void postProcessParameter(CodegenParameter parameter) {
super.postProcessParameter(parameter);
parameter.dataType = applyLocalTypeMapping(parameter.dataType);
+ if (parameter.isFormParam && parameter.isArray && "binary".equals(parameter.dataFormat)) {
+ parameter.isCollectionFormatMulti = true;
+ }
}
@Override
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ProcessUtils.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ProcessUtils.java
index 167c7d21124..9042eb92b39 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ProcessUtils.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ProcessUtils.java
@@ -63,6 +63,24 @@ public class ProcessUtils {
return false;
}
+ /**
+ * Returns a list of OAS Codegen security objects
+ *
+ * @param authMethods List of auth methods.
+ * @return A list of OAS Codegen security objects
+ */
+ public static List getHttpBasicMethods(List authMethods) {
+ List httpBasicMethods = new ArrayList<>();
+
+ for (CodegenSecurity cs : authMethods) {
+ if (Boolean.TRUE.equals(cs.isBasicBasic)) {
+ httpBasicMethods.add(cs);
+ }
+ }
+
+ return httpBasicMethods;
+ }
+
/**
* Returns true if the specified OAS model has at least one operation with API keys.
*
@@ -80,6 +98,24 @@ public class ProcessUtils {
return false;
}
+ /**
+ * Returns a list of OAS Codegen security objects
+ *
+ * @param authMethods List of auth methods.
+ * @return A list of OAS Codegen security objects
+ */
+ public static List getApiKeyMethods(List authMethods) {
+ List apiKeyMethods = new ArrayList<>();
+
+ for (CodegenSecurity cs : authMethods) {
+ if (Boolean.TRUE.equals(cs.isApiKey)) {
+ apiKeyMethods.add(cs);
+ }
+ }
+
+ return apiKeyMethods;
+ }
+
/**
* Returns true if the specified OAS model has at least one operation with the HTTP basic
* security scheme.
@@ -99,6 +135,24 @@ public class ProcessUtils {
return false;
}
+ /**
+ * Returns a list of OAS Codegen security objects
+ *
+ * @param authMethods List of auth methods.
+ * @return A list of OAS Codegen security objects
+ */
+ public static List getHttpSignatureMethods(List authMethods) {
+ List httpSignatureMethods = new ArrayList<>();
+
+ for (CodegenSecurity cs : authMethods) {
+ if (Boolean.TRUE.equals(cs.isHttpSignature)) {
+ httpSignatureMethods.add(cs);
+ }
+ }
+
+ return httpSignatureMethods;
+ }
+
/**
* Returns true if the specified OAS model has at least one operation with HTTP bearer.
*
@@ -116,6 +170,24 @@ public class ProcessUtils {
return false;
}
+ /**
+ * Returns a list of Bearer Codegen security objects
+ *
+ * @param authMethods List of auth methods.
+ * @return A list of Bearer Codegen security objects
+ */
+ public static List getHttpBearerMethods(List authMethods) {
+ List httpBearerMethods = new ArrayList<>();
+
+ for (CodegenSecurity cs : authMethods) {
+ if (Boolean.TRUE.equals(cs.isBasicBearer)) {
+ httpBearerMethods.add(cs);
+ }
+ }
+
+ return httpBearerMethods;
+ }
+
/**
* Returns true if the specified OAS model has at least one operation with OAuth.
*
diff --git a/modules/openapi-generator/src/main/resources/C-libcurl/model-body.mustache b/modules/openapi-generator/src/main/resources/C-libcurl/model-body.mustache
index e80036b8b31..ae52b8c30b1 100644
--- a/modules/openapi-generator/src/main/resources/C-libcurl/model-body.mustache
+++ b/modules/openapi-generator/src/main/resources/C-libcurl/model-body.mustache
@@ -248,6 +248,12 @@ void {{classname}}_free({{classname}}_t *{{classname}}) {
}
{{/isString}}
{{/isEnum}}
+ {{#isByteArray}}
+ if ({{{classname}}}->{{{name}}}) {
+ free({{{classname}}}->{{{name}}});
+ {{classname}}->{{name}} = NULL;
+ }
+ {{/isByteArray}}
{{#isBinary}}
if ({{{classname}}}->{{{name}}}) {
free({{{classname}}}->{{{name}}}->data);
@@ -660,7 +666,13 @@ fail:
{
goto end;
}
- list_addElement({{{name}}}List , &{{{name}}}_local->valuedouble);
+ double *{{{name}}}_local_value = (double *)calloc(1, sizeof(double));
+ if(!{{{name}}}_local_value)
+ {
+ goto end;
+ }
+ *{{{name}}}_local_value = {{{name}}}_local->valuedouble;
+ list_addElement({{{name}}}List , {{{name}}}_local_value);
{{/isNumeric}}
{{#isBoolean}}
if(!cJSON_IsBool({{{name}}}_local))
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/pojo.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/pojo.mustache
index 9a4c6dd3c90..55dc3717100 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/pojo.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/pojo.mustache
@@ -278,13 +278,17 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#vendorE
return false;
}{{#hasVars}}
{{classname}} {{classVarName}} = ({{classname}}) o;
- return {{#vars}}{{#isByteArray}}Arrays{{/isByteArray}}{{^isByteArray}}Objects{{/isByteArray}}.equals(this.{{name}}, {{classVarName}}.{{name}}){{^-last}} &&
+ return {{#vars}}{{#vendorExtensions.x-is-jackson-optional-nullable}}equalsNullable(this.{{name}}, {{classVarName}}.{{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^vendorExtensions.x-is-jackson-optional-nullable}}{{#isByteArray}}Arrays{{/isByteArray}}{{^isByteArray}}Objects{{/isByteArray}}.equals(this.{{name}}, {{classVarName}}.{{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^-last}} &&
{{/-last}}{{/vars}}{{#additionalPropertiesType}}&&
Objects.equals(this.additionalProperties, {{classVarName}}.additionalProperties){{/additionalPropertiesType}}{{#parent}} &&
super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}}
return {{#parent}}super.equals(o){{/parent}}{{^parent}}true{{/parent}};{{/hasVars}}
{{/useReflectionEqualsHashCode}}
- }
+ }{{#vendorExtensions.x-jackson-optional-nullable-helpers}}
+
+ private static boolean equalsNullable(JsonNullable a, JsonNullable b) {
+ return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && a.get().getClass().isArray() ? Arrays.equals((T[])a.get(), (T[])b.get()) : Objects.equals(a.get(), b.get()));
+ }{{/vendorExtensions.x-jackson-optional-nullable-helpers}}
@Override
public int hashCode() {
@@ -292,9 +296,18 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#vendorE
return HashCodeBuilder.reflectionHashCode(this);
{{/useReflectionEqualsHashCode}}
{{^useReflectionEqualsHashCode}}
- return Objects.hash({{#vars}}{{^isByteArray}}{{name}}{{/isByteArray}}{{#isByteArray}}Arrays.hashCode({{name}}){{/isByteArray}}{{^-last}}, {{/-last}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}{{#additionalPropertiesType}}{{#hasVars}}, {{/hasVars}}{{^hasVars}}{{#parent}}, {{/parent}}{{/hasVars}}additionalProperties{{/additionalPropertiesType}});
+ return Objects.hash({{#vars}}{{#vendorExtensions.x-is-jackson-optional-nullable}}hashCodeNullable({{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^vendorExtensions.x-is-jackson-optional-nullable}}{{^isByteArray}}{{name}}{{/isByteArray}}{{#isByteArray}}Arrays.hashCode({{name}}){{/isByteArray}}{{/vendorExtensions.x-is-jackson-optional-nullable}}{{^-last}}, {{/-last}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}{{#additionalPropertiesType}}{{#hasVars}}, {{/hasVars}}{{^hasVars}}{{#parent}}, {{/parent}}{{/hasVars}}additionalProperties{{/additionalPropertiesType}});
{{/useReflectionEqualsHashCode}}
- }
+ }{{#vendorExtensions.x-jackson-optional-nullable-helpers}}
+
+ private static int hashCodeNullable(JsonNullable a) {
+ if (a == null) {
+ return 1;
+ }
+ return a.isPresent()
+ ? (a.get().getClass().isArray() ? Arrays.hashCode((T[])a.get()) : Objects.hashCode(a.get()))
+ : 31;
+ }{{/vendorExtensions.x-jackson-optional-nullable-helpers}}
@Override
public String toString() {
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/microprofile/pojo.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/microprofile/pojo.mustache
index a457e531d6e..183b60cc1ac 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/microprofile/pojo.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/microprofile/pojo.mustache
@@ -46,6 +46,9 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}}{{#serializ
* {{{description}}}
**/
{{/description}}
+ {{^withXml}}
+ @JsonbProperty("{{baseName}}")
+ {{/withXml}}
{{#isContainer}}
private {{{datatypeWithEnum}}} {{name}}{{#required}} = {{{defaultValue}}}{{/required}}{{^required}} = null{{/required}};
{{/isContainer}}
@@ -76,9 +79,6 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}}{{#serializ
{{#deprecated}}
@Deprecated
{{/deprecated}}
- {{^withXml}}
- @JsonbProperty("{{baseName}}")
- {{/withXml}}
{{#vendorExtensions.x-extra-annotation}}
{{{vendorExtensions.x-extra-annotation}}}
{{/vendorExtensions.x-extra-annotation}}
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/native/pojo.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/native/pojo.mustache
index e1350909a53..2db2da784e9 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/native/pojo.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/native/pojo.mustache
@@ -281,13 +281,17 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#vendorE
return false;
}{{#hasVars}}
{{classname}} {{classVarName}} = ({{classname}}) o;
- return {{#vars}}{{#isByteArray}}Arrays{{/isByteArray}}{{^isByteArray}}Objects{{/isByteArray}}.equals(this.{{name}}, {{classVarName}}.{{name}}){{^-last}} &&
+ return {{#vars}}{{#vendorExtensions.x-is-jackson-optional-nullable}}equalsNullable(this.{{name}}, {{classVarName}}.{{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^vendorExtensions.x-is-jackson-optional-nullable}}{{#isByteArray}}Arrays{{/isByteArray}}{{^isByteArray}}Objects{{/isByteArray}}.equals(this.{{name}}, {{classVarName}}.{{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^-last}} &&
{{/-last}}{{/vars}}{{#additionalPropertiesType}}&&
Objects.equals(this.additionalProperties, {{classVarName}}.additionalProperties){{/additionalPropertiesType}}{{#parent}} &&
super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}}
return {{#parent}}super.equals(o){{/parent}}{{^parent}}true{{/parent}};{{/hasVars}}
{{/useReflectionEqualsHashCode}}
- }
+ }{{#vendorExtensions.x-jackson-optional-nullable-helpers}}
+
+ private static boolean equalsNullable(JsonNullable a, JsonNullable b) {
+ return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && a.get().getClass().isArray() ? Arrays.equals((T[])a.get(), (T[])b.get()) : Objects.equals(a.get(), b.get()));
+ }{{/vendorExtensions.x-jackson-optional-nullable-helpers}}
@Override
public int hashCode() {
@@ -295,9 +299,18 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#vendorE
return HashCodeBuilder.reflectionHashCode(this);
{{/useReflectionEqualsHashCode}}
{{^useReflectionEqualsHashCode}}
- return Objects.hash({{#vars}}{{^isByteArray}}{{name}}{{/isByteArray}}{{#isByteArray}}Arrays.hashCode({{name}}){{/isByteArray}}{{^-last}}, {{/-last}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}{{#additionalPropertiesType}}, additionalProperties{{/additionalPropertiesType}});
+ return Objects.hash({{#vars}}{{#vendorExtensions.x-is-jackson-optional-nullable}}hashCodeNullable({{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^vendorExtensions.x-is-jackson-optional-nullable}}{{^isByteArray}}{{name}}{{/isByteArray}}{{#isByteArray}}Arrays.hashCode({{name}}){{/isByteArray}}{{/vendorExtensions.x-is-jackson-optional-nullable}}{{^-last}}, {{/-last}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}{{#additionalPropertiesType}}, additionalProperties{{/additionalPropertiesType}});
{{/useReflectionEqualsHashCode}}
- }
+ }{{#vendorExtensions.x-jackson-optional-nullable-helpers}}
+
+ private static int hashCodeNullable(JsonNullable a) {
+ if (a == null) {
+ return 1;
+ }
+ return a.isPresent()
+ ? (a.get().getClass().isArray() ? Arrays.hashCode((T[])a.get()) : Objects.hashCode(a.get()))
+ : 31;
+ }{{/vendorExtensions.x-jackson-optional-nullable-helpers}}
@Override
public String toString() {
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/auth/RetryingOAuth.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/auth/RetryingOAuth.mustache
index 3ddacedb70e..6e6562448da 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/auth/RetryingOAuth.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/auth/RetryingOAuth.mustache
@@ -156,14 +156,12 @@ public class RetryingOAuth extends OAuth implements Interceptor {
oAuthClient.accessToken(tokenRequestBuilder.buildBodyMessage());
if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) {
setAccessToken(accessTokenResponse.getAccessToken());
- return !getAccessToken().equals(requestAccessToken);
}
} catch (OAuthSystemException | OAuthProblemException e) {
throw new IOException(e);
}
}
-
- return false;
+ return getAccessToken() == null || !getAccessToken().equals(requestAccessToken);
}
public TokenRequestBuilder getTokenRequestBuilder() {
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache
index 7e3d97298ea..f6002e0ef9e 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache
@@ -108,6 +108,9 @@ dependencies {
implementation 'com.squareup.okhttp3:logging-interceptor:4.9.1'
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'io.gsonfire:gson-fire:1.8.4'
+ {{#openApiNullable}}
+ implementation 'org.openapitools:jackson-databind-nullable:0.2.1'
+ {{/openApiNullable}}
{{#hasOAuthMethods}}
implementation group: 'org.apache.oltu.oauth2', name: 'org.apache.oltu.oauth2.client', version: '1.0.1'
{{/hasOAuthMethods}}
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache
index 8979b10a7f8..ccab8251805 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache
@@ -14,6 +14,9 @@ lazy val root = (project in file(".")).
"com.squareup.okhttp3" % "logging-interceptor" % "4.9.1",
"com.google.code.gson" % "gson" % "2.8.6",
"org.apache.commons" % "commons-lang3" % "3.10",
+ {{#openApiNullable}}
+ "org.openapitools" % "jackson-databind-nullable" % "0.2.1",
+ {{/openApiNullable}}
{{#hasOAuthMethods}}
"org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1",
{{/hasOAuthMethods}}
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/pom.mustache
index 74a1b796dcd..39f6f2b5c4b 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/pom.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/pom.mustache
@@ -318,6 +318,13 @@
${javax-annotation-version}provided
+ {{#openApiNullable}}
+
+ org.openapitools
+ jackson-databind-nullable
+ ${jackson-databind-nullable-version}
+
+ {{/openApiNullable}}
junit
@@ -325,6 +332,12 @@
${junit-version}test
+
+ org.mockito
+ mockito-core
+ 3.11.2
+ test
+ {{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}}
@@ -335,6 +348,9 @@
4.9.12.8.63.11
+ {{#openApiNullable}}
+ 0.2.1
+ {{/openApiNullable}}
{{#joda}}
2.10.9
{{/joda}}
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/webclient/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/webclient/ApiClient.mustache
index 28b91d3a1f8..cabd6408abc 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/webclient/ApiClient.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/webclient/ApiClient.mustache
@@ -96,6 +96,8 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
}
}
+ private static final String URI_TEMPLATE_ATTRIBUTE = WebClient.class.getName() + ".uriTemplate";
+
private HttpHeaders defaultHeaders = new HttpHeaders();
private MultiValueMap defaultCookies = new LinkedMultiValueMap();
@@ -676,6 +678,8 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
addCookiesToRequest(cookieParams, requestBuilder);
addCookiesToRequest(defaultCookies, requestBuilder);
+ requestBuilder.attribute(URI_TEMPLATE_ATTRIBUTE, path);
+
requestBuilder.body(selectBody(body, formParams, contentType));
return requestBuilder;
}
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/webclient/api.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/webclient/api.mustache
index 28dbea910c0..2f79b929315 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/webclient/api.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/webclient/api.mustache
@@ -16,7 +16,6 @@ import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
-import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.web.reactive.function.client.WebClient.ResponseSpec;
import org.springframework.web.reactive.function.client.WebClientResponseException;
diff --git a/modules/openapi-generator/src/main/resources/Java/pojo.mustache b/modules/openapi-generator/src/main/resources/Java/pojo.mustache
index 6590b93824d..77d080ccba3 100644
--- a/modules/openapi-generator/src/main/resources/Java/pojo.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/pojo.mustache
@@ -255,12 +255,16 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#vendorE
return false;
}{{#hasVars}}
{{classname}} {{classVarName}} = ({{classname}}) o;
- return {{#vars}}{{#isByteArray}}Arrays{{/isByteArray}}{{^isByteArray}}Objects{{/isByteArray}}.equals(this.{{name}}, {{classVarName}}.{{name}}){{^-last}} &&
+ return {{#vars}}{{#vendorExtensions.x-is-jackson-optional-nullable}}equalsNullable(this.{{name}}, {{classVarName}}.{{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^vendorExtensions.x-is-jackson-optional-nullable}}{{#isByteArray}}Arrays{{/isByteArray}}{{^isByteArray}}Objects{{/isByteArray}}.equals(this.{{name}}, {{classVarName}}.{{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^-last}} &&
{{/-last}}{{/vars}}{{#parent}} &&
super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}}
return {{#parent}}super.equals(o){{/parent}}{{^parent}}true{{/parent}};{{/hasVars}}
{{/useReflectionEqualsHashCode}}
- }
+ }{{#vendorExtensions.x-jackson-optional-nullable-helpers}}
+
+ private static boolean equalsNullable(JsonNullable a, JsonNullable b) {
+ return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && a.get().getClass().isArray() ? Arrays.equals((T[])a.get(), (T[])b.get()) : Objects.equals(a.get(), b.get()));
+ }{{/vendorExtensions.x-jackson-optional-nullable-helpers}}
@Override
public int hashCode() {
@@ -268,9 +272,18 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#vendorE
return HashCodeBuilder.reflectionHashCode(this);
{{/useReflectionEqualsHashCode}}
{{^useReflectionEqualsHashCode}}
- return Objects.hash({{#vars}}{{^isByteArray}}{{name}}{{/isByteArray}}{{#isByteArray}}Arrays.hashCode({{name}}){{/isByteArray}}{{^-last}}, {{/-last}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}});
+ return Objects.hash({{#vars}}{{#vendorExtensions.x-is-jackson-optional-nullable}}hashCodeNullable({{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^vendorExtensions.x-is-jackson-optional-nullable}}{{^isByteArray}}{{name}}{{/isByteArray}}{{#isByteArray}}Arrays.hashCode({{name}}){{/isByteArray}}{{/vendorExtensions.x-is-jackson-optional-nullable}}{{^-last}}, {{/-last}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}});
{{/useReflectionEqualsHashCode}}
- }
+ }{{#vendorExtensions.x-jackson-optional-nullable-helpers}}
+
+ private static int hashCodeNullable(JsonNullable a) {
+ if (a == null) {
+ return 1;
+ }
+ return a.isPresent()
+ ? (a.get().getClass().isArray() ? Arrays.hashCode((T[])a.get()) : Objects.hashCode(a.get()))
+ : 31;
+ }{{/vendorExtensions.x-jackson-optional-nullable-helpers}}
@Override
public String toString() {
diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/JacksonConfig.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/JacksonConfig.mustache
index 5a0da702332..43af8d12996 100644
--- a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/JacksonConfig.mustache
+++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/JacksonConfig.mustache
@@ -1,14 +1,19 @@
package {{invokerPackage}};
+import com.fasterxml.jackson.databind.ObjectMapper;
+{{#java8}}
+import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
+{{/java8}}
+{{^java8}}
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
-import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.format.ISODateTimeFormat;
+{{/java8}}
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
@@ -21,7 +26,10 @@ public class JacksonConfig implements ContextResolver {
public JacksonConfig() throws Exception {
objectMapper = new ObjectMapper()
- .setDateFormat(new RFC3339DateFormat())
+{{#java8}}
+ .registerModule(new JavaTimeModule())
+{{/java8}}
+{{^java8}}
.registerModule(new JodaModule() {
{
addSerializer(DateTime.class, new StdSerializer(DateTime.class) {
@@ -38,10 +46,12 @@ public class JacksonConfig implements ContextResolver {
});
}
- });
+ })
+{{/java8}}
+ .setDateFormat(new RFC3339DateFormat());
}
public ObjectMapper getContext(Class> arg0) {
return objectMapper;
}
-}
\ No newline at end of file
+}
diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/pom.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/pom.mustache
index 7c6ac1edc3e..997588b8b75 100644
--- a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/pom.mustache
+++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/pom.mustache
@@ -126,16 +126,25 @@
provided
+ {{#java8}}
+
+ com.fasterxml.jackson.datatype
+ jackson-datatype-jsr310
+ ${jackson-version}
+
+ {{/java8}}
+ {{^java8}}
com.fasterxml.jackson.datatypejackson-datatype-joda
- 2.11.2
+ ${jackson-version}joda-timejoda-time2.7
+ {{/java8}}
io.swaggerswagger-jaxrs
@@ -189,6 +198,7 @@
1.5.22
+ 2.11.29.2.9.v201502243.13.0.Final1.6.3
diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/api.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/api.mustache
index 770bfd30183..5a9522ffcfd 100644
--- a/modules/openapi-generator/src/main/resources/JavaSpring/api.mustache
+++ b/modules/openapi-generator/src/main/resources/JavaSpring/api.mustache
@@ -20,9 +20,6 @@ import org.springframework.http.ResponseEntity;
{{#useBeanValidation}}
import org.springframework.validation.annotation.Validated;
{{/useBeanValidation}}
-{{#vendorExtensions.x-spring-paginated}}
-import org.springframework.data.domain.Pageable;
-{{/vendorExtensions.x-spring-paginated}}
import org.springframework.web.bind.annotation.*;
{{#jdk8-no-delegate}}
{{^reactive}}
@@ -120,20 +117,21 @@ public interface {{classname}} {
{{/headerParams}}
})
{{/implicitHeaders}}
- @{{#lambda.titlecase}}{{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}}{{/lambda.titlecase}}Mapping(
+ @RequestMapping(
+ method = RequestMethod.{{httpMethod}},
value = "{{{path}}}"{{#singleContentTypes}}{{#hasProduces}},
produces = "{{{vendorExtensions.x-accepts}}}"{{/hasProduces}}{{#hasConsumes}},
consumes = "{{{vendorExtensions.x-contentType}}}"{{/hasConsumes}}{{/singleContentTypes}}{{^singleContentTypes}}{{#hasProduces}},
produces = { {{#produces}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/produces}} }{{/hasProduces}}{{#hasConsumes}},
consumes = { {{#consumes}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/consumes}} }{{/hasConsumes}}{{/singleContentTypes}}
)
- {{#jdk8-default-interface}}default {{/jdk8-default-interface}}{{#responseWrapper}}{{.}}<{{/responseWrapper}}ResponseEntity<{{>returnTypes}}>{{#responseWrapper}}>{{/responseWrapper}} {{#delegate-method}}_{{/delegate-method}}{{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{>cookieParams}}{{^-last}},{{/-last}}{{#-last}}{{#reactive}}, {{/reactive}}{{/-last}}{{/allParams}}{{#reactive}}@ApiIgnore final ServerWebExchange exchange{{/reactive}}{{#vendorExtensions.x-spring-paginated}}, @ApiIgnore final Pageable pageable{{/vendorExtensions.x-spring-paginated}}){{^jdk8-default-interface}};{{/jdk8-default-interface}}{{#jdk8-default-interface}}{{#unhandledException}} throws Exception{{/unhandledException}} {
+ {{#jdk8-default-interface}}default {{/jdk8-default-interface}}{{#responseWrapper}}{{.}}<{{/responseWrapper}}ResponseEntity<{{>returnTypes}}>{{#responseWrapper}}>{{/responseWrapper}} {{#delegate-method}}_{{/delegate-method}}{{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{>cookieParams}}{{^-last}},{{/-last}}{{#-last}}{{#reactive}}, {{/reactive}}{{/-last}}{{/allParams}}{{#reactive}}@ApiIgnore final ServerWebExchange exchange{{/reactive}}{{#vendorExtensions.x-spring-paginated}}, @ApiIgnore final org.springframework.data.domain.Pageable pageable{{/vendorExtensions.x-spring-paginated}}){{^jdk8-default-interface}};{{/jdk8-default-interface}}{{#jdk8-default-interface}}{{#unhandledException}} throws Exception{{/unhandledException}} {
{{#delegate-method}}
return {{operationId}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#reactive}}{{#hasParams}}, {{/hasParams}}exchange{{/reactive}}{{#vendorExtensions.x-spring-paginated}}, pageable{{/vendorExtensions.x-spring-paginated}});
}
// Override this method
- {{#jdk8-default-interface}}default {{/jdk8-default-interface}} {{#responseWrapper}}{{.}}<{{/responseWrapper}}ResponseEntity<{{>returnTypes}}>{{#responseWrapper}}>{{/responseWrapper}} {{operationId}}({{#allParams}}{{^isFile}}{{^isBodyParam}}{{>optionalDataType}}{{/isBodyParam}}{{#isBodyParam}}{{^reactive}}{{{dataType}}}{{/reactive}}{{#reactive}}{{^isArray}}Mono<{{{dataType}}}>{{/isArray}}{{#isArray}}Flux<{{{baseType}}}>{{/isArray}}{{/reactive}}{{/isBodyParam}}{{/isFile}}{{#isFile}}{{#reactive}}Flux{{/reactive}}{{^reactive}}MultipartFile{{/reactive}}{{/isFile}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#reactive}}{{#hasParams}}, {{/hasParams}}@ApiIgnore final ServerWebExchange exchange{{/reactive}}{{#vendorExtensions.x-spring-paginated}}, @ApiIgnore final Pageable pageable{{/vendorExtensions.x-spring-paginated}}){{#unhandledException}} throws Exception{{/unhandledException}} {
+ {{#jdk8-default-interface}}default {{/jdk8-default-interface}} {{#responseWrapper}}{{.}}<{{/responseWrapper}}ResponseEntity<{{>returnTypes}}>{{#responseWrapper}}>{{/responseWrapper}} {{operationId}}({{#allParams}}{{^isFile}}{{^isBodyParam}}{{>optionalDataType}}{{/isBodyParam}}{{#isBodyParam}}{{^reactive}}{{{dataType}}}{{/reactive}}{{#reactive}}{{^isArray}}Mono<{{{dataType}}}>{{/isArray}}{{#isArray}}Flux<{{{baseType}}}>{{/isArray}}{{/reactive}}{{/isBodyParam}}{{/isFile}}{{#isFile}}{{#reactive}}Flux{{/reactive}}{{^reactive}}MultipartFile{{/reactive}}{{/isFile}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#reactive}}{{#hasParams}}, {{/hasParams}}@ApiIgnore final ServerWebExchange exchange{{/reactive}}{{#vendorExtensions.x-spring-paginated}}, @ApiIgnore final org.springframework.data.domain.Pageable pageable{{/vendorExtensions.x-spring-paginated}}){{#unhandledException}} throws Exception{{/unhandledException}} {
{{/delegate-method}}
{{^isDelegate}}
{{>methodBody}}
diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/pojo.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/pojo.mustache
index 3938d4d289e..de2f292341e 100644
--- a/modules/openapi-generator/src/main/resources/JavaSpring/pojo.mustache
+++ b/modules/openapi-generator/src/main/resources/JavaSpring/pojo.mustache
@@ -132,16 +132,29 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}}{{^parent}}
return false;
}{{#hasVars}}
{{classname}} {{classVarName}} = ({{classname}}) o;
- return {{#vars}}{{#isByteArray}}Arrays{{/isByteArray}}{{^isByteArray}}Objects{{/isByteArray}}.equals(this.{{name}}, {{classVarName}}.{{name}}){{^-last}} &&
+ return {{#vars}}{{#vendorExtensions.x-is-jackson-optional-nullable}}equalsNullable(this.{{name}}, {{classVarName}}.{{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^vendorExtensions.x-is-jackson-optional-nullable}}{{#isByteArray}}Arrays{{/isByteArray}}{{^isByteArray}}Objects{{/isByteArray}}.equals(this.{{name}}, {{classVarName}}.{{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^-last}} &&
{{/-last}}{{/vars}}{{#parent}} &&
super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}}
return true;{{/hasVars}}
- }
+ }{{#vendorExtensions.x-jackson-optional-nullable-helpers}}
+
+ private static boolean equalsNullable(JsonNullable a, JsonNullable b) {
+ return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && a.get().getClass().isArray() ? Arrays.equals((T[])a.get(), (T[])b.get()) : Objects.equals(a.get(), b.get()));
+ }{{/vendorExtensions.x-jackson-optional-nullable-helpers}}
@Override
public int hashCode() {
- return Objects.hash({{#vars}}{{^isByteArray}}{{name}}{{/isByteArray}}{{#isByteArray}}Arrays.hashCode({{name}}){{/isByteArray}}{{^-last}}, {{/-last}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}});
- }
+ return Objects.hash({{#vars}}{{#vendorExtensions.x-is-jackson-optional-nullable}}hashCodeNullable({{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^vendorExtensions.x-is-jackson-optional-nullable}}{{^isByteArray}}{{name}}{{/isByteArray}}{{#isByteArray}}Arrays.hashCode({{name}}){{/isByteArray}}{{/vendorExtensions.x-is-jackson-optional-nullable}}{{^-last}}, {{/-last}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}});
+ }{{#vendorExtensions.x-jackson-optional-nullable-helpers}}
+
+ private static int hashCodeNullable(JsonNullable a) {
+ if (a == null) {
+ return 1;
+ }
+ return a.isPresent()
+ ? (a.get().getClass().isArray() ? Arrays.hashCode((T[])a.get()) : Objects.hashCode(a.get()))
+ : 31;
+ }{{/vendorExtensions.x-jackson-optional-nullable-helpers}}
@Override
public String toString() {
diff --git a/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig b/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig
index a213327b3f7..df636589cd5 100644
--- a/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig
+++ b/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig
@@ -55,6 +55,7 @@ org.openapitools.codegen.languages.HaskellServantCodegen
org.openapitools.codegen.languages.JavaClientCodegen
org.openapitools.codegen.languages.JavaCXFClientCodegen
org.openapitools.codegen.languages.JavaInflectorServerCodegen
+org.openapitools.codegen.languages.JavaMicronautClientCodegen
org.openapitools.codegen.languages.JavaMSF4JServerCodegen
org.openapitools.codegen.languages.JavaPKMSTServerCodegen
org.openapitools.codegen.languages.JavaPlayFrameworkCodegen
@@ -93,6 +94,7 @@ org.openapitools.codegen.languages.PhpSlim4ServerCodegen
org.openapitools.codegen.languages.PhpSilexServerCodegen
org.openapitools.codegen.languages.PhpSymfonyServerCodegen
org.openapitools.codegen.languages.PhpMezzioPathHandlerServerCodegen
+org.openapitools.codegen.languages.PhpDataTransferClientCodegen
org.openapitools.codegen.languages.PowerShellClientCodegen
org.openapitools.codegen.languages.ProtobufSchemaCodegen
org.openapitools.codegen.languages.PythonLegacyClientCodegen
diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/2.0/controller.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/2.0/controller.mustache
index de15c470d1e..a1b1701985d 100644
--- a/modules/openapi-generator/src/main/resources/aspnetcore/2.0/controller.mustache
+++ b/modules/openapi-generator/src/main/resources/aspnetcore/2.0/controller.mustache
@@ -23,7 +23,7 @@ namespace {{packageName}}.Controllers
/// {{#summary}}{{summary}}{{/summary}}
/// {{#notes}}
/// {{notes}}{{/notes}}{{#allParams}}
- /// {{description}}{{/allParams}}{{#responses}}
+ /// {{description}}{{#isDeprecated}} (deprecated){{/isDeprecated}}{{/allParams}}{{#responses}}
/// {{message}}{{/responses}}
[{{httpMethod}}]
[Route("{{{basePathWithoutHost}}}{{{path}}}")]
@@ -33,6 +33,9 @@ namespace {{packageName}}.Controllers
[ValidateModelState]{{#useSwashbuckle}}
[SwaggerOperation("{{operationId}}")]{{#responses}}{{#dataType}}
[SwaggerResponse(statusCode: {{code}}, type: typeof({{&dataType}}), description: "{{message}}")]{{/dataType}}{{^dataType}}{{/dataType}}{{/responses}}{{/useSwashbuckle}}
+ {{#isDeprecated}}
+ [Obsolete]
+ {{/isDeprecated}}
public virtual IActionResult {{operationId}}({{#allParams}}{{>pathParam}}{{>queryParam}}{{>bodyParam}}{{>formParam}}{{>headerParam}}{{^-last}}, {{/-last}}{{/allParams}})
{ {{#responses}}
{{#dataType}}
diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/2.1/controller.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/2.1/controller.mustache
index 4cc411514c5..c8203923b9d 100644
--- a/modules/openapi-generator/src/main/resources/aspnetcore/2.1/controller.mustache
+++ b/modules/openapi-generator/src/main/resources/aspnetcore/2.1/controller.mustache
@@ -31,7 +31,7 @@ namespace {{apiPackage}}
/// {{#summary}}{{summary}}{{/summary}}
/// {{#notes}}
/// {{notes}}{{/notes}}{{#allParams}}
- /// {{description}}{{/allParams}}{{#responses}}
+ /// {{description}}{{#isDeprecated}} (deprecated){{/isDeprecated}}{{/allParams}}{{#responses}}
/// {{message}}{{/responses}}
[{{httpMethod}}]
[Route("{{{basePathWithoutHost}}}{{{path}}}")]
@@ -50,6 +50,9 @@ namespace {{apiPackage}}
[SwaggerOperation("{{operationId}}")]{{#responses}}{{#dataType}}
[SwaggerResponse(statusCode: {{code}}, type: typeof({{&dataType}}), description: "{{message}}")]{{/dataType}}{{^dataType}}{{/dataType}}{{/responses}}{{/useSwashbuckle}}{{^useSwashbuckle}}{{#responses}}{{#dataType}}
[ProducesResponseType(statusCode: {{code}}, type: typeof({{&dataType}}))]{{/dataType}}{{^dataType}}{{/dataType}}{{/responses}}{{/useSwashbuckle}}
+ {{#isDeprecated}}
+ [Obsolete]
+ {{/isDeprecated}}
public {{operationModifier}} {{#operationResultTask}}{{#operationIsAsync}}async {{/operationIsAsync}}Task<{{/operationResultTask}}IActionResult{{#operationResultTask}}>{{/operationResultTask}} {{operationId}}({{#allParams}}{{>pathParam}}{{>queryParam}}{{>bodyParam}}{{>formParam}}{{>headerParam}}{{^-last}}{{^isCookieParam}}, {{/isCookieParam}}{{/-last}}{{/allParams}}){{^generateBody}};{{/generateBody}}
{{#generateBody}}
{
diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/controller.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/controller.mustache
index 9de20cebc10..9f6fcc803df 100644
--- a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/controller.mustache
+++ b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/controller.mustache
@@ -31,7 +31,7 @@ namespace {{apiPackage}}
/// {{#summary}}{{summary}}{{/summary}}
/// {{#notes}}
/// {{notes}}{{/notes}}{{#allParams}}
- /// {{description}}{{/allParams}}{{#responses}}
+ /// {{description}}{{#isDeprecated}} (deprecated){{/isDeprecated}}{{/allParams}}{{#responses}}
/// {{message}}{{/responses}}
[{{httpMethod}}]
[Route("{{{basePathWithoutHost}}}{{{path}}}")]
@@ -50,6 +50,9 @@ namespace {{apiPackage}}
[SwaggerOperation("{{operationId}}")]{{#responses}}{{#dataType}}
[SwaggerResponse(statusCode: {{code}}, type: typeof({{&dataType}}), description: "{{message}}")]{{/dataType}}{{^dataType}}{{/dataType}}{{/responses}}{{/useSwashbuckle}}{{^useSwashbuckle}}{{#responses}}{{#dataType}}
[ProducesResponseType(statusCode: {{code}}, type: typeof({{&dataType}}))]{{/dataType}}{{^dataType}}{{/dataType}}{{/responses}}{{/useSwashbuckle}}
+ {{#isDeprecated}}
+ [Obsolete]
+ {{/isDeprecated}}
public {{operationModifier}} {{#operationResultTask}}{{#operationIsAsync}}async {{/operationIsAsync}}Task<{{/operationResultTask}}IActionResult{{#operationResultTask}}>{{/operationResultTask}} {{operationId}}({{#allParams}}{{>pathParam}}{{>queryParam}}{{>bodyParam}}{{>formParam}}{{>headerParam}}{{^-last}}{{^isCookieParam}}, {{/isCookieParam}}{{/-last}}{{/allParams}}){{^generateBody}};{{/generateBody}}
{{#generateBody}}
{
diff --git a/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-source.mustache b/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-source.mustache
index dad2eb75c6c..7418caa9cdd 100644
--- a/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-source.mustache
+++ b/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-source.mustache
@@ -42,7 +42,7 @@ std::pair {{classname}}::handleParsingExcepti
} catch ({{helpersNamespace}}::ValidationException &e) {
return std::make_pair(Pistache::Http::Code::Bad_Request, e.what());
} catch (std::exception &e) {
- return std::make_pair(Pistache::Http::Code::Internal_Server_Error, e.what())
+ return std::make_pair(Pistache::Http::Code::Internal_Server_Error, e.what());
}
}
diff --git a/modules/openapi-generator/src/main/resources/csharp-dotnet2/api.mustache b/modules/openapi-generator/src/main/resources/csharp-dotnet2/api.mustache
index cfaf28d4cef..5990a0fbbd8 100644
--- a/modules/openapi-generator/src/main/resources/csharp-dotnet2/api.mustache
+++ b/modules/openapi-generator/src/main/resources/csharp-dotnet2/api.mustache
@@ -17,8 +17,11 @@ namespace {{apiPackage}}
///
/// {{summary}} {{notes}}
///
- {{#allParams}}/// {{description}}
+ {{#allParams}}/// {{description}}{{#isDeprecated}} (deprecated){{/isDeprecated}}
{{/allParams}}/// {{#returnType}}{{returnType}}{{/returnType}}
+ {{#isDeprecated}}
+ [Obsolete]
+ {{/isDeprecated}}
{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}});
{{/operation}}
}
@@ -80,8 +83,11 @@ namespace {{apiPackage}}
///
/// {{summary}} {{notes}}
///
- {{#allParams}}/// {{description}}
+ {{#allParams}}/// {{description}}{{#isDeprecated}} (deprecated){{/isDeprecated}}
{{/allParams}}/// {{#returnType}}{{returnType}}{{/returnType}}
+ {{#isDeprecated}}
+ [Obsolete]
+ {{/isDeprecated}}
public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}})
{
{{#allParams}}{{#required}}
diff --git a/modules/openapi-generator/src/main/resources/csharp-dotnet2/model.mustache b/modules/openapi-generator/src/main/resources/csharp-dotnet2/model.mustache
index 7c3311e1fd6..f9e13ed8f3c 100644
--- a/modules/openapi-generator/src/main/resources/csharp-dotnet2/model.mustache
+++ b/modules/openapi-generator/src/main/resources/csharp-dotnet2/model.mustache
@@ -21,6 +21,9 @@ namespace {{modelPackage}} {
/// {{{description}}}{{/description}}
[DataMember(Name="{{baseName}}", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "{{baseName}}")]
+ {{#deprecated}}
+ [Obsolete]
+ {{/deprecated}}
public {{{dataType}}} {{name}} { get; set; }
{{/vars}}
diff --git a/modules/openapi-generator/src/main/resources/csharp-nancyfx/api.mustache b/modules/openapi-generator/src/main/resources/csharp-nancyfx/api.mustache
index 02538ba251c..eb34a7fd50e 100644
--- a/modules/openapi-generator/src/main/resources/csharp-nancyfx/api.mustache
+++ b/modules/openapi-generator/src/main/resources/csharp-nancyfx/api.mustache
@@ -45,8 +45,11 @@ namespace {{packageName}}.{{packageContext}}.Modules
/// {{notes}}
///
/// Context of request
- {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
+ {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}}
{{/allParams}}/// {{#returnType}}{{returnType}}{{/returnType}}
+ {{#isDeprecated}}
+ [Obsolete]
+ {{/isDeprecated}}
{{#asyncServer}}{{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}}{{/asyncServer}}{{^asyncServer}}{{#returnType}}{{&returnType}}{{/returnType}}{{^returnType}}void{{/returnType}}{{/asyncServer}} {{operationId}}(NancyContext context{{#allParams.0}}, {{/allParams.0}}{{>paramsList}});{{^-last}}
{{/-last}}{{/operation}}
@@ -57,14 +60,16 @@ namespace {{packageName}}.{{packageContext}}.Modules
///
public abstract class Abstract{{classname}}Service: {{interfacePrefix}}{{classname}}Service
{
- {{#operation}}public virtual {{#asyncServer}}{{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}}{{/asyncServer}}{{^asyncServer}}{{#returnType}}{{&returnType}}{{/returnType}}{{^returnType}}void{{/returnType}}{{/asyncServer}} {{operationId}}(NancyContext context{{#allParams.0}}, {{/allParams.0}}{{>paramsList}})
+ {{#operation}}{{#isDeprecated}}[Obsolete]
+ {{/isDeprecated}}public virtual {{#asyncServer}}{{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}}{{/asyncServer}}{{^asyncServer}}{{#returnType}}{{&returnType}}{{/returnType}}{{^returnType}}void{{/returnType}}{{/asyncServer}} {{operationId}}(NancyContext context{{#allParams.0}}, {{/allParams.0}}{{>paramsList}})
{
{{^asyncServer}}{{#returnType}}return {{/returnType}}{{/asyncServer}}{{#asyncServer}}return {{/asyncServer}}{{operationId}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});
}{{^-last}}
{{/-last}}{{/operation}}
- {{#operation}}protected abstract {{#asyncServer}}{{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}}{{/asyncServer}}{{^asyncServer}}{{#returnType}}{{&returnType}}{{/returnType}}{{^returnType}}void{{/returnType}}{{/asyncServer}} {{operationId}}({{>paramsList}});{{^-last}}
+ {{#operation}}{{#isDeprecated}}[Obsolete]
+ {{/isDeprecated}}protected abstract {{#asyncServer}}{{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}}{{/asyncServer}}{{^asyncServer}}{{#returnType}}{{&returnType}}{{/returnType}}{{^returnType}}void{{/returnType}}{{/asyncServer}} {{operationId}}({{>paramsList}});{{^-last}}
{{/-last}}{{/operation}}
}
diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/HttpSigningConfiguration.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/HttpSigningConfiguration.mustache
index cc8c275e40b..c762fda011f 100644
--- a/modules/openapi-generator/src/main/resources/csharp-netcore/HttpSigningConfiguration.mustache
+++ b/modules/openapi-generator/src/main/resources/csharp-netcore/HttpSigningConfiguration.mustache
@@ -193,7 +193,7 @@ namespace {{packageName}}.Client
}
else if (header.Equals(HEADER_DATE))
{
- var utcDateTime = dateTime.ToString("r").ToString();
+ var utcDateTime = dateTime.ToUniversalTime().ToString("r");
HttpSignatureHeader.Add(header.ToLower(), utcDateTime);
HttpSignedRequestHeader.Add(HEADER_DATE, utcDateTime);
}
diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/WebRequestPathBuilder.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/WebRequestPathBuilder.mustache
index 8175f0e5757..30e5181eeac 100644
--- a/modules/openapi-generator/src/main/resources/csharp-netcore/WebRequestPathBuilder.mustache
+++ b/modules/openapi-generator/src/main/resources/csharp-netcore/WebRequestPathBuilder.mustache
@@ -1,5 +1,6 @@
{{>partial_header}}
using System.Collections.Generic;
+using System.Web;
namespace {{packageName}}.Client
{
@@ -21,7 +22,7 @@ namespace {{packageName}}.Client
{
foreach (var parameter in parameters)
{
- _path = _path.Replace("{" + parameter.Key + "}", parameter.Value);
+ _path = _path.Replace("{" + parameter.Key + "}", HttpUtility.UrlEncode(parameter.Value));
}
}
@@ -31,7 +32,7 @@ namespace {{packageName}}.Client
{
foreach (var value in parameter.Value)
{
- _query = _query + parameter.Key + "=" + value + "&";
+ _query = _query + parameter.Key + "=" + HttpUtility.UrlEncode(value) + "&";
}
}
}
diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/api.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/api.mustache
index 8d84eecefb4..bb4894411bc 100644
--- a/modules/openapi-generator/src/main/resources/csharp-netcore/api.mustache
+++ b/modules/openapi-generator/src/main/resources/csharp-netcore/api.mustache
@@ -30,8 +30,11 @@ namespace {{packageName}}.{{apiPackage}}
///
{{/notes}}
/// Thrown when fails to make API call
- {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
+ {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}}
{{/allParams}}/// {{#returnType}}{{returnType}}{{/returnType}}
+ {{#isDeprecated}}
+ [Obsolete]
+ {{/isDeprecated}}
{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}});
///
@@ -41,8 +44,11 @@ namespace {{packageName}}.{{apiPackage}}
/// {{notes}}
///
/// Thrown when fails to make API call
- {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
+ {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}}
{{/allParams}}/// ApiResponse of {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Object(void){{/returnType}}
+ {{#isDeprecated}}
+ [Obsolete]
+ {{/isDeprecated}}
ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}});
{{/operation}}
#endregion Synchronous Operations
@@ -64,10 +70,13 @@ namespace {{packageName}}.{{apiPackage}}
///
/// Thrown when fails to make API call
{{#allParams}}
- /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
+ /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}}
{{/allParams}}
/// Cancellation Token to cancel the request.
/// Task of {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}void{{/returnType}}
+ {{#isDeprecated}}
+ [Obsolete]
+ {{/isDeprecated}}
{{#returnType}}System.Threading.Tasks.Task<{{{returnType}}}>{{/returnType}}{{^returnType}}System.Threading.Tasks.Task{{/returnType}} {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
///
@@ -78,10 +87,13 @@ namespace {{packageName}}.{{apiPackage}}
///
/// Thrown when fails to make API call
{{#allParams}}
- /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
+ /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}}
{{/allParams}}
/// Cancellation Token to cancel the request.
/// Task of ApiResponse{{#returnType}} ({{returnType}}){{/returnType}}
+ {{#isDeprecated}}
+ [Obsolete]
+ {{/isDeprecated}}
System.Threading.Tasks.Task> {{operationId}}WithHttpInfoAsync({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
{{/operation}}
#endregion Asynchronous Operations
@@ -220,8 +232,11 @@ namespace {{packageName}}.{{apiPackage}}
/// {{summary}} {{notes}}
///
/// Thrown when fails to make API call
- {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
+ {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}}
{{/allParams}}/// {{#returnType}}{{returnType}}{{/returnType}}
+ {{#isDeprecated}}
+ [Obsolete]
+ {{/isDeprecated}}
public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}})
{
{{#returnType}}{{packageName}}.Client.ApiResponse<{{{returnType}}}> localVarResponse = {{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});
@@ -232,8 +247,11 @@ namespace {{packageName}}.{{apiPackage}}
/// {{summary}} {{notes}}
///
/// Thrown when fails to make API call
- {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
+ {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}}
{{/allParams}}/// ApiResponse of {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Object(void){{/returnType}}
+ {{#isDeprecated}}
+ [Obsolete]
+ {{/isDeprecated}}
public {{packageName}}.Client.ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}})
{
{{#allParams}}
@@ -429,10 +447,13 @@ namespace {{packageName}}.{{apiPackage}}
///
/// Thrown when fails to make API call
{{#allParams}}
- /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
+ /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}}
{{/allParams}}
/// Cancellation Token to cancel the request.
/// Task of {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}void{{/returnType}}
+ {{#isDeprecated}}
+ [Obsolete]
+ {{/isDeprecated}}
{{#returnType}}public async System.Threading.Tasks.Task<{{{returnType}}}>{{/returnType}}{{^returnType}}public async System.Threading.Tasks.Task{{/returnType}} {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
{{#returnType}}{{packageName}}.Client.ApiResponse<{{{returnType}}}> localVarResponse = await {{operationId}}WithHttpInfoAsync({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}cancellationToken).ConfigureAwait(false);
@@ -444,10 +465,13 @@ namespace {{packageName}}.{{apiPackage}}
///
/// Thrown when fails to make API call
{{#allParams}}
- /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
+ /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}}
{{/allParams}}
/// Cancellation Token to cancel the request.
/// Task of ApiResponse{{#returnType}} ({{returnType}}){{/returnType}}
+ {{#isDeprecated}}
+ [Obsolete]
+ {{/isDeprecated}}
public async System.Threading.Tasks.Task<{{packageName}}.Client.ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}>> {{operationId}}WithHttpInfoAsync({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
{{#allParams}}
diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/ApiClient.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/ApiClient.mustache
index e9c39ea9f6d..027fc537743 100644
--- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/ApiClient.mustache
+++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/ApiClient.mustache
@@ -158,7 +158,7 @@ namespace {{packageName}}.Client
}
}
///
- /// Provides a default implementation of an Api client (both synchronous and asynchronous implementatios),
+ /// Provides a default implementation of an Api client (both synchronous and asynchronous implementations),
/// encapsulating general REST accessor use cases.
///
///
diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/api.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/api.mustache
index 20ddfe96b98..bf3e4377995 100644
--- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/api.mustache
+++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/api.mustache
@@ -31,8 +31,11 @@ namespace {{packageName}}.{{apiPackage}}
///
{{/notes}}
/// Thrown when fails to make API call
- {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
+ {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}}
{{/allParams}}/// {{#returnType}}{{returnType}}{{/returnType}}
+ {{#isDeprecated}}
+ [Obsolete]
+ {{/isDeprecated}}
{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}});
///
@@ -42,8 +45,11 @@ namespace {{packageName}}.{{apiPackage}}
/// {{notes}}
///
/// Thrown when fails to make API call
- {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
+ {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}}
{{/allParams}}/// ApiResponse of {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Object(void){{/returnType}}
+ {{#isDeprecated}}
+ [Obsolete]
+ {{/isDeprecated}}
ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}});
{{/operation}}
#endregion Synchronous Operations
@@ -65,10 +71,13 @@ namespace {{packageName}}.{{apiPackage}}
///
/// Thrown when fails to make API call
{{#allParams}}
- /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
+ /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}}
{{/allParams}}
/// Cancellation Token to cancel the request.
/// Task of {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}void{{/returnType}}
+ {{#isDeprecated}}
+ [Obsolete]
+ {{/isDeprecated}}
{{#returnType}}System.Threading.Tasks.Task<{{{returnType}}}>{{/returnType}}{{^returnType}}System.Threading.Tasks.Task{{/returnType}} {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
///
@@ -79,10 +88,13 @@ namespace {{packageName}}.{{apiPackage}}
///
/// Thrown when fails to make API call
{{#allParams}}
- /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
+ /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}}
{{/allParams}}
/// Cancellation Token to cancel the request.
/// Task of ApiResponse{{#returnType}} ({{returnType}}){{/returnType}}
+ {{#isDeprecated}}
+ [Obsolete]
+ {{/isDeprecated}}
System.Threading.Tasks.Task> {{operationId}}WithHttpInfoAsync({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
{{/operation}}
#endregion Asynchronous Operations
@@ -318,8 +330,11 @@ namespace {{packageName}}.{{apiPackage}}
/// {{summary}} {{notes}}
///
/// Thrown when fails to make API call
- {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
+ {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}}
{{/allParams}}/// {{#returnType}}{{returnType}}{{/returnType}}
+ {{#isDeprecated}}
+ [Obsolete]
+ {{/isDeprecated}}
public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}})
{
{{#returnType}}{{packageName}}.Client.ApiResponse<{{{returnType}}}> localVarResponse = {{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});
@@ -330,8 +345,11 @@ namespace {{packageName}}.{{apiPackage}}
/// {{summary}} {{notes}}
///
/// Thrown when fails to make API call
- {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
+ {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}}
{{/allParams}}/// ApiResponse of {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Object(void){{/returnType}}
+ {{#isDeprecated}}
+ [Obsolete]
+ {{/isDeprecated}}
public {{packageName}}.Client.ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}})
{
{{#allParams}}
@@ -527,10 +545,13 @@ namespace {{packageName}}.{{apiPackage}}
///
/// Thrown when fails to make API call
{{#allParams}}
- /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
+ /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}}
{{/allParams}}
/// Cancellation Token to cancel the request.
/// Task of {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}void{{/returnType}}
+ {{#isDeprecated}}
+ [Obsolete]
+ {{/isDeprecated}}
{{#returnType}}public async System.Threading.Tasks.Task<{{{returnType}}}>{{/returnType}}{{^returnType}}public async System.Threading.Tasks.Task{{/returnType}} {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
{{#returnType}}{{packageName}}.Client.ApiResponse<{{{returnType}}}> localVarResponse = await {{operationId}}WithHttpInfoAsync({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}cancellationToken).ConfigureAwait(false);
@@ -542,10 +563,13 @@ namespace {{packageName}}.{{apiPackage}}
///
/// Thrown when fails to make API call
{{#allParams}}
- /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
+ /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}}
{{/allParams}}
/// Cancellation Token to cancel the request.
/// Task of ApiResponse{{#returnType}} ({{returnType}}){{/returnType}}
+ {{#isDeprecated}}
+ [Obsolete]
+ {{/isDeprecated}}
public async System.Threading.Tasks.Task<{{packageName}}.Client.ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}>> {{operationId}}WithHttpInfoAsync({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
{{#allParams}}
diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/modelAnyOf.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/modelAnyOf.mustache
index 931f7646da8..c1b96657ae0 100644
--- a/modules/openapi-generator/src/main/resources/csharp-netcore/modelAnyOf.mustache
+++ b/modules/openapi-generator/src/main/resources/csharp-netcore/modelAnyOf.mustache
@@ -100,7 +100,7 @@
{
{{classname}} new{{classname}} = null;
- if (jsonString == null)
+ if (string.IsNullOrEmpty(jsonString))
{
return new{{classname}};
}
diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/modelEnum.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/modelEnum.mustache
index 39bcd2eddc1..c977374019f 100644
--- a/modules/openapi-generator/src/main/resources/csharp-netcore/modelEnum.mustache
+++ b/modules/openapi-generator/src/main/resources/csharp-netcore/modelEnum.mustache
@@ -18,7 +18,7 @@
{{#allowableValues}}
{{#enumVars}}
///
- /// Enum {{name}} for value: {{{value}}}
+ /// Enum {{name}} for value: {{value}}
///
{{#isString}}
[EnumMember(Value = "{{{value}}}")]
diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/modelGeneric.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/modelGeneric.mustache
index 6eb1a2359d0..ad65a3b8361 100644
--- a/modules/openapi-generator/src/main/resources/csharp-netcore/modelGeneric.mustache
+++ b/modules/openapi-generator/src/main/resources/csharp-netcore/modelGeneric.mustache
@@ -33,6 +33,9 @@
{{/description}}
{{^conditionalSerialization}}
[DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})]
+ {{#deprecated}}
+ [Obsolete]
+ {{/deprecated}}
public {{#complexType}}{{{complexType}}}{{/complexType}}{{^complexType}}{{{datatypeWithEnum}}}{{/complexType}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}} {{name}} { get; set; }
{{#isReadOnly}}
@@ -49,6 +52,9 @@
{{#conditionalSerialization}}
{{#isReadOnly}}
[DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})]
+ {{#deprecated}}
+ [Obsolete]
+ {{/deprecated}}
public {{#complexType}}{{{complexType}}}{{/complexType}}{{^complexType}}{{{datatypeWithEnum}}}{{/complexType}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}} {{name}} { get; set; }
@@ -64,6 +70,9 @@
{{^isReadOnly}}
[DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})]
+ {{#deprecated}}
+ [Obsolete]
+ {{/deprecated}}
public {{#complexType}}{{{complexType}}}{{/complexType}}{{^complexType}}{{{datatypeWithEnum}}}{{/complexType}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}} {{name}}
{
get{ return _{{name}};}
@@ -184,6 +193,9 @@
{{#isDate}}
[JsonConverter(typeof(OpenAPIDateConverter))]
{{/isDate}}
+ {{#deprecated}}
+ [Obsolete]
+ {{/deprecated}}
public {{{dataType}}} {{name}} { get; {{#isReadOnly}}private {{/isReadOnly}}set; }
{{#isReadOnly}}
@@ -203,6 +215,9 @@
{{#isDate}}
[JsonConverter(typeof(OpenAPIDateConverter))]
{{/isDate}}
+ {{#deprecated}}
+ [Obsolete]
+ {{/deprecated}}
public {{{dataType}}} {{name}} { get; private set; }
///
@@ -219,6 +234,9 @@
[JsonConverter(typeof(OpenAPIDateConverter))]
{{/isDate}}
[DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})]
+ {{#deprecated}}
+ [Obsolete]
+ {{/deprecated}}
public {{{dataType}}} {{name}}
{
get{ return _{{name}};}
diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/modelInnerEnum.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/modelInnerEnum.mustache
index d9e96dccdb3..90090fea8c9 100644
--- a/modules/openapi-generator/src/main/resources/csharp-netcore/modelInnerEnum.mustache
+++ b/modules/openapi-generator/src/main/resources/csharp-netcore/modelInnerEnum.mustache
@@ -13,7 +13,7 @@
{{#allowableValues}}
{{#enumVars}}
///
- /// Enum {{name}} for value: {{{value}}}
+ /// Enum {{name}} for value: {{value}}
///
{{#isString}}
[EnumMember(Value = "{{{value}}}")]
diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/modelOneOf.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/modelOneOf.mustache
index d2d6e28b3f9..59e2dbf19eb 100644
--- a/modules/openapi-generator/src/main/resources/csharp-netcore/modelOneOf.mustache
+++ b/modules/openapi-generator/src/main/resources/csharp-netcore/modelOneOf.mustache
@@ -100,7 +100,7 @@
{
{{classname}} new{{classname}} = null;
- if (jsonString == null)
+ if (string.IsNullOrEmpty(jsonString))
{
return new{{classname}};
}
diff --git a/modules/openapi-generator/src/main/resources/csharp/api.mustache b/modules/openapi-generator/src/main/resources/csharp/api.mustache
index 700d2bdb2be..8e80b857ad5 100644
--- a/modules/openapi-generator/src/main/resources/csharp/api.mustache
+++ b/modules/openapi-generator/src/main/resources/csharp/api.mustache
@@ -31,8 +31,11 @@ namespace {{packageName}}.{{apiPackage}}
/// {{notes}}
///
/// Thrown when fails to make API call
- {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
+ {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}}
{{/allParams}}/// {{#returnType}}{{returnType}}{{/returnType}}
+ {{#isDeprecated}}
+ [Obsolete]
+ {{/isDeprecated}}
{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}} ({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}});
///
@@ -42,8 +45,11 @@ namespace {{packageName}}.{{apiPackage}}
/// {{notes}}
///
/// Thrown when fails to make API call
- {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
+ {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}}
{{/allParams}}/// ApiResponse of {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Object(void){{/returnType}}
+ {{#isDeprecated}}
+ [Obsolete]
+ {{/isDeprecated}}
ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}WithHttpInfo ({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}});
{{/operation}}
#endregion Synchronous Operations
@@ -57,9 +63,12 @@ namespace {{packageName}}.{{apiPackage}}
/// {{notes}}
///
/// Thrown when fails to make API call
- {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
+ {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}}
{{/allParams}}/// Cancellation Token to cancel request (optional)
/// Task of {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}void{{/returnType}}
+ {{#isDeprecated}}
+ [Obsolete]
+ {{/isDeprecated}}
{{#returnType}}System.Threading.Tasks.Task<{{{returnType}}}>{{/returnType}}{{^returnType}}System.Threading.Tasks.Task{{/returnType}} {{operationId}}Async ({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}CancellationToken cancellationToken = default(CancellationToken));
///
@@ -69,9 +78,12 @@ namespace {{packageName}}.{{apiPackage}}
/// {{notes}}
///
/// Thrown when fails to make API call
- {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
+ {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}}
{{/allParams}}/// Cancellation Token to cancel request (optional)
/// Task of ApiResponse{{#returnType}} ({{returnType}}){{/returnType}}
+ {{#isDeprecated}}
+ [Obsolete]
+ {{/isDeprecated}}
System.Threading.Tasks.Task> {{operationId}}WithHttpInfoAsync ({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}CancellationToken cancellationToken = default(CancellationToken));
{{/operation}}
#endregion Asynchronous Operations
@@ -191,8 +203,11 @@ namespace {{packageName}}.{{apiPackage}}
/// {{summary}} {{notes}}
///
/// Thrown when fails to make API call
- {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
+ {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}}
{{/allParams}}/// {{#returnType}}{{returnType}}{{/returnType}}
+ {{#isDeprecated}}
+ [Obsolete]
+ {{/isDeprecated}}
public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}} ({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}})
{
{{#returnType}}ApiResponse<{{{returnType}}}> localVarResponse = {{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});
@@ -203,8 +218,11 @@ namespace {{packageName}}.{{apiPackage}}
/// {{summary}} {{notes}}
///
/// Thrown when fails to make API call
- {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
+ {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}}
{{/allParams}}/// ApiResponse of {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Object(void){{/returnType}}
+ {{#isDeprecated}}
+ [Obsolete]
+ {{/isDeprecated}}
public ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}WithHttpInfo ({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}})
{
{{#allParams}}
@@ -335,9 +353,12 @@ namespace {{packageName}}.{{apiPackage}}
/// {{summary}} {{notes}}
///
/// Thrown when fails to make API call
- {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
+ {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}}
{{/allParams}}/// Cancellation Token to cancel request (optional)
/// Task of {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}void{{/returnType}}
+ {{#isDeprecated}}
+ [Obsolete]
+ {{/isDeprecated}}
{{#returnType}}public async System.Threading.Tasks.Task<{{{returnType}}}>{{/returnType}}{{^returnType}}public async System.Threading.Tasks.Task{{/returnType}} {{operationId}}Async ({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}CancellationToken cancellationToken = default(CancellationToken))
{
{{#returnType}}ApiResponse<{{{returnType}}}> localVarResponse = await {{operationId}}WithHttpInfoAsync({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}cancellationToken);
@@ -349,9 +370,12 @@ namespace {{packageName}}.{{apiPackage}}
/// {{summary}} {{notes}}
///
/// Thrown when fails to make API call
- {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
+ {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}}
{{/allParams}}/// Cancellation Token to cancel request (optional)
/// Task of ApiResponse{{#returnType}} ({{returnType}}){{/returnType}}
+ {{#isDeprecated}}
+ [Obsolete]
+ {{/isDeprecated}}
public async System.Threading.Tasks.Task> {{operationId}}WithHttpInfoAsync ({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}CancellationToken cancellationToken = default(CancellationToken))
{
{{#allParams}}
diff --git a/modules/openapi-generator/src/main/resources/csharp/modelGeneric.mustache b/modules/openapi-generator/src/main/resources/csharp/modelGeneric.mustache
index b2077256ffb..933ba0824ae 100644
--- a/modules/openapi-generator/src/main/resources/csharp/modelGeneric.mustache
+++ b/modules/openapi-generator/src/main/resources/csharp/modelGeneric.mustache
@@ -32,6 +32,9 @@
/// {{description}}
{{/description}}
[DataMember(Name="{{baseName}}", EmitDefaultValue={{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}{{#required}}true{{/required}}{{^required}}false{{/required}}{{/isNullable}}{{/vendorExtensions.x-emit-default-value}})]
+ {{#deprecated}}
+ [Obsolete]
+ {{/deprecated}}
public {{#complexType}}{{{complexType}}}{{/complexType}}{{^complexType}}{{{datatypeWithEnum}}}{{/complexType}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}} {{name}} { get; set; }
{{/isEnum}}
{{/vars}}
@@ -110,6 +113,9 @@ this.{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}};
/// {{description}}{{/description}}
[DataMember(Name="{{baseName}}", EmitDefaultValue={{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}{{#required}}true{{/required}}{{^required}}false{{/required}}{{/isNullable}}{{/vendorExtensions.x-emit-default-value}})]{{#isDate}}
[JsonConverter(typeof(OpenAPIDateConverter))]{{/isDate}}
+ {{#deprecated}}
+ [Obsolete]
+ {{/deprecated}}
public {{{dataType}}} {{name}} { get; {{#isReadOnly}}private {{/isReadOnly}}set; }
{{/isEnum}}
{{/isInherited}}
diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/api.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/api.mustache
index bcb912d6c26..295c6a67d7b 100644
--- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/api.mustache
+++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/api.mustache
@@ -44,10 +44,10 @@ class {{classname}} {
{{/isDeprecated}}
Future> {{nickname}}({ {{#allParams}}{{#isPathParam}}
required {{{dataType}}} {{paramName}},{{/isPathParam}}{{#isQueryParam}}
- {{#required}}required {{/required}}{{{dataType}}}{{^required}}?{{/required}} {{paramName}},{{/isQueryParam}}{{#isHeaderParam}}
- {{#required}}required {{/required}}{{{dataType}}}{{^required}}?{{/required}} {{paramName}},{{/isHeaderParam}}{{#isBodyParam}}
- {{#required}}required {{/required}}{{{dataType}}}{{^required}}?{{/required}} {{paramName}},{{/isBodyParam}}{{#isFormParam}}
- {{#required}}required {{/required}}{{{dataType}}}{{^required}}?{{/required}} {{paramName}},{{/isFormParam}}{{/allParams}}
+ {{#required}}{{^isNullable}}required {{/isNullable}}{{/required}}{{{dataType}}}{{#required}}{{#isNullable}}?{{/isNullable}}{{/required}}{{^required}}?{{/required}} {{paramName}}{{^isContainer}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}{{/isContainer}},{{/isQueryParam}}{{#isHeaderParam}}
+ {{#required}}{{^isNullable}}required {{/isNullable}}{{/required}}{{{dataType}}}{{#required}}{{#isNullable}}?{{/isNullable}}{{/required}}{{^required}}?{{/required}} {{paramName}}{{^isContainer}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}{{/isContainer}},{{/isHeaderParam}}{{#isBodyParam}}
+ {{#required}}{{^isNullable}}required {{/isNullable}}{{/required}}{{{dataType}}}{{#required}}{{#isNullable}}?{{/isNullable}}{{/required}}{{^required}}?{{/required}} {{paramName}},{{/isBodyParam}}{{#isFormParam}}
+ {{#required}}{{^isNullable}}required {{/isNullable}}{{/required}}{{{dataType}}}{{#required}}{{#isNullable}}?{{/isNullable}}{{/required}}{{^required}}?{{/required}} {{paramName}},{{/isFormParam}}{{/allParams}}
CancelToken? cancelToken,
Map? headers,
Map? extra,
diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/pubspec.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/pubspec.mustache
index 991de1e44b5..6bf879a4897 100644
--- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/pubspec.mustache
+++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/pubspec.mustache
@@ -9,8 +9,8 @@ environment:
dependencies:
dio: '>=4.0.0 <5.0.0'
{{#useBuiltValue}}
- built_value: '>=8.0.4 <9.0.0'
- built_collection: '>=5.0.0 <6.0.0'
+ built_value: '>=8.1.0 <9.0.0'
+ built_collection: '>=5.1.0 <6.0.0'
{{/useBuiltValue}}
{{#useDateLibTimeMachine}}
time_machine: ^0.9.16
@@ -18,7 +18,7 @@ dependencies:
dev_dependencies:
{{#useBuiltValue}}
- built_value_generator: '>=8.0.4 <9.0.0'
+ built_value_generator: '>=8.1.0 <9.0.0'
build_runner: any
{{/useBuiltValue}}
test: '>=1.16.0 <1.17.0'
diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/class.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/class.mustache
index 9eb53c756c7..816524bc73a 100644
--- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/class.mustache
+++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/class.mustache
@@ -33,7 +33,8 @@ abstract class {{classname}} implements Built<{{classname}}, {{classname}}Builde
{{/vars}}
{{classname}}._();
- static void _initializeBuilder({{{classname}}}Builder b) => b{{#vars}}{{#defaultValue}}
+ @BuiltValueHook(initializeBuilder: true)
+ static void _defaults({{{classname}}}Builder b) => b{{#vars}}{{#defaultValue}}
..{{{name}}} = {{#isEnum}}{{^isContainer}}const {{{enumName}}}._({{/isContainer}}{{/isEnum}}{{{defaultValue}}}{{#isEnum}}{{^isContainer}}){{/isContainer}}{{/isEnum}}{{/defaultValue}}{{/vars}};
factory {{classname}}([void updates({{classname}}Builder b)]) = _${{classname}};
diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/query_param.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/query_param.mustache
index 3a27e77225e..aa47f4f4394 100644
--- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/query_param.mustache
+++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/query_param.mustache
@@ -1 +1 @@
-{{#isContainer}}encodeCollectionQueryParameter<{{{baseType}}}>{{/isContainer}}{{^isContainer}}encodeQueryParameter{{/isContainer}}(_serializers, {{{paramName}}}, const FullType({{^isContainer}}{{{dataType}}}){{/isContainer}}{{#isContainer}}Built{{#isMap}}Map{{/isMap}}{{#isArray}}{{#uniqueItems}}Set{{/uniqueItems}}{{^uniqueItems}}List{{/uniqueItems}}{{/isArray}}, [{{#isMap}}FullType(String), {{/isMap}}FullType({{{baseType}}})]), format: ListFormat.{{collectionFormat}}{{/isContainer}})
\ No newline at end of file
+{{#isContainer}}{{#isMap}}encodeQueryParameter{{/isMap}}{{^isMap}}encodeCollectionQueryParameter<{{{baseType}}}>{{/isMap}}{{/isContainer}}{{^isContainer}}encodeQueryParameter{{/isContainer}}(_serializers, {{{paramName}}}, const FullType({{^isContainer}}{{{dataType}}}){{/isContainer}}{{#isContainer}}Built{{#isMap}}Map{{/isMap}}{{#isArray}}{{#uniqueItems}}Set{{/uniqueItems}}{{^uniqueItems}}List{{/uniqueItems}}{{/isArray}}, [{{#isMap}}FullType(String), {{/isMap}}FullType({{{baseType}}})]), {{#collectionFormat}}format: ListFormat.{{collectionFormat}},{{/collectionFormat}}{{/isContainer}})
\ No newline at end of file
diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/serialize.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/serialize.mustache
index 60dcd1773ba..54d8e99c757 100644
--- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/serialize.mustache
+++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/serialize.mustache
@@ -2,7 +2,7 @@
{{#isMultipart}}
_bodyData = FormData.fromMap({
{{#formParams}}
- {{^required}}{{^isNullable}}if ({{{paramName}}} != null) {{/isNullable}}{{/required}}r'{{{baseName}}}': {{#isFile}}{{{paramName}}}{{/isFile}}{{^isFile}}encodeFormParameter(_serializers, {{{paramName}}}, const FullType({{^isContainer}}{{{baseType}}}{{/isContainer}}{{#isContainer}}Built{{#isMap}}Map{{/isMap}}{{#isArray}}{{#uniqueItems}}Set{{/uniqueItems}}{{^uniqueItems}}List{{/uniqueItems}}{{/isArray}}, [{{#isMap}}FullType(String), {{/isMap}}FullType({{{baseType}}})]{{/isContainer}})){{/isFile}},
+ {{^required}}{{^isNullable}}if ({{{paramName}}} != null) {{/isNullable}}{{/required}}r'{{{baseName}}}': {{#isFile}}{{{paramName}}}{{#isArray}}.toList(){{/isArray}}{{/isFile}}{{^isFile}}encodeFormParameter(_serializers, {{{paramName}}}, const FullType({{^isContainer}}{{{baseType}}}{{/isContainer}}{{#isContainer}}Built{{#isMap}}Map{{/isMap}}{{#isArray}}{{#uniqueItems}}Set{{/uniqueItems}}{{^uniqueItems}}List{{/uniqueItems}}{{/isArray}}, [{{#isMap}}FullType(String), {{/isMap}}FullType({{{baseType}}})]{{/isContainer}})){{/isFile}},
{{/formParams}}
});
{{/isMultipart}}
@@ -16,7 +16,7 @@
{{/hasFormParams}}
{{#bodyParam}}
{{#isPrimitiveType}}
- _bodyData = {{paramName}}{{#isFile}}.finalize(){{/isFile}};
+ _bodyData = {{paramName}}{{#isFile}}{{#required}}{{#isNullable}}?{{/isNullable}}{{/required}}{{^required}}?{{/required}}.finalize(){{/isFile}};
{{/isPrimitiveType}}
{{^isPrimitiveType}}
{{#isContainer}}
diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/serializers.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/serializers.mustache
index 10925bc1112..e1f3dbe1df5 100644
--- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/serializers.mustache
+++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/serializers.mustache
@@ -11,7 +11,9 @@ import 'package:{{pubName}}/src/model/date.dart';{{/useDateLibCore}}
{{#useDateLibTimeMachine}}import 'package:time_machine/time_machine.dart';
import 'package:{{pubName}}/src/offset_date_serializer.dart';{{/useDateLibTimeMachine}}
{{#models}}{{#model}}import 'package:{{pubName}}/src/model/{{classFilename}}.dart';
-{{/model}}{{/models}}
+{{/model}}{{/models}}{{#builtValueSerializerImports}}import '{{{.}}}';
+{{/builtValueSerializerImports}}
+
part 'serializers.g.dart';
@SerializersFor([{{#models}}{{#model}}
diff --git a/modules/openapi-generator/src/main/resources/dart2/api_client.mustache b/modules/openapi-generator/src/main/resources/dart2/api_client.mustache
index d7f90713d5f..822fe2912c8 100644
--- a/modules/openapi-generator/src/main/resources/dart2/api_client.mustache
+++ b/modules/openapi-generator/src/main/resources/dart2/api_client.mustache
@@ -127,7 +127,7 @@ class ApiClient {
switch(method) {
case 'POST': return await _client.post(uri, headers: nullableHeaderParams, body: msgBody,);
case 'PUT': return await _client.put(uri, headers: nullableHeaderParams, body: msgBody,);
- case 'DELETE': return await _client.delete(uri, headers: nullableHeaderParams,);
+ case 'DELETE': return await _client.delete(uri, headers: nullableHeaderParams, body: msgBody,);
case 'PATCH': return await _client.patch(uri, headers: nullableHeaderParams, body: msgBody,);
case 'HEAD': return await _client.head(uri, headers: nullableHeaderParams,);
case 'GET': return await _client.get(uri, headers: nullableHeaderParams,);
diff --git a/modules/openapi-generator/src/main/resources/go-echo-server/api.mustache b/modules/openapi-generator/src/main/resources/go-echo-server/api.mustache
index 9ac9ad29838..6045cae0816 100644
--- a/modules/openapi-generator/src/main/resources/go-echo-server/api.mustache
+++ b/modules/openapi-generator/src/main/resources/go-echo-server/api.mustache
@@ -7,6 +7,9 @@ import (
){{#operation}}
// {{nickname}} - {{{summary}}}
+{{#isDeprecated}}
+// Deprecated
+{{/isDeprecated}}
func (c *Container) {{operationId}}(ctx echo.Context) error {
return ctx.JSON(http.StatusOK, models.HelloWorld {
Message: "Hello World",
diff --git a/modules/openapi-generator/src/main/resources/go-echo-server/main.mustache b/modules/openapi-generator/src/main/resources/go-echo-server/main.mustache
index ef0421cdd11..e8654aaa3f2 100644
--- a/modules/openapi-generator/src/main/resources/go-echo-server/main.mustache
+++ b/modules/openapi-generator/src/main/resources/go-echo-server/main.mustache
@@ -17,7 +17,7 @@ func main() {
e.Use(middleware.Recover())
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}
- // {{nickname}} - {{{summary}}}
+ // {{nickname}} - {{{summary}}}{{#isDeprecated}} (deprecated){{/isDeprecated}}
e.{{httpMethod.toUpperCase}}("{{{basePathWithoutHost}}}{{{path}}}", c.{{operationId}})
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
diff --git a/modules/openapi-generator/src/main/resources/go-echo-server/model.mustache b/modules/openapi-generator/src/main/resources/go-echo-server/model.mustache
index ef59462f11e..433d848254b 100644
--- a/modules/openapi-generator/src/main/resources/go-echo-server/model.mustache
+++ b/modules/openapi-generator/src/main/resources/go-echo-server/model.mustache
@@ -18,6 +18,9 @@ const (
type {{classname}} struct {
{{#vars}}{{#description}}
// {{{description}}}{{/description}}
+ {{#deprecated}}
+ // Deprecated
+ {{/deprecated}}
{{name}} {{#isNullable}}*{{/isNullable}}{{{dataType}}} `json:"{{baseName}}{{^required}},omitempty{{/required}}"{{#vendorExtensions.x-go-custom-tag}} {{{.}}}{{/vendorExtensions.x-go-custom-tag}}`
{{/vars}}
}{{/isEnum}}{{/model}}{{/models}}
diff --git a/modules/openapi-generator/src/main/resources/go-gin-server/controller-api.mustache b/modules/openapi-generator/src/main/resources/go-gin-server/controller-api.mustache
index 36eaf59209f..daad0d7dfff 100644
--- a/modules/openapi-generator/src/main/resources/go-gin-server/controller-api.mustache
+++ b/modules/openapi-generator/src/main/resources/go-gin-server/controller-api.mustache
@@ -9,6 +9,9 @@ import (
){{#operation}}
// {{nickname}} - {{{summary}}}
+{{#isDeprecated}}
+// Deprecated
+{{/isDeprecated}}
func {{nickname}}(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{})
}{{/operation}}{{/operations}}
diff --git a/modules/openapi-generator/src/main/resources/go-gin-server/model.mustache b/modules/openapi-generator/src/main/resources/go-gin-server/model.mustache
index 2f67ffafc3b..14993caf01a 100644
--- a/modules/openapi-generator/src/main/resources/go-gin-server/model.mustache
+++ b/modules/openapi-generator/src/main/resources/go-gin-server/model.mustache
@@ -19,6 +19,9 @@ const (
type {{classname}} struct {
{{#vars}}{{#description}}
// {{{description}}}{{/description}}
+ {{#deprecated}}
+ // Deprecated
+ {{/deprecated}}
{{name}} {{#isNullable}}*{{/isNullable}}{{{dataType}}} `json:"{{baseName}}{{^required}},omitempty{{/required}}"{{#vendorExtensions.x-go-custom-tag}} {{{.}}}{{/vendorExtensions.x-go-custom-tag}}`
{{/vars}}
}{{/isEnum}}{{/model}}{{/models}}
diff --git a/modules/openapi-generator/src/main/resources/go-server/api.mustache b/modules/openapi-generator/src/main/resources/go-server/api.mustache
index 8249ffb38f6..f08e1b27038 100644
--- a/modules/openapi-generator/src/main/resources/go-server/api.mustache
+++ b/modules/openapi-generator/src/main/resources/go-server/api.mustache
@@ -13,6 +13,9 @@ import (
// The {{classname}}Router implementation should parse necessary information from the http request,
// pass the data to a {{classname}}Servicer to perform the required actions, then write the service results to the http response.
type {{classname}}Router interface { {{#operations}}{{#operation}}
+ {{#isDeprecated}}
+ // Deprecated
+ {{/isDeprecated}}
{{operationId}}(http.ResponseWriter, *http.Request){{/operation}}{{/operations}}
}{{/apis}}{{/apiInfo}}{{#apiInfo}}{{#apis}}
@@ -22,5 +25,8 @@ type {{classname}}Router interface { {{#operations}}{{#operation}}
// while the service implementation can ignored with the .openapi-generator-ignore file
// and updated with the logic required for the API.
type {{classname}}Servicer interface { {{#operations}}{{#operation}}
+ {{#isDeprecated}}
+ // Deprecated
+ {{/isDeprecated}}
{{operationId}}(context.Context{{#allParams}}, {{dataType}}{{/allParams}}) (ImplResponse, error){{/operation}}{{/operations}}
}{{/apis}}{{/apiInfo}}
diff --git a/modules/openapi-generator/src/main/resources/go-server/controller-api.mustache b/modules/openapi-generator/src/main/resources/go-server/controller-api.mustache
index 6dd5138e525..68ed2514200 100644
--- a/modules/openapi-generator/src/main/resources/go-server/controller-api.mustache
+++ b/modules/openapi-generator/src/main/resources/go-server/controller-api.mustache
@@ -16,14 +16,34 @@ import (
{{/routers}}
)
-// A {{classname}}Controller binds http requests to an api service and writes the service results to the http response
+// {{classname}}Controller binds http requests to an api service and writes the service results to the http response
type {{classname}}Controller struct {
service {{classname}}Servicer
+ errorHandler ErrorHandler
+}
+
+// {{classname}}Option for how the controller is set up.
+type {{classname}}Option func(*{{classname}}Controller)
+
+// With{{classname}}ErrorHandler inject ErrorHandler into controller
+func With{{classname}}ErrorHandler(h ErrorHandler) {{classname}}Option {
+ return func(c *{{classname}}Controller) {
+ c.errorHandler = h
+ }
}
// New{{classname}}Controller creates a default api controller
-func New{{classname}}Controller(s {{classname}}Servicer) Router {
- return &{{classname}}Controller{service: s}
+func New{{classname}}Controller(s {{classname}}Servicer, opts ...{{classname}}Option) Router {
+ controller := &{{classname}}Controller{
+ service: s,
+ errorHandler: DefaultErrorHandler,
+ }
+
+ for _, opt := range opts {
+ opt(controller)
+ }
+
+ return controller
}
// Routes returns all of the api route for the {{classname}}Controller
@@ -39,17 +59,20 @@ func (c *{{classname}}Controller) Routes() Routes {
}{{#operations}}{{#operation}}
// {{nickname}} - {{{summary}}}
+{{#isDeprecated}}
+// Deprecated
+{{/isDeprecated}}
func (c *{{classname}}Controller) {{nickname}}(w http.ResponseWriter, r *http.Request) {
{{#hasFormParams}}
{{#isMultipart}}
if err := r.ParseMultipartForm(32 << 20); err != nil {
- w.WriteHeader(http.StatusBadRequest)
+ c.errorHandler(w, r, &ParsingError{Err: err}, nil)
return
}
{{/isMultipart}}
{{^isMultipart}}
if err := r.ParseForm(); err != nil {
- w.WriteHeader(http.StatusBadRequest)
+ c.errorHandler(w, r, &ParsingError{Err: err}, nil)
return
}
{{/isMultipart}}
@@ -69,14 +92,14 @@ func (c *{{classname}}Controller) {{nickname}}(w http.ResponseWriter, r *http.Re
{{#isLong}}
{{paramName}}, err := parseInt64Parameter({{#routers}}{{#mux}}params["{{baseName}}"]{{/mux}}{{#chi}}chi.URLParam(r, "{{baseName}}"){{/chi}}{{/routers}}, {{required}})
if err != nil {
- w.WriteHeader(http.StatusBadRequest)
+ c.errorHandler(w, r, &ParsingError{Err: err}, nil)
return
}
{{/isLong}}
{{#isInteger}}
{{paramName}}, err := parseInt32Parameter({{#routers}}{{#mux}}params["{{baseName}}"]{{/mux}}{{#chi}}chi.URLParam(r, "{{baseName}}"){{/chi}}{{/routers}}, {{required}})
if err != nil {
- w.WriteHeader(http.StatusBadRequest)
+ c.errorHandler(w, r, &ParsingError{Err: err}, nil)
return
}
{{/isInteger}}
@@ -89,14 +112,14 @@ func (c *{{classname}}Controller) {{nickname}}(w http.ResponseWriter, r *http.Re
{{#isLong}}
{{paramName}}, err := parseInt64Parameter(query.Get("{{baseName}}"), {{required}})
if err != nil {
- w.WriteHeader(http.StatusBadRequest)
+ c.errorHandler(w, r, &ParsingError{Err: err}, nil)
return
}
{{/isLong}}
{{#isInteger}}
{{paramName}}, err := parseInt32Parameter(query.Get("{{baseName}}"), {{required}})
if err != nil {
- w.WriteHeader(http.StatusBadRequest)
+ c.errorHandler(w, r, &ParsingError{Err: err}, nil)
return
}
{{/isInteger}}
@@ -121,7 +144,7 @@ func (c *{{classname}}Controller) {{nickname}}(w http.ResponseWriter, r *http.Re
{{paramName}}, err := ReadFormFileToTempFile(r, "{{baseName}}")
{{/isArray}}
if err != nil {
- w.WriteHeader(http.StatusBadRequest)
+ c.errorHandler(w, r, &ParsingError{Err: err}, nil)
return
}
{{/isFile}}
@@ -129,7 +152,7 @@ func (c *{{classname}}Controller) {{nickname}}(w http.ResponseWriter, r *http.Re
{{paramName}}, err := parseInt64ArrayParameter(r.FormValue("{{baseName}}"), ",", {{required}}){{/isArray}}{{^isArray}}
{{paramName}}, err := parseInt64Parameter(r.FormValue("{{baseName}}"), {{required}}){{/isArray}}
if err != nil {
- w.WriteHeader(http.StatusBadRequest)
+ c.errorHandler(w, r, &ParsingError{Err: err}, nil)
return
}
{{/isLong}}
@@ -137,7 +160,7 @@ func (c *{{classname}}Controller) {{nickname}}(w http.ResponseWriter, r *http.Re
{{paramName}}, err := parseInt32ArrayParameter(r.FormValue("{{baseName}}"), ",", {{required}}){{/isArray}}{{^isArray}}
{{paramName}}, err := parseInt32Parameter(r.FormValue("{{baseName}}"), {{required}}){{/isArray}}
if err != nil {
- w.WriteHeader(http.StatusBadRequest)
+ c.errorHandler(w, r, &ParsingError{Err: err}, nil)
return
}
{{/isInteger}}
@@ -151,17 +174,39 @@ func (c *{{classname}}Controller) {{nickname}}(w http.ResponseWriter, r *http.Re
{{paramName}} := r.Header.Get("{{baseName}}")
{{/isHeaderParam}}
{{#isBodyParam}}
- {{paramName}} := &{{dataType}}{}
- if err := json.NewDecoder(r.Body).Decode(&{{paramName}}); err != nil {
- w.WriteHeader(http.StatusBadRequest)
+ {{paramName}} := {{dataType}}{}
+ d := json.NewDecoder(r.Body)
+ {{^isAdditionalPropertiesTrue}}
+ d.DisallowUnknownFields()
+ {{/isAdditionalPropertiesTrue}}
+ if err := d.Decode(&{{paramName}}); err != nil {
+ c.errorHandler(w, r, &ParsingError{Err: err}, nil)
return
}
+ {{#isArray}}
+ {{#items.isModel}}
+ for _, el := range {{paramName}} {
+ if err := Assert{{baseType}}Required(el); err != nil {
+ c.errorHandler(w, r, err, nil)
+ return
+ }
+ }
+ {{/items.isModel}}
+ {{/isArray}}
+ {{^isArray}}
+ {{#isModel}}
+ if err := Assert{{baseType}}Required({{paramName}}); err != nil {
+ c.errorHandler(w, r, err, nil)
+ return
+ }
+ {{/isModel}}
+ {{/isArray}}
{{/isBodyParam}}
{{/allParams}}
- result, err := c.service.{{nickname}}(r.Context(){{#allParams}}, {{#isBodyParam}}*{{/isBodyParam}}{{paramName}}{{/allParams}})
+ result, err := c.service.{{nickname}}(r.Context(){{#allParams}}, {{paramName}}{{/allParams}})
// If an error occurred, encode the error with the status code
if err != nil {
- EncodeJSONResponse(err.Error(), &result.Code,{{#addResponseHeaders}} result.Headers,{{/addResponseHeaders}} w)
+ c.errorHandler(w, r, err, &result)
return
}
// If no error, encode the body and the result code
diff --git a/modules/openapi-generator/src/main/resources/go-server/error.mustache b/modules/openapi-generator/src/main/resources/go-server/error.mustache
new file mode 100644
index 00000000000..a4ffa03f53f
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/go-server/error.mustache
@@ -0,0 +1,54 @@
+{{>partial_header}}
+package {{packageName}}
+
+import (
+ "errors"
+ "fmt"
+ "net/http"
+)
+
+var (
+ // ErrTypeAssertionError is thrown when type an interface does not match the asserted type
+ ErrTypeAssertionError = errors.New("unable to assert type")
+)
+
+// ParsingError indicates that an error has occurred when parsing request parameters
+type ParsingError struct {
+ Err error
+}
+
+func (e *ParsingError) Unwrap() error {
+ return e.Err
+}
+
+func (e *ParsingError) Error() string {
+ return e.Err.Error()
+}
+
+// RequiredError indicates that an error has occurred when parsing request parameters
+type RequiredError struct {
+ Field string
+}
+
+func (e *RequiredError) Error() string {
+ return fmt.Sprintf("required field '%s' is zero value.", e.Field)
+}
+
+// ErrorHandler defines the required method for handling error. You may implement it and inject this into a controller if
+// you would like errors to be handled differently from the DefaultErrorHandler
+type ErrorHandler func(w http.ResponseWriter, r *http.Request, err error, result *ImplResponse)
+
+// DefaultErrorHandler defines the default logic on how to handle errors from the controller. Any errors from parsing
+// request params will return a StatusBadRequest. Otherwise, the error code originating from the servicer will be used.
+func DefaultErrorHandler(w http.ResponseWriter, r *http.Request, err error, result *ImplResponse) {
+ if _, ok := err.(*ParsingError); ok {
+ // Handle parsing errors
+ EncodeJSONResponse(err.Error(), func(i int) *int { return &i }(http.StatusBadRequest),{{#addResponseHeaders}} map[string][]string{},{{/addResponseHeaders}} w)
+ } else if _, ok := err.(*RequiredError); ok {
+ // Handle missing required errors
+ EncodeJSONResponse(err.Error(), func(i int) *int { return &i }(http.StatusUnprocessableEntity),{{#addResponseHeaders}} map[string][]string{},{{/addResponseHeaders}} w)
+ } else {
+ // Handle all other errors
+ EncodeJSONResponse(err.Error(), &result.Code,{{#addResponseHeaders}} result.Headers,{{/addResponseHeaders}} w)
+ }
+}
diff --git a/modules/openapi-generator/src/main/resources/go-server/helpers.mustache b/modules/openapi-generator/src/main/resources/go-server/helpers.mustache
index 13115656bc0..63b91ebb991 100644
--- a/modules/openapi-generator/src/main/resources/go-server/helpers.mustache
+++ b/modules/openapi-generator/src/main/resources/go-server/helpers.mustache
@@ -1,7 +1,11 @@
{{>partial_header}}
package {{packageName}}
-//Response return a ImplResponse struct filled
+import (
+ "reflect"
+)
+
+// Response return a ImplResponse struct filled
func Response(code int, body interface{}) ImplResponse {
return ImplResponse {
Code: code,
@@ -13,7 +17,7 @@ func Response(code int, body interface{}) ImplResponse {
}
{{#addResponseHeaders}}
-//ResponseWithHeaders return a ImplResponse struct filled, including headers
+// ResponseWithHeaders return a ImplResponse struct filled, including headers
func ResponseWithHeaders(code int, headers map[string][]string, body interface{}) ImplResponse {
return ImplResponse {
Code: code,
@@ -22,3 +26,35 @@ func ResponseWithHeaders(code int, headers map[string][]string, body interface{}
}
}
{{/addResponseHeaders}}
+
+// IsZeroValue checks if the val is the zero-ed value.
+func IsZeroValue(val interface{}) bool {
+ return val == nil || reflect.DeepEqual(val, reflect.Zero(reflect.TypeOf(val)).Interface())
+}
+
+// AssertInterfaceRequired recursively checks each struct in a slice against the callback.
+// This method traverse nested slices in a preorder fashion.
+func AssertRecurseInterfaceRequired(obj interface{}, callback func(interface{}) error) error {
+ return AssertRecurseValueRequired(reflect.ValueOf(obj), callback)
+}
+
+// AssertNestedValueRequired checks each struct in the nested slice against the callback.
+// This method traverse nested slices in a preorder fashion.
+func AssertRecurseValueRequired(value reflect.Value, callback func(interface{}) error) error {
+ switch value.Kind() {
+ // If it is a struct we check using callback
+ case reflect.Struct:
+ if err := callback(value.Interface()); err != nil {
+ return err
+ }
+
+ // If it is a slice we continue recursion
+ case reflect.Slice:
+ for i := 0; i < value.Len(); i += 1 {
+ if err := AssertRecurseValueRequired(value.Index(i), callback); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
diff --git a/modules/openapi-generator/src/main/resources/go-server/model.mustache b/modules/openapi-generator/src/main/resources/go-server/model.mustache
index 89860a8fe72..c13d81795ad 100644
--- a/modules/openapi-generator/src/main/resources/go-server/model.mustache
+++ b/modules/openapi-generator/src/main/resources/go-server/model.mustache
@@ -29,6 +29,106 @@ type {{classname}} struct {
{{/parent}}
{{#vars}}{{#description}}
// {{{description}}}{{/description}}
+ {{#deprecated}}
+ // Deprecated
+ {{/deprecated}}
{{name}} {{#isNullable}}*{{/isNullable}}{{{dataType}}} `json:"{{baseName}}{{^required}},omitempty{{/required}}"{{#vendorExtensions.x-go-custom-tag}} {{{.}}}{{/vendorExtensions.x-go-custom-tag}}`
{{/vars}}
-}{{/isEnum}}{{/model}}{{/models}}
+}{{/isEnum}}
+
+// Assert{{classname}}Required checks if the required fields are not zero-ed
+func Assert{{classname}}Required(obj {{classname}}) error {
+{{#hasRequired}}
+ elements := map[string]interface{}{
+{{#requiredVars}} "{{baseName}}": obj.{{name}},
+{{/requiredVars}} }
+ for name, el := range elements {
+ if isZero := IsZeroValue(el); isZero {
+ return &RequiredError{Field: name}
+ }
+ }
+
+{{/hasRequired}}
+{{#parent}}
+ {{^isMap}}
+ {{^isArray}}
+ if err := Assert{{{parent}}}Required(obj.{{{parent}}}); err != nil {
+ return err
+ }
+
+ {{/isArray}}
+ {{/isMap}}
+{{/parent}}
+{{#Vars}}
+ {{#isNullable}}
+ {{#isModel}}
+ if obj.{{name}} != nil {
+ {{/isModel}}
+ {{#isArray}}
+ {{#items.isModel}}
+ if obj.{{name}} != nil {
+ {{/items.isModel}}
+ {{^items.isModel}}
+ {{#mostInnerItems.isModel}}
+ {{^mostInnerItems.isPrimitiveType}}
+ if obj.{{name}} != nil {
+ {{/mostInnerItems.isPrimitiveType}}
+ {{/mostInnerItems.isModel}}
+ {{/items.isModel}}
+ {{/isArray}}
+ {{/isNullable}}
+ {{#isModel}}
+{{#isNullable}} {{/isNullable}} if err := Assert{{baseType}}Required({{#isNullable}}*{{/isNullable}}obj.{{name}}); err != nil {
+{{#isNullable}} {{/isNullable}} return err
+{{#isNullable}} {{/isNullable}} }
+ {{/isModel}}
+ {{#isArray}}
+ {{#items.isModel}}
+{{#isNullable}} {{/isNullable}} for _, el := range {{#isNullable}}*{{/isNullable}}obj.{{name}} {
+{{#isNullable}} {{/isNullable}} if err := Assert{{items.baseType}}Required(el); err != nil {
+{{#isNullable}} {{/isNullable}} return err
+{{#isNullable}} {{/isNullable}} }
+{{#isNullable}} {{/isNullable}} }
+ {{/items.isModel}}
+ {{^items.isModel}}
+ {{#mostInnerItems.isModel}}
+ {{^mostInnerItems.isPrimitiveType}}
+{{#isNullable}} {{/isNullable}} if err := AssertRecurse{{mostInnerItems.dataType}}Required({{#isNullable}}*{{/isNullable}}obj.{{name}}); err != nil {
+{{#isNullable}} {{/isNullable}} return err
+{{#isNullable}} {{/isNullable}} }
+ {{/mostInnerItems.isPrimitiveType}}
+ {{/mostInnerItems.isModel}}
+ {{/items.isModel}}
+ {{/isArray}}
+ {{#isNullable}}
+ {{#isModel}}
+ }
+ {{/isModel}}
+ {{#isArray}}
+ {{#items.isModel}}
+ }
+ {{/items.isModel}}
+ {{^items.isModel}}
+ {{#mostInnerItems.isModel}}
+ {{^mostInnerItems.isPrimitiveType}}
+ }
+ {{/mostInnerItems.isPrimitiveType}}
+ {{/mostInnerItems.isModel}}
+ {{/items.isModel}}
+ {{/isArray}}
+ {{/isNullable}}
+{{/Vars}}
+ return nil
+}
+
+// AssertRecurse{{classname}}Required recursively checks if required fields are not zero-ed in a nested slice.
+// Accepts only nested slice of {{classname}} (e.g. [][]{{classname}}), otherwise ErrTypeAssertionError is thrown.
+func AssertRecurse{{classname}}Required(objSlice interface{}) error {
+ return AssertRecurseInterfaceRequired(objSlice, func(obj interface{}) error {
+ a{{classname}}, ok := obj.({{classname}})
+ if !ok {
+ return ErrTypeAssertionError
+ }
+ return Assert{{classname}}Required(a{{classname}})
+ })
+}{{/model}}{{/models}}
diff --git a/modules/openapi-generator/src/main/resources/go-server/service.mustache b/modules/openapi-generator/src/main/resources/go-server/service.mustache
index a5664b0c350..2df7298b17b 100644
--- a/modules/openapi-generator/src/main/resources/go-server/service.mustache
+++ b/modules/openapi-generator/src/main/resources/go-server/service.mustache
@@ -20,6 +20,9 @@ func New{{classname}}Service() {{classname}}Servicer {
}{{#operations}}{{#operation}}
// {{nickname}} - {{summary}}
+{{#isDeprecated}}
+// Deprecated
+{{/isDeprecated}}
func (s *{{classname}}Service) {{nickname}}(ctx context.Context{{#allParams}}, {{paramName}} {{dataType}}{{/allParams}}) (ImplResponse, error) {
// TODO - update {{nickname}} with the required logic for this service method.
// Add {{classFilename}}_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
diff --git a/modules/openapi-generator/src/main/resources/go/README.mustache b/modules/openapi-generator/src/main/resources/go/README.mustache
index 4e9577633d4..de164be1cf8 100644
--- a/modules/openapi-generator/src/main/resources/go/README.mustache
+++ b/modules/openapi-generator/src/main/resources/go/README.mustache
@@ -86,7 +86,7 @@ All URIs are relative to *{{basePath}}*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
-{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}}
+{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{summary}}
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
## Documentation For Models
diff --git a/modules/openapi-generator/src/main/resources/go/api.mustache b/modules/openapi-generator/src/main/resources/go/api.mustache
index 3fd1db0c66c..8b93e7c6b08 100644
--- a/modules/openapi-generator/src/main/resources/go/api.mustache
+++ b/modules/openapi-generator/src/main/resources/go/api.mustache
@@ -22,20 +22,27 @@ type {{classname}} interface {
{{#operation}}
/*
- * {{operationId}}{{#summary}} {{{.}}}{{/summary}}{{^summary}} Method for {{operationId}}{{/summary}}
+ {{operationId}} {{{summary}}}{{^summary}}Method for {{operationId}}{{/summary}}
{{#notes}}
- * {{{unescapedNotes}}}
+
+ {{{unescapedNotes}}}
{{/notes}}
- * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().{{#pathParams}}
- * @param {{paramName}}{{#description}} {{{.}}}{{/description}}{{/pathParams}}
- * @return {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request
- */
+
+ @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().{{#pathParams}}
+ @param {{paramName}}{{#description}} {{{.}}}{{/description}}{{/pathParams}}
+ @return {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request
+ {{#isDeprecated}}
+
+ Deprecated
+ {{/isDeprecated}}
+ */
{{{nickname}}}(ctx _context.Context{{#pathParams}}, {{paramName}} {{{dataType}}}{{/pathParams}}) {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request
- /*
- * {{nickname}}Execute executes the request{{#returnType}}
- * @return {{{.}}}{{/returnType}}
- */
+ // {{nickname}}Execute executes the request{{#returnType}}
+ // @return {{{.}}}{{/returnType}}
+ {{#isDeprecated}}
+ // Deprecated
+ {{/isDeprecated}}
{{nickname}}Execute(r {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request) ({{#returnType}}{{{.}}}, {{/returnType}}*_nethttp.Response, error)
{{/operation}}
}
@@ -46,16 +53,19 @@ type {{classname}}Service service
{{#operation}}
type {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request struct {
- ctx _context.Context{{#generateInterfaces}}
- ApiService {{classname}}
-{{/generateInterfaces}}{{^generateInterfaces}}
- ApiService *{{classname}}Service
-{{/generateInterfaces}}
+ ctx _context.Context
+ ApiService {{#generateInterfaces}}{{classname}}{{/generateInterfaces}}{{^generateInterfaces}}*{{classname}}Service{{/generateInterfaces}}
{{#allParams}}
{{paramName}} {{^isPathParam}}*{{/isPathParam}}{{{dataType}}}
{{/allParams}}
}
{{#allParams}}{{^isPathParam}}
+{{#description}}
+// {{.}}
+{{/description}}
+{{#isDeprecated}}
+// Deprecated
+{{/isDeprecated}}
func (r {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request) {{vendorExtensions.x-export-param-name}}({{paramName}} {{{dataType}}}) {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request {
r.{{paramName}} = &{{paramName}}
return r
@@ -66,14 +76,20 @@ func (r {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Reques
}
/*
- * {{operationId}}{{#summary}} {{{.}}}{{/summary}}{{^summary}} Method for {{operationId}}{{/summary}}
+{{operationId}} {{{summary}}}{{^summary}}Method for {{operationId}}{{/summary}}
{{#notes}}
- * {{{unescapedNotes}}}
+
+{{{unescapedNotes}}}
{{/notes}}
- * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().{{#pathParams}}
- * @param {{paramName}}{{#description}} {{{.}}}{{/description}}{{/pathParams}}
- * @return {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request
- */
+
+ @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().{{#pathParams}}
+ @param {{paramName}}{{#description}} {{{.}}}{{/description}}{{/pathParams}}
+ @return {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request
+{{#isDeprecated}}
+
+Deprecated
+{{/isDeprecated}}
+*/
func (a *{{{classname}}}Service) {{{nickname}}}(ctx _context.Context{{#pathParams}}, {{paramName}} {{{dataType}}}{{/pathParams}}) {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request {
return {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request{
ApiService: a,
@@ -84,10 +100,11 @@ func (a *{{{classname}}}Service) {{{nickname}}}(ctx _context.Context{{#pathParam
}
}
-/*
- * Execute executes the request{{#returnType}}
- * @return {{{.}}}{{/returnType}}
- */
+// Execute executes the request{{#returnType}}
+// @return {{{.}}}{{/returnType}}
+{{#isDeprecated}}
+// Deprecated
+{{/isDeprecated}}
func (a *{{{classname}}}Service) {{nickname}}Execute(r {{#structPrefix}}{{&classname}}{{/structPrefix}}Api{{operationId}}Request) ({{#returnType}}{{{.}}}, {{/returnType}}*_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.Method{{httpMethod}}
@@ -106,7 +123,7 @@ func (a *{{{classname}}}Service) {{nickname}}Execute(r {{#structPrefix}}{{&class
}
localVarPath := localBasePath + "{{{path}}}"{{#pathParams}}
- localVarPath = strings.Replace(localVarPath, "{"+"{{baseName}}"+"}", _neturl.PathEscape(parameterToString(r.{{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}")), -1){{/pathParams}}
+ localVarPath = strings.Replace(localVarPath, "{"+"{{baseName}}"+"}", _neturl.PathEscape(parameterToString(r.{{paramName}}, "{{collectionFormat}}")), -1){{/pathParams}}
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
@@ -171,15 +188,15 @@ func (a *{{{classname}}}Service) {{nickname}}Execute(r {{#structPrefix}}{{&class
if reflect.TypeOf(t).Kind() == reflect.Slice {
s := reflect.ValueOf(t)
for i := 0; i < s.Len(); i++ {
- localVarQueryParams.Add("{{baseName}}", parameterToString(s.Index(i), "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
+ localVarQueryParams.Add("{{baseName}}", parameterToString(s.Index(i), "{{collectionFormat}}"))
}
} else {
- localVarQueryParams.Add("{{baseName}}", parameterToString(t, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
+ localVarQueryParams.Add("{{baseName}}", parameterToString(t, "{{collectionFormat}}"))
}
}
{{/isCollectionFormatMulti}}
{{^isCollectionFormatMulti}}
- localVarQueryParams.Add("{{baseName}}", parameterToString(*r.{{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
+ localVarQueryParams.Add("{{baseName}}", parameterToString(*r.{{paramName}}, "{{collectionFormat}}"))
{{/isCollectionFormatMulti}}
{{/required}}
{{^required}}
@@ -189,14 +206,14 @@ func (a *{{{classname}}}Service) {{nickname}}Execute(r {{#structPrefix}}{{&class
if reflect.TypeOf(t).Kind() == reflect.Slice {
s := reflect.ValueOf(t)
for i := 0; i < s.Len(); i++ {
- localVarQueryParams.Add("{{baseName}}", parameterToString(s.Index(i), "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
+ localVarQueryParams.Add("{{baseName}}", parameterToString(s.Index(i), "{{collectionFormat}}"))
}
} else {
- localVarQueryParams.Add("{{baseName}}", parameterToString(t, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
+ localVarQueryParams.Add("{{baseName}}", parameterToString(t, "{{collectionFormat}}"))
}
{{/isCollectionFormatMulti}}
{{^isCollectionFormatMulti}}
- localVarQueryParams.Add("{{baseName}}", parameterToString(*r.{{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
+ localVarQueryParams.Add("{{baseName}}", parameterToString(*r.{{paramName}}, "{{collectionFormat}}"))
{{/isCollectionFormatMulti}}
}
{{/required}}
@@ -224,11 +241,11 @@ func (a *{{{classname}}}Service) {{nickname}}Execute(r {{#structPrefix}}{{&class
}
{{#headerParams}}
{{#required}}
- localVarHeaderParams["{{baseName}}"] = parameterToString(*r.{{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}")
+ localVarHeaderParams["{{baseName}}"] = parameterToString(*r.{{paramName}}, "{{collectionFormat}}")
{{/required}}
{{^required}}
if r.{{paramName}} != nil {
- localVarHeaderParams["{{baseName}}"] = parameterToString(*r.{{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}")
+ localVarHeaderParams["{{baseName}}"] = parameterToString(*r.{{paramName}}, "{{collectionFormat}}")
}
{{/required}}
{{/headerParams}}
@@ -253,7 +270,7 @@ func (a *{{{classname}}}Service) {{nickname}}Execute(r {{#structPrefix}}{{&class
{{/isFile}}
{{^isFile}}
{{#required}}
- localVarFormParams.Add("{{baseName}}", parameterToString(*r.{{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
+ localVarFormParams.Add("{{baseName}}", parameterToString(*r.{{paramName}}, "{{collectionFormat}}"))
{{/required}}
{{^required}}
{{#isModel}}
@@ -267,7 +284,7 @@ func (a *{{{classname}}}Service) {{nickname}}Execute(r {{#structPrefix}}{{&class
{{/isModel}}
{{^isModel}}
if r.{{paramName}} != nil {
- localVarFormParams.Add("{{baseName}}", parameterToString(*r.{{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
+ localVarFormParams.Add("{{baseName}}", parameterToString(*r.{{paramName}}, "{{collectionFormat}}"))
}
{{/isModel}}
{{/required}}
diff --git a/modules/openapi-generator/src/main/resources/go/api_doc.mustache b/modules/openapi-generator/src/main/resources/go/api_doc.mustache
index 458465f8947..c99fff852bb 100644
--- a/modules/openapi-generator/src/main/resources/go/api_doc.mustache
+++ b/modules/openapi-generator/src/main/resources/go/api_doc.mustache
@@ -1,12 +1,12 @@
# {{invokerPackage}}\{{classname}}{{#description}}
-{{description}}{{/description}}
+{{.}}{{/description}}
All URIs are relative to *{{basePath}}*
Method | HTTP request | Description
------------- | ------------- | -------------
-{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}}
+{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{summary}}
{{/operation}}{{/operations}}
{{#operations}}
@@ -60,7 +60,7 @@ func main() {
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.{{/-last}}{{/pathParams}}{{#pathParams}}
-**{{paramName}}** | {{^isPrimitiveType}}{{^isFile}}[{{/isFile}}{{/isPrimitiveType}}**{{dataType}}**{{^isPrimitiveType}}{{^isFile}}]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}} | {{description}} | {{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}{{/pathParams}}
+**{{paramName}}** | {{^isPrimitiveType}}{{^isFile}}[{{/isFile}}{{/isPrimitiveType}}**{{dataType}}**{{^isPrimitiveType}}{{^isFile}}]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}} | {{description}} | {{#defaultValue}}[default to {{.}}]{{/defaultValue}}{{/pathParams}}
### Other Parameters
@@ -69,7 +69,7 @@ Other parameters are passed through a pointer to a api{{{nickname}}}Request stru
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}}{{#allParams}}
-{{^isPathParam}} **{{paramName}}** | {{#isContainer}}{{#isArray}}{{#items}}{{^isPrimitiveType}}{{^isFile}}[{{/isFile}}{{/isPrimitiveType}}**[]{{dataType}}**{{^isPrimitiveType}}{{^isFile}}]({{^baseType}}{{dataType}}{{/baseType}}{{baseType}}.md){{/isFile}}{{/isPrimitiveType}}{{/items}}{{/isArray}}{{#isMap}}{{#items}}{{^isPrimitiveType}}{{^isFile}}[{{/isFile}}{{/isPrimitiveType}}**map[string]{{dataType}}**{{^isPrimitiveType}}{{^isFile}}]({{^baseType}}{{dataType}}{{/baseType}}{{baseType}}.md){{/isFile}}{{/isPrimitiveType}}{{/items}}{{/isMap}}{{/isContainer}}{{^isContainer}}{{^isPrimitiveType}}{{^isFile}}[{{/isFile}}{{/isPrimitiveType}}**{{dataType}}**{{^isPrimitiveType}}{{^isFile}}]({{^baseType}}{{dataType}}{{/baseType}}{{baseType}}.md){{/isFile}}{{/isPrimitiveType}}{{/isContainer}} | {{description}} | {{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}{{/isPathParam}}{{/allParams}}
+{{^isPathParam}} **{{paramName}}** | {{#isContainer}}{{#isArray}}{{#items}}{{^isPrimitiveType}}{{^isFile}}[{{/isFile}}{{/isPrimitiveType}}**[]{{dataType}}**{{^isPrimitiveType}}{{^isFile}}]({{^baseType}}{{dataType}}{{/baseType}}{{baseType}}.md){{/isFile}}{{/isPrimitiveType}}{{/items}}{{/isArray}}{{#isMap}}{{#items}}{{^isPrimitiveType}}{{^isFile}}[{{/isFile}}{{/isPrimitiveType}}**map[string]{{dataType}}**{{^isPrimitiveType}}{{^isFile}}]({{^baseType}}{{dataType}}{{/baseType}}{{baseType}}.md){{/isFile}}{{/isPrimitiveType}}{{/items}}{{/isMap}}{{/isContainer}}{{^isContainer}}{{^isPrimitiveType}}{{^isFile}}[{{/isFile}}{{/isPrimitiveType}}**{{dataType}}**{{^isPrimitiveType}}{{^isFile}}]({{^baseType}}{{dataType}}{{/baseType}}{{baseType}}.md){{/isFile}}{{/isPrimitiveType}}{{/isContainer}} | {{description}} | {{#defaultValue}}[default to {{.}}]{{/defaultValue}}{{/isPathParam}}{{/allParams}}
### Return type
diff --git a/modules/openapi-generator/src/main/resources/go/client.mustache b/modules/openapi-generator/src/main/resources/go/client.mustache
index 572bd7f800c..8cc5dfd6009 100644
--- a/modules/openapi-generator/src/main/resources/go/client.mustache
+++ b/modules/openapi-generator/src/main/resources/go/client.mustache
@@ -47,12 +47,7 @@ type APIClient struct {
{{#apis}}
{{#operations}}
- {{#generateInterfaces}}
- {{classname}} {{classname}}
- {{/generateInterfaces}}
- {{^generateInterfaces}}
- {{classname}} *{{classname}}Service
- {{/generateInterfaces}}
+ {{classname}} {{#generateInterfaces}}{{classname}}{{/generateInterfaces}}{{^generateInterfaces}}*{{classname}}Service{{/generateInterfaces}}
{{/operations}}
{{/apis}}
{{/apiInfo}}
diff --git a/modules/openapi-generator/src/main/resources/go/configuration.mustache b/modules/openapi-generator/src/main/resources/go/configuration.mustache
index f33b012fc41..610f9edc5d2 100644
--- a/modules/openapi-generator/src/main/resources/go/configuration.mustache
+++ b/modules/openapi-generator/src/main/resources/go/configuration.mustache
@@ -117,7 +117,7 @@ type Configuration struct {
func NewConfiguration() *Configuration {
cfg := &Configuration{
DefaultHeader: make(map[string]string),
- UserAgent: "{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{{packageVersion}}}/go{{/httpUserAgent}}",
+ UserAgent: "{{{httpUserAgent}}}{{^httpUserAgent}}OpenAPI-Generator/{{{packageVersion}}}/go{{/httpUserAgent}}",
Debug: false,
{{#servers}}
{{#-first}}
diff --git a/modules/openapi-generator/src/main/resources/go/model_anyof.mustache b/modules/openapi-generator/src/main/resources/go/model_anyof.mustache
index 5dfa75302f1..d0738523a2a 100644
--- a/modules/openapi-generator/src/main/resources/go/model_anyof.mustache
+++ b/modules/openapi-generator/src/main/resources/go/model_anyof.mustache
@@ -1,4 +1,4 @@
-// {{classname}}{{#description}} {{{description}}}{{/description}}{{^description}} struct for {{{classname}}}{{/description}}
+// {{classname}} {{{description}}}{{^description}}struct for {{{classname}}}{{/description}}
type {{classname}} struct {
{{#anyOf}}
{{{.}}} *{{{.}}}
diff --git a/modules/openapi-generator/src/main/resources/go/model_enum.mustache b/modules/openapi-generator/src/main/resources/go/model_enum.mustache
index 11dfbfc7d33..2432e5c8b36 100644
--- a/modules/openapi-generator/src/main/resources/go/model_enum.mustache
+++ b/modules/openapi-generator/src/main/resources/go/model_enum.mustache
@@ -1,5 +1,5 @@
-// {{{classname}}} {{#description}}{{{.}}}{{/description}}{{^description}}the model '{{{classname}}}'{{/description}}
-type {{{classname}}} {{^format}}{{dataType}}{{/format}}{{#format}}{{{format}}}{{/format}}
+// {{{classname}}} {{{description}}}{{^description}}the model '{{{classname}}}'{{/description}}
+type {{{classname}}} {{{format}}}{{^format}}{{dataType}}{{/format}}
// List of {{{name}}}
const (
@@ -21,7 +21,7 @@ var allowed{{{classname}}}EnumValues = []{{{classname}}}{
}
func (v *{{{classname}}}) UnmarshalJSON(src []byte) error {
- var value {{^format}}{{dataType}}{{/format}}{{#format}}{{{format}}}{{/format}}
+ var value {{{format}}}{{^format}}{{dataType}}{{/format}}
err := json.Unmarshal(src, &value)
if err != nil {
return err
@@ -39,7 +39,7 @@ func (v *{{{classname}}}) UnmarshalJSON(src []byte) error {
// New{{{classname}}}FromValue returns a pointer to a valid {{{classname}}}
// for the value passed as argument, or an error if the value passed is not allowed by the enum
-func New{{{classname}}}FromValue(v {{^format}}{{dataType}}{{/format}}{{#format}}{{{format}}}{{/format}}) (*{{{classname}}}, error) {
+func New{{{classname}}}FromValue(v {{{format}}}{{^format}}{{dataType}}{{/format}}) (*{{{classname}}}, error) {
ev := {{{classname}}}(v)
if ev.IsValid() {
return &ev, nil
diff --git a/modules/openapi-generator/src/main/resources/go/model_oneof.mustache b/modules/openapi-generator/src/main/resources/go/model_oneof.mustache
index a0322e34074..e67a172de67 100644
--- a/modules/openapi-generator/src/main/resources/go/model_oneof.mustache
+++ b/modules/openapi-generator/src/main/resources/go/model_oneof.mustache
@@ -1,4 +1,4 @@
-// {{classname}} - {{#description}}{{{description}}}{{/description}}{{^description}}struct for {{{classname}}}{{/description}}
+// {{classname}} - {{{description}}}{{^description}}struct for {{{classname}}}{{/description}}
type {{classname}} struct {
{{#oneOf}}
{{{.}}} *{{{.}}}
diff --git a/modules/openapi-generator/src/main/resources/go/model_simple.mustache b/modules/openapi-generator/src/main/resources/go/model_simple.mustache
index da651274308..a2e30fc4b8f 100644
--- a/modules/openapi-generator/src/main/resources/go/model_simple.mustache
+++ b/modules/openapi-generator/src/main/resources/go/model_simple.mustache
@@ -1,4 +1,4 @@
-// {{classname}}{{#description}} {{{description}}}{{/description}}{{^description}} struct for {{{classname}}}{{/description}}
+// {{classname}} {{{description}}}{{^description}}struct for {{{classname}}}{{/description}}
type {{classname}} struct {
{{#parent}}
{{^isMap}}
@@ -16,6 +16,9 @@ type {{classname}} struct {
{{#description}}
// {{{description}}}
{{/description}}
+{{#deprecated}}
+ // Deprecated
+{{/deprecated}}
{{name}} {{^required}}{{^isNullable}}*{{/isNullable}}{{/required}}{{{dataType}}} `json:"{{baseName}}{{^required}},omitempty{{/required}}"{{#withXml}} xml:"{{baseName}}{{#isXmlAttribute}},attr{{/isXmlAttribute}}"{{/withXml}}{{#vendorExtensions.x-go-custom-tag}} {{{.}}}{{/vendorExtensions.x-go-custom-tag}}`
{{/vars}}
{{#isAdditionalPropertiesTrue}}
@@ -84,6 +87,9 @@ func New{{classname}}WithDefaults() *{{classname}} {
{{#isNullable}}
// If the value is explicit nil, the zero value for {{vendorExtensions.x-go-base-type}} will be returned
{{/isNullable}}
+{{#deprecated}}
+// Deprecated
+{{/deprecated}}
func (o *{{classname}}) Get{{name}}() {{vendorExtensions.x-go-base-type}} {
if o == nil{{#isNullable}}{{^vendorExtensions.x-golang-is-container}} || o.{{name}}.Get() == nil{{/vendorExtensions.x-golang-is-container}}{{/isNullable}} {
var ret {{vendorExtensions.x-go-base-type}}
@@ -108,6 +114,9 @@ func (o *{{classname}}) Get{{name}}() {{vendorExtensions.x-go-base-type}} {
{{#isNullable}}
// NOTE: If the value is an explicit nil, `nil, true` will be returned
{{/isNullable}}
+{{#deprecated}}
+// Deprecated
+{{/deprecated}}
func (o *{{classname}}) Get{{name}}Ok() (*{{vendorExtensions.x-go-base-type}}, bool) {
if o == nil {{#isNullable}}{{#vendorExtensions.x-golang-is-container}}|| o.{{name}} == nil{{/vendorExtensions.x-golang-is-container}}{{/isNullable}} {
return nil, false
@@ -126,6 +135,9 @@ func (o *{{classname}}) Get{{name}}Ok() (*{{vendorExtensions.x-go-base-type}}, b
}
// Set{{name}} sets field value
+{{#deprecated}}
+// Deprecated
+{{/deprecated}}
func (o *{{classname}}) Set{{name}}(v {{vendorExtensions.x-go-base-type}}) {
{{#isNullable}}
{{#vendorExtensions.x-golang-is-container}}
@@ -143,6 +155,9 @@ func (o *{{classname}}) Set{{name}}(v {{vendorExtensions.x-go-base-type}}) {
{{/required}}
{{^required}}
// Get{{name}} returns the {{name}} field value if set, zero value otherwise{{#isNullable}} (both if not set or set to explicit null){{/isNullable}}.
+{{#deprecated}}
+// Deprecated
+{{/deprecated}}
func (o *{{classname}}) Get{{name}}() {{vendorExtensions.x-go-base-type}} {
if o == nil {{^isNullable}}|| o.{{name}} == nil{{/isNullable}}{{#isNullable}}{{^vendorExtensions.x-golang-is-container}}|| o.{{name}}.Get() == nil{{/vendorExtensions.x-golang-is-container}}{{/isNullable}} {
var ret {{vendorExtensions.x-go-base-type}}
@@ -166,6 +181,9 @@ func (o *{{classname}}) Get{{name}}() {{vendorExtensions.x-go-base-type}} {
{{#isNullable}}
// NOTE: If the value is an explicit nil, `nil, true` will be returned
{{/isNullable}}
+{{#deprecated}}
+// Deprecated
+{{/deprecated}}
func (o *{{classname}}) Get{{name}}Ok() (*{{vendorExtensions.x-go-base-type}}, bool) {
if o == nil {{^isNullable}}|| o.{{name}} == nil{{/isNullable}}{{#isNullable}}{{#vendorExtensions.x-golang-is-container}}|| o.{{name}} == nil{{/vendorExtensions.x-golang-is-container}}{{/isNullable}} {
return nil, false
@@ -193,6 +211,9 @@ func (o *{{classname}}) Has{{name}}() bool {
}
// Set{{name}} gets a reference to the given {{dataType}} and assigns it to the {{name}} field.
+{{#deprecated}}
+// Deprecated
+{{/deprecated}}
func (o *{{classname}}) Set{{name}}(v {{vendorExtensions.x-go-base-type}}) {
{{#isNullable}}
{{#vendorExtensions.x-golang-is-container}}
@@ -286,6 +307,9 @@ func (o *{{{classname}}}) UnmarshalJSON(bytes []byte) (err error) {
{{#description}}
// {{{description}}}
{{/description}}
+ {{#deprecated}}
+ // Deprecated
+ {{/deprecated}}
{{name}} {{^required}}{{^isNullable}}*{{/isNullable}}{{/required}}{{{dataType}}} `json:"{{baseName}}{{^required}},omitempty{{/required}}"{{#withXml}} xml:"{{baseName}}{{#isXmlAttribute}},attr{{/isXmlAttribute}}"{{/withXml}}{{#vendorExtensions.x-go-custom-tag}} {{{.}}}{{/vendorExtensions.x-go-custom-tag}}`
{{/vars}}
}
diff --git a/modules/openapi-generator/src/main/resources/go/partial_header.mustache b/modules/openapi-generator/src/main/resources/go/partial_header.mustache
index ee1ead4cf39..d8f219cdfc4 100644
--- a/modules/openapi-generator/src/main/resources/go/partial_header.mustache
+++ b/modules/openapi-generator/src/main/resources/go/partial_header.mustache
@@ -1,18 +1,18 @@
/*
- {{#appName}}
- * {{{appName}}}
- *
- {{/appName}}
- {{#appDescription}}
- * {{{appDescription}}}
- *
- {{/appDescription}}
- {{#version}}
- * API version: {{{version}}}
- {{/version}}
- {{#infoEmail}}
- * Contact: {{{infoEmail}}}
- {{/infoEmail}}
- */
+{{#appName}}
+{{{.}}}
+
+{{/appName}}
+{{#appDescription}}
+{{{.}}}
+
+{{/appDescription}}
+{{#version}}
+API version: {{{.}}}
+{{/version}}
+{{#infoEmail}}
+Contact: {{{.}}}
+{{/infoEmail}}
+*/
// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.
diff --git a/modules/openapi-generator/src/main/resources/java-micronaut-client/api.mustache b/modules/openapi-generator/src/main/resources/java-micronaut-client/api.mustache
new file mode 100644
index 00000000000..4232340e520
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/java-micronaut-client/api.mustache
@@ -0,0 +1,70 @@
+{{>licenseInfo}}
+package {{package}};
+
+import io.micronaut.http.annotation.*;
+import io.micronaut.core.annotation.*;
+import io.micronaut.http.client.annotation.Client;
+{{#configureAuth}}
+import {{invokerPackage}}.auth.Authorization;
+{{/configureAuth}}
+import {{invokerPackage}}.query.QueryParam;
+import io.micronaut.core.convert.format.Format;
+import reactor.core.publisher.Mono;
+{{#imports}}import {{import}};
+{{/imports}}
+import javax.annotation.Generated;
+{{^fullJavaUtil}}
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+{{/fullJavaUtil}}{{#useBeanValidation}}
+import javax.validation.Valid;
+import javax.validation.constraints.*;
+{{/useBeanValidation}}
+
+{{>generatedAnnotation}}
+@Client("${base-path}")
+public interface {{classname}} {
+{{#operations}}{{#operation}}
+ /**
+ {{#summary}}
+ * {{summary}}
+ {{/summary}}
+ {{#notes}}
+ * {{notes}}
+ {{/notes}}
+ {{^summary}}
+ {{^notes}}
+ * {{nickname}}
+ {{/notes}}
+ {{/summary}}
+ *
+{{#allParams}}
+ * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}
+{{/allParams}}
+{{#returnType}}
+ * @return {{returnType}}
+{{/returnType}}
+{{#externalDocs}}
+ * {{description}}
+ * @see {{summary}} Documentation
+{{/externalDocs}}
+ */
+ @{{#lambda.pascalcase}}{{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}}{{/lambda.pascalcase}}(uri="{{{path}}}")
+ {{#vendorExtensions.x-contentType}}
+ @Produces(value={"{{vendorExtensions.x-contentType}}"})
+ {{/vendorExtensions.x-contentType}}
+ @Consumes(value={"{{vendorExtensions.x-accepts}}"})
+ {{!auth methods}}
+ {{#configureAuth}}
+ {{#authMethods}}
+ @Authorization(name="{{{name}}}"{{!scopes}}{{#isOAuth}}, scopes={{=< >=}}{<={{ }}=>{{#scopes}}"{{{scope}}}"{{^-last}}, {{/-last}}{{/scopes}}{{=< >=}}}<={{ }}=>{{/isOAuth}})
+ {{/authMethods}}
+ {{/configureAuth}}
+ {{#returnType}}Mono<{{{returnType}}}>{{/returnType}}{{^returnType}}Mono