Compare commits

..

22 Commits

Author SHA1 Message Date
William Cheng
212b4f7847 Prepare 5.0.0-beta2 release (#7345)
* update version

* update doc

* update samples
2020-09-04 13:03:45 +08:00
William Cheng
14d41310b9 [Go] replace go generator with go-experimental generator (#7337)
* replace go with go-experimental

* update samples

* extends with abstract go class

* rearrange

* remove deprecated

* minor fix

* remove go deprecated samples

* update pom, clean up samples

* mark generator as deprecated
2020-09-04 09:56:42 +08:00
William Cheng
1f50207bda [doc] Update new-generator steps (new.sh) (#7336)
* [doc] Update new-generator steps (new.sh) (#7334)

* remove CommonMarkDocumentationCodegen

Co-authored-by: Jim Schubert <james.schubert@gmail.com>
2020-09-03 22:04:43 +08:00
William Cheng
e0ec332e38 Revert "[doc] Update new-generator steps (new.sh) (#7334)" (#7335)
This reverts commit 151752aa9d.
2020-09-03 14:21:26 +08:00
Jim Schubert
151752aa9d [doc] Update new-generator steps (new.sh) (#7334) 2020-09-02 22:14:52 -04:00
Jim Schubert
a6d30cac9d [core] Templating: limit compilation to supported extensions and constrain target paths (#6598) 2020-09-02 15:52:35 -04:00
Hippolyte HENRY
91ea6a17d9 [Java] Unalias type when generating default value for model property (#5017)
Co-authored-by: Jim Schubert <james.schubert@gmail.com>
2020-09-02 07:52:38 -04:00
William Cheng
966b87e66c add aws v4 signature support to go-experimental (#7326) 2020-09-02 15:28:22 +08:00
William Cheng
d50d31cd5e add structPrefix support to go-experimental (#7327) 2020-09-01 20:51:37 +08:00
William Cheng
20eb4d0b91 Add a link to SmartHR Tech Blog (#7324) 2020-09-01 11:01:23 +08:00
Jim Schubert
26bb348354 Revert "Correct allOf with only one child schema (no discriminator)" (#7323)
This reverts commit 972120c35a.
2020-08-31 22:46:57 -04:00
William Cheng
972120c35a Correct allOf with only one child schema (no discriminator) (#6901) 2020-08-31 21:47:18 -04:00
Arvind Thirunarayanan
ab5b0fa8d4 [Go]: Interface definitions for api functions (#5914)
Introduces a new "generateInterfaces" option, allowing for better testability of generated clients
2020-08-31 21:43:40 -04:00
William Cheng
9fd66fbbcb Update bug_report.md (#7320) 2020-08-31 21:09:13 -04:00
William Cheng
19c5ed783a update samples 2020-08-31 23:17:55 +08:00
Oleh Kurpiak
14a500c6fe [Java][Client] Use java8 OffsetDateTime for clients (#7190)
* use java8 OffsetDateTime for clients

* use java8 OffsetDateTime for clients

* fix javadoc

* add javadoc to JavaTimeFormatter.mustache

* add javadoc to JavaTimeFormatter.mustache

* add javadoc to JavaTimeFormatter.mustache
2020-08-31 22:31:28 +08:00
Patouche
b9662dc25d [java] Intro openApiNullable property to enable/disable OpenAPI Jackson Nullable library (#6154)
* Add option to prevent usage of jackson-nullable (#2901)

Add a option for all java client and server to prevent
usage of third party library (jackson-databind-nullable)
which may be forbidden in some company

Add samples for Vertx, Spring MVC, Spring Cloud, Feign and Play

Upgrade dependencies for org.openapitools:jackson-databind-nullable

* Samples - Remove dependency org.openapitools:jackson-databind-nullable (#2901)

* Fix generation of gradle file for vertx (#2901)

* Regenerate samples (#2901)

* Fix documentation and up to date (#2901)

* Fix forgotten regeneration of vertx after dependency integration (#2901)

* Regenerate template after rebase (#2901)

* Use yaml config files introduce in #6509 to manage samples (#2901)

* Regenerate template using the config (#2901)

* Fix bad version during testing generated samples (#2901)

* Regenerate template after fix bad version (#2901)

* Fix merge, allow for set importing on codegen model

Co-authored-by: Jim Schubert <james.schubert@gmail.com>
2020-08-31 21:25:18 +08:00
William Cheng
7032c401ea [Spring Boot] update dependencies, mark java8 option as deprecated (#7306)
* update springboot dependencies

* update doc

* update samples
2020-08-31 13:53:50 +08:00
Gmtstephane
15de43f7e4 Remove dot in golang type (#7307) 2020-08-31 13:50:20 +08:00
Jim Schubert
8eea149e14 [doc] Document usage of post-process file feature (#7315) 2020-08-31 13:44:44 +08:00
QP Hou
30074833cd fix http bear auth documentation for go clinets (#7312) 2020-08-31 13:43:34 +08:00
Jiri Kuncar
d5a680e85f [Extensions][Go][Java] Test x-auth-id-alias (#6642)
Co-authored-by: Jim Schubert <james.schubert@gmail.com>
2020-08-30 21:46:55 -04:00
2044 changed files with 109331 additions and 62438 deletions

View File

@@ -11,10 +11,10 @@ assignees: ''
- [ ] Have you provided a full/minimal spec to reproduce the issue?
- [ ] Have you validated the input using an OpenAPI validator ([example](https://apidevtools.org/swagger-parser/online/))?
- [ ] What's the version of OpenAPI Generator used?
- [ ] Have you [tested with the latest master](https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-to-test-with-the-latest-master-of-openapi-generator) to confirm the issuue still exists?
- [ ] Have you search for related issues/PRs?
- [ ] What's the actual output vs expected output?
- [ ] [Optional] Bounty to sponsor the fix ([example](https://www.bountysource.com/issues/66123212-javascript-client-produces-a-wrong-object-for-a-string-enum-type-that-is-used-with-ref))
- [ ] [Optional] Sponsorship to speed up the bug fix or feature request ([example](https://github.com/OpenAPITools/openapi-generator/issues/6178))
<!--
Please follow the issue template below for bug reports.

View File

@@ -772,6 +772,7 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- 2020-07-26 - [Dartのhttp_interceptorライブラリを使うと配列のクエリパラメータが消えてしまう件の応急処置](https://qiita.com/gyamoto/items/eeeff81b6770487319ed) by [@gyamoto](https://qiita.com/gyamoto)
- 2020-08-03 - [Criando Bibliotecas para APIs RESTful com OpenAPI, Swagger Editor e OpenAPI Generator](https://medium.com/@everisBrasil/criando-bibliotecas-para-apis-restful-com-openapi-swagger-editor-e-openapi-generator-75349a6420fd) by [everis Brasil (an NTT DATA Company)](https://medium.com/@everisBrasil)
- 2020-08-19 - [マイクロサービスを連携してみよう](https://thinkit.co.jp/article/17704) by [岡井 裕矢(おかい ゆうや)](https://thinkit.co.jp/author/17588), [泉 勝(いずみ まさる)](https://thinkit.co.jp/author/17705) at [Think ITシンクイット](https://thinkit.co.jp/)
- 2020-08-25 - [OpenAPI Generator と TypeScript で型安全にフロントエンド開発をしている話](https://tech.smarthr.jp/entry/2020/08/25/135631) at [SmartHR Tech Blog](https://tech.smarthr.jp/)
## [6 - About Us](#table-of-contents)

View File

@@ -1,6 +0,0 @@
generatorName: go-experimental
outputDir: samples/client/petstore/go-experimental/go-petstore
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/go-experimental
additionalProperties:
packageName: petstore

View File

@@ -1,8 +0,0 @@
generatorName: go-experimental
outputDir: samples/openapi3/client/petstore/go-experimental/go-petstore
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml
templateDir: modules/openapi-generator/src/main/resources/go-experimental
additionalProperties:
enumClassPrefix: "true"
packageName: petstore
disallowAdditionalPropertiesIfNotPresent: false

View File

@@ -0,0 +1,6 @@
generatorName: go
outputDir: samples/openapi3/client/extensions/x-auth-id-alias/go-experimental
inputSpec: modules/openapi-generator/src/test/resources/3_0/extensions/x-auth-id-alias.yaml
templateDir: modules/openapi-generator/src/main/resources/go
additionalProperties:
packageName: x_auth_id_alias

View File

@@ -4,3 +4,4 @@ inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-e
templateDir: modules/openapi-generator/src/main/resources/go
additionalProperties:
packageName: petstore
generateInterfaces: true

View File

@@ -1,8 +0,0 @@
generatorName: go
outputDir: samples/client/petstore/go/go-petstore-withXml
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/go
additionalProperties:
packageName: petstore
withXml: "true"
withGoCodegenComment: "true"

View File

@@ -1,7 +1,9 @@
generatorName: go
outputDir: samples/openapi3/client/petstore/go/go-petstore
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml
templateDir: modules/openapi-generator/src/main/resources/go
additionalProperties:
enumClassPrefix: "true"
packageName: petstore
disallowAdditionalPropertiesIfNotPresent: false
generateInterfaces: true

View File

@@ -0,0 +1,11 @@
generatorName: java
outputDir: samples/client/petstore/java/feign-no-nullable
library: feign
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/Java
additionalProperties:
booleanGetterPrefix: is
artifactId: petstore-feign-no-nullable
hideGenerationTimestamp: "true"
additionalModelTypeAnnotations: '@javax.annotation.concurrent.Immutable'
openApiNullable: "false"

View File

@@ -0,0 +1,7 @@
generatorName: java
outputDir: samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8
library: jersey2
inputSpec: modules/openapi-generator/src/test/resources/3_0/extensions/x-auth-id-alias.yaml
additionalProperties:
artifactId: openapi3-extensions-x-auth-id-alias-jersey2-java8
hideGenerationTimestamp: true

View File

@@ -0,0 +1,7 @@
generatorName: java-play-framework
outputDir: samples/server/petstore/java-play-framework-no-nullable
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaPlayFramework
additionalProperties:
hideGenerationTimestamp: "true"
openApiNullable: "false"

View File

@@ -0,0 +1,9 @@
generatorName: java
outputDir: samples/client/petstore/java/vertx-no-nullable
library: vertx
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/Java
additionalProperties:
artifactId: petstore-vertx-no-nullable
hideGenerationTimestamp: "true"
openApiNullable: "false"

View File

@@ -0,0 +1,11 @@
generatorName: spring
outputDir: samples/server/petstore/springboot-beanvalidation-no-nullable
library: spring-boot
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
java8: "false"
useBeanValidation: true
artifactId: spring-boot-beanvalidation-no-nullable
hideGenerationTimestamp: "true"
openApiNullable: "false"

View File

@@ -0,0 +1,10 @@
generatorName: spring
outputDir: samples/client/petstore/spring-cloud-no-nullable
library: spring-cloud
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-cloud
additionalProperties:
artifactId: petstore-spring-cloud-no-nullable
responseWrapper: HystrixCommand
hideGenerationTimestamp: "true"
openApiNullable: "false"

View File

@@ -0,0 +1,10 @@
generatorName: spring
outputDir: samples/server/petstore/spring-mvc-no-nullable
library: spring-mvc
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
artifactId: spring-mvc-server-no-nullable
openApiNullable: "false"
serverPort: "8002"
hideGenerationTimestamp: "true"

View File

@@ -29,7 +29,7 @@ The following generators are available:
* [erlang-proper](generators/erlang-proper.md)
* [flash-deprecated (deprecated)](generators/flash-deprecated.md)
* [go](generators/go.md)
* [go-experimental (experimental)](generators/go-experimental.md)
* [go-deprecated (deprecated)](generators/go-deprecated.md)
* [groovy](generators/groovy.md)
* [haskell-http-client](generators/haskell-http-client.md)
* [java](generators/java.md)

View File

@@ -0,0 +1,211 @@
---
title: Config Options for go-deprecated
sidebar_label: go-deprecated
---
| Option | Description | Values | Default |
| ------ | ----------- | ------ | ------- |
|enumClassPrefix|Prefix enum with class name| |false|
|generateInterfaces|Generate interfaces for api classes| |false|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true|
|isGoSubmodule|whether the generated Go module is a submodule| |false|
|packageName|Go package name (convention: lowercase).| |openapi|
|packageVersion|Go package version.| |1.0.0|
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
|structPrefix|whether to prefix struct with the class name. e.g. DeletePetOpts =&gt; PetApiDeletePetOpts| |false|
|withAWSV4Signature|whether to include AWS v4 signature support| |false|
|withGoCodegenComment|whether to include Go codegen comment to disable Go Lint and collapse by default in GitHub PRs and diffs| |false|
|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 |
| ---------- | ------- |
## INSTANTIATION TYPES
| Type/Alias | Instantiated By |
| ---------- | --------------- |
## LANGUAGE PRIMITIVES
<ul class="column-ul">
<li>bool</li>
<li>byte</li>
<li>complex128</li>
<li>complex64</li>
<li>float32</li>
<li>float64</li>
<li>int</li>
<li>int32</li>
<li>int64</li>
<li>interface{}</li>
<li>map[string]interface{}</li>
<li>rune</li>
<li>string</li>
<li>uint</li>
<li>uint32</li>
<li>uint64</li>
</ul>
## RESERVED WORDS
<ul class="column-ul">
<li>bool</li>
<li>break</li>
<li>byte</li>
<li>case</li>
<li>chan</li>
<li>complex128</li>
<li>complex64</li>
<li>const</li>
<li>continue</li>
<li>default</li>
<li>defer</li>
<li>else</li>
<li>error</li>
<li>fallthrough</li>
<li>float32</li>
<li>float64</li>
<li>for</li>
<li>func</li>
<li>go</li>
<li>goto</li>
<li>if</li>
<li>import</li>
<li>int</li>
<li>int16</li>
<li>int32</li>
<li>int64</li>
<li>int8</li>
<li>interface</li>
<li>map</li>
<li>nil</li>
<li>package</li>
<li>range</li>
<li>return</li>
<li>rune</li>
<li>select</li>
<li>string</li>
<li>struct</li>
<li>switch</li>
<li>type</li>
<li>uint</li>
<li>uint16</li>
<li>uint32</li>
<li>uint64</li>
<li>uint8</li>
<li>uintptr</li>
<li>var</li>
</ul>
## 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

View File

@@ -7,6 +7,7 @@ sidebar_label: go-experimental
| ------ | ----------- | ------ | ------- |
|disallowAdditionalPropertiesIfNotPresent|Specify the behavior when the 'additionalProperties' keyword is not present in the OAS document. If false: the 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications. If true: when the 'additionalProperties' keyword is not present in a schema, the value of 'additionalProperties' is set to false, i.e. no additional properties are allowed. Note: this mode is not compliant with the JSON schema specification. This is the original openapi-generator behavior.This setting is currently ignored for OAS 2.0 documents: 1) When the 'additionalProperties' keyword is not present in a 2.0 schema, additional properties are NOT allowed. 2) Boolean values of the 'additionalProperties' keyword are ignored. It's as if additional properties are NOT allowed.Note: the root cause are issues #1369 and #1371, which must be resolved in the swagger-parser project.|<dl><dt>**false**</dt><dd>The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.</dd><dt>**true**</dt><dd>when the 'additionalProperties' keyword is not present in a schema, the value of 'additionalProperties' is automatically set to false, i.e. no additional properties are allowed. Note: this mode is not compliant with the JSON schema specification. This is the original openapi-generator behavior.</dd></dl>|true|
|enumClassPrefix|Prefix enum with class name| |false|
|generateInterfaces|Generate interfaces for api classes| |false|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true|
|isGoSubmodule|whether the generated Go module is a submodule| |false|
|packageName|Go package name (convention: lowercase).| |openapi|

View File

@@ -5,13 +5,16 @@ sidebar_label: go
| Option | Description | Values | Default |
| ------ | ----------- | ------ | ------- |
|disallowAdditionalPropertiesIfNotPresent|Specify the behavior when the 'additionalProperties' keyword is not present in the OAS document. If false: the 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications. If true: when the 'additionalProperties' keyword is not present in a schema, the value of 'additionalProperties' is set to false, i.e. no additional properties are allowed. Note: this mode is not compliant with the JSON schema specification. This is the original openapi-generator behavior.This setting is currently ignored for OAS 2.0 documents: 1) When the 'additionalProperties' keyword is not present in a 2.0 schema, additional properties are NOT allowed. 2) Boolean values of the 'additionalProperties' keyword are ignored. It's as if additional properties are NOT allowed.Note: the root cause are issues #1369 and #1371, which must be resolved in the swagger-parser project.|<dl><dt>**false**</dt><dd>The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.</dd><dt>**true**</dt><dd>when the 'additionalProperties' keyword is not present in a schema, the value of 'additionalProperties' is automatically set to false, i.e. no additional properties are allowed. Note: this mode is not compliant with the JSON schema specification. This is the original openapi-generator behavior.</dd></dl>|true|
|enumClassPrefix|Prefix enum with class name| |false|
|generateInterfaces|Generate interfaces for api classes| |false|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true|
|isGoSubmodule|whether the generated Go module is a submodule| |false|
|packageName|Go package name (convention: lowercase).| |openapi|
|packageVersion|Go package version.| |1.0.0|
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
|structPrefix|whether to prefix struct with the class name. e.g. DeletePetOpts =&gt; PetApiDeletePetOpts| |false|
|useOneOfDiscriminatorLookup|Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and onlye one match in oneOf's schemas) will be skipped.| |false|
|withAWSV4Signature|whether to include AWS v4 signature support| |false|
|withGoCodegenComment|whether to include Go codegen comment to disable Go Lint and collapse by default in GitHub PRs and diffs| |false|
|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|

View File

@@ -30,6 +30,7 @@ sidebar_label: groovy
|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|

View File

@@ -32,6 +32,7 @@ sidebar_label: java-inflector
|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|

View File

@@ -34,6 +34,7 @@ sidebar_label: java-msf4j
|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|

View File

@@ -34,6 +34,7 @@ sidebar_label: java-pkmst
|licenseName|The name of the license| |Unlicense|
|licenseUrl|The URL of the license| |http://unlicense.org|
|modelPackage|package for generated models| |com.prokarma.pkmst.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|

View File

@@ -36,6 +36,7 @@ sidebar_label: java-play-framework
|licenseName|The name of the license| |Unlicense|
|licenseUrl|The URL of the license| |http://unlicense.org|
|modelPackage|package for generated models| |apimodels|
|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|

View File

@@ -32,6 +32,7 @@ sidebar_label: java-undertow-server
|licenseName|The name of the license| |Unlicense|
|licenseUrl|The URL of the license| |http://unlicense.org|
|modelPackage|package for generated models| |null|
|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|

View File

@@ -32,6 +32,7 @@ sidebar_label: java-vertx-web
|licenseName|The name of the license| |Unlicense|
|licenseUrl|The URL of the license| |http://unlicense.org|
|modelPackage|package for generated models| |org.openapitools.vertxweb.server.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|

View File

@@ -32,6 +32,7 @@ sidebar_label: java-vertx
|licenseName|The name of the license| |Unlicense|
|licenseUrl|The URL of the license| |http://unlicense.org|
|modelPackage|package for generated models| |org.openapitools.server.api.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|

View File

@@ -36,6 +36,7 @@ sidebar_label: java
|licenseUrl|The URL of the license| |http://unlicense.org|
|microprofileFramework|Framework for microprofile. Possible values &quot;kumuluzee&quot;| |null|
|modelPackage|package for generated models| |org.openapitools.client.model|
|openApiNullable|Enable OpenAPI Jackson Nullable library| |true|
|parcelableModel|Whether to generate models for Android that implement Parcelable with the okhttp-gson library.| |false|
|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|

View File

@@ -37,6 +37,7 @@ sidebar_label: jaxrs-cxf-cdi
|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|
|openApiSpecFileLocation|Location where the file containing the spec will be generated in the output folder. No file generated when set to null or empty string.| |null|
|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|

View File

@@ -32,6 +32,7 @@ sidebar_label: jaxrs-cxf-client
|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|

View File

@@ -40,6 +40,7 @@ sidebar_label: jaxrs-cxf-extended
|licenseUrl|The URL of the license| |http://unlicense.org|
|loadTestDataFromFile|Load test data from a generated JSON file| |false|
|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|

View File

@@ -38,6 +38,7 @@ sidebar_label: jaxrs-cxf
|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|

View File

@@ -34,6 +34,7 @@ sidebar_label: jaxrs-jersey
|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|

View File

@@ -34,6 +34,7 @@ sidebar_label: jaxrs-resteasy-eap
|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|

View File

@@ -34,6 +34,7 @@ sidebar_label: jaxrs-resteasy
|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|

View File

@@ -37,6 +37,7 @@ sidebar_label: jaxrs-spec
|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|
|openApiSpecFileLocation|Location where the file containing the spec will be generated in the output folder. No file generated when set to null or empty string.| |null|
|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|

View File

@@ -35,12 +35,13 @@ sidebar_label: spring
|implicitHeaders|Skip header parameters in the generated API methods using @ApiImplicitParams annotation.| |false|
|interfaceOnly|Whether to generate only API interface stubs without the server files.| |false|
|invokerPackage|root package for generated code| |org.openapitools.api|
|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|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64. Use java8 default interface when a responseWrapper is used</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
|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|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64. Use java8 default interface when a responseWrapper is used. IMPORTANT: This option has been deprecated as Java 8 is the default.</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|<dl><dt>**true**</dt><dd>The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.</dd><dt>**false**</dt><dd>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.</dd></dl>|true|
|library|library template (sub-template)|<dl><dt>**spring-boot**</dt><dd>Spring-boot Server application using the SpringFox integration.</dd><dt>**spring-mvc**</dt><dd>Spring-MVC Server application using the SpringFox integration.</dd><dt>**spring-cloud**</dt><dd>Spring-Cloud-Feign client with Spring-Boot auto-configured settings.</dd></dl>|spring-boot|
|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|

View File

@@ -23,7 +23,7 @@ The minimum set of files required to create a new generator are:
- Should include a README explaining usage
- Must include an `api.mustache`
- Exists under `modules/openapi-generator/src/main/resources/` (plus `embeddedTemplate` dir value, see below)
* Sample scripts under `./bin`
* Config file under `./bin/configs`
- Gives users a "real life" example of generated output
- Samples are used by CI to verify generators and test for regressions in some cases
@@ -43,6 +43,8 @@ Usage:
-c Create a client generator
-s Create a server generator
-d Create a documentation generator
-H Create a schema generator
-f Create a config generator
-t When specified, creates test file(s) for the generator.
-h Display help.
@@ -55,8 +57,7 @@ Examples:
modules/openapi-generator/src/main/resources/kotlin-server/README.mustache
modules/openapi-generator/src/main/resources/kotlin-server/model.mustache
modules/openapi-generator/src/main/resources/kotlin-server/api.mustache
bin/windows/kotlin-server-petstore.bat
bin/kotlin-server-petstore.sh
bin/configs/kotlin-server-petstore-new.yaml
Create a generic C# server generator:
./new.sh -n csharp -s -t
@@ -65,8 +66,7 @@ Examples:
modules/openapi-generator/src/main/resources/csharp-server/README.mustache
modules/openapi-generator/src/main/resources/csharp-server/model.mustache
modules/openapi-generator/src/main/resources/csharp-server/api.mustache
bin/windows/csharp-server-petstore.bat
bin/csharp-server-petstore.sh
bin/configs/csharp-server-petstore-new.yaml
modules/openapi-generator/src/test/java/org/openapitools/codegen/csharp/CsharpServerCodegenTest.java
modules/openapi-generator/src/test/java/org/openapitools/codegen/csharp/CsharpServerCodegenModelTest.java
modules/openapi-generator/src/test/java/org/openapitools/codegen/csharp/CsharpServerCodegenOptionsTest.java
@@ -88,8 +88,7 @@ Creating modules/openapi-generator/src/main/java/org/openapitools/codegen/langua
Creating modules/openapi-generator/src/main/resources/common-mark-documentation/README.mustache
Creating modules/openapi-generator/src/main/resources/common-mark-documentation/model.mustache
Creating modules/openapi-generator/src/main/resources/common-mark-documentation/api.mustache
Creating bin/windows/common-mark-documentation-petstore.bat
Creating bin/common-mark-documentation-petstore.sh
Creating bin/configs/common-mark-documentation-petstore-new.yaml
Finished.
```
@@ -151,7 +150,7 @@ The `templateDir` variable refers to the "current" template directory setting, a
Both of these variables exist because the generator will fallback to files under `embeddedTemplateDir` if they are not defined in the user's custom template directory.
```java
apiPackage = File.separator + "Apis";
apiPackage = "Apis";
```
This sets the "package" location for anything considered an API document. You might want to change this setting if, for instance, your language doesn't support uppercase letters in the path. We don't need to worry about that here.
@@ -159,7 +158,7 @@ This sets the "package" location for anything considered an API document. You mi
Every templated output from `api.mustache` (registered via `apiTemplateFiles` above) will end up in the directory defined by `apiPackage` here.
```java
modelPackage = File.separator + "Models";
modelPackage = "Models";
```
Similarly, this sets the package for `Models`.
@@ -330,61 +329,29 @@ To compile quickly to test this out, you can run `mvn clean package -DskipTests`
### Compile Sample
The `new.sh` script created `bin/common-mark-documentation-petstore.sh`:
The `new.sh` script created the generation config file `bin/configs/common-mark-documentation-petstore-new.yaml`:
```bash
#!/bin/sh
SCRIPT="$0"
while [ -h "$SCRIPT" ] ; do
ls=$(ls -ld "$SCRIPT")
link=$(expr "$ls" : '.*-> \(.*\)$')
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=$(dirname "$SCRIPT")/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=$(dirname "$SCRIPT")/..
APP_DIR=$(cd "${APP_DIR}"; pwd)
fi
executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar"
if [ ! -f "$executable" ]
then
mvn clean package
fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g common-mark -o samples/documentation/petstore/common/mark"
java ${JAVA_OPTS} -jar ${executable} ${ags}
generatorName: common-mark
outputDir: samples/documentation/petstore/common/mark
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/common-mark
additionalProperties:
hideGenerationTimestamp: "true"
```
This script is often used to apply default options for generation. A common option in most of these script is to define the template directory as the generator's directory under `resources`. This allows template maintainers to modify and test out template changes which don't require recompilation of the entire project. You'd still need to recompile the project in full if you add or modify behaviors to the generator (such as adding a `CliOption`).
This configuration file is passed to the generator's CLI tool during continuous integration builds, and many outputs are compiled and tested as a regression test on every build. Contributors are also asked to run `./bin/utils/ensure-up-to-date` before opening a pull request to regenerate all samples defined under `./bin/configs`. This allows maintainers to quickly verify whether changes impact other generators.
Add `-t modules/openapi-generator/src/main/resources/common-mark-documentation` to `ags` line to simplify the evaluation of template-only modifications:
Configuration based examples allow us to test the same samples in each tooling option (CLI, Gradle Plugin, Maven Plugin, etc.).
```diff
diff --git a/bin/markdown-documentation-petstore.sh b/bin/markdown-documentation-petstore.sh
index d816771478..94b4ce6d12 100644
--- a/bin/markdown-documentation-petstore.sh
+++ b/bin/markdown-documentation-petstore.sh
@@ -26,6 +26,6 @@ fi
You can compile your generator by running:
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
-ags="$@ generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g common-mark -o samples/documentation/petstore/common-mark"
+ags="$@ generate -t modules/openapi-generator/src/main/resources/common-mark-documentation -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g common-mark -o samples/documentation/petstore/common/markdown"
java ${JAVA_OPTS} -jar ${executable} ${ags}
```bash
./bin/generate-samples.sh bin/configs/common-mark-documentation-petstore-new.yaml
```
This configuration file can be used to demonstrate the default options for generation. A common option in most of these configs is to define the template directory as the generator's directory under `resources`. This allows template maintainers to modify and test out template changes which don't require recompilation of the entire project. You'd still need to recompile the project in full if you add or modify behaviors to the generator (such as adding a `CliOption`).
### Verify output
Creating a new generator will be an iterative task. Once you've generated the sample, you'll want to try it out. For compiled client/server outputs, this would mean running the code or creating a small sample project to consume your artifact just to make sure it works.

View File

@@ -4,7 +4,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>5.0.0-SNAPSHOT</version>
<version>5.0.0-beta2</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath>
</parent>

View File

@@ -6,7 +6,7 @@
<artifactId>openapi-generator-project</artifactId>
<groupId>org.openapitools</groupId>
<!-- RELEASE_VERSION -->
<version>5.0.0-SNAPSHOT</version>
<version>5.0.0-beta2</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath>
</parent>

View File

@@ -45,6 +45,16 @@ public interface TemplatingEngineAdapter {
*/
String[] getFileExtensions();
/**
* Determine if the adapter handles compilation of the file
* @param filename The template filename
*
* @return True if the file should be compiled by this adapter, else false.
*/
default boolean handlesFile(String filename) {
return filename != null && filename.length() > 0 && Arrays.stream(getFileExtensions()).anyMatch(i -> filename.endsWith("." + i));
}
/**
* Compiles a template into a string
*
@@ -65,9 +75,10 @@ public interface TemplatingEngineAdapter {
* @param templateFile The original target filename
* @return True if the template is available in the template search path, false if it can not be found
*/
@SuppressWarnings({"java:S2093"}) // ignore java:S2093 because we have double-assignment to the closeable
default boolean templateExists(TemplatingExecutor generator, String templateFile) {
return Arrays.stream(getFileExtensions()).anyMatch(ext -> {
int idx = templateFile.lastIndexOf(".");
int idx = templateFile.lastIndexOf('.');
String baseName;
if (idx > 0 && idx < templateFile.length() - 1) {
baseName = templateFile.substring(0, idx);

View File

@@ -97,7 +97,7 @@ task validateGoodSpec(type: org.openapitools.generator.gradle.plugin.tasks.Valid
[source,group]
----
plugins {
id "org.openapi.generator" version "4.3.1"
id "org.openapi.generator" version "5.0.0-beta2"
}
----
@@ -113,7 +113,7 @@ buildscript {
// url "https://plugins.gradle.org/m2/"
}
dependencies {
classpath "org.openapitools:openapi-generator-gradle-plugin:4.3.1"
classpath "org.openapitools:openapi-generator-gradle-plugin:5.0.0-beta2"
}
}

View File

@@ -1,5 +1,5 @@
# RELEASE_VERSION
openApiGeneratorVersion=5.0.0-SNAPSHOT
openApiGeneratorVersion=5.0.0-beta2
# /RELEASE_VERSION
# BEGIN placeholders

View File

@@ -4,7 +4,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>5.0.0-SNAPSHOT</version>
<version>5.0.0-beta2</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath>
</parent>

View File

@@ -18,5 +18,5 @@ gradle generateGoWithInvalidSpec # expected outcome: BUILD FAILED
The samples can be tested against other versions of the plugin using the `openApiGeneratorVersion` property. For example:
```bash
gradle -PopenApiGeneratorVersion=4.3.0 openApiValidate
gradle -PopenApiGeneratorVersion=5.0.0-beta2 openApiValidate
```

View File

@@ -12,7 +12,7 @@ Add to your `build->plugins` section (default phase is `generate-sources` phase)
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>4.3.1</version>
<version>5.0.0-beta2</version>
<!-- /RELEASE_VERSION -->
<executions>
<execution>

View File

@@ -13,7 +13,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>5.0.0-SNAPSHOT</version>
<version>5.0.0-beta2</version>
<!-- /RELEASE_VERSION -->
<executions>
<execution>

View File

@@ -19,7 +19,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>5.0.0-SNAPSHOT</version>
<version>5.0.0-beta2</version>
<!-- /RELEASE_VERSION -->
<dependencies>
<dependency>

View File

@@ -13,7 +13,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>5.0.0-SNAPSHOT</version>
<version>5.0.0-beta2</version>
<!-- /RELEASE_VERSION -->
<executions>
<execution>

View File

@@ -13,7 +13,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>4.3.1</version>
<version>5.0.0-beta2</version>
<!-- /RELEASE_VERSION -->
<executions>
<execution>

View File

@@ -5,7 +5,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>5.0.0-SNAPSHOT</version>
<version>5.0.0-beta2</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath>
</parent>

View File

@@ -4,7 +4,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>5.0.0-SNAPSHOT</version>
<version>5.0.0-beta2</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath>
</parent>

View File

@@ -4,7 +4,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>5.0.0-SNAPSHOT</version>
<version>5.0.0-beta2</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath>
</parent>

View File

@@ -4973,6 +4973,15 @@ public class DefaultCodegen implements CodegenConfig {
return library;
}
/**
* check if current active library equals to passed
* @param library - library to be compared with
* @return {@code true} if passed library is active, {@code false} otherwise
*/
public final boolean isLibrary(String library) {
return library.equals(this.library);
}
/**
* Set Git host.
*

View File

@@ -913,6 +913,11 @@ public class DefaultGenerator implements Generator {
File target = new File(adjustedOutputFilename);
if (ignoreProcessor.allowsFile(target)) {
if (shouldGenerate) {
Path outDir = java.nio.file.Paths.get(this.config.getOutputDir()).toAbsolutePath();
Path absoluteTarget = target.toPath().toAbsolutePath();
if (!absoluteTarget.startsWith(outDir)) {
throw new RuntimeException(String.format(Locale.ROOT, "Target files must be generated within the output directory; absoluteTarget=%s outDir=%s", absoluteTarget, outDir));
}
return this.templateProcessor.write(templateData,templateName, target);
} else {
this.templateProcessor.skip(target.toPath(), String.format(Locale.ROOT, "Skipped by %s options supplied by user.", skippedByOption));

View File

@@ -1,5 +1,6 @@
package org.openapitools.codegen;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.api.TemplatePathLocator;
import org.openapitools.codegen.api.TemplateProcessor;
@@ -12,14 +13,8 @@ import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
import java.util.Scanner;
import java.nio.file.*;
import java.util.*;
import java.util.regex.Pattern;
/**
@@ -59,6 +54,10 @@ public class TemplateManager implements TemplatingExecutor, TemplateProcessor {
throw new TemplateNotFoundException(name);
}
if (name == null || name.contains("..")) {
throw new IllegalArgumentException("Template location must be constrained to template directory.");
}
return template;
}
@@ -104,7 +103,12 @@ public class TemplateManager implements TemplatingExecutor, TemplateProcessor {
* @param name The location of the template
* @return The raw template contents
*/
@SuppressWarnings({"java:S112"})
// ignored rule java:S112 as RuntimeException is used to match previous exception type
public String readTemplate(String name) {
if (name == null || name.contains("..")) {
throw new IllegalArgumentException("Template location must be constrained to template directory.");
}
try {
Reader reader = getTemplateReader(name);
if (reader == null) {
@@ -118,15 +122,12 @@ public class TemplateManager implements TemplatingExecutor, TemplateProcessor {
throw new RuntimeException("can't load template " + name);
}
@SuppressWarnings("squid:S2095")
// ignored rule as used in the CLI and it's required to return a reader
@SuppressWarnings({"squid:S2095", "java:S112"})
// ignored rule squid:S2095 as used in the CLI and it's required to return a reader
// ignored rule java:S112 as RuntimeException is used to match previous exception type
public Reader getTemplateReader(String name) {
InputStream is = null;
try {
is = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(name));
if (is == null) {
is = new FileInputStream(new File(name)); // May throw but never return a null value
}
InputStream is = getInputStream(name);
return new InputStreamReader(is, StandardCharsets.UTF_8);
} catch (FileNotFoundException e) {
LOGGER.error(e.getMessage());
@@ -134,6 +135,18 @@ public class TemplateManager implements TemplatingExecutor, TemplateProcessor {
}
}
private InputStream getInputStream(String name) throws FileNotFoundException {
InputStream is;
is = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(name));
if (is == null) {
if (name == null || name.contains("..")) {
throw new IllegalArgumentException("Template location must be constrained to template directory.");
}
is = new FileInputStream(new File(name)); // May throw but never return a null value
}
return is;
}
/**
* Writes data to a compiled template
*
@@ -145,18 +158,32 @@ public class TemplateManager implements TemplatingExecutor, TemplateProcessor {
*/
@Override
public File write(Map<String, Object> data, String template, File target) throws IOException {
String templateContent = this.engineAdapter.compileTemplate(this, data, template);
return writeToFile(target.getPath(), templateContent);
if (this.engineAdapter.handlesFile(template)) {
// Only pass files with valid endings through template engine
String templateContent = this.engineAdapter.compileTemplate(this, data, template);
return writeToFile(target.getPath(), templateContent);
} else {
// Do a straight copy of the file if not listed as supported by the template engine.
InputStream is;
try {
// look up the file using the same template resolution logic the adapters would use.
String fullTemplatePath = getFullTemplateFile(template);
is = getInputStream(fullTemplatePath);
} catch (TemplateNotFoundException ex) {
is = new FileInputStream(Paths.get(template).toFile());
}
return writeToFile(target.getAbsolutePath(), IOUtils.toByteArray(is));
}
}
@Override
public void ignore(Path path, String context) {
LOGGER.info("Ignored {} ({})", path.toString(), context);
LOGGER.info("Ignored {} ({})", path, context);
}
@Override
public void skip(Path path, String context) {
LOGGER.info("Skipped {} ({})", path.toString(), context);
LOGGER.info("Skipped {} ({})", path, context);
}
/**
@@ -189,23 +216,23 @@ public class TemplateManager implements TemplatingExecutor, TemplateProcessor {
try {
tempFile = writeToFileRaw(tempFilename, contents);
if (!filesEqual(tempFile, outputFile)) {
LOGGER.info("writing file " + filename);
LOGGER.info("writing file {}", filename);
Files.move(tempFile.toPath(), outputFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
tempFile = null;
} else {
LOGGER.info("skipping unchanged file " + filename);
LOGGER.info("skipping unchanged file {}", filename);
}
} finally {
if (tempFile != null && tempFile.exists()) {
try {
tempFile.delete();
Files.delete(tempFile.toPath());
} catch (Exception ex) {
LOGGER.error("Error removing temporary file " + tempFile, ex);
LOGGER.error("Error removing temporary file {}", tempFile, ex);
}
}
}
} else {
LOGGER.info("writing file " + filename);
LOGGER.info("writing file {}", filename);
outputFile = writeToFileRaw(filename, contents);
}
@@ -216,7 +243,7 @@ public class TemplateManager implements TemplatingExecutor, TemplateProcessor {
// Use Paths.get here to normalize path (for Windows file separator, space escaping on Linux/Mac, etc)
File output = Paths.get(filename).toFile();
if (this.options.isSkipOverwrite() && output.exists()) {
LOGGER.info("skip overwrite of file " + filename);
LOGGER.info("skip overwrite of file {}", filename);
return output;
}

View File

@@ -22,6 +22,11 @@ import java.util.Locale;
import java.util.ServiceLoader;
public class TemplatingEngineLoader {
private TemplatingEngineLoader() {
throw new IllegalStateException("Utility class");
}
@SuppressWarnings({"java:S112"}) // ignore java:S112 as generic RuntimeException is acceptable here
public static TemplatingEngineAdapter byIdentifier(String id) {
ServiceLoader<TemplatingEngineAdapter> loader = ServiceLoader.load(TemplatingEngineAdapter.class, TemplatingEngineLoader.class.getClassLoader());
@@ -37,7 +42,7 @@ public class TemplatingEngineLoader {
// Attempt to load skipping SPI
return (TemplatingEngineAdapter) Class.forName(id).getDeclaredConstructor().newInstance();
} catch (Exception e) {
throw new RuntimeException(String.format(Locale.ROOT, "Couldn't load template engine adapter %s. Available options: \n%s", id, sb.toString()), e);
throw new RuntimeException(String.format(Locale.ROOT, "Couldn't load template engine adapter %s. Available options: %n%s", id, sb.toString()), e);
}
}
}

View File

@@ -42,6 +42,7 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
protected boolean withXml = false;
protected boolean enumClassPrefix = false;
protected boolean structPrefix = false;
protected boolean generateInterfaces = false;
protected String packageName = "openapi";
protected Set<String> numberTypes;
@@ -630,7 +631,7 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
}
}
if (this instanceof GoClientExperimentalCodegen && model.isEnum) {
if (this instanceof GoClientCodegen && model.isEnum) {
imports.add(createMapping("import", "fmt"));
}
@@ -780,6 +781,10 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
this.structPrefix = structPrefix;
}
public void setGenerateInterfaces(boolean generateInterfaces) {
this.generateInterfaces = generateInterfaces;
}
@Override
public String toDefaultValue(Schema schema) {
if (schema.getDefault() != null) {

View File

@@ -24,6 +24,7 @@ import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.ComposedSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.servers.Server;
import io.swagger.v3.parser.util.SchemaTypeUtil;
import org.apache.commons.io.FilenameUtils;
@@ -61,6 +62,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
public static final String BOOLEAN_GETTER_PREFIX = "booleanGetterPrefix";
public static final String ADDITIONAL_MODEL_TYPE_ANNOTATIONS = "additionalModelTypeAnnotations";
public static final String DISCRIMINATOR_CASE_SENSITIVE = "discriminatorCaseSensitive";
public static final String OPENAPI_NULLABLE = "openApiNullable";
protected String dateLibrary = "threetenbp";
protected boolean supportAsync = false;
@@ -100,6 +102,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
protected String parentVersion = "";
protected boolean parentOverridden = false;
protected List<String> additionalModelTypeAnnotations = new LinkedList<>();
protected boolean openApiNullable = true;
public AbstractJavaCodegen() {
super();
@@ -218,6 +221,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
cliOptions.add(CliOption.newBoolean(DISABLE_HTML_ESCAPING, "Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)", disableHtmlEscaping));
cliOptions.add(CliOption.newString(BOOLEAN_GETTER_PREFIX, "Set booleanGetterPrefix").defaultValue(this.getBooleanGetterPrefix()));
cliOptions.add(CliOption.newString(ADDITIONAL_MODEL_TYPE_ANNOTATIONS, "Additional annotations for model type(class level annotations)"));
cliOptions.add(CliOption.newBoolean(OPENAPI_NULLABLE, "Enable OpenAPI Jackson Nullable library", this.openApiNullable));
cliOptions.add(CliOption.newString(CodegenConstants.PARENT_GROUP_ID, CodegenConstants.PARENT_GROUP_ID_DESC));
cliOptions.add(CliOption.newString(CodegenConstants.PARENT_ARTIFACT_ID, CodegenConstants.PARENT_ARTIFACT_ID_DESC));
@@ -412,6 +416,11 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
}
additionalProperties.put(WITH_XML, withXml);
if (additionalProperties.containsKey(OPENAPI_NULLABLE)) {
this.setOpenApiNullable(Boolean.valueOf(additionalProperties.get(OPENAPI_NULLABLE).toString()));
}
additionalProperties.put(OPENAPI_NULLABLE, openApiNullable);
if (additionalProperties.containsKey(CodegenConstants.PARENT_GROUP_ID)) {
this.setParentGroupId((String) additionalProperties.get(CodegenConstants.PARENT_GROUP_ID));
}
@@ -757,16 +766,23 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
@Override
public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) {
Schema<?> items = getSchemaItems((ArraySchema) p);
return getSchemaType(p) + "<" + getTypeDeclaration(ModelUtils.unaliasSchema(this.openAPI, items)) + ">";
} else if (ModelUtils.isMapSchema(p) && !ModelUtils.isComposedSchema(p)) {
Schema<?> schema = ModelUtils.unaliasSchema(this.openAPI, p);
Schema<?> target = ModelUtils.isGenerateAliasAsModel() ? p : schema;
if (ModelUtils.isArraySchema(target)) {
Schema<?> items = getSchemaItems((ArraySchema) schema);
return getSchemaType(target) + "<" + getTypeDeclaration(items) + ">";
} else if (ModelUtils.isMapSchema(target)) {
// Note: ModelUtils.isMapSchema(p) returns true when p is a composed schema that also defines
// additionalproperties: true
Schema<?> inner = getSchemaAdditionalProperties(p);
return getSchemaType(p) + "<String, " + getTypeDeclaration(ModelUtils.unaliasSchema(this.openAPI, inner)) + ">";
Schema<?> inner = getAdditionalProperties(target);
if (inner == null) {
LOGGER.error("`{}` (map property) does not have a proper inner type defined. Default to type:string", p.getName());
inner = new StringSchema().description("TODO default missing map inner type to string");
p.setAdditionalProperties(inner);
}
return getSchemaType(target) + "<String, " + getTypeDeclaration(inner) + ">";
}
return super.getTypeDeclaration(p);
return super.getTypeDeclaration(target);
}
@Override
@@ -1507,6 +1523,14 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
this.booleanGetterPrefix = booleanGetterPrefix;
}
public boolean isOpenApiNullable() {
return openApiNullable;
}
public void setOpenApiNullable(final boolean openApiNullable) {
this.openApiNullable = openApiNullable;
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection

View File

@@ -17,29 +17,37 @@
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 io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.*;
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.openapitools.codegen.utils.ProcessUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.EnumSet;
import java.util.*;
import static org.openapitools.codegen.utils.StringUtils.camelize;
public class GoClientCodegen extends AbstractGoCodegen {
private static final Logger LOGGER = LoggerFactory.getLogger(GoClientCodegen.class);
protected String packageVersion = "1.0.0";
protected String apiDocPath = "docs/";
protected String modelDocPath = "docs/";
protected boolean isGoSubmodule = false;
public static final String WITH_GO_CODEGEN_COMMENT = "withGoCodegenComment";
public static final String WITH_XML = "withXml";
public static final String STRUCT_PREFIX = "structPrefix";
public static final String WITH_AWSV4_SIGNATURE = "withAWSV4Signature";
public static final String GENERATE_INTERFACES = "generateInterfaces";
protected String goImportAlias = "openapiclient";
protected boolean isGoSubmodule = false;
protected boolean useOneOfDiscriminatorLookup = false; // use oneOf discriminator's mapping for model lookup
public GoClientCodegen() {
super();
@@ -73,15 +81,16 @@ public class GoClientCodegen extends AbstractGoCodegen {
)
);
outputFolder = "generated-code/go";
modelTemplateFiles.put("model.mustache", ".go");
apiTemplateFiles.put("api.mustache", ".go");
generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata).stability(Stability.STABLE).build();
outputFolder = "generated-code/go";
embeddedTemplateDir = templateDir = "go";
usesOptionals = false;
apiTemplateFiles.put("api.mustache", ".go");
modelDocTemplateFiles.put("model_doc.mustache", ".md");
apiDocTemplateFiles.put("api_doc.mustache", ".md");
embeddedTemplateDir = templateDir = "go";
// default HIDE_GENERATION_TIMESTAMP to true
hideGenerationTimestamp = Boolean.TRUE;
@@ -91,16 +100,73 @@ public class GoClientCodegen extends AbstractGoCodegen {
cliOptions.add(CliOption.newBoolean(CodegenConstants.ENUM_CLASS_PREFIX, CodegenConstants.ENUM_CLASS_PREFIX_DESC));
cliOptions.add(CliOption.newBoolean(STRUCT_PREFIX, "whether to prefix struct with the class name. e.g. DeletePetOpts => PetApiDeletePetOpts"));
cliOptions.add(CliOption.newBoolean(WITH_AWSV4_SIGNATURE, "whether to include AWS v4 signature support"));
cliOptions.add(CliOption.newBoolean(GENERATE_INTERFACES, "Generate interfaces for api classes"));
// option to change the order of form/body parameter
cliOptions.add(CliOption.newBoolean(
CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS,
CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS_DESC)
.defaultValue(Boolean.FALSE.toString()));
cliOptions.add(new CliOption(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP, CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP_DESC).defaultValue("false"));
// option to change how we process + set the data in the 'additionalProperties' keyword.
CliOption disallowAdditionalPropertiesIfNotPresentOpt = CliOption.newBoolean(
CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT,
CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT_DESC).defaultValue(Boolean.TRUE.toString());
Map<String, String> disallowAdditionalPropertiesIfNotPresentOpts = new HashMap<>();
disallowAdditionalPropertiesIfNotPresentOpts.put("false",
"The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.");
disallowAdditionalPropertiesIfNotPresentOpts.put("true",
"when the 'additionalProperties' keyword is not present in a schema, " +
"the value of 'additionalProperties' is automatically set to false, i.e. no additional properties are allowed. " +
"Note: this mode is not compliant with the JSON schema specification. " +
"This is the original openapi-generator behavior.");
disallowAdditionalPropertiesIfNotPresentOpt.setEnum(disallowAdditionalPropertiesIfNotPresentOpts);
cliOptions.add(disallowAdditionalPropertiesIfNotPresentOpt);
this.setDisallowAdditionalPropertiesIfNotPresent(true);
}
/**
* Configures a friendly name for the generator. This will be used by the
* generator to select the library with the -g flag.
*
* @return the friendly name for the generator
*/
@Override
public String getName() {
return "go";
}
/**
* Configures the type of generator.
*
* @return the CodegenType for this generator
* @see org.openapitools.codegen.CodegenType
*/
@Override
public CodegenType getTag() {
return CodegenType.CLIENT;
}
@Override
public String toGetter(String name) {
return "Get" + getterAndSetterCapitalize(name);
}
/**
* Returns human-friendly help for the generator. Provide the consumer with help
* tips, parameters here
*
* @return A string value for the help message
*/
@Override
public String getHelp() {
return "Generates a Go client library.";
}
@Override
public void processOpts() {
this.setLegacyDiscriminatorBehavior(false);
super.processOpts();
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) {
@@ -124,17 +190,6 @@ public class GoClientCodegen extends AbstractGoCodegen {
modelPackage = packageName;
apiPackage = packageName;
supportingFiles.add(new SupportingFile("openapi.mustache", "api", "openapi.yaml"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
supportingFiles.add(new SupportingFile("configuration.mustache", "", "configuration.go"));
supportingFiles.add(new SupportingFile("client.mustache", "", "client.go"));
supportingFiles.add(new SupportingFile("response.mustache", "", "response.go"));
supportingFiles.add(new SupportingFile("go.mod.mustache", "", "go.mod"));
supportingFiles.add(new SupportingFile("go.sum", "", "go.sum"));
supportingFiles.add(new SupportingFile(".travis.yml", "", ".travis.yml"));
if (additionalProperties.containsKey(WITH_GO_CODEGEN_COMMENT)) {
setWithGoCodegenComment(Boolean.parseBoolean(additionalProperties.get(WITH_GO_CODEGEN_COMMENT).toString()));
additionalProperties.put(WITH_GO_CODEGEN_COMMENT, withGoCodegenComment);
@@ -164,39 +219,68 @@ public class GoClientCodegen extends AbstractGoCodegen {
setStructPrefix(Boolean.parseBoolean(additionalProperties.get(STRUCT_PREFIX).toString()));
additionalProperties.put(STRUCT_PREFIX, structPrefix);
}
if (additionalProperties.containsKey(GENERATE_INTERFACES)) {
setGenerateInterfaces(Boolean.parseBoolean(additionalProperties.get(GENERATE_INTERFACES).toString()));
additionalProperties.put(GENERATE_INTERFACES, generateInterfaces);
}
// Generate the 'signing.py' module, but only if the 'HTTP signature' security scheme is specified in the OAS.
Map<String, SecurityScheme> securitySchemeMap = openAPI != null ?
(openAPI.getComponents() != null ? openAPI.getComponents().getSecuritySchemes() : null) : null;
List<CodegenSecurity> authMethods = fromSecurity(securitySchemeMap);
if (ProcessUtils.hasHttpSignatureMethods(authMethods)) {
supportingFiles.add(new SupportingFile("signing.mustache", "", "signing.go"));
}
if (additionalProperties.containsKey("goImportAlias")) {
setGoImportAlias(additionalProperties.get("goImportAlias").toString());
} else {
additionalProperties.put("goImportAlias", goImportAlias);
}
if (additionalProperties.containsKey(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP)) {
setUseOneOfDiscriminatorLookup(convertPropertyToBooleanAndWriteBack(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP));
} else {
additionalProperties.put(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP, getUseOneOfDiscriminatorLookup());
}
if (additionalProperties.containsKey(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT)) {
this.setDisallowAdditionalPropertiesIfNotPresent(Boolean.valueOf(additionalProperties
.get(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT).toString()));
}
supportingFiles.add(new SupportingFile("openapi.mustache", "api", "openapi.yaml"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
supportingFiles.add(new SupportingFile("configuration.mustache", "", "configuration.go"));
supportingFiles.add(new SupportingFile("client.mustache", "", "client.go"));
supportingFiles.add(new SupportingFile("response.mustache", "", "response.go"));
supportingFiles.add(new SupportingFile("go.mod.mustache", "", "go.mod"));
supportingFiles.add(new SupportingFile("go.sum", "", "go.sum"));
supportingFiles.add(new SupportingFile(".travis.yml", "", ".travis.yml"));
supportingFiles.add(new SupportingFile("utils.mustache", "", "utils.go"));
}
/**
* Configures the type of generator.
*
* @return the CodegenType for this generator
* @see org.openapitools.codegen.CodegenType
*/
@Override
public CodegenType getTag() {
return CodegenType.CLIENT;
public void setUseOneOfDiscriminatorLookup(boolean useOneOfDiscriminatorLookup) {
this.useOneOfDiscriminatorLookup = useOneOfDiscriminatorLookup;
}
/**
* Configures a friendly name for the generator. This will be used by the generator
* to select the library with the -g flag.
*
* @return the friendly name for the generator
*/
@Override
public String getName() {
return "go";
public boolean getUseOneOfDiscriminatorLookup() {
return this.useOneOfDiscriminatorLookup;
}
/**
* Returns human-friendly help for the generator. Provide the consumer with help
* tips, parameters here
*
* @return A string value for the help message
*/
@Override
public String getHelp() {
return "Generates a Go client library (beta).";
public void setGoImportAlias(String goImportAlias) {
this.goImportAlias = goImportAlias;
}
public void setPackageVersion(String packageVersion) {
this.packageVersion = packageVersion;
}
public void setIsGoSubmodule(boolean isGoSubmodule) {
this.isGoSubmodule = isGoSubmodule;
}
/**
@@ -233,12 +317,267 @@ public class GoClientCodegen extends AbstractGoCodegen {
return toApiName(name);
}
public void setPackageVersion(String packageVersion) {
this.packageVersion = packageVersion;
@Override
public String toModelName(String name) {
// underscoring would also lowercase the whole name, thus losing acronyms which are in capitals
return camelize(toModel(name, false));
}
public void setIsGoSubmodule(boolean isGoSubmodule) {
this.isGoSubmodule = isGoSubmodule;
public String escapeReservedWord(String name) {
if (this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return name + '_';
}
@Override
public String toEnumDefaultValue(String value, String datatype) {
String prefix = "";
if (enumClassPrefix) {
prefix = datatype.toUpperCase(Locale.ROOT) + "_";
}
return prefix + value;
}
@Override
public void updateCodegenPropertyEnum(CodegenProperty var) {
// make sure the inline enums have plain defaults (e.g. string, int, float)
String enumDefault = null;
if (var.isEnum && var.defaultValue != null) {
enumDefault = var.defaultValue;
}
super.updateCodegenPropertyEnum(var);
if (var.isEnum && enumDefault != null) {
var.defaultValue = enumDefault;
}
}
@Override
public String toDefaultValue(Schema p) {
p = ModelUtils.getReferencedSchema(this.openAPI, p);
if (ModelUtils.isStringSchema(p)) {
if (p.getDefault() != null) {
return "\"" + escapeText((String) p.getDefault()) + "\"";
}
return null;
}
return super.toDefaultValue(p);
}
@Override
public CodegenProperty fromProperty(String name, Schema p) {
CodegenProperty prop = super.fromProperty(name, p);
String cc = camelize(prop.name, true);
if (isReservedWord(cc)) {
cc = escapeReservedWord(cc);
}
prop.nameInCamelCase = cc;
return prop;
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
// The superclass determines the list of required golang imports. The actual list of imports
// depends on which types are used, some of which are changed in the code below (but then preserved
// and used through x-go-base-type in templates). So super.postProcessModels
// must be invoked at the beginning of this method.
objs = super.postProcessModels(objs);
List<Map<String, String>> imports = (List<Map<String, String>>) objs.get("imports");
List<Map<String, Object>> models = (List<Map<String, Object>>) objs.get("models");
for (Map<String, Object> m : models) {
Object v = m.get("model");
if (v instanceof CodegenModel) {
CodegenModel model = (CodegenModel) v;
if (model.isEnum) {
continue;
}
for (CodegenProperty param : model.vars) {
param.vendorExtensions.put("x-go-base-type", param.dataType);
if (!param.isNullable || param.isMapContainer || param.isListContainer ||
param.isFreeFormObject || param.isAnyType) {
continue;
}
if (param.isDateTime) {
// Note this could have been done by adding the following line in processOpts(),
// however, we only want to represent the DateTime object as NullableTime if
// it's marked as nullable in the spec.
// typeMapping.put("DateTime", "NullableTime");
param.dataType = "NullableTime";
} else {
param.dataType = "Nullable" + Character.toUpperCase(param.dataType.charAt(0))
+ param.dataType.substring(1);
}
}
// additional import for different cases
// oneOf
if (model.oneOf != null && !model.oneOf.isEmpty()) {
imports.add(createMapping("import", "fmt"));
}
// anyOf
if (model.anyOf != null && !model.anyOf.isEmpty()) {
imports.add(createMapping("import", "fmt"));
}
// additionalProperties: true and parent
if (model.isAdditionalPropertiesTrue && model.parent != null && Boolean.FALSE.equals(model.isMapModel)) {
imports.add(createMapping("import", "reflect"));
imports.add(createMapping("import", "strings"));
}
}
}
return objs;
}
@Override
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> objs, List<Object> allModels) {
objs = super.postProcessOperationsWithModels(objs, allModels);
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
HashMap<String, CodegenModel> modelMaps = new HashMap<String, CodegenModel>();
HashMap<String, Integer> processedModelMaps = new HashMap<String, Integer>();
for (Object o : allModels) {
HashMap<String, Object> h = (HashMap<String, Object>) o;
CodegenModel m = (CodegenModel) h.get("model");
modelMaps.put(m.classname, m);
}
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation op : operationList) {
for (CodegenParameter p : op.allParams) {
p.vendorExtensions.put("x-go-example", constructExampleCode(p, modelMaps, processedModelMaps));
}
}
processedModelMaps.clear();
for (CodegenOperation operation : operationList) {
for (CodegenParameter cp : operation.allParams) {
cp.vendorExtensions.put("x-go-example", constructExampleCode(cp, modelMaps, processedModelMaps));
}
}
return objs;
}
private String constructExampleCode(CodegenParameter codegenParameter, HashMap<String, CodegenModel> modelMaps, HashMap<String, Integer> processedModelMap) {
if (codegenParameter.isListContainer) { // array
return codegenParameter.dataType + "{" + constructExampleCode(codegenParameter.items, modelMaps, processedModelMap) + "}";
} else if (codegenParameter.isMapContainer) {
return "map[string]string{ \"Key\" = \"Value\" }";
} else if (codegenParameter.isPrimitiveType) { // primitive type
if (codegenParameter.isString) {
if (StringUtils.isEmpty(codegenParameter.example)) {
return "\"" + codegenParameter.example + "\"";
} else {
return "\"" + codegenParameter.paramName + "_example\"";
}
} else if (codegenParameter.isBoolean) { // boolean
if (Boolean.parseBoolean(codegenParameter.example)) {
return "true";
} else {
return "false";
}
} else if (codegenParameter.isUri) { // URL
return "URL(string: \"https://example.com\")!";
} else if (codegenParameter.isDateTime || codegenParameter.isDate) { // datetime or date
return "Get-Date";
} else { // numeric
if (StringUtils.isEmpty(codegenParameter.example)) {
return codegenParameter.example;
} else {
return "987";
}
}
} else { // model
// look up the model
if (modelMaps.containsKey(codegenParameter.dataType)) {
return constructExampleCode(modelMaps.get(codegenParameter.dataType), modelMaps, processedModelMap);
} else {
//LOGGER.error("Error in constructing examples. Failed to look up the model " + codegenParameter.dataType);
return "TODO";
}
}
}
private String constructExampleCode(CodegenProperty codegenProperty, HashMap<String, CodegenModel> modelMaps, HashMap<String, Integer> processedModelMap) {
if (codegenProperty.isListContainer) { // array
return codegenProperty.dataType + "{" + constructExampleCode(codegenProperty.items, modelMaps, processedModelMap) + ")";
} else if (codegenProperty.isMapContainer) { // map
return "map[string]string{ \"Key\" = \"Value\" }";
} else if (codegenProperty.isPrimitiveType) { // primitive type
if (codegenProperty.isString) {
if (StringUtils.isEmpty(codegenProperty.example)) {
return "\"" + codegenProperty.example + "\"";
} else {
return "\"" + codegenProperty.name + "_example\"";
}
} else if (codegenProperty.isBoolean) { // boolean
if (Boolean.parseBoolean(codegenProperty.example)) {
return "true";
} else {
return "false";
}
} else if (codegenProperty.isUri) { // URL
return "\"https://example.com\")!";
} else if (codegenProperty.isDateTime || codegenProperty.isDate) { // datetime or date
return "time.Now()";
} else { // numeric
String example;
if (StringUtils.isEmpty(codegenProperty.example)) {
example = codegenProperty.example;
} else {
example = "123";
}
if (codegenProperty.isLong) {
return "int64(" + example + ")";
} else {
return example;
}
}
} else {
// look up the model
if (modelMaps.containsKey(codegenProperty.dataType)) {
return constructExampleCode(modelMaps.get(codegenProperty.dataType), modelMaps, processedModelMap);
} else {
//LOGGER.error("Error in constructing examples. Failed to look up the model " + codegenProperty.dataType);
return "\"TODO\"";
}
}
}
private String constructExampleCode(CodegenModel codegenModel, HashMap<String, CodegenModel> modelMaps, HashMap<String, Integer> processedModelMap) {
String example;
// break infinite recursion. Return, in case a model is already processed in the current context.
String model = codegenModel.name;
if (processedModelMap.containsKey(model)) {
int count = processedModelMap.get(model);
if (count == 1) {
processedModelMap.put(model, 2);
} else if (count == 2) {
return "";
} else {
throw new RuntimeException("Invalid count when constructing example: " + count);
}
} else {
processedModelMap.put(model, 1);
}
example = "" + goImportAlias + "." + codegenModel.name + "{";
List<String> propertyExamples = new ArrayList<>();
for (CodegenProperty codegenProperty : codegenModel.allVars) {
propertyExamples.add(codegenProperty.name + ": " + constructExampleCode(codegenProperty, modelMaps, processedModelMap));
}
example += StringUtils.join(propertyExamples, ", ");
example += "}";
return example;
}
}

View File

@@ -1,403 +0,0 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* 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.media.Schema;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.*;
import org.openapitools.codegen.meta.GeneratorMetadata;
import org.openapitools.codegen.meta.Stability;
import org.openapitools.codegen.utils.ModelUtils;
import org.openapitools.codegen.utils.ProcessUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import static org.openapitools.codegen.utils.StringUtils.camelize;
public class GoClientExperimentalCodegen extends GoClientCodegen {
private static final Logger LOGGER = LoggerFactory.getLogger(GoClientExperimentalCodegen.class);
protected String goImportAlias = "openapiclient";
protected boolean useOneOfDiscriminatorLookup = false; // use oneOf discriminator's mapping for model lookup
public GoClientExperimentalCodegen() {
super();
outputFolder = "generated-code/go-experimental";
embeddedTemplateDir = templateDir = "go-experimental";
usesOptionals = false;
generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata).stability(Stability.EXPERIMENTAL).build();
cliOptions.add(new CliOption(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP, CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP_DESC).defaultValue("false"));
// option to change how we process + set the data in the 'additionalProperties' keyword.
CliOption disallowAdditionalPropertiesIfNotPresentOpt = CliOption.newBoolean(
CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT,
CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT_DESC).defaultValue(Boolean.TRUE.toString());
Map<String, String> disallowAdditionalPropertiesIfNotPresentOpts = new HashMap<>();
disallowAdditionalPropertiesIfNotPresentOpts.put("false",
"The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.");
disallowAdditionalPropertiesIfNotPresentOpts.put("true",
"when the 'additionalProperties' keyword is not present in a schema, " +
"the value of 'additionalProperties' is automatically set to false, i.e. no additional properties are allowed. " +
"Note: this mode is not compliant with the JSON schema specification. " +
"This is the original openapi-generator behavior.");
disallowAdditionalPropertiesIfNotPresentOpt.setEnum(disallowAdditionalPropertiesIfNotPresentOpts);
cliOptions.add(disallowAdditionalPropertiesIfNotPresentOpt);
this.setDisallowAdditionalPropertiesIfNotPresent(true);
}
/**
* Configures a friendly name for the generator. This will be used by the
* generator to select the library with the -g flag.
*
* @return the friendly name for the generator
*/
@Override
public String getName() {
return "go-experimental";
}
@Override
public String toGetter(String name) {
return "Get" + getterAndSetterCapitalize(name);
}
/**
* Returns human-friendly help for the generator. Provide the consumer with help
* tips, parameters here
*
* @return A string value for the help message
*/
@Override
public String getHelp() {
return "Generates a Go client library (experimental and may subject to breaking changes without further notice).";
}
@Override
public void processOpts() {
this.setLegacyDiscriminatorBehavior(false);
super.processOpts();
supportingFiles.add(new SupportingFile("utils.mustache", "", "utils.go"));
// Generate the 'signing.py' module, but only if the 'HTTP signature' security scheme is specified in the OAS.
Map<String, SecurityScheme> securitySchemeMap = openAPI != null ?
(openAPI.getComponents() != null ? openAPI.getComponents().getSecuritySchemes() : null) : null;
List<CodegenSecurity> authMethods = fromSecurity(securitySchemeMap);
if (ProcessUtils.hasHttpSignatureMethods(authMethods)) {
supportingFiles.add(new SupportingFile("signing.mustache", "", "signing.go"));
}
if (additionalProperties.containsKey("goImportAlias")) {
setGoImportAlias(additionalProperties.get("goImportAlias").toString());
} else {
additionalProperties.put("goImportAlias", goImportAlias);
}
if (additionalProperties.containsKey(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP)) {
setUseOneOfDiscriminatorLookup(convertPropertyToBooleanAndWriteBack(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP));
} else {
additionalProperties.put(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP, useOneOfDiscriminatorLookup);
}
if (additionalProperties.containsKey(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT)) {
this.setDisallowAdditionalPropertiesIfNotPresent(Boolean.valueOf(additionalProperties
.get(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT).toString()));
}
}
public void setUseOneOfDiscriminatorLookup(boolean useOneOfDiscriminatorLookup) {
this.useOneOfDiscriminatorLookup = useOneOfDiscriminatorLookup;
}
public boolean getUseOneOfDiscriminatorLookup() {
return this.useOneOfDiscriminatorLookup;
}
public void setGoImportAlias(String goImportAlias) {
this.goImportAlias = goImportAlias;
}
@Override
public String toModelName(String name) {
// underscoring would also lowercase the whole name, thus losing acronyms which are in capitals
return camelize(toModel(name, false));
}
public String escapeReservedWord(String name) {
if (this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return name + '_';
}
@Override
public String toEnumDefaultValue(String value, String datatype) {
String prefix = "";
if (enumClassPrefix) {
prefix = datatype.toUpperCase(Locale.ROOT) + "_";
}
return prefix + value;
}
@Override
public void updateCodegenPropertyEnum(CodegenProperty var) {
// make sure the inline enums have plain defaults (e.g. string, int, float)
String enumDefault = null;
if (var.isEnum && var.defaultValue != null) {
enumDefault = var.defaultValue;
}
super.updateCodegenPropertyEnum(var);
if (var.isEnum && enumDefault != null) {
var.defaultValue = enumDefault;
}
}
@Override
public String toDefaultValue(Schema p) {
p = ModelUtils.getReferencedSchema(this.openAPI, p);
if (ModelUtils.isStringSchema(p)) {
if (p.getDefault() != null) {
return "\"" + escapeText((String) p.getDefault()) + "\"";
}
return null;
}
return super.toDefaultValue(p);
}
@Override
public CodegenProperty fromProperty(String name, Schema p) {
CodegenProperty prop = super.fromProperty(name, p);
String cc = camelize(prop.name, true);
if (isReservedWord(cc)) {
cc = escapeReservedWord(cc);
}
prop.nameInCamelCase = cc;
return prop;
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
// The superclass determines the list of required golang imports. The actual list of imports
// depends on which types are used, some of which are changed in the code below (but then preserved
// and used through x-go-base-type in templates). So super.postProcessModels
// must be invoked at the beginning of this method.
objs = super.postProcessModels(objs);
List<Map<String, String>> imports = (List<Map<String, String>>) objs.get("imports");
List<Map<String, Object>> models = (List<Map<String, Object>>) objs.get("models");
for (Map<String, Object> m : models) {
Object v = m.get("model");
if (v instanceof CodegenModel) {
CodegenModel model = (CodegenModel) v;
if (model.isEnum) {
continue;
}
for (CodegenProperty param : model.vars) {
param.vendorExtensions.put("x-go-base-type", param.dataType);
if (!param.isNullable || param.isMapContainer || param.isListContainer ||
param.isFreeFormObject || param.isAnyType) {
continue;
}
if (param.isDateTime) {
// Note this could have been done by adding the following line in processOpts(),
// however, we only want to represent the DateTime object as NullableTime if
// it's marked as nullable in the spec.
// typeMapping.put("DateTime", "NullableTime");
param.dataType = "NullableTime";
} else {
param.dataType = "Nullable" + Character.toUpperCase(param.dataType.charAt(0))
+ param.dataType.substring(1);
}
}
// additional import for different cases
// oneOf
if (model.oneOf != null && !model.oneOf.isEmpty()) {
imports.add(createMapping("import", "fmt"));
}
// anyOf
if (model.anyOf != null && !model.anyOf.isEmpty()) {
imports.add(createMapping("import", "fmt"));
}
// additionalProperties: true and parent
if (model.isAdditionalPropertiesTrue && model.parent != null && Boolean.FALSE.equals(model.isMapModel)) {
imports.add(createMapping("import", "reflect"));
imports.add(createMapping("import", "strings"));
}
}
}
return objs;
}
@Override
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> objs, List<Object> allModels) {
objs = super.postProcessOperationsWithModels(objs, allModels);
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
HashMap<String, CodegenModel> modelMaps = new HashMap<String, CodegenModel>();
HashMap<String, Integer> processedModelMaps = new HashMap<String, Integer>();
for (Object o : allModels) {
HashMap<String, Object> h = (HashMap<String, Object>) o;
CodegenModel m = (CodegenModel) h.get("model");
modelMaps.put(m.classname, m);
}
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation op : operationList) {
for (CodegenParameter p : op.allParams) {
p.vendorExtensions.put("x-go-example", constructExampleCode(p, modelMaps, processedModelMaps));
}
}
processedModelMaps.clear();
for (CodegenOperation operation : operationList) {
for (CodegenParameter cp : operation.allParams) {
cp.vendorExtensions.put("x-go-example", constructExampleCode(cp, modelMaps, processedModelMaps));
}
}
return objs;
}
private String constructExampleCode(CodegenParameter codegenParameter, HashMap<String, CodegenModel> modelMaps, HashMap<String, Integer> processedModelMap) {
if (codegenParameter.isListContainer) { // array
return codegenParameter.dataType + "{" + constructExampleCode(codegenParameter.items, modelMaps, processedModelMap) + "}";
} else if (codegenParameter.isMapContainer) {
return "map[string]string{ \"Key\" = \"Value\" }";
} else if (codegenParameter.isPrimitiveType) { // primitive type
if (codegenParameter.isString) {
if (StringUtils.isEmpty(codegenParameter.example)) {
return "\"" + codegenParameter.example + "\"";
} else {
return "\"" + codegenParameter.paramName + "_example\"";
}
} else if (codegenParameter.isBoolean) { // boolean
if (Boolean.parseBoolean(codegenParameter.example)) {
return "true";
} else {
return "false";
}
} else if (codegenParameter.isUri) { // URL
return "URL(string: \"https://example.com\")!";
} else if (codegenParameter.isDateTime || codegenParameter.isDate) { // datetime or date
return "Get-Date";
} else { // numeric
if (StringUtils.isEmpty(codegenParameter.example)) {
return codegenParameter.example;
} else {
return "987";
}
}
} else { // model
// look up the model
if (modelMaps.containsKey(codegenParameter.dataType)) {
return constructExampleCode(modelMaps.get(codegenParameter.dataType), modelMaps, processedModelMap);
} else {
//LOGGER.error("Error in constructing examples. Failed to look up the model " + codegenParameter.dataType);
return "TODO";
}
}
}
private String constructExampleCode(CodegenProperty codegenProperty, HashMap<String, CodegenModel> modelMaps, HashMap<String, Integer> processedModelMap) {
if (codegenProperty.isListContainer) { // array
return codegenProperty.dataType + "{" + constructExampleCode(codegenProperty.items, modelMaps, processedModelMap) + ")";
} else if (codegenProperty.isMapContainer) { // map
return "map[string]string{ \"Key\" = \"Value\" }";
} else if (codegenProperty.isPrimitiveType) { // primitive type
if (codegenProperty.isString) {
if (StringUtils.isEmpty(codegenProperty.example)) {
return "\"" + codegenProperty.example + "\"";
} else {
return "\"" + codegenProperty.name + "_example\"";
}
} else if (codegenProperty.isBoolean) { // boolean
if (Boolean.parseBoolean(codegenProperty.example)) {
return "true";
} else {
return "false";
}
} else if (codegenProperty.isUri) { // URL
return "\"https://example.com\")!";
} else if (codegenProperty.isDateTime || codegenProperty.isDate) { // datetime or date
return "time.Now()";
} else { // numeric
String example;
if (StringUtils.isEmpty(codegenProperty.example)) {
example = codegenProperty.example;
} else {
example = "123";
}
if (codegenProperty.isLong) {
return "int64(" + example + ")";
} else {
return example;
}
}
} else {
// look up the model
if (modelMaps.containsKey(codegenProperty.dataType)) {
return constructExampleCode(modelMaps.get(codegenProperty.dataType), modelMaps, processedModelMap);
} else {
//LOGGER.error("Error in constructing examples. Failed to look up the model " + codegenProperty.dataType);
return "\"TODO\"";
}
}
}
private String constructExampleCode(CodegenModel codegenModel, HashMap<String, CodegenModel> modelMaps, HashMap<String, Integer> processedModelMap) {
String example;
// break infinite recursion. Return, in case a model is already processed in the current context.
String model = codegenModel.name;
if (processedModelMap.containsKey(model)) {
int count = processedModelMap.get(model);
if (count == 1) {
processedModelMap.put(model, 2);
} else if (count == 2) {
return "";
} else {
throw new RuntimeException("Invalid count when constructing example: " + count);
}
} else {
processedModelMap.put(model, 1);
}
example = "" + goImportAlias + "." + codegenModel.name + "{";
List<String> propertyExamples = new ArrayList<>();
for (CodegenProperty codegenProperty : codegenModel.allVars) {
propertyExamples.add(codegenProperty.name + ": " + constructExampleCode(codegenProperty, modelMaps, processedModelMap));
}
example += StringUtils.join(propertyExamples, ", ");
example += "}";
return example;
}
}

View File

@@ -0,0 +1,255 @@
/*
* 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 org.openapitools.codegen.CliOption;
import org.openapitools.codegen.CodegenConstants;
import org.openapitools.codegen.CodegenType;
import org.openapitools.codegen.SupportingFile;
import org.openapitools.codegen.meta.features.*;
import org.openapitools.codegen.meta.GeneratorMetadata;
import org.openapitools.codegen.meta.Stability;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.EnumSet;
public class GoDeprecatedClientCodegen extends AbstractGoCodegen {
private static final Logger LOGGER = LoggerFactory.getLogger(GoDeprecatedClientCodegen.class);
protected String packageVersion = "1.0.0";
protected String apiDocPath = "docs/";
protected String modelDocPath = "docs/";
protected boolean isGoSubmodule = false;
public static final String WITH_GO_CODEGEN_COMMENT = "withGoCodegenComment";
public static final String WITH_XML = "withXml";
public static final String STRUCT_PREFIX = "structPrefix";
public static final String WITH_AWSV4_SIGNATURE = "withAWSV4Signature";
public static final String GENERATE_INTERFACES = "generateInterfaces";
public GoDeprecatedClientCodegen() {
super();
generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata).stability(Stability.DEPRECATED).build();
modifyFeatureSet(features -> features
.includeDocumentationFeatures(DocumentationFeature.Readme)
.wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML))
.securityFeatures(EnumSet.of(
SecurityFeature.BasicAuth,
SecurityFeature.ApiKey,
SecurityFeature.OAuth2_Implicit
))
.includeGlobalFeatures(
GlobalFeature.ParameterizedServer
)
.excludeGlobalFeatures(
GlobalFeature.XMLStructureDefinitions,
GlobalFeature.Callbacks,
GlobalFeature.LinkObjects,
GlobalFeature.ParameterStyling
)
.excludeSchemaSupportFeatures(
SchemaSupportFeature.Polymorphism
)
.includeParameterFeatures(
ParameterFeature.Cookie
)
.includeClientModificationFeatures(
ClientModificationFeature.BasePath,
ClientModificationFeature.UserAgent
)
);
outputFolder = "generated-code/go-deprecated";
modelTemplateFiles.put("model.mustache", ".go");
apiTemplateFiles.put("api.mustache", ".go");
modelDocTemplateFiles.put("model_doc.mustache", ".md");
apiDocTemplateFiles.put("api_doc.mustache", ".md");
embeddedTemplateDir = templateDir = "go-deprecated";
// default HIDE_GENERATION_TIMESTAMP to true
hideGenerationTimestamp = Boolean.TRUE;
cliOptions.add(CliOption.newBoolean(CodegenConstants.IS_GO_SUBMODULE, CodegenConstants.IS_GO_SUBMODULE_DESC));
cliOptions.add(CliOption.newBoolean(WITH_GO_CODEGEN_COMMENT, "whether to include Go codegen comment to disable Go Lint and collapse by default in GitHub PRs and diffs"));
cliOptions.add(CliOption.newBoolean(WITH_XML, "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)"));
cliOptions.add(CliOption.newBoolean(CodegenConstants.ENUM_CLASS_PREFIX, CodegenConstants.ENUM_CLASS_PREFIX_DESC));
cliOptions.add(CliOption.newBoolean(STRUCT_PREFIX, "whether to prefix struct with the class name. e.g. DeletePetOpts => PetApiDeletePetOpts"));
cliOptions.add(CliOption.newBoolean(WITH_AWSV4_SIGNATURE, "whether to include AWS v4 signature support"));
cliOptions.add(CliOption.newBoolean(GENERATE_INTERFACES, "Generate interfaces for api classes"));
// option to change the order of form/body parameter
cliOptions.add(CliOption.newBoolean(
CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS,
CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS_DESC)
.defaultValue(Boolean.FALSE.toString()));
}
@Override
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) {
setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME));
} else {
setPackageName("openapi");
}
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) {
setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION));
} else {
setPackageVersion("1.0.0");
}
additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName);
additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion);
additionalProperties.put("apiDocPath", apiDocPath);
additionalProperties.put("modelDocPath", modelDocPath);
modelPackage = packageName;
apiPackage = packageName;
supportingFiles.add(new SupportingFile("openapi.mustache", "api", "openapi.yaml"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
supportingFiles.add(new SupportingFile("configuration.mustache", "", "configuration.go"));
supportingFiles.add(new SupportingFile("client.mustache", "", "client.go"));
supportingFiles.add(new SupportingFile("response.mustache", "", "response.go"));
supportingFiles.add(new SupportingFile("go.mod.mustache", "", "go.mod"));
supportingFiles.add(new SupportingFile("go.sum", "", "go.sum"));
supportingFiles.add(new SupportingFile(".travis.yml", "", ".travis.yml"));
if (additionalProperties.containsKey(WITH_GO_CODEGEN_COMMENT)) {
setWithGoCodegenComment(Boolean.parseBoolean(additionalProperties.get(WITH_GO_CODEGEN_COMMENT).toString()));
additionalProperties.put(WITH_GO_CODEGEN_COMMENT, withGoCodegenComment);
}
if (additionalProperties.containsKey(WITH_AWSV4_SIGNATURE)) {
setWithAWSV4Signature(Boolean.parseBoolean(additionalProperties.get(WITH_AWSV4_SIGNATURE).toString()));
additionalProperties.put(WITH_AWSV4_SIGNATURE, withAWSV4Signature);
}
if (additionalProperties.containsKey(WITH_XML)) {
setWithXml(Boolean.parseBoolean(additionalProperties.get(WITH_XML).toString()));
additionalProperties.put(WITH_XML, withXml);
}
if (additionalProperties.containsKey(CodegenConstants.ENUM_CLASS_PREFIX)) {
setEnumClassPrefix(Boolean.parseBoolean(additionalProperties.get(CodegenConstants.ENUM_CLASS_PREFIX).toString()));
additionalProperties.put(CodegenConstants.ENUM_CLASS_PREFIX, enumClassPrefix);
}
if (additionalProperties.containsKey(CodegenConstants.IS_GO_SUBMODULE)) {
setIsGoSubmodule(Boolean.parseBoolean(additionalProperties.get(CodegenConstants.IS_GO_SUBMODULE).toString()));
additionalProperties.put(CodegenConstants.IS_GO_SUBMODULE, isGoSubmodule);
}
if (additionalProperties.containsKey(STRUCT_PREFIX)) {
setStructPrefix(Boolean.parseBoolean(additionalProperties.get(STRUCT_PREFIX).toString()));
additionalProperties.put(STRUCT_PREFIX, structPrefix);
}
if (additionalProperties.containsKey(GENERATE_INTERFACES)) {
setGenerateInterfaces(Boolean.parseBoolean(additionalProperties.get(GENERATE_INTERFACES).toString()));
additionalProperties.put(GENERATE_INTERFACES, generateInterfaces);
}
}
/**
* Configures the type of generator.
*
* @return the CodegenType for this generator
* @see org.openapitools.codegen.CodegenType
*/
@Override
public CodegenType getTag() {
return CodegenType.CLIENT;
}
/**
* Configures a friendly name for the generator. This will be used by the generator
* to select the library with the -g flag.
*
* @return the friendly name for the generator
*/
@Override
public String getName() {
return "go-deprecated";
}
/**
* Returns human-friendly help for the generator. Provide the consumer with help
* tips, parameters here
*
* @return A string value for the help message
*/
@Override
public String getHelp() {
return "Generates a Go client library (beta). NOTE: this generator has been deprecated. Please use `go` client generator instead.";
}
/**
* Location to write api files. You can use the apiPackage() as defined when the class is
* instantiated
*/
@Override
public String apiFileFolder() {
return outputFolder + File.separator;
}
@Override
public String modelFileFolder() {
return outputFolder + File.separator;
}
@Override
public String apiDocFileFolder() {
return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar);
}
@Override
public String modelDocFileFolder() {
return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar);
}
@Override
public String toModelDocFilename(String name) {
return toModelName(name);
}
@Override
public String toApiDocFilename(String name) {
return toApiName(name);
}
public void setPackageVersion(String packageVersion) {
this.packageVersion = packageVersion;
}
public void setIsGoSubmodule(boolean isGoSubmodule) {
this.isGoSubmodule = isGoSubmodule;
}
}

View File

@@ -325,13 +325,16 @@ public class JavaClientCodegen extends AbstractJavaCodegen
supportingFiles.add(new SupportingFile("ServerVariable.mustache", invokerFolder, "ServerVariable.java"));
supportingFiles.add(new SupportingFile("openapi.mustache", "api", "openapi.yaml"));
if (dateLibrary.equals("java8") && (isLibrary(WEBCLIENT) || isLibrary(VERTX) || isLibrary(RESTTEMPLATE) || isLibrary(RESTEASY) || isLibrary(MICROPROFILE) || isLibrary(JERSEY2))) {
supportingFiles.add(new SupportingFile("JavaTimeFormatter.mustache", invokerFolder, "JavaTimeFormatter.java"));
}
if (!(RESTTEMPLATE.equals(getLibrary()) || REST_ASSURED.equals(getLibrary()) || NATIVE.equals(getLibrary()) || MICROPROFILE.equals(getLibrary()))) {
if (!(RESTTEMPLATE.equals(getLibrary()) || isLibrary(REST_ASSURED) || isLibrary(NATIVE) || isLibrary(MICROPROFILE))) {
supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java"));
}
// google-api-client doesn't use the OpenAPI auth, because it uses Google Credential directly (HttpRequestInitializer)
if (!(GOOGLE_API_CLIENT.equals(getLibrary()) || REST_ASSURED.equals(getLibrary()) || NATIVE.equals(getLibrary()) || MICROPROFILE.equals(getLibrary()))) {
if (!(isLibrary(GOOGLE_API_CLIENT) || isLibrary(REST_ASSURED) || isLibrary(NATIVE) || isLibrary(MICROPROFILE))) {
supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java"));
supportingFiles.add(new SupportingFile("auth/HttpBearerAuth.mustache", authFolder, "HttpBearerAuth.java"));
supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java"));
@@ -779,11 +782,14 @@ public class JavaClientCodegen extends AbstractJavaCodegen
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
boolean addImports = false;
for (CodegenProperty var : cm.vars) {
boolean isOptionalNullable = Boolean.FALSE.equals(var.required) && Boolean.TRUE.equals(var.isNullable);
// only add JsonNullable and related imports to optional and nullable values
addImports |= isOptionalNullable;
var.getVendorExtensions().put("x-is-jackson-optional-nullable", isOptionalNullable);
if (this.openApiNullable) {
boolean isOptionalNullable = Boolean.FALSE.equals(var.required) && Boolean.TRUE.equals(var.isNullable);
// only add JsonNullable and related imports to optional and nullable values
addImports |= isOptionalNullable;
var.getVendorExtensions().put("x-is-jackson-optional-nullable", isOptionalNullable);
}
if (Boolean.TRUE.equals(var.getVendorExtensions().get("x-enum-as-string"))) {
// treat enum string as just string
@@ -808,6 +814,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
importsHashSet.put("import", "java.util.HashSet");
imports.add(importsHashSet);
}
}
if (addImports) {
@@ -824,34 +831,34 @@ public class JavaClientCodegen extends AbstractJavaCodegen
}
}
}
}
// add implements for serializable/parcelable to all models
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
// add implements for serializable/parcelable to all models
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
cm.getVendorExtensions().putIfAbsent("x-implements", new ArrayList<String>());
if (JERSEY2.equals(getLibrary())) {
cm.getVendorExtensions().put("x-implements", new ArrayList<String>());
cm.getVendorExtensions().putIfAbsent("x-implements", new ArrayList<String>());
if (JERSEY2.equals(getLibrary())) {
cm.getVendorExtensions().put("x-implements", new ArrayList<String>());
if (cm.oneOf != null && !cm.oneOf.isEmpty() && cm.oneOf.contains("ModelNull")) {
// if oneOf contains "null" type
cm.isNullable = true;
cm.oneOf.remove("ModelNull");
if (cm.oneOf != null && !cm.oneOf.isEmpty() && cm.oneOf.contains("ModelNull")) {
// if oneOf contains "null" type
cm.isNullable = true;
cm.oneOf.remove("ModelNull");
}
if (cm.anyOf != null && !cm.anyOf.isEmpty() && cm.anyOf.contains("ModelNull")) {
// if anyOf contains "null" type
cm.isNullable = true;
cm.anyOf.remove("ModelNull");
}
}
if (cm.anyOf != null && !cm.anyOf.isEmpty() && cm.anyOf.contains("ModelNull")) {
// if anyOf contains "null" type
cm.isNullable = true;
cm.anyOf.remove("ModelNull");
if (this.parcelableModel) {
((ArrayList<String>) cm.getVendorExtensions().get("x-implements")).add("Parcelable");
}
if (this.serializableModel) {
((ArrayList<String>) cm.getVendorExtensions().get("x-implements")).add("Serializable");
}
}
if (this.parcelableModel) {
((ArrayList<String>) cm.getVendorExtensions().get("x-implements")).add("Parcelable");
}
if (this.serializableModel) {
((ArrayList<String>) cm.getVendorExtensions().get("x-implements")).add("Serializable");
}
}
@@ -951,8 +958,6 @@ public class JavaClientCodegen extends AbstractJavaCodegen
setSerializationLibrary(serializationLibrary);
}
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
generateYAMLSpecFile(objs);

View File

@@ -129,35 +129,35 @@ public class PhpLumenServerCodegen extends AbstractPhpCodegen {
supportingFiles.add(new SupportingFile("storage_logs_gitignore", srcBasePath + File.separator + "storage" + File.separator + "framework" + File.separator + "views", ".gitignore"));
supportingFiles.add(new SupportingFile("storage_framework_cache_gitignore", srcBasePath + File.separator + "storage" + File.separator + "framework" + File.separator + "cache", ".gitignore"));
supportingFiles.add(new SupportingFile("storage_logs_gitignore", srcBasePath + File.separator + "storage" + File.separator + "framework" + File.separator + "cache" + File.separator + "data", ".gitignore"));
supportingFiles.add(new SupportingFile("artisan", srcBasePath, "artisan"));
supportingFiles.add(new SupportingFile("artisan.mustache", srcBasePath, "artisan"));
supportingFiles.add(new SupportingFile("composer.mustache", srcBasePath, "composer.json"));
supportingFiles.add(new SupportingFile("readme.md", srcBasePath, "readme.md"));
supportingFiles.add(new SupportingFile("User.php", srcBasePath + File.separator + "app", "User.php"));
supportingFiles.add(new SupportingFile("Kernel.php", srcBasePath + File.separator + "app" + File.separator + "Console", "Kernel.php"));
supportingFiles.add(new SupportingFile("User.php.mustache", srcBasePath + File.separator + "app", "User.php"));
supportingFiles.add(new SupportingFile("Kernel.php.mustache", srcBasePath + File.separator + "app" + File.separator + "Console", "Kernel.php"));
supportingFiles.add(new SupportingFile(".gitkeep", srcBasePath + File.separator + "app" + File.separator + "Console" + File.separator + "Commands", ".gitkeep"));
supportingFiles.add(new SupportingFile("Event.php", srcBasePath + File.separator + "app" + File.separator + "Events", "Event.php"));
supportingFiles.add(new SupportingFile("ExampleEvent.php", srcBasePath + File.separator + "app" + File.separator + "Events", "ExampleEvent.php"));
supportingFiles.add(new SupportingFile("Handler.php", srcBasePath + File.separator + "app" + File.separator + "Exceptions", "Handler.php"));
supportingFiles.add(new SupportingFile("Controller.php", srcBasePath + File.separator + "app" + File.separator + "Http" + File.separator + "Controllers" + File.separator, "Controller.php"));
supportingFiles.add(new SupportingFile("ExampleController.php", srcBasePath + File.separator + "app" + File.separator + "Http" + File.separator + "Controllers" + File.separator, "ExampleController.php"));
supportingFiles.add(new SupportingFile("Authenticate.php", srcBasePath + File.separator + "app" + File.separator + "Http" + File.separator + "Middleware" + File.separator, "Authenticate.php"));
supportingFiles.add(new SupportingFile("ExampleMiddleware.php", srcBasePath + File.separator + "app" + File.separator + "Http" + File.separator + "Middleware" + File.separator, "ExampleMiddleware.php"));
supportingFiles.add(new SupportingFile("ExampleJob.php", srcBasePath + File.separator + "app" + File.separator + "Jobs", "ExampleJob.php"));
supportingFiles.add(new SupportingFile("Job.php", srcBasePath + File.separator + "app" + File.separator + "Jobs", "Job.php"));
supportingFiles.add(new SupportingFile("ExampleListener.php", srcBasePath + File.separator + "app" + File.separator + "Listeners", "ExampleListener.php"));
supportingFiles.add(new SupportingFile("AppServiceProvider.php", srcBasePath + File.separator + "app" + File.separator + "Providers", "AppServiceProvider.php"));
supportingFiles.add(new SupportingFile("AuthServiceProvider.php", srcBasePath + File.separator + "app" + File.separator + "Providers", "AuthServiceProvider.php"));
supportingFiles.add(new SupportingFile("EventServiceProvider.php", srcBasePath + File.separator + "app" + File.separator + "Providers", "EventServiceProvider.php"));
supportingFiles.add(new SupportingFile("app.php", srcBasePath + File.separator + "bootstrap", "app.php"));
supportingFiles.add(new SupportingFile("ModelFactory.php", srcBasePath + File.separator + "database" + File.separator + "factories", "ModelFactory.php"));
supportingFiles.add(new SupportingFile("Event.php.mustache", srcBasePath + File.separator + "app" + File.separator + "Events", "Event.php"));
supportingFiles.add(new SupportingFile("ExampleEvent.php.mustache", srcBasePath + File.separator + "app" + File.separator + "Events", "ExampleEvent.php"));
supportingFiles.add(new SupportingFile("Handler.php.mustache", srcBasePath + File.separator + "app" + File.separator + "Exceptions", "Handler.php"));
supportingFiles.add(new SupportingFile("Controller.php.mustache", srcBasePath + File.separator + "app" + File.separator + "Http" + File.separator + "Controllers" + File.separator, "Controller.php"));
supportingFiles.add(new SupportingFile("ExampleController.php.mustache", srcBasePath + File.separator + "app" + File.separator + "Http" + File.separator + "Controllers" + File.separator, "ExampleController.php"));
supportingFiles.add(new SupportingFile("Authenticate.php.mustache", srcBasePath + File.separator + "app" + File.separator + "Http" + File.separator + "Middleware" + File.separator, "Authenticate.php"));
supportingFiles.add(new SupportingFile("ExampleMiddleware.php.mustache", srcBasePath + File.separator + "app" + File.separator + "Http" + File.separator + "Middleware" + File.separator, "ExampleMiddleware.php"));
supportingFiles.add(new SupportingFile("ExampleJob.php.mustache", srcBasePath + File.separator + "app" + File.separator + "Jobs", "ExampleJob.php"));
supportingFiles.add(new SupportingFile("Job.php.mustache", srcBasePath + File.separator + "app" + File.separator + "Jobs", "Job.php"));
supportingFiles.add(new SupportingFile("ExampleListener.php.mustache", srcBasePath + File.separator + "app" + File.separator + "Listeners", "ExampleListener.php"));
supportingFiles.add(new SupportingFile("AppServiceProvider.php.mustache", srcBasePath + File.separator + "app" + File.separator + "Providers", "AppServiceProvider.php"));
supportingFiles.add(new SupportingFile("AuthServiceProvider.php.mustache", srcBasePath + File.separator + "app" + File.separator + "Providers", "AuthServiceProvider.php"));
supportingFiles.add(new SupportingFile("EventServiceProvider.php.mustache", srcBasePath + File.separator + "app" + File.separator + "Providers", "EventServiceProvider.php"));
supportingFiles.add(new SupportingFile("app.php.mustache", srcBasePath + File.separator + "bootstrap", "app.php"));
supportingFiles.add(new SupportingFile("ModelFactory.php.mustache", srcBasePath + File.separator + "database" + File.separator + "factories", "ModelFactory.php"));
supportingFiles.add(new SupportingFile(".gitkeep", srcBasePath + File.separator + "database" + File.separator + "migrations", ".gitkeep"));
supportingFiles.add(new SupportingFile("DatabaseSeeder.php", srcBasePath + File.separator + "database" + File.separator + "seeds", "DatabaseSeeder.php"));
supportingFiles.add(new SupportingFile("DatabaseSeeder.php.mustache", srcBasePath + File.separator + "database" + File.separator + "seeds", "DatabaseSeeder.php"));
supportingFiles.add(new SupportingFile(".htaccess", srcBasePath + File.separator + "public", ".htaccess"));
supportingFiles.add(new SupportingFile("index.php", srcBasePath + File.separator + "public", "index.php"));
supportingFiles.add(new SupportingFile("index.php.mustache", srcBasePath + File.separator + "public", "index.php"));
supportingFiles.add(new SupportingFile(".gitkeep", srcBasePath + File.separator + "resources" + File.separator + "views", ".gitkeep"));
supportingFiles.add(new SupportingFile("routes.mustache", srcBasePath + File.separator + "routes", "web.php"));
supportingFiles.add(new SupportingFile("ExampleTest.php", srcBasePath + File.separator + "tests", "ExampleTest.php"));
supportingFiles.add(new SupportingFile("TestCase.php", srcBasePath + File.separator + "tests", "TestCase.php"));
supportingFiles.add(new SupportingFile("ExampleTest.php.mustache", srcBasePath + File.separator + "tests", "ExampleTest.php"));
supportingFiles.add(new SupportingFile("TestCase.php.mustache", srcBasePath + File.separator + "tests", "TestCase.php"));
supportingFiles.add(new SupportingFile("editorconfig", srcBasePath, ".editorconfig"));
supportingFiles.add(new SupportingFile("styleci", srcBasePath, ".styleci.yml"));
supportingFiles.add(new SupportingFile("phpunit.xml", srcBasePath, "phpunit.xml"));

View File

@@ -236,7 +236,8 @@ public class PythonBluePlanetServerCodegen extends AbstractPythonConnexionServer
@Override
public String modelDocFileFolder() {
return (outputFolder + File.separator + modelDocPath).replace('.', File.separatorChar);
// character replaces should _only_ occur on paths we define. Don't replace on outputFolder (which is supplied by the user and should always be considered correct)
return outputFolder + File.separator + modelDocPath.replace('.', File.separatorChar);
}
@Override

View File

@@ -186,7 +186,7 @@ public class SpringCodegen extends AbstractJavaCodegen
CliOption option = cliOptions.stream().filter(o -> JAVA_8.equals(o.getOpt())).findFirst()
.orElseThrow(() -> new RuntimeException("Missing java8 option"));
Map<String, String> java8ModeOptions = option.getEnum();
java8ModeOptions.put("true", "Use Java 8 classes such as Base64. Use java8 default interface when a responseWrapper is used");
java8ModeOptions.put("true", "Use Java 8 classes such as Base64. Use java8 default interface when a responseWrapper is used. IMPORTANT: This option has been deprecated as Java 8 is the default.");
}
@Override
@@ -217,9 +217,9 @@ public class SpringCodegen extends AbstractJavaCodegen
// Process java8 option before common java ones to change the default dateLibrary to java8.
LOGGER.info("----------------------------------");
if (additionalProperties.containsKey(JAVA_8)) {
LOGGER.info("has JAVA8");
this.setJava8(Boolean.valueOf(additionalProperties.get(JAVA_8).toString()));
additionalProperties.put(JAVA_8, java8);
LOGGER.warn("java8 option has been deprecated as it's set to true by default (JDK7 support has been deprecated)");
}
if (this.java8 && !additionalProperties.containsKey(DATE_LIBRARY)) {
setDateLibrary("java8");

View File

@@ -35,13 +35,17 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Arrays;
import java.util.Locale;
import java.util.Map;
public class HandlebarsEngineAdapter extends AbstractTemplatingEngineAdapter {
static Logger LOGGER = LoggerFactory.getLogger(HandlebarsEngineAdapter.class);
static final Logger LOGGER = LoggerFactory.getLogger(HandlebarsEngineAdapter.class);
private final String[] extensions = new String[]{"handlebars", "hbs"};
// We use this as a simple lookup for valid file name extensions. This adapter will inspect .mustache (built-in) and infer the relevant handlebars filename
private final String[] canCompileFromExtensions = new String[]{".handlebars",".hbs",".mustache"};
/**
* Provides an identifier used to load the adapter. This could be a name, uuid, or any other string.
*
@@ -71,7 +75,7 @@ public class HandlebarsEngineAdapter extends AbstractTemplatingEngineAdapter {
Handlebars handlebars = new Handlebars(loader);
handlebars.registerHelperMissing((obj, options) -> {
LOGGER.warn(String.format(Locale.ROOT, "Unregistered helper name '%s', processing template:\n%s", options.helperName, options.fn.text()));
LOGGER.warn(String.format(Locale.ROOT, "Unregistered helper name '%s', processing template:%n%s", options.helperName, options.fn.text()));
return "";
});
handlebars.registerHelper("json", Jackson2Helper.INSTANCE);
@@ -82,6 +86,7 @@ public class HandlebarsEngineAdapter extends AbstractTemplatingEngineAdapter {
return tmpl.apply(context);
}
@SuppressWarnings({"java:S108"})
public TemplateSource findTemplate(TemplatingExecutor generator, String templateFile) {
String[] possibilities = getModifiedFileLocation(templateFile);
for (String file : possibilities) {
@@ -104,5 +109,17 @@ public class HandlebarsEngineAdapter extends AbstractTemplatingEngineAdapter {
public String[] getFileExtensions() {
return extensions;
}
/**
* Determine if the adapter handles compilation of the file
*
* @param filename The template filename
* @return True if the file should be compiled by this adapter, else false.
*/
@Override
public boolean handlesFile(String filename) {
// disallow any extension-only files like ".hbs" or ".mustache", and only consider a file compilable if it's handlebars or mustache (from which we later infer the handlebars filename)
return Arrays.stream(canCompileFromExtensions).anyMatch(suffix -> !suffix.equalsIgnoreCase(filename) && filename.endsWith(suffix));
}
}

View File

@@ -39,7 +39,7 @@ public class MustacheEngineAdapter implements TemplatingEngineAdapter {
return "mustache";
}
public String[] extensions = new String[]{"mustache"};
private final String[] extensions = new String[]{"mustache"};
Mustache.Compiler compiler = Mustache.compiler();
/**
@@ -61,6 +61,7 @@ public class MustacheEngineAdapter implements TemplatingEngineAdapter {
return tmpl.execute(bundle);
}
@SuppressWarnings({"java:S108"}) // catch-all is expected, and is later thrown
public Reader findTemplate(TemplatingExecutor generator, String name) {
for (String extension : extensions) {
try {
@@ -69,12 +70,6 @@ public class MustacheEngineAdapter implements TemplatingEngineAdapter {
}
}
// support files without targeted extension (e.g. .gitignore, README.md), etc.
try {
return new StringReader(generator.getFullTemplateContents(name));
} catch (Exception ignored) {
}
throw new TemplateNotFoundException(name);
}

View File

@@ -12,6 +12,7 @@ import com.fasterxml.jackson.datatype.joda.JodaModule;
{{/joda}}
{{#java8}}
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import java.time.OffsetDateTime;
{{/java8}}
{{#threetenbp}}
import com.fasterxml.jackson.datatype.threetenbp.ThreeTenModule;
@@ -67,7 +68,7 @@ import {{invokerPackage}}.auth.OAuth;
{{/hasOAuthMethods}}
{{>generatedAnnotation}}
public class ApiClient {
public class ApiClient{{#java8}} extends JavaTimeFormatter{{/java8}} {
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private Map<String, String> defaultCookieMap = new HashMap<String, String>();
private String basePath = "{{{basePath}}}";
@@ -499,7 +500,9 @@ public class ApiClient {
return "";
} else if (param instanceof Date) {
return formatDate((Date) param);
} else if (param instanceof Collection) {
} {{#java8}}else if (param instanceof OffsetDateTime) {
return formatOffsetDateTime((OffsetDateTime) param);
} {{/java8}}else if (param instanceof Collection) {
StringBuilder b = new StringBuilder();
for(Object o : (Collection<?>)param) {
if(b.length() > 0) {

View File

@@ -0,0 +1,53 @@
{{>licenseInfo}}
package {{invokerPackage}};
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
/**
* Class that add parsing/formatting support for Java 8+ {@code OffsetDateTime} class.
* It's generated for java clients when {@code AbstractJavaCodegen#dateLibrary} specified as {@code java8}.
*/
{{>generatedAnnotation}}
public class JavaTimeFormatter {
private DateTimeFormatter offsetDateTimeFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
/**
* Get the date format used to parse/format {@code OffsetDateTime} parameters.
* @return DateTimeFormatter
*/
public DateTimeFormatter getOffsetDateTimeFormatter() {
return offsetDateTimeFormatter;
}
/**
* Set the date format used to parse/format {@code OffsetDateTime} parameters.
* @param offsetDateTimeFormatter {@code DateTimeFormatter}
*/
public void setOffsetDateTimeFormatter(DateTimeFormatter offsetDateTimeFormatter) {
this.offsetDateTimeFormatter = offsetDateTimeFormatter;
}
/**
* Parse the given string into {@code OffsetDateTime} object.
* @param str String
* @return {@code OffsetDateTime}
*/
public OffsetDateTime parseOffsetDateTime(String str) {
try {
return OffsetDateTime.parse(str, offsetDateTimeFormatter);
} catch (DateTimeParseException e) {
throw new RuntimeException(e);
}
}
/**
* Format the given {@code OffsetDateTime} object into string.
* @param offsetDateTime {@code OffsetDateTime}
* @return {@code OffsetDateTime} in string format
*/
public String formatOffsetDateTime(OffsetDateTime offsetDateTime) {
return offsetDateTimeFormatter.format(offsetDateTime);
}
}

View File

@@ -138,7 +138,9 @@ ext {
swagger_annotations_version = "1.5.22"
jackson_version = "2.10.3"
jackson_databind_version = "2.10.4"
{{#openApiNullable}}
jackson_databind_nullable_version = "0.2.1"
{{/openApiNullable}}
{{#threetenbp}}
jackson_threetenbp_version = "2.9.10"
{{/threetenbp}}
@@ -156,7 +158,9 @@ dependencies {
compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version"
compile "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:$jackson_version"
{{#openApiNullable}}
compile "org.openapitools:jackson-databind-nullable:$jackson_databind_nullable_version"
{{/openApiNullable}}
{{#joda}}
compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version"
{{/joda}}

View File

@@ -15,7 +15,9 @@ import org.threeten.bp.*;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
{{#openApiNullable}}
import org.openapitools.jackson.nullable.JsonNullableModule;
{{/openApiNullable}}
{{#joda}}
import com.fasterxml.jackson.datatype.joda.JodaModule;
{{/joda}}
@@ -181,8 +183,10 @@ public class ApiClient {
module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME);
objectMapper.registerModule(module);
{{/threetenbp}}
{{#openApiNullable}}
JsonNullableModule jnm = new JsonNullableModule();
objectMapper.registerModule(jnm);
{{/openApiNullable}}
return objectMapper;
}

View File

@@ -122,7 +122,9 @@ ext {
swagger_annotations_version = "1.5.24"
jackson_version = "2.10.3"
jackson_databind_version = "2.10.3"
{{#openApiNullable}}
jackson_databind_nullable_version = "0.2.1"
{{/openApiNullable}}
{{#threetenbp}}
jackson_threetenbp_version = "2.9.10"
{{/threetenbp}}
@@ -142,7 +144,9 @@ dependencies {
compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version"
{{#openApiNullable}}
compile "org.openapitools:jackson-databind-nullable:$jackson_databind_nullable_version"
{{/openApiNullable}}
{{#joda}}
compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version"
{{/joda}}

View File

@@ -274,11 +274,13 @@
<artifactId>jackson-databind</artifactId>
<version>${jackson-databind-version}</version>
</dependency>
{{#openApiNullable}}
<dependency>
<groupId>org.openapitools</groupId>
<artifactId>jackson-databind-nullable</artifactId>
<version>${jackson-databind-nullable-version}</version>
</dependency>
{{/openApiNullable}}
{{#withXml}}
<!-- XML Support -->
@@ -351,7 +353,9 @@
<feign-version>10.11</feign-version>
<feign-form-version>3.8.0</feign-form-version>
<jackson-version>2.10.3</jackson-version>
{{#openApiNullable}}
<jackson-databind-nullable-version>0.2.1</jackson-databind-nullable-version>
{{/openApiNullable}}
<jackson-databind-version>2.10.3</jackson-databind-version>
{{#threetenbp}}
<jackson-threetenbp-version>2.9.10</jackson-threetenbp-version>

View File

@@ -4,7 +4,9 @@ import {{apiPackage}}.*;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
{{#openApiNullable}}
import org.openapitools.jackson.nullable.JsonNullableModule;
{{/openApiNullable}}
{{#joda}}
import com.fasterxml.jackson.datatype.joda.JodaModule;
{{/joda}}
@@ -54,8 +56,10 @@ public class ApiClient {
module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME);
objectMapper.registerModule(module);
{{/threetenbp}}
{{#openApiNullable}}
JsonNullableModule jnm = new JsonNullableModule();
objectMapper.registerModule(jnm);
{{/openApiNullable}}
return objectMapper;
}

View File

@@ -122,7 +122,9 @@ ext {
swagger_annotations_version = "1.5.22"
jackson_version = "2.10.1"
jackson_databind_version = "2.10.4"
{{#openApiNullable}}
jackson_databind_nullable_version = "0.2.1"
{{/openApiNullable}}
google_api_client_version = "1.23.0"
jersey_common_version = "2.25.1"
jodatime_version = "2.9.9"
@@ -141,7 +143,9 @@ dependencies {
compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version"
compile "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:$jackson_version"
{{#openApiNullable}}
compile "org.openapitools:jackson-databind-nullable:$jackson_databind_nullable_version"
{{/openApiNullable}}
{{#java8}}
compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version"
{{/java8}}

View File

@@ -267,11 +267,13 @@
<artifactId>jackson-databind</artifactId>
<version>${jackson-version}</version>
</dependency>
{{#openApiNullable}}
<dependency>
<groupId>org.openapitools</groupId>
<artifactId>jackson-databind-nullable</artifactId>
<version>${jackson-databind-nullable-version}</version>
</dependency>
{{/openApiNullable}}
{{#withXml}}
<!-- XML processing: Jackson -->
<dependency>
@@ -328,7 +330,9 @@
<jersey-common-version>2.25.1</jersey-common-version>
<jackson-version>2.10.4</jackson-version>
<jackson-databind-version>2.10.4</jackson-databind-version>
{{#openApiNullable}}
<jackson-databind-nullable-version>0.2.1</jackson-databind-nullable-version>
{{/openApiNullable}}
{{#joda}}
<jodatime-version>2.9.9</jodatime-version>
{{/joda}}

View File

@@ -55,6 +55,9 @@ import java.util.List;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Date;
{{#java8}}
import java.time.OffsetDateTime;
{{/java8}}
import java.net.URLEncoder;
@@ -77,7 +80,7 @@ import {{invokerPackage}}.auth.OAuth;
{{/hasOAuthMethods}}
{{>generatedAnnotation}}
public class ApiClient {
public class ApiClient{{#java8}} extends JavaTimeFormatter{{/java8}} {
protected Map<String, String> defaultHeaderMap = new HashMap<String, String>();
protected Map<String, String> defaultCookieMap = new HashMap<String, String>();
protected String basePath = "{{{basePath}}}";
@@ -695,7 +698,9 @@ public class ApiClient {
return "";
} else if (param instanceof Date) {
return formatDate((Date) param);
} else if (param instanceof Collection) {
} {{#java8}}else if (param instanceof OffsetDateTime) {
return formatOffsetDateTime((OffsetDateTime) param);
} {{/java8}}else if (param instanceof Collection) {
StringBuilder b = new StringBuilder();
for(Object o : (Collection)param) {
if(b.length() > 0) {

View File

@@ -5,7 +5,9 @@ import org.threeten.bp.*;
{{/threetenbp}}
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
{{#openApiNullable}}
import org.openapitools.jackson.nullable.JsonNullableModule;
{{/openApiNullable}}
{{#java8}}
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
{{/java8}}
@@ -54,8 +56,10 @@ public class JSON implements ContextResolver<ObjectMapper> {
module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME);
mapper.registerModule(module);
{{/threetenbp}}
{{#openApiNullable}}
JsonNullableModule jnm = new JsonNullableModule();
mapper.registerModule(jnm);
{{/openApiNullable}}
}
/**

View File

@@ -121,7 +121,9 @@ ext {
swagger_annotations_version = "1.5.22"
jackson_version = "2.10.3"
jackson_databind_version = "2.10.4"
{{#openApiNullable}}
jackson_databind_nullable_version = "0.2.1"
{{/openApiNullable}}
{{#supportJava6}}
jersey_version = "2.6"
commons_io_version=2.5
@@ -152,7 +154,9 @@ dependencies {
compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version"
{{#openApiNullable}}
compile "org.openapitools:jackson-databind-nullable:$jackson_databind_nullable_version"
{{/openApiNullable}}
{{#joda}}
compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version"
{{/joda}}

View File

@@ -296,11 +296,13 @@
<artifactId>jackson-databind</artifactId>
<version>${jackson-databind-version}</version>
</dependency>
{{#openApiNullable}}
<dependency>
<groupId>org.openapitools</groupId>
<artifactId>jackson-databind-nullable</artifactId>
<version>${jackson-databind-nullable-version}</version>
</dependency>
{{/openApiNullable}}
{{#withXml}}
<!-- XML processing: JAXB -->
<dependency>

View File

@@ -6,7 +6,9 @@ import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
{{#openApiNullable}}
import org.openapitools.jackson.nullable.JsonNullableModule;
{{/openApiNullable}}
import java.io.InputStream;
import java.net.URI;
@@ -155,8 +157,10 @@ public class ApiClient {
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
mapper.registerModule(new JavaTimeModule());
{{#openApiNullable}}
JsonNullableModule jnm = new JsonNullableModule();
mapper.registerModule(jnm);
{{/openApiNullable}}
URI baseURI = URI.create("{{{basePath}}}");
scheme = baseURI.getScheme();
host = baseURI.getHost();

View File

@@ -7,7 +7,9 @@ import org.threeten.bp.*;
{{/threetenbp}}
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
{{#openApiNullable}}
import org.openapitools.jackson.nullable.JsonNullableModule;
{{/openApiNullable}}
{{#java8}}
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
{{/java8}}
@@ -52,8 +54,10 @@ public class JacksonObjectMapper extends Jackson2Mapper {
module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME);
mapper.registerModule(module);
{{/threetenbp}}
{{#openApiNullable}}
JsonNullableModule jnm = new JsonNullableModule();
mapper.registerModule(jnm);
{{/openApiNullable}}
return mapper;
};
}

View File

@@ -101,7 +101,9 @@ ext {
{{#jackson}}
jackson_version = "2.10.3"
jackson_databind_version = "2.10.3"
{{#openApiNullable}}
jackson_databind_nullable_version = "0.2.1"
{{/openApiNullable}}
{{#threetenbp}}
jackson_threetenbp_version = "2.10.0"
{{/threetenbp}}
@@ -128,7 +130,9 @@ dependencies {
compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version"
compile "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:$jackson_version"
{{#openApiNullable}}
compile "org.openapitools:jackson-databind-nullable:$jackson_databind_nullable_version"
{{/openApiNullable}}
{{#withXml}}
compile "com.fasterxml.jackson.dataformat:jackson-dataformat-xml:$jackson_version"
{{/withXml}}

View File

@@ -17,7 +17,9 @@ lazy val root = (project in file(".")).
"com.fasterxml.jackson.core" % "jackson-core" % "2.10.3",
"com.fasterxml.jackson.core" % "jackson-annotations" % "2.10.3",
"com.fasterxml.jackson.core" % "jackson-databind" % "2.10.3",
{{#openApiNullable}}
"org.openapitools" % "jackson-databind-nullable" % "0.2.1",
{{/openApiNullable}}
{{#withXml}}
"com.fasterxml.jackson.dataformat" % "jackson-dataformat-xml" % "2.10.3",
{{/withXml}}

View File

@@ -22,6 +22,9 @@ import java.util.Map.Entry;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
{{#java8}}
import java.time.OffsetDateTime;
{{/java8}}
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
@@ -48,7 +51,7 @@ import {{invokerPackage}}.auth.OAuth;
{{/hasOAuthMethods}}
{{>generatedAnnotation}}
public class ApiClient {
public class ApiClient{{#java8}} extends JavaTimeFormatter{{/java8}} {
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private Map<String, String> defaultCookieMap = new HashMap<String, String>();
private String basePath = "{{{basePath}}}";
@@ -333,7 +336,9 @@ public class ApiClient {
return "";
} else if (param instanceof Date) {
return formatDate((Date) param);
} else if (param instanceof Collection) {
} {{#java8}}else if (param instanceof OffsetDateTime) {
return formatOffsetDateTime((OffsetDateTime) param);
} {{/java8}}else if (param instanceof Collection) {
StringBuilder b = new StringBuilder();
for(Object o : (Collection)param) {
if(b.length() > 0) {

View File

@@ -2,7 +2,9 @@ package {{invokerPackage}};
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
{{#openApiNullable}}
import org.openapitools.jackson.nullable.JsonNullableModule;
{{/openApiNullable}}
{{#java8}}
import com.fasterxml.jackson.datatype.jsr310.*;
{{/java8}}
@@ -27,8 +29,10 @@ public class JSON implements ContextResolver<ObjectMapper> {
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
mapper.setDateFormat(new RFC3339DateFormat());
{{#openApiNullable}}
JsonNullableModule jnm = new JsonNullableModule();
mapper.registerModule(jnm);
{{/openApiNullable}}
{{#java8}}
mapper.registerModule(new JavaTimeModule());
{{/java8}}

View File

@@ -121,7 +121,9 @@ ext {
swagger_annotations_version = "1.5.22"
jackson_version = "2.10.4"
jackson_databind_version = "2.10.4"
{{#openApiNullable}}
jackson_databind_nullable_version = "0.2.1"
{{/openApiNullable}}
threetenbp_version = "2.9.10"
resteasy_version = "3.1.3.Final"
{{^java8}}
@@ -144,7 +146,9 @@ dependencies {
compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version"
compile "com.github.joschi.jackson:jackson-datatype-threetenbp:$threetenbp_version"
{{#openApiNullable}}
compile "org.openapitools:jackson-databind-nullable:$jackson_databind_nullable_version"
{{/openApiNullable}}
{{#java8}}
compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version"
{{/java8}}

View File

@@ -226,11 +226,13 @@
<artifactId>jackson-databind</artifactId>
<version>${jackson-databind-version}</version>
</dependency>
{{#openApiNullable}}
<dependency>
<groupId>org.openapitools</groupId>
<artifactId>jackson-databind-nullable</artifactId>
<version>${jackson-databind-nullable-version}</version>
</dependency>
{{/openApiNullable}}
{{#withXml}}
<!-- XML processing: Jackson -->

View File

@@ -39,7 +39,9 @@ import com.fasterxml.jackson.datatype.threetenbp.ThreeTenModule;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter;
import com.fasterxml.jackson.databind.ObjectMapper;
{{#openApiNullable}}
import org.openapitools.jackson.nullable.JsonNullableModule;
{{/openApiNullable}}
{{/threetenbp}}
import java.io.BufferedReader;
@@ -64,6 +66,9 @@ import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TimeZone;
{{#java8}}
import java.time.OffsetDateTime;
{{/java8}}
import {{invokerPackage}}.auth.Authentication;
{{#hasHttpBasicMethods}}
@@ -81,7 +86,7 @@ import {{invokerPackage}}.auth.OAuth;
{{>generatedAnnotation}}
@Component("{{invokerPackage}}.ApiClient")
public class ApiClient {
public class ApiClient{{#java8}} extends JavaTimeFormatter{{/java8}} {
public enum CollectionFormat {
CSV(","), TSV("\t"), SSV(" "), PIPES("|"), MULTI(null);
@@ -402,7 +407,9 @@ public class ApiClient {
return "";
} else if (param instanceof Date) {
return formatDate( (Date) param);
} else if (param instanceof Collection) {
} {{#java8}}else if (param instanceof OffsetDateTime) {
return formatOffsetDateTime((OffsetDateTime) param);
} {{/java8}}else if (param instanceof Collection) {
StringBuilder b = new StringBuilder();
for(Object o : (Collection<?>) param) {
if(b.length() > 0) {
@@ -702,7 +709,9 @@ public class ApiClient {
messageConverters.add(new MappingJackson2HttpMessageConverter());
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
{{#openApiNullable}}
xmlMapper.registerModule(new JsonNullableModule());
{{/openApiNullable}}
messageConverters.add(new MappingJackson2XmlHttpMessageConverter(xmlMapper));
RestTemplate restTemplate = new RestTemplate(messageConverters);
@@ -716,7 +725,9 @@ public class ApiClient {
module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME);
module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME);
mapper.registerModule(module);
{{#openApiNullable}}
mapper.registerModule(new JsonNullableModule());
{{/openApiNullable}}
}
}
{{/threetenbp}}

View File

@@ -122,7 +122,9 @@ ext {
swagger_annotations_version = "1.5.22"
jackson_version = "2.10.4"
jackson_databind_version = "2.10.4"
{{#openApiNullable}}
jackson_databind_nullable_version = "0.2.1"
{{/openApiNullable}}
spring_web_version = "5.2.5.RELEASE"
jodatime_version = "2.9.9"
junit_version = "4.13"
@@ -140,7 +142,9 @@ dependencies {
compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version"
compile "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:$jackson_version"
{{#openApiNullable}}
compile "org.openapitools:jackson-databind-nullable:$jackson_databind_nullable_version"
{{/openApiNullable}}
{{#java8}}
compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version"
{{/java8}}

View File

@@ -124,7 +124,9 @@ ext {
{{#usePlayWS}}
jackson_version = "2.10.4"
jackson_databind_version = "2.10.4"
{{#openApiNullable}}
jackson_databind_nullable_version = "0.2.1"
{{/openApiNullable}}
{{#play24}}
play_version = "2.4.11"
{{/play24}}
@@ -195,7 +197,9 @@ dependencies {
compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version"
{{#openApiNullable}}
compile "org.openapitools:jackson-databind-nullable:$jackson_databind_nullable_version"
{{/openApiNullable}}
compile "com.fasterxml.jackson.datatype:jackson-datatype-{{^java8}}joda{{/java8}}{{#java8}}jsr310{{/java8}}:$jackson_version"
{{/usePlayWS}}
compile 'javax.annotation:javax.annotation-api:1.3.2'

View File

@@ -9,7 +9,9 @@ import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import retrofit2.converter.jackson.JacksonConverterFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
{{#openApiNullable}}
import org.openapitools.jackson.nullable.JsonNullableModule;
{{/openApiNullable}}
import play.libs.Json;
import play.libs.ws.WSClient;
@@ -72,8 +74,10 @@ public class ApiClient {
}
ObjectMapper mapper = Json.mapper();
{{#openApiNullable}}
JsonNullableModule jnm = new JsonNullableModule();
mapper.registerModule(jnm);
{{/openApiNullable}}
return new Retrofit.Builder()
.baseUrl(basePath)

View File

@@ -9,7 +9,9 @@ import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import retrofit2.converter.jackson.JacksonConverterFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
{{#openApiNullable}}
import org.openapitools.jackson.nullable.JsonNullableModule;
{{/openApiNullable}}
import play.libs.Json;
import play.libs.ws.WSClient;
@@ -71,8 +73,10 @@ public class ApiClient {
}
ObjectMapper mapper = Json.mapper();
{{#openApiNullable}}
JsonNullableModule jnm = new JsonNullableModule();
mapper.registerModule(jnm);
{{/openApiNullable}}
return new Retrofit.Builder()
.baseUrl(basePath)

View File

@@ -13,7 +13,9 @@ import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import retrofit2.converter.jackson.JacksonConverterFactory;
{{#openApiNullable}}
import org.openapitools.jackson.nullable.JsonNullableModule;
{{/openApiNullable}}
import play.libs.Json;
import play.libs.ws.WSClient;
@@ -91,8 +93,10 @@ public class ApiClient {
}
if (defaultMapper == null) {
defaultMapper = Json.mapper();
{{#openApiNullable}}
JsonNullableModule jnm = new JsonNullableModule();
defaultMapper.registerModule(jnm);
{{/openApiNullable}}
}
return new Retrofit.Builder()

View File

@@ -342,11 +342,13 @@
<artifactId>jackson-databind</artifactId>
<version>${jackson-version}</version>
</dependency>
{{#openApiNullable}}
<dependency>
<groupId>org.openapitools</groupId>
<artifactId>jackson-databind-nullable</artifactId>
<version>${jackson-databind-nullable-version}</version>
</dependency>
{{/openApiNullable}}
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-{{^java8}}joda{{/java8}}{{#java8}}jsr310{{/java8}}</artifactId>
@@ -428,7 +430,9 @@
{{#play26}}
<play-version>2.6.7</play-version>
{{/play26}}
{{#openApiNullable}}
<jackson-databind-nullable-version>0.2.1</jackson-databind-nullable-version>
{{/openApiNullable}}
{{/usePlayWS}}
<retrofit-version>2.5.0</retrofit-version>
{{#useRxJava}}

View File

@@ -15,7 +15,9 @@ import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
{{#openApiNullable}}
import org.openapitools.jackson.nullable.JsonNullableModule;
{{/openApiNullable}}
import io.vertx.core.*;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.file.AsyncFile;
@@ -31,6 +33,9 @@ import io.vertx.ext.web.client.HttpResponse;
import io.vertx.ext.web.client.WebClient;
import io.vertx.ext.web.client.WebClientOptions;
{{#java8}}
import java.time.OffsetDateTime;
{{/java8}}
import java.text.DateFormat;
import java.util.*;
import java.util.function.Consumer;
@@ -40,7 +45,7 @@ import java.util.regex.Pattern;
import static java.util.stream.Collectors.toMap;
{{>generatedAnnotation}}
public class ApiClient {
public class ApiClient{{#java8}} extends JavaTimeFormatter{{/java8}} {
private static final Pattern CONTENT_DISPOSITION_PATTERN = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?");
private static final OpenOptions FILE_DOWNLOAD_OPTIONS = new OpenOptions().setCreate(true).setTruncateExisting(true);
@@ -81,8 +86,10 @@ public class ApiClient {
this.objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
this.objectMapper.registerModule(new JavaTimeModule());
this.objectMapper.setDateFormat(dateFormat);
{{#openApiNullable}}
JsonNullableModule jnm = new JsonNullableModule();
this.objectMapper.registerModule(jnm);
{{/openApiNullable}}
// Setup authentications (key: authentication name, value: authentication).
this.authentications = new HashMap<>();{{#authMethods}}{{#isBasic}}{{#isBasicBasic}}
@@ -291,7 +298,9 @@ public class ApiClient {
return "";
} else if (param instanceof Date) {
return formatDate((Date) param);
} else if (param instanceof Collection) {
} {{#java8}}else if (param instanceof OffsetDateTime) {
return formatOffsetDateTime((OffsetDateTime) param);
} {{/java8}}else if (param instanceof Collection) {
StringBuilder b = new StringBuilder();
for (Object o : (Collection) param) {
if (b.length() > 0) {

View File

@@ -32,7 +32,12 @@ ext {
jackson_databind_version = "2.10.4"
vertx_version = "3.4.2"
junit_version = "4.13"
{{#openApiNullable}}
jackson_databind_nullable_version = "0.2.1"
{{/openApiNullable}}
{{#threetenbp}}
jackson_threeten_version = "2.9.10"
{{/threetenbp}}
}
dependencies {
@@ -50,9 +55,11 @@ dependencies {
compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version"
{{/java8}}
{{#threetenbp}}
compile "com.github.joschi.jackson:jackson-datatype-threetenbp:$jackson_version"
compile "com.github.joschi.jackson:jackson-datatype-threetenbp:jackson_threeten_version"
{{/threetenbp}}
{{#openApiNullable}}
compile "org.openapitools:jackson-databind-nullable:$jackson_databind_nullable_version"
{{/openApiNullable}}
compile 'javax.annotation:javax.annotation-api:1.3.2'
testCompile "junit:junit:$junit_version"
testCompile "io.vertx:vertx-unit:$vertx_version"

View File

@@ -257,11 +257,13 @@
<artifactId>jackson-databind</artifactId>
<version>${jackson-databind}</version>
</dependency>
{{#openApiNullable}}
<dependency>
<groupId>org.openapitools</groupId>
<artifactId>jackson-databind-nullable</artifactId>
<version>${jackson-databind-nullable-version}</version>
</dependency>
{{/openApiNullable}}
{{#joda}}
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>

Some files were not shown because too many files have changed in this diff Show More