diff --git a/docs/generators/java.md b/docs/generators/java.md index 08d9f1ef3aa..37fd2bc694a 100644 --- a/docs/generators/java.md +++ b/docs/generators/java.md @@ -320,7 +320,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl ### Schema Feature | Name | Supported | Defined By | | ---- | --------- | ---------- | -|AdditionalProperties|✗|OAS2,OAS3 +|AdditionalProperties|✓|OAS2,OAS3 |AllOf|✓|OAS2,OAS3 |AnyOf|✓|OAS3 |Const|✗|OAS3 @@ -328,9 +328,9 @@ These options may be applied as additional-properties (cli) or configOptions (pl |Default|✗|OAS2,OAS3 |DependentRequired|✗|OAS3 |DependentSchemas|✗|OAS3 -|Discriminator|✓|OAS2,OAS3 +|Discriminator|✗|OAS2,OAS3 |Else|✗|OAS3 -|Enum|✓|OAS2,OAS3 +|Enum|✗|OAS2,OAS3 |ExclusiveMinimum|✓|OAS2,OAS3 |ExclusiveMaximum|✓|OAS2,OAS3 |Format|✓|OAS2,OAS3 @@ -348,9 +348,9 @@ These options may be applied as additional-properties (cli) or configOptions (pl |Minimum|✓|OAS2,OAS3 |MultipleOf|✓|OAS2,OAS3 |Not|✓|OAS3 -|Nullable|✗|OAS3 +|Nullable|✓|OAS3 |OneOf|✓|OAS3 -|Pattern|✓|OAS2,OAS3 +|Pattern|✗|OAS2,OAS3 |PatternProperties|✗|OAS3 |PrefixItems|✗|OAS3 |Properties|✓|OAS2,OAS3 diff --git a/docs/generators/jaxrs-jersey.md b/docs/generators/jaxrs-jersey.md deleted file mode 100644 index c8b84f80026..00000000000 --- a/docs/generators/jaxrs-jersey.md +++ /dev/null @@ -1,367 +0,0 @@ ---- -title: Documentation for the jaxrs-jersey generator ---- - -## METADATA - -| Property | Value | Notes | -| -------- | ----- | ----- | -| generator name | jaxrs-jersey | pass this to the generate command after -g | -| generator stability | STABLE | | -| generator type | SERVER | | -| generator language | Java | | -| generator default templating engine | mustache | | -| helpTxt | Generates a Java JAXRS Server application based on Jersey framework. | | - -## CONFIG OPTIONS -These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. - -| Option | Description | Values | Default | -| ------ | ----------- | ------ | ------- | -|additionalEnumTypeAnnotations|Additional annotations for enum type(class level annotations)| |null| -|additionalModelTypeAnnotations|Additional annotations for model type(class level annotations). List separated by semicolon(;) or new line (Linux or Windows)| |null| -|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| -|apiPackage|package for generated api classes| |org.openapijsonschematools.api| -|artifactDescription|artifact description in generated pom.xml| |OpenAPI Java| -|artifactId|artifactId in generated pom.xml. This also becomes part of the generated library's filename| |openapi-jaxrs-server| -|artifactUrl|artifact URL in generated pom.xml| |https://github.com/openapi-json-schema-tools/openapi-json-schema-generator| -|artifactVersion|artifact version in generated pom.xml. This also becomes part of the generated library's filename| |1.0.0| -|bigDecimalAsString|Treat BigDecimal values as Strings to avoid precision loss.| |false| -|booleanGetterPrefix|Set booleanGetterPrefix| |get| -|dateLibrary|Option. Date library to use|
**joda**
Joda (for legacy app only)
**legacy**
Legacy java.util.Date
**java8-localdatetime**
Java 8 using LocalDateTime (for legacy app only)
**java8**
Java 8 native JSR310 (preferred for jdk 1.8+)
|legacy| -|developerEmail|developer email in generated pom.xml| |team@openapijsonschematools.org| -|developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| -|developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| -|developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapijsonschematools.org| -|disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| -|disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
**false**
The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
**true**
Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
|true| -|discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| -|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| -|enumUnknownDefaultCase|If the server adds new enum cases, that are unknown by an old spec/client, the client will fail to parse the network response.With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the server sends an enum case that is not known by the client/spec, they can safely fallback to this case.|
**false**
No changes to the enum's are made, this is the default option.
**true**
With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the enum case sent by the server is not known by the client/spec, can safely be decoded to this case.
|false| -|fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false| -|groupId|groupId in generated pom.xml| |org.openapijsonschematools| -|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false| -|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false| -|implFolder|folder for generated implementation code| |src/main/java| -|implicitHeaders|Skip header parameters in the generated API methods using @ApiImplicitParams annotation.| |false| -|implicitHeadersRegex|Skip header parameters that matches given regex in the generated API methods using @ApiImplicitParams annotation. Note: this parameter is ignored when implicitHeaders=true| |null| -|invokerPackage|root package for generated code| |org.openapijsonschematools.api| -|legacyDiscriminatorBehavior|Set to false for generators with better support for discriminators. (Python, Java, Go, PowerShell, C#have this enabled by default).|
**true**
The mapping in the discriminator includes descendant schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendant schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| -|library|library template (sub-template)|
**jersey1**
Jersey core 1.x
**jersey2**
Jersey core 2.x
|jersey2| -|licenseName|The name of the license| |Unlicense| -|licenseUrl|The URL of the license| |http://unlicense.org| -|modelPackage|package for generated models| |org.openapijsonschematools.model| -|openApiNullable|Enable OpenAPI Jackson Nullable library| |true| -|parentArtifactId|parent artifactId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null| -|parentGroupId|parent groupId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null| -|parentVersion|parent version in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null| -|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| -|scmConnection|SCM connection in generated pom.xml| |scm:git:git@github.com:openapi-json-schema-tools/openapi-json-schema-generator.git| -|scmDeveloperConnection|SCM developer connection in generated pom.xml| |scm:git:git@github.com:openapi-json-schema-tools/openapi-json-schema-generator.git| -|scmUrl|SCM URL in generated pom.xml| |https://github.com/openapi-json-schema-tools/openapi-json-schema-generator| -|serializableModel|boolean - toggle "implements Serializable" for generated models| |false| -|serverPort|The port on which the server should be started| |8080| -|snapshotVersion|Uses a SNAPSHOT version.|
**true**
Use a SnapShot Version
**false**
Use a Release Version
|null| -|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| -|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| -|sourceFolder|source folder for generated code| |src/gen/java| -|supportJava6|Whether to support Java6 with the Jersey1/2 library.| |false| -|testOutput|Set output folder for models and APIs tests| |${project.build.directory}/generated-test-sources/openapi| -|title|a title describing the application| |OpenAPI Server| -|useBeanValidation|Use BeanValidation API annotations| |true| -|useTags|use tags for creating interface and controller classnames| |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| - -## SUPPORTED VENDOR EXTENSIONS - -| Extension name | Description | Applicable for | Default value | -| -------------- | ----------- | -------------- | ------------- | -|x-discriminator-value|Used with model inheritance to specify value for discriminator that identifies current model|MODEL| -|x-implements|Ability to specify interfaces that model must implements|MODEL|empty array -|x-setter-extra-annotation|Custom annotation that can be specified over java setter for specific field|FIELD|When field is array & uniqueItems, then this extension is used to add `@JsonDeserialize(as = LinkedHashSet.class)` over setter, otherwise no value -|x-tags|Specify multiple swagger tags for operation|OPERATION|null -|x-accepts|Specify custom value for 'Accept' header for operation|OPERATION|null -|x-content-type|Specify custom value for 'Content-Type' header for operation|OPERATION|null -|x-class-extra-annotation|List of custom annotations to be added to model|MODEL|null -|x-field-extra-annotation|List of custom annotations to be added to property|FIELD|null - - -## INSTANTIATION TYPES - -| Type/Alias | Instantiated By | -| ---------- | --------------- | -|array|ArrayList| -|map|HashMap| -|set|LinkedHashSet| - - -## LANGUAGE PRIMITIVES - - - -## RESERVED WORDS - - - -## FEATURE SET - - -### Client Modification Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|BasePath|✓|ToolingExtension -|Authorizations|✗|ToolingExtension -|UserAgent|✗|ToolingExtension -|MockServer|✗|ToolingExtension - -### Components Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|schemas|✗|OAS3 -|responses|✗|OAS3 -|parameters|✗|OAS3 -|examples|✗|OAS3 -|requestBodies|✗|OAS3 -|headers|✗|OAS3 -|securitySchemes|✗|OAS3 -|links|✗|OAS3 -|callbacks|✗|OAS3 -|pathItems|✗|OAS3 - -### Data Type Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|Custom|✗|OAS2,OAS3 -|Int32|✓|OAS2,OAS3 -|Int64|✓|OAS2,OAS3 -|Integer|✗|OAS2,OAS3 -|Float|✓|OAS2,OAS3 -|Double|✓|OAS2,OAS3 -|Number|✗|OAS2,OAS3 -|String|✓|OAS2,OAS3 -|Byte|✓|OAS2,OAS3 -|Binary|✓|OAS2,OAS3 -|Boolean|✓|OAS2,OAS3 -|Date|✓|OAS2,OAS3 -|DateTime|✓|OAS2,OAS3 -|Password|✓|OAS2,OAS3 -|File|✓|OAS2 -|Uuid|✗|OAS2,OAS3 -|Array|✓|OAS2,OAS3 -|Null|✗|OAS3 -|AnyType|✗|OAS2,OAS3 -|Object|✓|OAS2,OAS3 -|Enum|✓|OAS2,OAS3 - -### Documentation Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|Readme|✓|ToolingExtension -|Servers|✗|OAS3 -|Security|✗|OAS2,OAS3 -|ComponentSchemas|✓|OAS3 -|ComponentResponses|✗|OAS3 -|ComponentParameters|✗|OAS3 -|ComponentRequestBodies|✗|OAS3 -|ComponentHeaders|✗|OAS3 -|ComponentSecuritySchemes|✗|OAS3 -|ComponentLinks|✗|OAS3 -|ComponentCallbacks|✗|OAS3 -|ComponentPathItems|✗|OAS3 -|Api|✓|ToolingExtension - -### Global Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|Info|✓|OAS2,OAS3 -|Servers|✗|OAS3 -|Paths|✗|OAS2,OAS3 -|Webhooks|✗|OAS3 -|Components|✓|OAS3 -|Security|✗|OAS2,OAS3 -|Tags|✗|OAS2,OAS3 -|ExternalDocs|✗|OAS2,OAS3 - -### Operation Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|Responses_HttpStatusCode|✓|OAS3 -|Responses_RangedResponseCodes|✗|OAS3 -|Responses_Default|✓|OAS3 -|Responses_RedirectionResponse|✗|OAS3 - -### Parameter Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|Name|✗|OAS2,OAS3 -|Required|✗|OAS2,OAS3 -|In_Path|✓|OAS2,OAS3 -|In_Query|✓|OAS2,OAS3 -|In_Header|✓|OAS2,OAS3 -|In_Cookie|✓|OAS3 -|Style_Matrix|✗|OAS3 -|Style_Label|✗|OAS3 -|Style_Form|✗|OAS3 -|Style_Simple|✗|OAS3 -|Style_SpaceDelimited|✗|OAS3 -|Style_PipeDelimited|✗|OAS3 -|Style_DeepObject|✗|OAS3 -|Explode|✗|OAS3 -|Schema|✗|OAS3 -|Content|✗|OAS3 - -### Schema Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|AdditionalProperties|✗|OAS2,OAS3 -|AllOf|✗|OAS2,OAS3 -|AnyOf|✗|OAS3 -|Const|✗|OAS3 -|Contains|✗|OAS3 -|Default|✗|OAS2,OAS3 -|DependentRequired|✗|OAS3 -|DependentSchemas|✗|OAS3 -|Discriminator|✓|OAS2,OAS3 -|Else|✗|OAS3 -|Enum|✓|OAS2,OAS3 -|ExclusiveMinimum|✓|OAS2,OAS3 -|ExclusiveMaximum|✓|OAS2,OAS3 -|Format|✓|OAS2,OAS3 -|If|✗|OAS3 -|Items|✓|OAS2,OAS3 -|MaxContains|✗|OAS3 -|MaxItems|✓|OAS2,OAS3 -|MaxLength|✓|OAS2,OAS3 -|MaxProperties|✓|OAS2,OAS3 -|Maximum|✓|OAS2,OAS3 -|MinContains|✗|OAS3 -|MinItems|✓|OAS2,OAS3 -|MinLength|✓|OAS2,OAS3 -|MinProperties|✓|OAS2,OAS3 -|Minimum|✓|OAS2,OAS3 -|MultipleOf|✓|OAS2,OAS3 -|Not|✗|OAS3 -|Nullable|✗|OAS3 -|OneOf|✗|OAS3 -|Pattern|✓|OAS2,OAS3 -|PatternProperties|✗|OAS3 -|PrefixItems|✗|OAS3 -|Properties|✓|OAS2,OAS3 -|PropertyNames|✗|OAS3 -|Ref|✗|OAS2,OAS3 -|Required|✓|OAS2,OAS3 -|Then|✗|OAS3 -|Type|✓|OAS2,OAS3 -|UnevaluatedItems|✗|OAS3 -|UnevaluatedProperties|✗|OAS3 -|UniqueItems|✓|OAS2,OAS3 -|Xml|✗|OAS2,OAS3 - -### Security Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|HTTP_Basic|✗|OAS2,OAS3 -|ApiKey|✗|OAS2,OAS3 -|OpenIDConnect|✗|OAS3 -|HTTP_Bearer|✗|OAS2,OAS3 -|OAuth2_Implicit|✗|OAS2,OAS3 -|OAuth2_Password|✗|OAS2,OAS3 -|OAuth2_ClientCredentials|✗|OAS2,OAS3 -|OAuth2_AuthorizationCode|✗|OAS2,OAS3 - -### Wire Format Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|JSON|✓|OAS2,OAS3 -|XML|✓|OAS2,OAS3 -|PROTOBUF|✗|ToolingExtension -|Custom|✗|OAS2,OAS3 diff --git a/docs/generators/jmeter.md b/docs/generators/jmeter.md deleted file mode 100644 index 6f4d35709ba..00000000000 --- a/docs/generators/jmeter.md +++ /dev/null @@ -1,220 +0,0 @@ ---- -title: Documentation for the jmeter generator ---- - -## METADATA - -| Property | Value | Notes | -| -------- | ----- | ----- | -| generator name | jmeter | pass this to the generate command after -g | -| generator stability | STABLE | | -| generator type | CLIENT | | -| generator language | Java | | -| generator default templating engine | mustache | | -| helpTxt | Generates a JMeter .jmx file. | | - -## CONFIG OPTIONS -These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. - -| Option | Description | Values | Default | -| ------ | ----------- | ------ | ------- | -|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| -|disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
**false**
The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
**true**
Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
|true| -|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| -|enumUnknownDefaultCase|If the server adds new enum cases, that are unknown by an old spec/client, the client will fail to parse the network response.With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the server sends an enum case that is not known by the client/spec, they can safely fallback to this case.|
**false**
No changes to the enum's are made, this is the default option.
**true**
With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the enum case sent by the server is not known by the client/spec, can safely be decoded to this case.
|false| -|legacyDiscriminatorBehavior|Set to false for generators with better support for discriminators. (Python, Java, Go, PowerShell, C#have this enabled by default).|
**true**
The mapping in the discriminator includes descendant schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendant schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| -|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| -|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| -|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| - -## INSTANTIATION TYPES - -| Type/Alias | Instantiated By | -| ---------- | --------------- | - - -## LANGUAGE PRIMITIVES - - - -## RESERVED WORDS - - - -## FEATURE SET - - -### Client Modification Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|BasePath|✓|ToolingExtension -|Authorizations|✗|ToolingExtension -|UserAgent|✗|ToolingExtension -|MockServer|✗|ToolingExtension - -### Components Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|schemas|✗|OAS3 -|responses|✗|OAS3 -|parameters|✗|OAS3 -|examples|✗|OAS3 -|requestBodies|✗|OAS3 -|headers|✗|OAS3 -|securitySchemes|✗|OAS3 -|links|✗|OAS3 -|callbacks|✗|OAS3 -|pathItems|✗|OAS3 - -### Data Type Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|Custom|✗|OAS2,OAS3 -|Int32|✓|OAS2,OAS3 -|Int64|✓|OAS2,OAS3 -|Integer|✗|OAS2,OAS3 -|Float|✓|OAS2,OAS3 -|Double|✓|OAS2,OAS3 -|Number|✗|OAS2,OAS3 -|String|✓|OAS2,OAS3 -|Byte|✓|OAS2,OAS3 -|Binary|✓|OAS2,OAS3 -|Boolean|✓|OAS2,OAS3 -|Date|✓|OAS2,OAS3 -|DateTime|✓|OAS2,OAS3 -|Password|✓|OAS2,OAS3 -|File|✓|OAS2 -|Uuid|✗|OAS2,OAS3 -|Array|✓|OAS2,OAS3 -|Null|✗|OAS3 -|AnyType|✗|OAS2,OAS3 -|Object|✓|OAS2,OAS3 -|Enum|✓|OAS2,OAS3 - -### Documentation Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|Readme|✗|ToolingExtension -|Servers|✗|OAS3 -|Security|✗|OAS2,OAS3 -|ComponentSchemas|✓|OAS3 -|ComponentResponses|✗|OAS3 -|ComponentParameters|✗|OAS3 -|ComponentRequestBodies|✗|OAS3 -|ComponentHeaders|✗|OAS3 -|ComponentSecuritySchemes|✗|OAS3 -|ComponentLinks|✗|OAS3 -|ComponentCallbacks|✗|OAS3 -|ComponentPathItems|✗|OAS3 -|Api|✓|ToolingExtension - -### Global Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|Info|✓|OAS2,OAS3 -|Servers|✗|OAS3 -|Paths|✗|OAS2,OAS3 -|Webhooks|✗|OAS3 -|Components|✓|OAS3 -|Security|✗|OAS2,OAS3 -|Tags|✗|OAS2,OAS3 -|ExternalDocs|✗|OAS2,OAS3 - -### Operation Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|Responses_HttpStatusCode|✓|OAS3 -|Responses_RangedResponseCodes|✗|OAS3 -|Responses_Default|✓|OAS3 -|Responses_RedirectionResponse|✗|OAS3 - -### Parameter Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|Name|✗|OAS2,OAS3 -|Required|✗|OAS2,OAS3 -|In_Path|✓|OAS2,OAS3 -|In_Query|✓|OAS2,OAS3 -|In_Header|✓|OAS2,OAS3 -|In_Cookie|✓|OAS3 -|Style_Matrix|✗|OAS3 -|Style_Label|✗|OAS3 -|Style_Form|✗|OAS3 -|Style_Simple|✗|OAS3 -|Style_SpaceDelimited|✗|OAS3 -|Style_PipeDelimited|✗|OAS3 -|Style_DeepObject|✗|OAS3 -|Explode|✗|OAS3 -|Schema|✗|OAS3 -|Content|✗|OAS3 - -### Schema Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|AdditionalProperties|✗|OAS2,OAS3 -|AllOf|✗|OAS2,OAS3 -|AnyOf|✗|OAS3 -|Const|✗|OAS3 -|Contains|✗|OAS3 -|Default|✗|OAS2,OAS3 -|DependentRequired|✗|OAS3 -|DependentSchemas|✗|OAS3 -|Discriminator|✓|OAS2,OAS3 -|Else|✗|OAS3 -|Enum|✓|OAS2,OAS3 -|ExclusiveMinimum|✓|OAS2,OAS3 -|ExclusiveMaximum|✓|OAS2,OAS3 -|Format|✓|OAS2,OAS3 -|If|✗|OAS3 -|Items|✓|OAS2,OAS3 -|MaxContains|✗|OAS3 -|MaxItems|✓|OAS2,OAS3 -|MaxLength|✓|OAS2,OAS3 -|MaxProperties|✓|OAS2,OAS3 -|Maximum|✓|OAS2,OAS3 -|MinContains|✗|OAS3 -|MinItems|✓|OAS2,OAS3 -|MinLength|✓|OAS2,OAS3 -|MinProperties|✓|OAS2,OAS3 -|Minimum|✓|OAS2,OAS3 -|MultipleOf|✓|OAS2,OAS3 -|Not|✗|OAS3 -|Nullable|✗|OAS3 -|OneOf|✗|OAS3 -|Pattern|✓|OAS2,OAS3 -|PatternProperties|✗|OAS3 -|PrefixItems|✗|OAS3 -|Properties|✓|OAS2,OAS3 -|PropertyNames|✗|OAS3 -|Ref|✗|OAS2,OAS3 -|Required|✓|OAS2,OAS3 -|Then|✗|OAS3 -|Type|✓|OAS2,OAS3 -|UnevaluatedItems|✗|OAS3 -|UnevaluatedProperties|✗|OAS3 -|UniqueItems|✓|OAS2,OAS3 -|Xml|✗|OAS2,OAS3 - -### Security Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|HTTP_Basic|✓|OAS2,OAS3 -|ApiKey|✓|OAS2,OAS3 -|OpenIDConnect|✗|OAS3 -|HTTP_Bearer|✗|OAS2,OAS3 -|OAuth2_Implicit|✓|OAS2,OAS3 -|OAuth2_Password|✗|OAS2,OAS3 -|OAuth2_ClientCredentials|✗|OAS2,OAS3 -|OAuth2_AuthorizationCode|✗|OAS2,OAS3 - -### Wire Format Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|JSON|✓|OAS2,OAS3 -|XML|✓|OAS2,OAS3 -|PROTOBUF|✗|ToolingExtension -|Custom|✗|OAS2,OAS3 diff --git a/docs/generators/kotlin.md b/docs/generators/kotlin.md deleted file mode 100644 index ae0cfb7cddb..00000000000 --- a/docs/generators/kotlin.md +++ /dev/null @@ -1,330 +0,0 @@ ---- -title: Documentation for the kotlin generator ---- - -## METADATA - -| Property | Value | Notes | -| -------- | ----- | ----- | -| generator name | kotlin | pass this to the generate command after -g | -| generator stability | STABLE | | -| generator type | CLIENT | | -| generator language | Kotlin | | -| generator default templating engine | mustache | | -| helpTxt | Generates a Kotlin client. | | - -## CONFIG OPTIONS -These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. - -| Option | Description | Values | Default | -| ------ | ----------- | ------ | ------- | -|apiSuffix|suffix for api classes| |Api| -|artifactId|Generated artifact id (name of jar).| |kotlin-client| -|artifactVersion|Generated artifact's package version.| |1.0.0| -|collectionType|Option. Collection type to use|
**array**
kotlin.Array
**list**
kotlin.collections.List
|list| -|dateLibrary|Option. Date library to use|
**threetenbp-localdatetime**
Threetenbp - Backport of JSR310 (jvm only, for legacy app only)
**string**
String
**java8-localdatetime**
Java 8 native JSR310 (jvm only, for legacy app only)
**java8**
Java 8 native JSR310 (jvm only, preferred for jdk 1.8+)
**threetenbp**
Threetenbp - Backport of JSR310 (jvm only, preferred for jdk < 1.8)
|java8| -|enumPropertyNaming|Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original'| |camelCase| -|generateRoomModels|Generate Android Room database models in addition to API models (JVM Volley library only)| |false| -|groupId|Generated artifact package's organization (i.e. maven groupId).| |org.openapijsonschematools| -|idea|Add IntellJ Idea plugin and mark Kotlin main and test folders as source folders.| |false| -|library|Library template (sub-template) to use|
**jvm-ktor**
Platform: Java Virtual Machine. HTTP client: Ktor 1.6.7. JSON processing: Gson, Jackson (default).
**jvm-okhttp4**
[DEFAULT] Platform: Java Virtual Machine. HTTP client: OkHttp 4.2.0 (Android 5.0+ and Java 8+). JSON processing: Moshi 1.8.0.
**jvm-okhttp3**
Platform: Java Virtual Machine. HTTP client: OkHttp 3.12.4 (Android 2.3+ and Java 7+). JSON processing: Moshi 1.8.0.
**jvm-retrofit2**
Platform: Java Virtual Machine. HTTP client: Retrofit 2.6.2.
**multiplatform**
Platform: Kotlin multiplatform. HTTP client: Ktor 1.6.7. JSON processing: Kotlinx Serialization: 1.2.1.
**jvm-volley**
Platform: JVM for Android. HTTP client: Volley 1.2.1. JSON processing: gson 2.8.9
|jvm-okhttp4| -|modelMutable|Create mutable models| |false| -|moshiCodeGen|Whether to enable codegen with the Moshi library. Refer to the [official Moshi doc](https://github.com/square/moshi#codegen) for more info.| |false| -|omitGradlePluginVersions|Whether to declare Gradle plugin versions in build files.| |false| -|omitGradleWrapper|Whether to omit Gradle wrapper for creating a sub project.| |false| -|packageName|Generated artifact package name.| |org.openapijsonschematools.client| -|parcelizeModels|toggle "@Parcelize" for generated models| |null| -|requestDateConverter|JVM-Option. Defines in how to handle date-time objects that are used for a request (as query or parameter)|
**toJson**
[DEFAULT] Date formatter option using a json converter.
**toString**
Use the 'toString'-method of the date-time object to retrieve the related string representation.
|toJson| -|serializableModel|boolean - toggle "implements Serializable" for generated models| |null| -|serializationLibrary|What serialization library to use: 'moshi' (default), or 'gson' or 'jackson'| |moshi| -|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |null| -|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |null| -|sourceFolder|source folder for generated code| |src/main/kotlin| -|supportAndroidApiLevel25AndBelow|[WARNING] This flag will generate code that has a known security vulnerability. It uses `kotlin.io.createTempFile` instead of `java.nio.file.Files.createTempFile` in order to support Android API level 25 and bellow. For more info, please check the following links https://github.com/OpenAPITools/openapi-generator/security/advisories/GHSA-23x4-m842-fmwf, https://github.com/OpenAPITools/openapi-generator/pull/9284| |false| -|useCoroutines|Whether to use the Coroutines adapter with the retrofit2 library.| |false| -|useRxJava|Whether to use the RxJava adapter with the retrofit2 library. IMPORTANT: this option has been deprecated. Please use `useRxJava3` instead.| |false| -|useRxJava2|Whether to use the RxJava2 adapter with the retrofit2 library. IMPORTANT: this option has been deprecated. Please use `useRxJava3` instead.| |false| -|useRxJava3|Whether to use the RxJava3 adapter with the retrofit2 library.| |false| - -## INSTANTIATION TYPES - -| Type/Alias | Instantiated By | -| ---------- | --------------- | -|array|kotlin.collections.ArrayList| -|list|kotlin.collections.ArrayList| -|map|kotlin.collections.HashMap| - - -## LANGUAGE PRIMITIVES - - - -## RESERVED WORDS - - - -## FEATURE SET - - -### Client Modification Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|BasePath|✓|ToolingExtension -|Authorizations|✗|ToolingExtension -|UserAgent|✗|ToolingExtension -|MockServer|✗|ToolingExtension - -### Components Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|schemas|✗|OAS3 -|responses|✗|OAS3 -|parameters|✗|OAS3 -|examples|✗|OAS3 -|requestBodies|✗|OAS3 -|headers|✗|OAS3 -|securitySchemes|✗|OAS3 -|links|✗|OAS3 -|callbacks|✗|OAS3 -|pathItems|✗|OAS3 - -### Data Type Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|Custom|✗|OAS2,OAS3 -|Int32|✓|OAS2,OAS3 -|Int64|✓|OAS2,OAS3 -|Integer|✗|OAS2,OAS3 -|Float|✓|OAS2,OAS3 -|Double|✓|OAS2,OAS3 -|Number|✗|OAS2,OAS3 -|String|✓|OAS2,OAS3 -|Byte|✓|OAS2,OAS3 -|Binary|✓|OAS2,OAS3 -|Boolean|✓|OAS2,OAS3 -|Date|✓|OAS2,OAS3 -|DateTime|✓|OAS2,OAS3 -|Password|✓|OAS2,OAS3 -|File|✓|OAS2 -|Uuid|✗|OAS2,OAS3 -|Array|✓|OAS2,OAS3 -|Null|✗|OAS3 -|AnyType|✗|OAS2,OAS3 -|Object|✓|OAS2,OAS3 -|Enum|✓|OAS2,OAS3 - -### Documentation Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|Readme|✓|ToolingExtension -|Servers|✗|OAS3 -|Security|✗|OAS2,OAS3 -|ComponentSchemas|✓|OAS3 -|ComponentResponses|✗|OAS3 -|ComponentParameters|✗|OAS3 -|ComponentRequestBodies|✗|OAS3 -|ComponentHeaders|✗|OAS3 -|ComponentSecuritySchemes|✗|OAS3 -|ComponentLinks|✗|OAS3 -|ComponentCallbacks|✗|OAS3 -|ComponentPathItems|✗|OAS3 -|Api|✓|ToolingExtension - -### Global Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|Info|✓|OAS2,OAS3 -|Servers|✗|OAS3 -|Paths|✗|OAS2,OAS3 -|Webhooks|✗|OAS3 -|Components|✓|OAS3 -|Security|✗|OAS2,OAS3 -|Tags|✗|OAS2,OAS3 -|ExternalDocs|✗|OAS2,OAS3 - -### Operation Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|Responses_HttpStatusCode|✓|OAS3 -|Responses_RangedResponseCodes|✗|OAS3 -|Responses_Default|✓|OAS3 -|Responses_RedirectionResponse|✗|OAS3 - -### Parameter Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|Name|✗|OAS2,OAS3 -|Required|✗|OAS2,OAS3 -|In_Path|✓|OAS2,OAS3 -|In_Query|✓|OAS2,OAS3 -|In_Header|✓|OAS2,OAS3 -|In_Cookie|✗|OAS3 -|Style_Matrix|✗|OAS3 -|Style_Label|✗|OAS3 -|Style_Form|✗|OAS3 -|Style_Simple|✗|OAS3 -|Style_SpaceDelimited|✗|OAS3 -|Style_PipeDelimited|✗|OAS3 -|Style_DeepObject|✗|OAS3 -|Explode|✗|OAS3 -|Schema|✗|OAS3 -|Content|✗|OAS3 - -### Schema Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|AdditionalProperties|✗|OAS2,OAS3 -|AllOf|✗|OAS2,OAS3 -|AnyOf|✗|OAS3 -|Const|✗|OAS3 -|Contains|✗|OAS3 -|Default|✗|OAS2,OAS3 -|DependentRequired|✗|OAS3 -|DependentSchemas|✗|OAS3 -|Discriminator|✓|OAS2,OAS3 -|Else|✗|OAS3 -|Enum|✓|OAS2,OAS3 -|ExclusiveMinimum|✓|OAS2,OAS3 -|ExclusiveMaximum|✓|OAS2,OAS3 -|Format|✓|OAS2,OAS3 -|If|✗|OAS3 -|Items|✓|OAS2,OAS3 -|MaxContains|✗|OAS3 -|MaxItems|✓|OAS2,OAS3 -|MaxLength|✓|OAS2,OAS3 -|MaxProperties|✓|OAS2,OAS3 -|Maximum|✓|OAS2,OAS3 -|MinContains|✗|OAS3 -|MinItems|✓|OAS2,OAS3 -|MinLength|✓|OAS2,OAS3 -|MinProperties|✓|OAS2,OAS3 -|Minimum|✓|OAS2,OAS3 -|MultipleOf|✓|OAS2,OAS3 -|Not|✗|OAS3 -|Nullable|✗|OAS3 -|OneOf|✗|OAS3 -|Pattern|✓|OAS2,OAS3 -|PatternProperties|✗|OAS3 -|PrefixItems|✗|OAS3 -|Properties|✓|OAS2,OAS3 -|PropertyNames|✗|OAS3 -|Ref|✗|OAS2,OAS3 -|Required|✓|OAS2,OAS3 -|Then|✗|OAS3 -|Type|✓|OAS2,OAS3 -|UnevaluatedItems|✗|OAS3 -|UnevaluatedProperties|✗|OAS3 -|UniqueItems|✓|OAS2,OAS3 -|Xml|✗|OAS2,OAS3 - -### Security Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|HTTP_Basic|✓|OAS2,OAS3 -|ApiKey|✓|OAS2,OAS3 -|OpenIDConnect|✗|OAS3 -|HTTP_Bearer|✓|OAS2,OAS3 -|OAuth2_Implicit|✗|OAS2,OAS3 -|OAuth2_Password|✗|OAS2,OAS3 -|OAuth2_ClientCredentials|✗|OAS2,OAS3 -|OAuth2_AuthorizationCode|✗|OAS2,OAS3 - -### Wire Format Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|JSON|✓|OAS2,OAS3 -|XML|✗|OAS2,OAS3 -|PROTOBUF|✗|ToolingExtension -|Custom|✗|OAS2,OAS3 diff --git a/src/main/java/org/openapijsonschematools/codegen/generators/AbstractJavaJAXRSServerGenerator.java b/src/main/java/org/openapijsonschematools/codegen/generators/AbstractJavaJAXRSServerGenerator.java deleted file mode 100644 index f3bcbc945a8..00000000000 --- a/src/main/java/org/openapijsonschematools/codegen/generators/AbstractJavaJAXRSServerGenerator.java +++ /dev/null @@ -1,196 +0,0 @@ -/* - * 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.openapijsonschematools.codegen.generators; - -import com.google.common.annotations.VisibleForTesting; -import io.swagger.v3.oas.models.OpenAPI; -import io.swagger.v3.oas.models.Operation; -import io.swagger.v3.oas.models.PathItem; -import org.apache.commons.lang3.StringUtils; -import org.openapijsonschematools.codegen.generators.models.CliOption; -import org.openapijsonschematools.codegen.common.CodegenConstants; -import org.openapijsonschematools.codegen.generators.generatormetadata.GeneratorType; -import org.openapijsonschematools.codegen.generators.openapimodels.CodegenOperation; -import org.openapijsonschematools.codegen.generators.features.BeanValidationFeatures; -import org.openapijsonschematools.codegen.common.URLPathUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.net.URL; -import java.util.*; - -public abstract class AbstractJavaJAXRSServerGenerator extends AbstractJavaGenerator implements BeanValidationFeatures { - public static final String SERVER_PORT = "serverPort"; - public static final String USE_TAGS = "useTags"; - - /** - * Name of the sub-directory in "src/main/resource" where to find the - * Mustache template for the JAX-RS Codegen. - */ - protected static final String JAXRS_TEMPLATE_DIRECTORY_NAME = "JavaJaxRS"; - protected String implFolder = "src/main/java"; - protected String testResourcesFolder = "src/test/resources"; - protected String title = "OpenAPI Server"; - protected String serverPort = "8080"; - - protected boolean useBeanValidation = true; - protected boolean useTags = false; - - private final Logger LOGGER = LoggerFactory.getLogger(AbstractJavaJAXRSServerGenerator.class); - - public AbstractJavaJAXRSServerGenerator() { - super(); - - sourceFolder = "src/gen/java"; - invokerPackage = "org.openapijsonschematools.api"; - artifactId = "openapi-jaxrs-server"; - dateLibrary = "legacy"; //TODO: add joda support to all jax-rs - apiPackage = "org.openapijsonschematools.api"; - modelPackage = "org.openapijsonschematools.model"; - - // clioOptions default redefinition need to be updated - updateOption(CodegenConstants.INVOKER_PACKAGE, this.getInvokerPackage()); - updateOption(CodegenConstants.ARTIFACT_ID, this.getArtifactId()); - updateOption(CodegenConstants.API_PACKAGE, apiPackage); - updateOption(CodegenConstants.MODEL_PACKAGE, modelPackage); - updateOption(DATE_LIBRARY, this.getDateLibrary()); - updateOption(CodegenConstants.SOURCE_FOLDER, this.getSourceFolder()); - - additionalProperties.put("title", title); - // java inflector uses the jackson lib - additionalProperties.put(JACKSON, "true"); - - cliOptions.add(new CliOption(CodegenConstants.IMPL_FOLDER, CodegenConstants.IMPL_FOLDER_DESC).defaultValue(implFolder)); - cliOptions.add(new CliOption("title", "a title describing the application").defaultValue(title)); - cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations",useBeanValidation)); - cliOptions.add(new CliOption(SERVER_PORT, "The port on which the server should be started").defaultValue(serverPort)); - cliOptions.add(CliOption.newBoolean(USE_TAGS, "use tags for creating interface and controller classnames")); - } - - - // =============== - // COMMONS METHODS - // =============== - - @Override - public GeneratorType getTag() { - return GeneratorType.SERVER; - } - - @Override - public void processOpts() { - super.processOpts(); - - if (additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER)) { - implFolder = (String) additionalProperties.get(CodegenConstants.IMPL_FOLDER); - } - - if (additionalProperties.containsKey(USE_BEANVALIDATION)) { - setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION)); - } - - if (additionalProperties.containsKey(USE_TAGS)) { - setUseTags(convertPropertyToBoolean(USE_TAGS)); - } - - writePropertyBack(USE_BEANVALIDATION, useBeanValidation); - } - - @Override - public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { - if (useTags) { - super.addOperationToGroup(tag, resourcePath, operation, co, operations); - } - } - - @Override - public void preprocessOpenAPI(OpenAPI openAPI) { - super.preprocessOpenAPI(openAPI); - /* TODO there should be no need for the following logic - if ("/".equals(swagger.getBasePath())) { - swagger.setBasePath(""); - } - */ - - if (!this.additionalProperties.containsKey(SERVER_PORT)) { - URL url = URLPathUtils.getServerURL(openAPI, serverVariableOverrides()); - // 8080 is the default value for a JEE Server: - this.additionalProperties.put(SERVER_PORT, URLPathUtils.getPort(url, serverPort)); - } - - if (openAPI.getPaths() != null) { - for (Map.Entry openAPIGetPathsEntry : openAPI.getPaths().entrySet()) { - String pathname = openAPIGetPathsEntry.getKey(); - PathItem path = openAPIGetPathsEntry.getValue(); - if (path.readOperations() != null) { - for (Operation operation : path.readOperations()) { - if (operation.getTags() != null) { - List> tags = new ArrayList>(); - for (String tag : operation.getTags()) { - Map value = new HashMap(); - value.put("tag", tag); - tags.add(value); - } - if (operation.getTags().size() > 0) { - String tag = operation.getTags().get(0); - operation.setTags(Arrays.asList(tag)); - } - operation.addExtension("x-tags", tags); - } - } - } - } - } - } - - @Override - public String toApiName(final String name) { - String computed = name; - if (computed.length() > 0) { - computed = sanitizeName(computed); - } - return super.toApiName(computed); - } - - private static String getCommonPath(String path1, String path2) { - final String[] parts1 = StringUtils.split(path1, "/"); - final String[] parts2 = StringUtils.split(path2, "/"); - StringBuilder builder = new StringBuilder(); - for (int i = 0; i < Math.min(parts1.length, parts2.length); i++) { - if (!parts1[i].equals(parts2[i])) { - break; - } - builder.append("/").append(parts1[i]); - } - return builder.toString(); - } - - private String implFileFolder(String output) { - return outputFolder + "/" + output + "/" + apiPackage().replace('.', '/'); - } - - @Override - public void setUseBeanValidation(boolean useBeanValidation) { - this.useBeanValidation = useBeanValidation; - } - - @VisibleForTesting - public void setUseTags(boolean useTags) { - this.useTags = useTags; - } -} diff --git a/src/main/java/org/openapijsonschematools/codegen/generators/AbstractKotlinGenerator.java b/src/main/java/org/openapijsonschematools/codegen/generators/AbstractKotlinGenerator.java deleted file mode 100644 index 58b0e9a8f5b..00000000000 --- a/src/main/java/org/openapijsonschematools/codegen/generators/AbstractKotlinGenerator.java +++ /dev/null @@ -1,858 +0,0 @@ -/* - * 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.openapijsonschematools.codegen.generators; - -import io.swagger.v3.oas.models.media.Schema; -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.lang3.StringUtils; -import org.openapijsonschematools.codegen.generators.models.CliOption; -import org.openapijsonschematools.codegen.common.CodegenConstants; -import org.openapijsonschematools.codegen.generators.generatormetadata.GeneratorLanguage; -import org.openapijsonschematools.codegen.generators.openapimodels.CodegenPatternInfo; -import org.openapijsonschematools.codegen.generators.openapimodels.CodegenSchema; -import org.openapijsonschematools.codegen.common.ModelUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.io.IOException; -import java.util.*; -import java.util.regex.Pattern; - -import static org.openapijsonschematools.codegen.common.StringUtils.*; - -public abstract class AbstractKotlinGenerator extends DefaultGenerator implements Generator { - - public static final String SERIALIZATION_LIBRARY_DESC = "What serialization library to use: 'moshi' (default), or 'gson' or 'jackson'"; - - public enum SERIALIZATION_LIBRARY_TYPE {moshi, gson, jackson, kotlinx_serialization} - - public static final String MODEL_MUTABLE = "modelMutable"; - public static final String MODEL_MUTABLE_DESC = "Create mutable models"; - - private final Logger LOGGER = LoggerFactory.getLogger(AbstractKotlinGenerator.class); - - protected String artifactId; - protected String artifactVersion = "1.0.0"; - protected String groupId = "org.openapijsonschematools"; - protected String packageName = "org.openapijsonschematools"; - protected String apiSuffix = "Api"; - - protected String sourceFolder = "src/main/kotlin"; - protected String testFolder = "src/test/kotlin"; - - protected String apiDocPath = "docs/"; - protected String modelDocPath = "docs/"; - protected boolean parcelizeModels = false; - protected boolean serializableModel = false; - protected boolean needsDataClassBody = false; - - protected boolean nonPublicApi = false; - - protected CodegenConstants.ENUM_PROPERTY_NAMING_TYPE enumPropertyNaming = CodegenConstants.ENUM_PROPERTY_NAMING_TYPE.camelCase; - protected SERIALIZATION_LIBRARY_TYPE serializationLibrary = SERIALIZATION_LIBRARY_TYPE.moshi; - - // model classes cannot use the same property names defined in HashMap - // ref: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-hash-map/ - protected Set propertyAdditionalKeywords = new HashSet<>(Arrays.asList("entries", "keys", "size", "values")); - - private Map schemaKeyToModelNameCache = new HashMap<>(); - - public AbstractKotlinGenerator() { - super(); - - supportsInheritance = true; - setSortModelPropertiesByRequiredFlag(true); - - languageSpecificPrimitives = new HashSet<>(Arrays.asList( - "kotlin.Byte", - "kotlin.ByteArray", - "kotlin.Short", - "kotlin.Int", - "kotlin.Long", - "kotlin.Float", - "kotlin.Double", - "kotlin.Boolean", - "kotlin.Char", - "kotlin.String", - "kotlin.Array", - "kotlin.collections.List", - "kotlin.collections.MutableList", - "kotlin.collections.Map", - "kotlin.collections.MutableMap", - "kotlin.collections.Set", - "kotlin.collections.MutableSet" - )); - - // this includes hard reserved words defined by https://github.com/JetBrains/kotlin/blob/master/core/descriptors/src/org/jetbrains/kotlin/renderer/KeywordStringsGenerated.java - // as well as keywords from https://kotlinlang.org/docs/reference/keyword-reference.html - reservedWords = new HashSet<>(Arrays.asList( - "ApiResponse", // Used in the auto-generated api client - "abstract", - "actual", - "annotation", - "as", - "break", - "class", - "companion", - "const", - "constructor", - "continue", - "contract", - "crossinline", - "data", - "delegate", - "do", - "dynamic", - "else", - "enum", - "expect", - "external", - "false", - "field", - "final", - "finally", - "for", - "fun", - "if", - "import", - "in", - "infix", - "init", - "inline", - "inner", - "interface", - "internal", - "is", - "it", - "lateinit", - "noinline", - "null", - "object", - "open", - "operator", - "out", - "override", - "package", - "param", - "private", - "property", - "protected", - "public", - "receiver", - "reified", - "return", - "sealed", - "setparam", - "super", - "suspend", - "tailrec", - "this", - "throw", - "true", - "try", - "typealias", - "typeof", - "val", - "value", - "var", - "vararg", - "when", - "where", - "while" - )); - - defaultIncludes = new HashSet<>(Arrays.asList( - "kotlin.Byte", - "kotlin.ByteArray", - "kotlin.Short", - "kotlin.Int", - "kotlin.Long", - "kotlin.Float", - "kotlin.Double", - "kotlin.Boolean", - "kotlin.Char", - "kotlin.Array", - "kotlin.collections.List", - "kotlin.collections.MutableList", - "kotlin.collections.Set", - "kotlin.collections.MutableSet", - "kotlin.collections.Map", - "kotlin.collections.MutableMap" - )); - - typeMapping = new HashMap<>(); - typeMapping.put("string", "kotlin.String"); - typeMapping.put("boolean", "kotlin.Boolean"); - typeMapping.put("integer", "kotlin.Int"); - typeMapping.put("float", "kotlin.Float"); - typeMapping.put("long", "kotlin.Long"); - typeMapping.put("double", "kotlin.Double"); - typeMapping.put("ByteArray", "kotlin.ByteArray"); - typeMapping.put("number", "java.math.BigDecimal"); - typeMapping.put("decimal", "java.math.BigDecimal"); - typeMapping.put("date-time", "java.time.OffsetDateTime"); - typeMapping.put("date", "java.time.LocalDate"); - typeMapping.put("file", "java.io.File"); - typeMapping.put("array", "kotlin.Array"); - typeMapping.put("list", "kotlin.collections.List"); - typeMapping.put("set", "kotlin.collections.Set"); - typeMapping.put("map", "kotlin.collections.Map"); - typeMapping.put("object", "kotlin.Any"); - typeMapping.put("binary", "kotlin.ByteArray"); - typeMapping.put("Date", "java.time.LocalDate"); - typeMapping.put("DateTime", "java.time.OffsetDateTime"); - typeMapping.put("AnyType", "kotlin.Any"); - - instantiationTypes.put("array", "kotlin.collections.ArrayList"); - instantiationTypes.put("list", "kotlin.collections.ArrayList"); - instantiationTypes.put("map", "kotlin.collections.HashMap"); - - specialCharReplacements.put(";", "Semicolon"); - - cliOptions.clear(); - addOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC, sourceFolder); - addOption(CodegenConstants.PACKAGE_NAME, "Generated artifact package name.", packageName); - addOption(CodegenConstants.API_SUFFIX, CodegenConstants.API_SUFFIX_DESC, apiSuffix); - addOption(CodegenConstants.GROUP_ID, "Generated artifact package's organization (i.e. maven groupId).", groupId); - addOption(CodegenConstants.ARTIFACT_ID, "Generated artifact id (name of jar).", artifactId); - addOption(CodegenConstants.ARTIFACT_VERSION, "Generated artifact's package version.", artifactVersion); - - CliOption enumPropertyNamingOpt = new CliOption(CodegenConstants.ENUM_PROPERTY_NAMING, CodegenConstants.ENUM_PROPERTY_NAMING_DESC); - cliOptions.add(enumPropertyNamingOpt.defaultValue(enumPropertyNaming.name())); - - CliOption serializationLibraryOpt = new CliOption(CodegenConstants.SERIALIZATION_LIBRARY, SERIALIZATION_LIBRARY_DESC); - cliOptions.add(serializationLibraryOpt.defaultValue(serializationLibrary.name())); - - cliOptions.add(new CliOption(CodegenConstants.PARCELIZE_MODELS, CodegenConstants.PARCELIZE_MODELS_DESC)); - cliOptions.add(new CliOption(CodegenConstants.SERIALIZABLE_MODEL, CodegenConstants.SERIALIZABLE_MODEL_DESC)); - cliOptions.add(new CliOption(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC)); - cliOptions.add(new CliOption(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG_DESC)); - - cliOptions.add(CliOption.newBoolean(MODEL_MUTABLE, MODEL_MUTABLE_DESC, false)); - } - - @Override - public String apiDocFileFolder() { - return (outputFolder + File.separator + apiDocPath).replace('/', File.separatorChar); - } - - @Override - public String apiFileFolder() { - return (outputFolder + File.separator + sourceFolder + File.separator + apiPackage().replace('.', File.separatorChar)).replace('/', File.separatorChar); - } - - @Override - public String apiTestFileFolder() { - return (outputFolder + File.separator + testFolder + File.separator + apiPackage().replace('.', File.separatorChar)).replace('/', File.separatorChar); - } - - @Override - public String escapeQuotationMark(String input) { - // remove " to avoid code injection - return input.replace("\"", ""); - } - - @Override - public String escapeReservedWord(String name) { - // TODO: Allow enum escaping as an option (e.g. backticks vs append/prepend underscore vs match model property escaping). - return String.format(Locale.ROOT, "`%s`", name); - } - - @Override - public String escapeUnsafeCharacters(String input) { - return input.replace("*/", "*_/").replace("/*", "/_*"); - } - - public CodegenConstants.ENUM_PROPERTY_NAMING_TYPE getEnumPropertyNaming() { - return this.enumPropertyNaming; - } - - public SERIALIZATION_LIBRARY_TYPE getSerializationLibrary() { - return this.serializationLibrary; - } - - /** - * Sets the naming convention for Kotlin enum properties - * - * @param enumPropertyNamingType The string representation of the naming convention, as defined by CodegenConstants.ENUM_PROPERTY_NAMING_TYPE - */ - public void setEnumPropertyNaming(final String enumPropertyNamingType) { - try { - this.enumPropertyNaming = CodegenConstants.ENUM_PROPERTY_NAMING_TYPE.valueOf(enumPropertyNamingType); - } catch (IllegalArgumentException ex) { - StringBuilder sb = new StringBuilder(enumPropertyNamingType + " is an invalid enum property naming option. Please choose from:"); - for (CodegenConstants.ENUM_PROPERTY_NAMING_TYPE t : CodegenConstants.ENUM_PROPERTY_NAMING_TYPE.values()) { - sb.append("\n ").append(t.name()); - } - throw new RuntimeException(sb.toString()); - } - } - - /** - * Sets the serialization engine for Kotlin - * - * @param enumSerializationLibrary The string representation of the serialization library as defined by - * {@link AbstractKotlinGenerator.SERIALIZATION_LIBRARY_TYPE} - */ - public void setSerializationLibrary(final String enumSerializationLibrary) { - try { - this.serializationLibrary = SERIALIZATION_LIBRARY_TYPE.valueOf(enumSerializationLibrary); - } catch (IllegalArgumentException ex) { - StringBuilder sb = new StringBuilder(enumSerializationLibrary + " is an invalid enum property naming option. Please choose from:"); - for (SERIALIZATION_LIBRARY_TYPE t : SERIALIZATION_LIBRARY_TYPE.values()) { - sb.append("\n ").append(t.name()); - } - throw new RuntimeException(sb.toString()); - } - } - - @Override - public TreeMap postProcessModels(TreeMap models) { - for (CodegenSchema cm : models.values()) { - if (cm.discriminator != null) { - cm.vendorExtensions.put("x-has-data-class-body", true); - break; - } - - for (CodegenSchema var : cm.properties.values()) { - if (var.enumInfo != null || isSerializableModel()) { - cm.vendorExtensions.put("x-has-data-class-body", true); - break; - } - } - } - return models; - } - - @Override - public void processOpts() { - super.processOpts(); - - if (StringUtils.isEmpty(System.getenv("KOTLIN_POST_PROCESS_FILE"))) { - LOGGER.info("Environment variable KOTLIN_POST_PROCESS_FILE not defined so the Kotlin code may not be properly formatted. To define it, try 'export KOTLIN_POST_PROCESS_FILE=\"/usr/local/bin/ktlint -F\"' (Linux/Mac)"); - LOGGER.info("NOTE: To enable file post-processing, 'enablePostProcessFile' must be set to `true` (--enable-post-process-file for CLI)."); - } - - if (additionalProperties.containsKey(MODEL_MUTABLE)) { - additionalProperties.put(MODEL_MUTABLE, Boolean.parseBoolean(additionalProperties.get(MODEL_MUTABLE).toString())); - } - - if (additionalProperties.containsKey(CodegenConstants.ENUM_PROPERTY_NAMING)) { - setEnumPropertyNaming((String) additionalProperties.get(CodegenConstants.ENUM_PROPERTY_NAMING)); - } - - if (additionalProperties.containsKey(CodegenConstants.SERIALIZATION_LIBRARY)) { - setSerializationLibrary((String) additionalProperties.get(CodegenConstants.SERIALIZATION_LIBRARY)); - additionalProperties.put(this.serializationLibrary.name(), true); - } else { - additionalProperties.put(this.serializationLibrary.name(), true); - } - - if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) { - this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); - } else { - additionalProperties.put(CodegenConstants.SOURCE_FOLDER, sourceFolder); - } - - if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { - this.setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); - if (!additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) - this.setModelPackage(packageName + ".models"); - if (!additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) - this.setApiPackage(packageName + ".apis"); - } else { - additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); - } - - if (additionalProperties.containsKey(CodegenConstants.API_SUFFIX)) { - this.setApiSuffix((String) additionalProperties.get(CodegenConstants.API_SUFFIX)); - } - - if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_ID)) { - this.setArtifactId((String) additionalProperties.get(CodegenConstants.ARTIFACT_ID)); - } else { - additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); - } - - if (additionalProperties.containsKey(CodegenConstants.GROUP_ID)) { - this.setGroupId((String) additionalProperties.get(CodegenConstants.GROUP_ID)); - } else { - additionalProperties.put(CodegenConstants.GROUP_ID, groupId); - } - - if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_VERSION)) { - this.setArtifactVersion((String) additionalProperties.get(CodegenConstants.ARTIFACT_VERSION)); - } else { - additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); - } - - if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { - LOGGER.warn("{} with {} generator is ignored. Use {}.", CodegenConstants.INVOKER_PACKAGE, this.getName(), CodegenConstants.PACKAGE_NAME); - } - - if (additionalProperties.containsKey(CodegenConstants.SERIALIZABLE_MODEL)) { - this.setSerializableModel(convertPropertyToBooleanAndWriteBack(CodegenConstants.SERIALIZABLE_MODEL)); - } else { - additionalProperties.put(CodegenConstants.SERIALIZABLE_MODEL, serializableModel); - } - - if (additionalProperties.containsKey(CodegenConstants.LIBRARY)) { - this.setLibrary((String) additionalProperties.get(CodegenConstants.LIBRARY)); - } - - if (additionalProperties.containsKey(CodegenConstants.PARCELIZE_MODELS)) { - this.setParcelizeModels(convertPropertyToBooleanAndWriteBack(CodegenConstants.PARCELIZE_MODELS)); - } else { - additionalProperties.put(CodegenConstants.PARCELIZE_MODELS, parcelizeModels); - } - - if (additionalProperties.containsKey(CodegenConstants.NON_PUBLIC_API)) { - this.setNonPublicApi(convertPropertyToBooleanAndWriteBack(CodegenConstants.NON_PUBLIC_API)); - } else { - additionalProperties.put(CodegenConstants.NON_PUBLIC_API, nonPublicApi); - } - - additionalProperties.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, getSortParamsByRequiredFlag()); - additionalProperties.put(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, getSortModelPropertiesByRequiredFlag()); - - additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage()); - additionalProperties.put(CodegenConstants.MODEL_PACKAGE, modelPackage()); - - additionalProperties.put("apiDocPath", apiDocPath); - additionalProperties.put("modelDocPath", modelDocPath); - - if (isModelMutable()) { - typeMapping.put("list", "kotlin.collections.MutableList"); - typeMapping.put("set", "kotlin.collections.MutableSet"); - typeMapping.put("map", "kotlin.collections.MutableMap"); - } - } - - protected boolean isModelMutable() { - return Boolean.TRUE.equals(additionalProperties.get(MODEL_MUTABLE)); - } - - public void setArtifactId(String artifactId) { - this.artifactId = artifactId; - } - - public void setArtifactVersion(String artifactVersion) { - this.artifactVersion = artifactVersion; - } - - public void setGroupId(String groupId) { - this.groupId = groupId; - } - - public void setPackageName(String packageName) { - this.packageName = packageName; - } - - public void setApiSuffix(String apiSuffix) { - this.apiSuffix = apiSuffix; - } - - public void setSourceFolder(String sourceFolder) { - this.sourceFolder = sourceFolder; - } - - public void setTestFolder(String testFolder) { - this.testFolder = testFolder; - } - - public Boolean getParcelizeModels() { - return parcelizeModels; - } - - public void setParcelizeModels(Boolean parcelizeModels) { - this.parcelizeModels = parcelizeModels; - } - - public boolean isSerializableModel() { - return serializableModel; - } - - public void setSerializableModel(boolean serializableModel) { - this.serializableModel = serializableModel; - } - - public boolean nonPublicApi() { - return nonPublicApi; - } - - public void setNonPublicApi(boolean nonPublicApi) { - this.nonPublicApi = nonPublicApi; - } - - public boolean isNeedsDataClassBody() { - return needsDataClassBody; - } - - public void setNeedsDataClassBody(boolean needsDataClassBody) { - this.needsDataClassBody = needsDataClassBody; - } - - /** - * Return the sanitized variable name for enum - * - * @param value enum variable name - * @param prop property - * @return the sanitized variable name for enum - */ - @Override - public String toEnumVarName(String value, Schema prop) { - String modified; - if (value.length() == 0) { - modified = "EMPTY"; - } else { - modified = value; - modified = sanitizeKotlinSpecificNames(modified); - } - - switch (getEnumPropertyNaming()) { - case original: - // NOTE: This is provided as a last-case allowance, but will still result in reserved words being escaped. - modified = value; - break; - case camelCase: - // NOTE: Removes hyphens and underscores - modified = camelize(modified, true); - break; - case PascalCase: - // NOTE: Removes hyphens and underscores - String result = camelize(modified); - modified = titleCase(result); - break; - case snake_case: - // NOTE: Removes hyphens - modified = underscore(modified); - break; - case UPPERCASE: - modified = underscore(modified).toUpperCase(Locale.ROOT); - break; - } - - if (reservedWords.contains(modified)) { - return escapeReservedWord(modified); - } - // NOTE: another sanitize because camelize can create an invalid name - return sanitizeKotlinSpecificNames(modified); - } - - @Override - public String toApiName(String name) { - if (name.length() == 0) { - return "DefaultApi"; - } - return (this.apiSuffix.isEmpty() ? camelize(name) : camelize(name) + this.apiSuffix); - } - - /** - * Return the fully-qualified "Model" name for import - * - * @param name the name of the "Model" - * @return the fully-qualified "Model" name for import - */ - @Override - public String toModelImport(String name) { - // toModelImport is called while processing operations, but DefaultGenerator doesn't - // define imports correctly with fully qualified primitives and models as defined in this generator. - if (needToImport(name)) { - return super.toModelImport(name); - } - - return name; - } - - /** - * Output the proper model name (capitalized). - * In case the name belongs to the TypeSystem it won't be renamed. - * - * @param name the name of the model - * @return capitalized model name - */ - @Override - public String toModelName(final String name, String jsonPath) { - // memoization - String origName = name; - if (schemaKeyToModelNameCache.containsKey(origName)) { - return schemaKeyToModelNameCache.get(origName); - } - - // Allow for explicitly configured kotlin.* and java.* types - if (name.startsWith("kotlin.") || name.startsWith("java.")) { - return name; - } - - // If schemaMapping contains name, assume this is a legitimate model name. - if (schemaMapping.containsKey(name)) { - return schemaMapping.get(name); - } - - String modifiedName = name.replaceAll("\\.", ""); - String sanitizedName = sanitizeKotlinSpecificNames(modifiedName); - - String nameWithPrefixSuffix = sanitizedName; - if (!StringUtils.isEmpty(modelNamePrefix)) { - // add '_' so that model name can be camelized correctly - nameWithPrefixSuffix = modelNamePrefix + "_" + nameWithPrefixSuffix; - } - - if (!StringUtils.isEmpty(modelNameSuffix)) { - // add '_' so that model name can be camelized correctly - nameWithPrefixSuffix = nameWithPrefixSuffix + "_" + modelNameSuffix; - } - - // Camelize name of nested properties - modifiedName = camelize(nameWithPrefixSuffix); - - // model name cannot use reserved keyword, e.g. return - if (isReservedWord(modifiedName)) { - final String modelName = "Model" + modifiedName; - LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", modifiedName, modelName); - return modelName; - } - - // model name starts with number - if (modifiedName.matches("^\\d.*")) { - final String modelName = "Model" + modifiedName; // e.g. 200Response => Model200Response (after camelize) - LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name, - modelName); - return modelName; - } - - schemaKeyToModelNameCache.put(origName, titleCase(modifiedName)); - return schemaKeyToModelNameCache.get(origName); - } - - @Override - public String toModelFilename(String name, String jsonPath) { - // Should be the same as the model name - return toModelName(name, jsonPath); - } - - /** - * Sanitize against Kotlin specific naming conventions, which may differ from those required by {@link DefaultGenerator#sanitizeName}. - * - * @param name string to be sanitize - * @return sanitized string - */ - private String sanitizeKotlinSpecificNames(final String name) { - String word = name; - for (Map.Entry specialCharacters : specialCharReplacements.entrySet()) { - word = replaceSpecialCharacters(word, specialCharacters); - } - - // Fallback, replace unknowns with underscore. - word = Pattern.compile("\\W+", Pattern.UNICODE_CHARACTER_CLASS).matcher(word).replaceAll("_"); - if (word.matches("\\d.*")) { - word = "_" + word; - } - - // _, __, and ___ are reserved in Kotlin. Treat all names with only underscores consistently, regardless of count. - if (word.matches("^_*$")) { - word = word.replaceAll("\\Q_\\E", "Underscore"); - } - - return word; - } - - private String replaceSpecialCharacters(String word, Map.Entry specialCharacters) { - String specialChar = specialCharacters.getKey(); - String replacementChar = specialCharacters.getValue(); - // Underscore is the only special character we'll allow - if (!specialChar.equals("_") && word.contains(specialChar)) { - return replaceCharacters(word, specialChar, replacementChar); - } - return word; - } - - private String replaceCharacters(String word, String oldValue, String newValue) { - if (!word.contains(oldValue)) { - return word; - } - if (word.equals(oldValue)) { - return newValue; - } - int i = word.indexOf(oldValue); - String start = word.substring(0, i); - String end = recurseOnEndOfWord(word, oldValue, newValue, i); - return start + newValue + end; - } - - private String recurseOnEndOfWord(String word, String oldValue, String newValue, int lastReplacedValue) { - String end = word.substring(lastReplacedValue + 1); - if (!end.isEmpty()) { - end = titleCase(end); - end = replaceCharacters(end, oldValue, newValue); - } - return end; - } - - private String titleCase(final String input) { - return input.substring(0, 1).toUpperCase(Locale.ROOT) + input.substring(1); - } - - @Override - protected boolean isReservedWord(String word) { - // We want case-sensitive escaping, to avoid unnecessary backtick-escaping. - return reservedWords.contains(word); - } - - /** - * Check the type to see if it needs import the library/module/package - * - * @param type name of the type - * @return true if the library/module/package of the corresponding type needs to be imported - */ - @Override - protected boolean needToImport(String type) { - // provides extra protection against improperly trying to import language primitives and java types - boolean imports = !type.startsWith("kotlin.") && !type.startsWith("java.") && - !defaultIncludes.contains(type) && !languageSpecificPrimitives.contains(type) && - !type.contains("."); - return imports; - } - - @Override - public String toParamName(String name) { - // to avoid conflicts with 'callback' parameter for async call - if ("callback".equals(name)) { - return "paramCallback"; - } - - // should be the same as variable name - return toVariableName(name); - } - - @Override - public String toVarName(String name) { - name = toVariableName(name); - if (propertyAdditionalKeywords.contains(name)) { - return camelize("property_" + name, true); - } else { - return name; - } - } - - protected String toVariableName(String name) { - // sanitize name - name = sanitizeName(name, "\\W-[\\$]"); - name = sanitizeKotlinSpecificNames(name); - - if (name.toLowerCase(Locale.ROOT).matches("^_*class$")) { - return "propertyClass"; - } - - if ("_".equals(name)) { - name = "_u"; - } - - // if it's all upper case, do nothing - if (name.matches("^[A-Z0-9_]*$")) { - return name; - } - - if (startsWithTwoUppercaseLetters(name)) { - name = name.substring(0, 2).toLowerCase(Locale.ROOT) + name.substring(2); - } - - // If name contains special chars -> replace them. - if ((name.chars().anyMatch(character -> specialCharReplacements.keySet().contains(String.valueOf((char) character))))) { - List allowedCharacters = new ArrayList<>(); - allowedCharacters.add("_"); - allowedCharacters.add("$"); - name = escape(name, specialCharReplacements, allowedCharacters, "_"); - } - - // camelize (lower first character) the variable name - // pet_id => petId - name = camelize(name, true); - - // for reserved word or word starting with number or containing dollar symbol, escape it - if (isReservedWord(name) || name.matches("(^\\d.*)|(.*[$].*)")) { - name = escapeReservedWord(name); - } - - return name; - } - - @Override - public CodegenPatternInfo getPatternInfo(String pattern) { - return new CodegenPatternInfo(escapeText(pattern), null); - } - - private boolean startsWithTwoUppercaseLetters(String name) { - boolean startsWithTwoUppercaseLetters = false; - if (name.length() > 1) { - startsWithTwoUppercaseLetters = name.substring(0, 2).equals(name.substring(0, 2).toUpperCase(Locale.ROOT)); - } - return startsWithTwoUppercaseLetters; - } - - @Override - public void postProcessFile(File file, String fileType) { - if (file == null) { - return; - } - - String kotlinPostProcessFile = System.getenv("KOTLIN_POST_PROCESS_FILE"); - if (StringUtils.isEmpty(kotlinPostProcessFile)) { - return; // skip if KOTLIN_POST_PROCESS_FILE env variable is not defined - } - - // only process files with kt extension - if ("kt".equals(FilenameUtils.getExtension(file.toString()))) { - String command = kotlinPostProcessFile + " " + file; - try { - Process p = Runtime.getRuntime().exec(command); - p.waitFor(); - int exitValue = p.exitValue(); - if (exitValue != 0) { - LOGGER.error("Error running the command ({}). Exit value: {}", command, exitValue); - } else { - LOGGER.info("Successfully executed: {}", command); - } - } catch (InterruptedException | IOException e) { - LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage()); - // Restore interrupted state - Thread.currentThread().interrupt(); - } - } - } - - private String fixNumberValue(String number, Schema p) { - if (ModelUtils.isFloatSchema(p)) { - return number + "f"; - } else if (ModelUtils.isDoubleSchema(p)) { - if (number.contains(".")) { - return number; - } - return number + ".0"; - } else if (ModelUtils.isLongSchema(p)) { - return number + "L"; - } - return number; - } - - @Override - public GeneratorLanguage generatorLanguage() { - return GeneratorLanguage.KOTLIN; - } -} diff --git a/src/main/java/org/openapijsonschematools/codegen/generators/DefaultGenerator.java b/src/main/java/org/openapijsonschematools/codegen/generators/DefaultGenerator.java index a3fb44acc14..7a33da4c9d4 100644 --- a/src/main/java/org/openapijsonschematools/codegen/generators/DefaultGenerator.java +++ b/src/main/java/org/openapijsonschematools/codegen/generators/DefaultGenerator.java @@ -171,18 +171,10 @@ public class DefaultGenerator implements Generator { GlobalFeature.Components ) .includeSchemaFeatures( - SchemaFeature.Discriminator, SchemaFeature.Enum, - SchemaFeature.ExclusiveMaximum, SchemaFeature.ExclusiveMinimum, - SchemaFeature.Format, SchemaFeature.Items, - SchemaFeature.MaxItems, SchemaFeature.MaxLength, - SchemaFeature.MaxProperties, SchemaFeature.Maximum, - SchemaFeature.MinItems, SchemaFeature.MinLength, - SchemaFeature.MinProperties, SchemaFeature.Minimum, - SchemaFeature.MultipleOf, - SchemaFeature.Pattern, SchemaFeature.Properties, - SchemaFeature.Required, SchemaFeature.Type, - SchemaFeature.UniqueItems - // Union (OneOf) not 100% yet. + SchemaFeature.Type, SchemaFeature.Format, + SchemaFeature.Items, SchemaFeature.Properties, + SchemaFeature.Required, SchemaFeature.AdditionalProperties, + SchemaFeature.Ref ) .includeParameterFeatures( ParameterFeature.In_Path, ParameterFeature.In_Query, ParameterFeature.In_Header, diff --git a/src/main/java/org/openapijsonschematools/codegen/generators/JMeterClientGenerator.java b/src/main/java/org/openapijsonschematools/codegen/generators/JMeterClientGenerator.java deleted file mode 100644 index 372f804ae4a..00000000000 --- a/src/main/java/org/openapijsonschematools/codegen/generators/JMeterClientGenerator.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * 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.openapijsonschematools.codegen.generators; - -import io.swagger.v3.oas.models.OpenAPI; -import io.swagger.v3.oas.models.Operation; -import io.swagger.v3.oas.models.PathItem; -import org.openapijsonschematools.codegen.generators.generatormetadata.GeneratorType; -import org.openapijsonschematools.codegen.generators.generatormetadata.features.ClientModificationFeature; -import org.openapijsonschematools.codegen.generators.generatormetadata.features.ParameterFeature; -import org.openapijsonschematools.codegen.generators.generatormetadata.features.SchemaFeature; -import org.openapijsonschematools.codegen.generators.generatormetadata.features.SecurityFeature; -import org.openapijsonschematools.codegen.generators.generatormetadata.features.WireFormatFeature; - -import java.io.File; -import java.util.Arrays; -import java.util.EnumSet; -import java.util.HashSet; -import java.util.Map; - -public class JMeterClientGenerator extends DefaultGenerator implements Generator { - - // source folder where to write the files - protected String sourceFolder = ""; - protected String apiVersion = "1.0.0"; - - /** - * Configures the type of generator. - * - * @return the GeneratorType for this generator - * @see GeneratorType - */ - @Override - public GeneratorType getTag() { - return GeneratorType.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 "jmeter"; - } - - /** - * 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 JMeter .jmx file."; - } - - public JMeterClientGenerator() { - super(); - - modifyFeatureSet(features -> features - .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML)) - .securityFeatures(EnumSet.of( - SecurityFeature.HTTP_Basic, - SecurityFeature.ApiKey, - SecurityFeature.OAuth2_Implicit - )) - .excludeSchemaFeatures( - SchemaFeature.Not - ) - .includeParameterFeatures( - ParameterFeature.In_Cookie - ) - .includeClientModificationFeatures( - ClientModificationFeature.BasePath - ) - ); - - // set the output folder here - outputFolder = "generated-code/JMeterClientGenerator"; - - /* - * Api classes. You can write classes for each Api file with the apiTemplateFiles map. - * as with models, add multiple entries with different extensions for multiple files per - * class - */ - - /* - * Template Location. This is the location which templates will be read from. The generator - * will use the resource stream to attempt to read the templates. - */ - embeddedTemplateDir = templateDir = "jmeter-client"; - - /* - * Api Package. Optional, if needed, this can be used in templates - */ - apiPackage = ""; - - /* - * Model Package. Optional, if needed, this can be used in templates - */ - modelPackage = ""; - - /* - * Reserved words. Override this with reserved words specific to your language - */ - reservedWords = new HashSet<>( - Arrays.asList( - "sample1", // replace with static values - "sample2") - ); - - /* - * Additional Properties. These values can be passed to the templates and - * are available in models, apis, and supporting files - */ - additionalProperties.put("apiVersion", apiVersion); - // supportingFiles.add(new SupportingFile("testdata-localhost.mustache", "input", "testdata-localhost.csv")); - } - - @Override - public void preprocessOpenAPI(OpenAPI openAPI) { - if (openAPI != null && openAPI.getPaths() != null) { - for (Map.Entry openAPIGetPathsEntry : openAPI.getPaths().entrySet()) { - String pathname = openAPIGetPathsEntry.getKey(); - PathItem path = openAPIGetPathsEntry.getValue(); - if (path.readOperations() != null) { - for (Operation operation : path.readOperations()) { - String pathWithDollars = pathname.replaceAll("\\{", "\\$\\{"); - operation.addExtension("x-path", pathWithDollars); - } - } - } - } - } - - /** - * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping - * those terms here. This logic is only called if a variable matches the reserved words - * - * @return the escaped term - */ - @Override - public String escapeReservedWord(String name) { - if (this.reservedWordsMappings().containsKey(name)) { - return this.reservedWordsMappings().get(name); - } - return "_" + name; - } - - /** - * 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 + sourceFolder + File.separator + apiPackage().replace('.', File.separatorChar); - } - - @Override - public String escapeQuotationMark(String input) { - // remove ' to avoid code injection - return input.replace("'", ""); - } - - @Override - public String escapeUnsafeCharacters(String input) { - return input.replace("*/", "*_/").replace("/*", "/_*"); - } - -} diff --git a/src/main/java/org/openapijsonschematools/codegen/generators/JavaClientGenerator.java b/src/main/java/org/openapijsonschematools/codegen/generators/JavaClientGenerator.java index 732449bb872..8c3860046f4 100644 --- a/src/main/java/org/openapijsonschematools/codegen/generators/JavaClientGenerator.java +++ b/src/main/java/org/openapijsonschematools/codegen/generators/JavaClientGenerator.java @@ -17,7 +17,6 @@ package org.openapijsonschematools.codegen.generators; -import org.apache.commons.lang3.StringUtils; import org.openapijsonschematools.codegen.common.ModelUtils; import org.openapijsonschematools.codegen.generators.generatormetadata.FeatureSet; import org.openapijsonschematools.codegen.generators.generatormetadata.Stability; @@ -26,7 +25,6 @@ import org.openapijsonschematools.codegen.common.CodegenConstants; import org.openapijsonschematools.codegen.generators.generatormetadata.GeneratorType; import org.openapijsonschematools.codegen.generators.models.VendorExtension; -import org.openapijsonschematools.codegen.generators.openapimodels.CodegenDiscriminator; import org.openapijsonschematools.codegen.generators.openapimodels.CodegenHeader; import org.openapijsonschematools.codegen.generators.openapimodels.CodegenKey; import org.openapijsonschematools.codegen.generators.openapimodels.CodegenParameter; @@ -53,9 +51,6 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -import static com.google.common.base.CaseFormat.LOWER_CAMEL; -import static com.google.common.base.CaseFormat.UPPER_UNDERSCORE; -import static java.util.Collections.sort; import static org.openapijsonschematools.codegen.common.StringUtils.camelize; public class JavaClientGenerator extends AbstractJavaGenerator @@ -185,7 +180,50 @@ public JavaClientGenerator() { // TODO: Move GlobalFeature.ParameterizedServer to library: jersey after moving featureSet to generatorMetadata modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) - .includeSchemaFeatures(SchemaFeature.AllOf, SchemaFeature.AnyOf, SchemaFeature.OneOf, SchemaFeature.Not, SchemaFeature.Ref) + .includeSchemaFeatures( + SchemaFeature.AdditionalProperties, + SchemaFeature.AllOf, + SchemaFeature.AnyOf, + // SchemaFeature.Const, + // SchemaFeature.Contains, + // SchemaFeature.Default, + // SchemaFeature.DependentRequired, + // SchemaFeature.DependentSchemas, + // SchemaFeature.Discriminator, + // SchemaFeature.Else, + // SchemaFeature.Enum, + SchemaFeature.ExclusiveMaximum, + SchemaFeature.ExclusiveMinimum, + SchemaFeature.Format, + // SchemaFeature.If, + SchemaFeature.Items, + // SchemaFeature.MaxContains, + SchemaFeature.MaxItems, + SchemaFeature.MaxLength, + SchemaFeature.MaxProperties, + SchemaFeature.Maximum, + // SchemaFeature.MinContains, + SchemaFeature.MinItems, + SchemaFeature.MinLength, + SchemaFeature.MinProperties, + SchemaFeature.Minimum, + SchemaFeature.MultipleOf, + SchemaFeature.Not, + SchemaFeature.Nullable, + SchemaFeature.OneOf, + // SchemaFeature.Pattern, + // SchemaFeature.PatternProperties, + // SchemaFeature.PrefixItems, + SchemaFeature.Properties, + // SchemaFeature.PropertyNames, + SchemaFeature.Ref, + SchemaFeature.Required, + // SchemaFeature.Then, + SchemaFeature.Type, + // SchemaFeature.UnevaluatedItems, + // SchemaFeature.UnevaluatedProperties, + SchemaFeature.UniqueItems + ) ); outputFolder = "generated-code" + File.separator + "java"; diff --git a/src/main/java/org/openapijsonschematools/codegen/generators/JavaJerseyServerGenerator.java b/src/main/java/org/openapijsonschematools/codegen/generators/JavaJerseyServerGenerator.java deleted file mode 100644 index 7e3885bdc06..00000000000 --- a/src/main/java/org/openapijsonschematools/codegen/generators/JavaJerseyServerGenerator.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * 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.openapijsonschematools.codegen.generators; - -import org.apache.commons.lang3.StringUtils; -import org.openapijsonschematools.codegen.generators.models.CliOption; -import org.openapijsonschematools.codegen.common.CodegenConstants; -import org.openapijsonschematools.codegen.generators.openapimodels.CodegenSchema; -import org.openapijsonschematools.codegen.templating.SupportingFile; -import org.openapijsonschematools.codegen.generators.generatormetadata.features.DocumentationFeature; - -import java.util.HashMap; -import java.util.Map; - -public class JavaJerseyServerGenerator extends AbstractJavaJAXRSServerGenerator { - - protected static final String LIBRARY_JERSEY1 = "jersey1"; - protected static final String LIBRARY_JERSEY2 = "jersey2"; - - /** - * Default library template to use. (Default: jersey2) - */ - public static final String DEFAULT_JERSEY_LIBRARY = LIBRARY_JERSEY2; - - public JavaJerseyServerGenerator() { - super(); - - modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme)); - - outputFolder = "generated-code/JavaJaxRS-Jersey"; - - apiTestTemplateFiles.clear(); // TODO: add test template - - // clear model and api doc template as this codegen - // does not support auto-generated markdown doc at the moment - //TODO: add doc templates - Map modelDocTemplates = jsonPathDocTemplateFiles.get( - CodegenConstants.JSON_PATH_LOCATION_TYPE.SCHEMA - ); - if (modelDocTemplates != null) { - modelDocTemplates.remove("model_doc.mustache"); - } - HashMap temp = (HashMap) jsonPathDocTemplateFiles.get( - CodegenConstants.JSON_PATH_LOCATION_TYPE.API_TAG - ); -// temp.remove("api_doc.mustache"); - embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME; - - CliOption library = new CliOption(CodegenConstants.LIBRARY, CodegenConstants.LIBRARY_DESC).defaultValue(DEFAULT_JERSEY_LIBRARY); - supportedLibraries.put(LIBRARY_JERSEY1, "Jersey core 1.x"); - supportedLibraries.put(LIBRARY_JERSEY2, "Jersey core 2.x"); - library.setEnum(supportedLibraries); - - cliOptions.add(library); - cliOptions.add(CliOption.newBoolean(SUPPORT_JAVA6, "Whether to support Java6 with the Jersey1/2 library.")); - } - - @Override - public String getName() { - return "jaxrs-jersey"; - } - - @Override - public String getHelp() { - return "Generates a Java JAXRS Server application based on Jersey framework."; - } - - @Override - public void postProcessModelProperty(CodegenSchema model, CodegenSchema property) { - super.postProcessModelProperty(model, property); - if ("null".equals(property.example)) { - property.example = null; - } - - //Add imports for Jackson - if (model.enumInfo == null) { - model.imports.add("JsonProperty"); - } - } - - @Override - public void processOpts() { - super.processOpts(); - - // use default library if unset - if (StringUtils.isEmpty(library)) { - setLibrary(DEFAULT_JERSEY_LIBRARY); - } - - if (additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER)) { - implFolder = (String) additionalProperties.get(CodegenConstants.IMPL_FOLDER); - } - - if ("joda".equals(dateLibrary)) { - supportingFiles.add(new SupportingFile("JodaDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaDateTimeProvider.java")); - supportingFiles.add(new SupportingFile("JodaLocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaLocalDateProvider.java")); - } else if (dateLibrary.startsWith("java8")) { - supportingFiles.add(new SupportingFile("OffsetDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "OffsetDateTimeProvider.java")); - supportingFiles.add(new SupportingFile("LocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateProvider.java")); - } - - supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml") - .doNotOverwrite()); - supportingFiles.add(new SupportingFile("README.mustache", "", "README.md") - .doNotOverwrite()); - supportingFiles.add(new SupportingFile("ApiException.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiException.java")); - supportingFiles.add(new SupportingFile("ApiOriginFilter.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiOriginFilter.java")); - supportingFiles.add(new SupportingFile("ApiResponseMessage.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiResponseMessage.java")); - supportingFiles.add(new SupportingFile("NotFoundException.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "NotFoundException.java")); - supportingFiles.add(new SupportingFile("jacksonJsonProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JacksonJsonProvider.java")); - supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "RFC3339DateFormat.java")); - supportingFiles.add(new SupportingFile("bootstrap.mustache", (implFolder + '/' + apiPackage).replace(".", "/"), "Bootstrap.java") - .doNotOverwrite()); - supportingFiles.add(new SupportingFile("web.mustache", ("src/main/webapp/WEB-INF"), "web.xml") - .doNotOverwrite()); - supportingFiles.add(new SupportingFile("StringUtil.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "StringUtil.java")); - - // JsonNullable is not implemented for this generator - openApiNullable = false; - } - -} diff --git a/src/main/java/org/openapijsonschematools/codegen/generators/KotlinClientGenerator.java b/src/main/java/org/openapijsonschematools/codegen/generators/KotlinClientGenerator.java deleted file mode 100644 index d2cf22342f4..00000000000 --- a/src/main/java/org/openapijsonschematools/codegen/generators/KotlinClientGenerator.java +++ /dev/null @@ -1,795 +0,0 @@ -/* - * 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.openapijsonschematools.codegen.generators; - -import java.io.File; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.openapijsonschematools.codegen.generators.models.CliOption; -import org.openapijsonschematools.codegen.common.CodegenConstants; -import org.openapijsonschematools.codegen.generators.generatormetadata.GeneratorType; -import org.openapijsonschematools.codegen.generators.generatormetadata.features.SchemaFeature; -import org.openapijsonschematools.codegen.generators.openapimodels.CodegenSchema; -import org.openapijsonschematools.codegen.templating.SupportingFile; -import org.openapijsonschematools.codegen.generators.generatormetadata.features.ClientModificationFeature; -import org.openapijsonschematools.codegen.generators.generatormetadata.features.DocumentationFeature; -import org.openapijsonschematools.codegen.generators.generatormetadata.features.ParameterFeature; -import org.openapijsonschematools.codegen.generators.generatormetadata.features.SecurityFeature; -import org.openapijsonschematools.codegen.generators.generatormetadata.features.WireFormatFeature; -import org.openapijsonschematools.codegen.common.ProcessUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static java.util.Collections.sort; - -public class KotlinClientGenerator extends AbstractKotlinGenerator { - - private final Logger LOGGER = LoggerFactory.getLogger(KotlinClientGenerator.class); - - protected static final String JVM = "jvm"; - protected static final String JVM_KTOR = "jvm-ktor"; - protected static final String JVM_OKHTTP = "jvm-okhttp"; - protected static final String JVM_OKHTTP4 = "jvm-okhttp4"; - protected static final String JVM_OKHTTP3 = "jvm-okhttp3"; - protected static final String JVM_RETROFIT2 = "jvm-retrofit2"; - protected static final String MULTIPLATFORM = "multiplatform"; - protected static final String JVM_VOLLEY = "jvm-volley"; - - public static final String USE_RX_JAVA = "useRxJava"; - public static final String USE_RX_JAVA2 = "useRxJava2"; - public static final String USE_RX_JAVA3 = "useRxJava3"; - public static final String USE_COROUTINES = "useCoroutines"; - public static final String DO_NOT_USE_RX_AND_COROUTINES = "doNotUseRxAndCoroutines"; - public static final String GENERATE_ROOM_MODELS = "generateRoomModels"; - public static final String ROOM_MODEL_PACKAGE = "roomModelPackage"; - public static final String OMIT_GRADLE_PLUGIN_VERSIONS = "omitGradlePluginVersions"; - public static final String OMIT_GRADLE_WRAPPER = "omitGradleWrapper"; - public static final String IDEA = "idea"; - - public static final String DATE_LIBRARY = "dateLibrary"; - public static final String REQUEST_DATE_CONVERTER = "requestDateConverter"; - public static final String COLLECTION_TYPE = "collectionType"; - - public static final String MOSHI_CODE_GEN = "moshiCodeGen"; - - public static final String SUPPORT_ANDROID_API_LEVEL_25_AND_BELLOW = "supportAndroidApiLevel25AndBelow"; - - protected static final String VENDOR_EXTENSION_BASE_NAME_LITERAL = "x-base-name-literal"; - - protected String dateLibrary = DateLibrary.JAVA8.value; - protected String requestDateConverter = RequestDateConverter.TO_JSON.value; - protected String collectionType = CollectionType.LIST.value; - protected boolean useRxJava = false; - protected boolean useRxJava2 = false; - protected boolean useRxJava3 = false; - protected boolean useCoroutines = false; - // backwards compatibility for openapi configs that specify neither rx1 nor rx2 - // (mustache does not allow for boolean operators so we need this extra field) - protected boolean doNotUseRxAndCoroutines = true; - protected boolean generateRoomModels = false; - protected String roomModelPackage = ""; - - - protected String authFolder; - - public enum DateLibrary { - STRING("string"), - THREETENBP("threetenbp"), - THREETENBP_LOCALDATETIME("threetenbp-localdatetime"), - JAVA8("java8"), - JAVA8_LOCALDATETIME("java8-localdatetime"); - - public final String value; - - DateLibrary(String value) { - this.value = value; - } - } - - public enum RequestDateConverter { - TO_STRING("toString"), - TO_JSON("toJson"); - - public final String value; - - RequestDateConverter(String value) { - this.value = value; - } - } - - public enum CollectionType { - ARRAY("array"), - LIST("list"); - - public final String value; - - CollectionType(String value) { - this.value = value; - } - } - - /** - * Constructs an instance of `KotlinClientGenerator`. - */ - public KotlinClientGenerator() { - super(); - - /* - * OAuth flows supported _only_ by client explicitly setting bearer token. The "flows" are not supported. - */ - modifyFeatureSet(features -> features - .includeDocumentationFeatures(DocumentationFeature.Readme) - .excludeWireFormatFeatures(WireFormatFeature.XML, WireFormatFeature.PROTOBUF) - .excludeSecurityFeatures( - SecurityFeature.OpenIDConnect, - SecurityFeature.OAuth2_Password, - SecurityFeature.OAuth2_AuthorizationCode, - SecurityFeature.OAuth2_ClientCredentials, - SecurityFeature.OAuth2_Implicit - ) - .excludeSchemaFeatures( - SchemaFeature.Not - ) - .excludeParameterFeatures( - ParameterFeature.In_Cookie - ) - .includeClientModificationFeatures(ClientModificationFeature.BasePath) - ); - - artifactId = "kotlin-client"; - packageName = "org.openapijsonschematools.client"; - - // cliOptions default redefinition need to be updated - updateOption(CodegenConstants.ARTIFACT_ID, this.artifactId); - updateOption(CodegenConstants.PACKAGE_NAME, this.packageName); - - outputFolder = "generated-code" + File.separator + "kotlin-client"; - jsonPathTemplateFiles.put( - CodegenConstants.JSON_PATH_LOCATION_TYPE.SCHEMA, - new HashMap() {{ - put("model.mustache", ".kt"); - }} - ); - if (generateRoomModels) { - jsonPathTemplateFiles.get(CodegenConstants.JSON_PATH_LOCATION_TYPE.SCHEMA).put( - "model_room.mustache", ".kt" - ); - } - jsonPathDocTemplateFiles.put( - CodegenConstants.JSON_PATH_LOCATION_TYPE.SCHEMA, - new HashMap() {{ - put("model_doc.mustache", ".md"); - }} - ); - jsonPathDocTemplateFiles.put( - CodegenConstants.JSON_PATH_LOCATION_TYPE.API_TAG, - new HashMap() {{ - put("api_doc.mustache", ".md"); - }} - ); - embeddedTemplateDir = templateDir = "kotlin-client"; - apiPackage = packageName + ".apis"; - modelPackage = packageName + ".models"; - - CliOption dateLibrary = new CliOption(DATE_LIBRARY, "Option. Date library to use"); - Map dateOptions = new HashMap<>(); - dateOptions.put(DateLibrary.THREETENBP.value, "Threetenbp - Backport of JSR310 (jvm only, preferred for jdk < 1.8)"); - dateOptions.put(DateLibrary.THREETENBP_LOCALDATETIME.value, "Threetenbp - Backport of JSR310 (jvm only, for legacy app only)"); - dateOptions.put(DateLibrary.STRING.value, "String"); - dateOptions.put(DateLibrary.JAVA8.value, "Java 8 native JSR310 (jvm only, preferred for jdk 1.8+)"); - dateOptions.put(DateLibrary.JAVA8_LOCALDATETIME.value, "Java 8 native JSR310 (jvm only, for legacy app only)"); - dateLibrary.setEnum(dateOptions); - dateLibrary.setDefault(this.dateLibrary); - cliOptions.add(dateLibrary); - - CliOption collectionType = new CliOption(COLLECTION_TYPE, "Option. Collection type to use"); - Map collectionOptions = new HashMap<>(); - collectionOptions.put(CollectionType.ARRAY.value, "kotlin.Array"); - collectionOptions.put(CollectionType.LIST.value, "kotlin.collections.List"); - collectionType.setEnum(collectionOptions); - collectionType.setDefault(this.collectionType); - cliOptions.add(collectionType); - - supportedLibraries.put(JVM_KTOR, "Platform: Java Virtual Machine. HTTP client: Ktor 1.6.7. JSON processing: Gson, Jackson (default)."); - supportedLibraries.put(JVM_OKHTTP4, "[DEFAULT] Platform: Java Virtual Machine. HTTP client: OkHttp 4.2.0 (Android 5.0+ and Java 8+). JSON processing: Moshi 1.8.0."); - supportedLibraries.put(JVM_OKHTTP3, "Platform: Java Virtual Machine. HTTP client: OkHttp 3.12.4 (Android 2.3+ and Java 7+). JSON processing: Moshi 1.8.0."); - supportedLibraries.put(JVM_RETROFIT2, "Platform: Java Virtual Machine. HTTP client: Retrofit 2.6.2."); - supportedLibraries.put(MULTIPLATFORM, "Platform: Kotlin multiplatform. HTTP client: Ktor 1.6.7. JSON processing: Kotlinx Serialization: 1.2.1."); - supportedLibraries.put(JVM_VOLLEY, "Platform: JVM for Android. HTTP client: Volley 1.2.1. JSON processing: gson 2.8.9"); - - CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "Library template (sub-template) to use"); - libraryOption.setEnum(supportedLibraries); - libraryOption.setDefault(JVM_OKHTTP4); - cliOptions.add(libraryOption); - setLibrary(JVM_OKHTTP4); - - CliOption requestDateConverter = new CliOption(REQUEST_DATE_CONVERTER, "JVM-Option. Defines in how to handle date-time objects that are used for a request (as query or parameter)"); - Map requestDateConverterOptions = new HashMap<>(); - requestDateConverterOptions.put(RequestDateConverter.TO_JSON.value, "[DEFAULT] Date formatter option using a json converter."); - requestDateConverterOptions.put(RequestDateConverter.TO_STRING.value, "Use the 'toString'-method of the date-time object to retrieve the related string representation."); - requestDateConverter.setEnum(requestDateConverterOptions); - requestDateConverter.setDefault(this.requestDateConverter); - cliOptions.add(requestDateConverter); - - cliOptions.add(CliOption.newBoolean(USE_RX_JAVA, "Whether to use the RxJava adapter with the retrofit2 library. IMPORTANT: this option has been deprecated. Please use `useRxJava3` instead.")); - cliOptions.add(CliOption.newBoolean(USE_RX_JAVA2, "Whether to use the RxJava2 adapter with the retrofit2 library. IMPORTANT: this option has been deprecated. Please use `useRxJava3` instead.")); - cliOptions.add(CliOption.newBoolean(USE_RX_JAVA3, "Whether to use the RxJava3 adapter with the retrofit2 library.")); - cliOptions.add(CliOption.newBoolean(USE_COROUTINES, "Whether to use the Coroutines adapter with the retrofit2 library.")); - cliOptions.add(CliOption.newBoolean(OMIT_GRADLE_PLUGIN_VERSIONS, "Whether to declare Gradle plugin versions in build files.")); - cliOptions.add(CliOption.newBoolean(OMIT_GRADLE_WRAPPER, "Whether to omit Gradle wrapper for creating a sub project.")); - cliOptions.add(CliOption.newBoolean(IDEA, "Add IntellJ Idea plugin and mark Kotlin main and test folders as source folders.")); - - cliOptions.add(CliOption.newBoolean(MOSHI_CODE_GEN, "Whether to enable codegen with the Moshi library. Refer to the [official Moshi doc](https://github.com/square/moshi#codegen) for more info.")); - - cliOptions.add(CliOption.newBoolean(GENERATE_ROOM_MODELS, "Generate Android Room database models in addition to API models (JVM Volley library only)", false)); - - cliOptions.add(CliOption.newBoolean(SUPPORT_ANDROID_API_LEVEL_25_AND_BELLOW, "[WARNING] This flag will generate code that has a known security vulnerability. It uses `kotlin.io.createTempFile` instead of `java.nio.file.Files.createTempFile` in order to support Android API level 25 and bellow. For more info, please check the following links https://github.com/OpenAPITools/openapi-generator/security/advisories/GHSA-23x4-m842-fmwf, https://github.com/OpenAPITools/openapi-generator/pull/9284")); - } - - public GeneratorType getTag() { - return GeneratorType.CLIENT; - } - - public String getName() { - return "kotlin"; - } - - public String getHelp() { - return "Generates a Kotlin client."; - } - - public boolean getGenerateRoomModels() { - return generateRoomModels; - } - - public void setGenerateRoomModels(Boolean generateRoomModels) { - this.generateRoomModels = generateRoomModels; - } - - public void setUseRxJava(boolean useRxJava) { - if (useRxJava) { - this.useRxJava2 = false; - this.useRxJava3 = false; - this.doNotUseRxAndCoroutines = false; - this.useCoroutines = false; - } - this.useRxJava = useRxJava; - } - - public void setUseRxJava2(boolean useRxJava2) { - if (useRxJava2) { - this.useRxJava = false; - this.useRxJava3 = false; - this.doNotUseRxAndCoroutines = false; - this.useCoroutines = false; - } - this.useRxJava2 = useRxJava2; - } - - public void setUseRxJava3(boolean useRxJava3) { - if (useRxJava3) { - this.useRxJava = false; - this.useRxJava2 = false; - this.doNotUseRxAndCoroutines = false; - this.useCoroutines = false; - } - this.useRxJava3 = useRxJava3; - } - - public void setDoNotUseRxAndCoroutines(boolean doNotUseRxAndCoroutines) { - if (doNotUseRxAndCoroutines) { - this.useRxJava = false; - this.useRxJava2 = false; - this.useRxJava3 = false; - this.useCoroutines = false; - } - this.doNotUseRxAndCoroutines = doNotUseRxAndCoroutines; - } - - public void setUseCoroutines(boolean useCoroutines) { - if (useCoroutines) { - this.useRxJava = false; - this.useRxJava2 = false; - this.useRxJava3 = false; - this.doNotUseRxAndCoroutines = false; - } - this.useCoroutines = useCoroutines; - } - - - public void setDateLibrary(String library) { - this.dateLibrary = library; - } - - public void setRequestDateConverter(String converter) { - this.requestDateConverter = converter; - } - - public void setCollectionType(String collectionType) { - this.collectionType = collectionType; - } - - public void setRoomModelPackage(String roomModelPackage) { - this.roomModelPackage = roomModelPackage; - } - - public String roomModelFileFolder() { - return outputFolder + File.separator + sourceFolder + File.separator + roomModelPackage.replace('.', File.separatorChar); - } - - @Override - public void processOpts() { - if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) { - setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); - } else { - // Set the value to defaults if we haven't overridden - if (MULTIPLATFORM.equals(getLibrary())) { - setSourceFolder("src/commonMain/kotlin"); - } else if (JVM_VOLLEY.equals(getLibrary())) { - // Android plugin wants it's source in java - setSourceFolder("src/main/java"); - } else { - setSourceFolder(super.sourceFolder); - } - additionalProperties.put(CodegenConstants.SOURCE_FOLDER, this.sourceFolder); - } - - super.processOpts(); - - boolean hasRx = additionalProperties.containsKey(USE_RX_JAVA); - boolean hasRx2 = additionalProperties.containsKey(USE_RX_JAVA2); - boolean hasRx3 = additionalProperties.containsKey(USE_RX_JAVA3); - boolean hasCoroutines = additionalProperties.containsKey(USE_COROUTINES); - int optionCount = 0; - if (hasRx) { - optionCount++; - } - if (hasRx2) { - optionCount++; - } - if (hasRx3) { - optionCount++; - } - if (hasCoroutines) { - optionCount++; - } - boolean hasConflict = optionCount > 1; - - // RxJava & Coroutines - if (hasConflict) { - LOGGER.warn("You specified RxJava versions 1 and 2 and 3 or Coroutines together, please choose one of them."); - } else if (hasRx) { - this.setUseRxJava(Boolean.parseBoolean(additionalProperties.get(USE_RX_JAVA).toString())); - } else if (hasRx2) { - this.setUseRxJava2(Boolean.parseBoolean(additionalProperties.get(USE_RX_JAVA2).toString())); - } else if (hasRx3) { - this.setUseRxJava3(Boolean.parseBoolean(additionalProperties.get(USE_RX_JAVA3).toString())); - } else if (hasCoroutines) { - this.setUseCoroutines(Boolean.parseBoolean(additionalProperties.get(USE_COROUTINES).toString())); - } - - if (!hasRx && !hasRx2 && !hasRx3 && !hasCoroutines) { - setDoNotUseRxAndCoroutines(true); - additionalProperties.put(DO_NOT_USE_RX_AND_COROUTINES, true); - } - - // infrastructure destination folder - final String infrastructureFolder = (sourceFolder + File.separator + packageName + File.separator + "infrastructure").replace(".", "/"); - authFolder = (sourceFolder + File.separator + packageName + File.separator + "auth").replace(".", "/"); - - // request destination folder - final String requestFolder = (sourceFolder + File.separator + packageName + File.separator + "request").replace(".", "/"); - - // auth destination folder - final String authFolder = (sourceFolder + File.separator + packageName + File.separator + "auth").replace(".", "/"); - - // additional properties - if (additionalProperties.containsKey(DATE_LIBRARY)) { - setDateLibrary(additionalProperties.get(DATE_LIBRARY).toString()); - } - - if (additionalProperties.containsKey(REQUEST_DATE_CONVERTER)) { - setRequestDateConverter(additionalProperties.get(REQUEST_DATE_CONVERTER).toString()); - } - - commonSupportingFiles(); - - switch (getLibrary()) { - case JVM_KTOR: - processJVMKtorLibrary(infrastructureFolder); - break; - case JVM_OKHTTP3: - case JVM_OKHTTP4: - processJVMOkHttpLibrary(infrastructureFolder); - break; - case JVM_VOLLEY: - processJVMVolleyLibrary(infrastructureFolder, requestFolder, authFolder); - break; - case JVM_RETROFIT2: - processJVMRetrofit2Library(infrastructureFolder); - break; - case MULTIPLATFORM: - processMultiplatformLibrary(infrastructureFolder); - break; - default: - break; - } - - processDateLibrary(); - processRequestDateConverter(); - - if (additionalProperties.containsKey(COLLECTION_TYPE)) { - setCollectionType(additionalProperties.get(COLLECTION_TYPE).toString()); - } - - if (CollectionType.LIST.value.equals(collectionType)) { - if (isModelMutable()) { - typeMapping.put("array", "kotlin.collections.MutableList"); - typeMapping.put("list", "kotlin.collections.MutableList"); - } else { - typeMapping.put("array", "kotlin.collections.List"); - typeMapping.put("list", "kotlin.collections.List"); - } - additionalProperties.put("isList", true); - } - - if (usesRetrofit2Library()) { - boolean hasOAuthMethods = true; - - if (hasOAuthMethods) { - supportingFiles.add(new SupportingFile("auth/OAuth.kt.mustache", authFolder, "OAuth.kt")); - supportingFiles.add(new SupportingFile("auth/OAuthFlow.kt.mustache", authFolder, "OAuthFlow.kt")); - supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.kt.mustache", authFolder, "OAuthOkHttpClient.kt")); - } - - if (hasOAuthMethods || ProcessUtils.hasApiKeyMethods(openAPI)) { - supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.kt.mustache", authFolder, "ApiKeyAuth.kt")); - } - - if (ProcessUtils.hasHttpBearerMethods(openAPI)) { - supportingFiles.add(new SupportingFile("auth/HttpBearerAuth.kt.mustache", authFolder, "HttpBearerAuth.kt")); - } - - if (ProcessUtils.hasHttpBasicMethods(openAPI)) { - supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.kt.mustache", authFolder, "HttpBasicAuth.kt")); - } - } - } - - private void processDateLibrary() { - if (DateLibrary.THREETENBP.value.equals(dateLibrary) || DateLibrary.THREETENBP_LOCALDATETIME.value.equals(dateLibrary)) { - processThreeTenBpDate(dateLibrary); - } else if (DateLibrary.STRING.value.equals(dateLibrary)) { - processStringDate(); - } else if (DateLibrary.JAVA8.value.equals(dateLibrary) || DateLibrary.JAVA8_LOCALDATETIME.value.equals(dateLibrary)) { - processJava8Date(dateLibrary); - } - } - - private void processRequestDateConverter() { - if (RequestDateConverter.TO_JSON.value.equals(requestDateConverter)) { - additionalProperties.put(RequestDateConverter.TO_JSON.value, true); - } else if (RequestDateConverter.TO_STRING.value.equals(requestDateConverter)) { - additionalProperties.put(RequestDateConverter.TO_STRING.value, true); - } - } - - private void processThreeTenBpDate(String dateLibrary) { - additionalProperties.put(DateLibrary.THREETENBP.value, true); - typeMapping.put("date", "LocalDate"); - defaultIncludes.add("org.threeten.bp.LocalDate"); - - if (dateLibrary.equals(DateLibrary.THREETENBP.value)) { - typeMapping.put("date-time", "org.threeten.bp.OffsetDateTime"); - typeMapping.put("DateTime", "OffsetDateTime"); - defaultIncludes.add("org.threeten.bp.OffsetDateTime"); - } else if (dateLibrary.equals(DateLibrary.THREETENBP_LOCALDATETIME.value)) { - typeMapping.put("date-time", "org.threeten.bp.LocalDateTime"); - typeMapping.put("DateTime", "LocalDateTime"); - defaultIncludes.add("org.threeten.bp.LocalDateTime"); - } - } - - private void processStringDate() { - typeMapping.put("date-time", "kotlin.String"); - typeMapping.put("date", "kotlin.String"); - typeMapping.put("Date", "kotlin.String"); - typeMapping.put("DateTime", "kotlin.String"); - } - - private void processJava8Date(String dateLibrary) { - additionalProperties.put(DateLibrary.JAVA8.value, true); - - if (dateLibrary.equals(DateLibrary.JAVA8.value)) { - typeMapping.put("date-time", "java.time.OffsetDateTime"); - typeMapping.put("DateTime", "OffsetDateTime"); - } else if (dateLibrary.equals(DateLibrary.JAVA8_LOCALDATETIME.value)) { - typeMapping.put("date-time", "java.time.LocalDateTime"); - typeMapping.put("DateTime", "LocalDateTime"); - } - } - - private void processJVMRetrofit2Library(String infrastructureFolder) { - additionalProperties.put(JVM, true); - additionalProperties.put(JVM_RETROFIT2, true); - supportingFiles.add(new SupportingFile("infrastructure/ApiClient.kt.mustache", infrastructureFolder, "ApiClient.kt")); - supportingFiles.add(new SupportingFile("infrastructure/ResponseExt.kt.mustache", infrastructureFolder, "ResponseExt.kt")); - supportingFiles.add(new SupportingFile("infrastructure/CollectionFormats.kt.mustache", infrastructureFolder, "CollectionFormats.kt")); - addSupportingSerializerAdapters(infrastructureFolder); - } - - private void processJVMVolleyLibrary(String infrastructureFolder, String requestFolder, String authFolder) { - - additionalProperties.put(JVM, true); - additionalProperties.put(JVM_VOLLEY, true); - - if (additionalProperties.containsKey(GENERATE_ROOM_MODELS)) { - this.setGenerateRoomModels(convertPropertyToBooleanAndWriteBack(GENERATE_ROOM_MODELS)); - // Hide this option behind a property getter and setter in case we need to check it elsewhere - if (getGenerateRoomModels()) { - jsonPathTemplateFiles.get(CodegenConstants.JSON_PATH_LOCATION_TYPE.SCHEMA).put( - "model_room.mustache", "RoomModel.kt" - ); - supportingFiles.add(new SupportingFile("infrastructure/ITransformForStorage.mustache", infrastructureFolder, "ITransformForStorage.kt")); - - } - } else { - additionalProperties.put(GENERATE_ROOM_MODELS, generateRoomModels); - } - - if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { - if (!additionalProperties.containsKey(ROOM_MODEL_PACKAGE)) - this.setRoomModelPackage(packageName + ".models.room"); - else - this.setRoomModelPackage(additionalProperties.get(ROOM_MODEL_PACKAGE).toString()); - } - additionalProperties.put(ROOM_MODEL_PACKAGE, roomModelPackage); - - supportingFiles.add(new SupportingFile("infrastructure/CollectionFormats.kt.mustache", infrastructureFolder, "CollectionFormats.kt")); - - // We have auth related partial files, so they can be overridden, but don't generate them explicitly - supportingFiles.add(new SupportingFile("request/GsonRequest.mustache", requestFolder, "GsonRequest.kt")); - supportingFiles.add(new SupportingFile("request/IRequestFactory.mustache", requestFolder, "IRequestFactory.kt")); - supportingFiles.add(new SupportingFile("request/RequestFactory.mustache", requestFolder, "RequestFactory.kt")); - supportingFiles.add(new SupportingFile("infrastructure/CollectionFormats.kt.mustache", infrastructureFolder, "CollectionFormats.kt")); - - if (getSerializationLibrary() != SERIALIZATION_LIBRARY_TYPE.gson) { - throw new RuntimeException("This library currently only supports gson serialization. Try adding '--additional-properties serializationLibrary=gson' to your command."); - } - addSupportingSerializerAdapters(infrastructureFolder); - supportingFiles.remove(new SupportingFile("jvm-common/infrastructure/Serializer.kt.mustache", infrastructureFolder, "Serializer.kt")); - - } - - private void addSupportingSerializerAdapters(final String infrastructureFolder) { - supportingFiles.add(new SupportingFile("jvm-common/infrastructure/Serializer.kt.mustache", infrastructureFolder, "Serializer.kt")); - - switch (getSerializationLibrary()) { - case moshi: - if (enumUnknownDefaultCase) { - supportingFiles.add(new SupportingFile("jvm-common/infrastructure/SerializerHelper.kt.mustache", infrastructureFolder, "SerializerHelper.kt")); - } - supportingFiles.add(new SupportingFile("jvm-common/infrastructure/ByteArrayAdapter.kt.mustache", infrastructureFolder, "ByteArrayAdapter.kt")); - supportingFiles.add(new SupportingFile("jvm-common/infrastructure/UUIDAdapter.kt.mustache", infrastructureFolder, "UUIDAdapter.kt")); - supportingFiles.add(new SupportingFile("jvm-common/infrastructure/LocalDateAdapter.kt.mustache", infrastructureFolder, "LocalDateAdapter.kt")); - supportingFiles.add(new SupportingFile("jvm-common/infrastructure/LocalDateTimeAdapter.kt.mustache", infrastructureFolder, "LocalDateTimeAdapter.kt")); - supportingFiles.add(new SupportingFile("jvm-common/infrastructure/OffsetDateTimeAdapter.kt.mustache", infrastructureFolder, "OffsetDateTimeAdapter.kt")); - supportingFiles.add(new SupportingFile("jvm-common/infrastructure/BigDecimalAdapter.kt.mustache", infrastructureFolder, "BigDecimalAdapter.kt")); - supportingFiles.add(new SupportingFile("jvm-common/infrastructure/BigIntegerAdapter.kt.mustache", infrastructureFolder, "BigIntegerAdapter.kt")); - supportingFiles.add(new SupportingFile("jvm-common/infrastructure/URIAdapter.kt.mustache", infrastructureFolder, "URIAdapter.kt")); - break; - - case gson: - supportingFiles.add(new SupportingFile("jvm-common/infrastructure/ByteArrayAdapter.kt.mustache", infrastructureFolder, "ByteArrayAdapter.kt")); - supportingFiles.add(new SupportingFile("jvm-common/infrastructure/LocalDateAdapter.kt.mustache", infrastructureFolder, "LocalDateAdapter.kt")); - supportingFiles.add(new SupportingFile("jvm-common/infrastructure/LocalDateTimeAdapter.kt.mustache", infrastructureFolder, "LocalDateTimeAdapter.kt")); - supportingFiles.add(new SupportingFile("jvm-common/infrastructure/OffsetDateTimeAdapter.kt.mustache", infrastructureFolder, "OffsetDateTimeAdapter.kt")); - break; - - case jackson: - break; - - case kotlinx_serialization: - supportingFiles.add(new SupportingFile("jvm-common/infrastructure/AtomicBooleanAdapter.kt.mustache", infrastructureFolder, "AtomicBooleanAdapter.kt")); - supportingFiles.add(new SupportingFile("jvm-common/infrastructure/AtomicIntegerAdapter.kt.mustache", infrastructureFolder, "AtomicIntegerAdapter.kt")); - supportingFiles.add(new SupportingFile("jvm-common/infrastructure/AtomicLongAdapter.kt.mustache", infrastructureFolder, "AtomicLongAdapter.kt")); - supportingFiles.add(new SupportingFile("jvm-common/infrastructure/URIAdapter.kt.mustache", infrastructureFolder, "URIAdapter.kt")); - supportingFiles.add(new SupportingFile("jvm-common/infrastructure/URLAdapter.kt.mustache", infrastructureFolder, "URLAdapter.kt")); - supportingFiles.add(new SupportingFile("jvm-common/infrastructure/BigIntegerAdapter.kt.mustache", infrastructureFolder, "BigIntegerAdapter.kt")); - supportingFiles.add(new SupportingFile("jvm-common/infrastructure/BigDecimalAdapter.kt.mustache", infrastructureFolder, "BigDecimalAdapter.kt")); - supportingFiles.add(new SupportingFile("jvm-common/infrastructure/LocalDateAdapter.kt.mustache", infrastructureFolder, "LocalDateAdapter.kt")); - supportingFiles.add(new SupportingFile("jvm-common/infrastructure/LocalDateTimeAdapter.kt.mustache", infrastructureFolder, "LocalDateTimeAdapter.kt")); - supportingFiles.add(new SupportingFile("jvm-common/infrastructure/OffsetDateTimeAdapter.kt.mustache", infrastructureFolder, "OffsetDateTimeAdapter.kt")); - supportingFiles.add(new SupportingFile("jvm-common/infrastructure/UUIDAdapter.kt.mustache", infrastructureFolder, "UUIDAdapter.kt")); - supportingFiles.add(new SupportingFile("jvm-common/infrastructure/StringBuilderAdapter.kt.mustache", infrastructureFolder, "StringBuilderAdapter.kt")); - supportingFiles.add(new SupportingFile("jvm-common/infrastructure/proguard-rules.pro.mustache", "", "proguard-rules.pro")); - break; - } - } - - private void processJVMKtorLibrary(final String infrastructureFolder) { - // in future kotlinx.serialization may be added - if (this.serializationLibrary != SERIALIZATION_LIBRARY_TYPE.gson && this.serializationLibrary != SERIALIZATION_LIBRARY_TYPE.jackson) { - this.serializationLibrary = SERIALIZATION_LIBRARY_TYPE.jackson; - } - - additionalProperties.put(JVM, true); - additionalProperties.put(JVM_KTOR, true); - - defaultIncludes.add("io.ktor.client.request.forms.InputProvider"); - - supportingFiles.add(new SupportingFile("infrastructure/ApiAbstractions.kt.mustache", infrastructureFolder, "ApiAbstractions.kt")); - supportingFiles.add(new SupportingFile("infrastructure/ApiClient.kt.mustache", infrastructureFolder, "ApiClient.kt")); - supportingFiles.add(new SupportingFile("infrastructure/HttpResponse.kt.mustache", infrastructureFolder, "HttpResponse.kt")); - supportingFiles.add(new SupportingFile("infrastructure/RequestConfig.kt.mustache", infrastructureFolder, "RequestConfig.kt")); - supportingFiles.add(new SupportingFile("infrastructure/RequestMethod.kt.mustache", infrastructureFolder, "RequestMethod.kt")); - - supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.kt.mustache", authFolder, "ApiKeyAuth.kt")); - supportingFiles.add(new SupportingFile("auth/Authentication.kt.mustache", authFolder, "Authentication.kt")); - supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.kt.mustache", authFolder, "HttpBasicAuth.kt")); - supportingFiles.add(new SupportingFile("auth/HttpBearerAuth.kt.mustache", authFolder, "HttpBearerAuth.kt")); - supportingFiles.add(new SupportingFile("auth/OAuth.kt.mustache", authFolder, "OAuth.kt")); - } - - private void processJVMOkHttpLibrary(final String infrastructureFolder) { - commonJvmMultiplatformSupportingFiles(infrastructureFolder); - addSupportingSerializerAdapters(infrastructureFolder); - - additionalProperties.put(JVM, true); - additionalProperties.put(JVM_OKHTTP, true); - - if (JVM_OKHTTP4.equals(getLibrary())) { - additionalProperties.put(JVM_OKHTTP4, true); - } else if (JVM_OKHTTP3.equals(getLibrary())) { - additionalProperties.put(JVM_OKHTTP3, true); - } - - supportedLibraries.put(JVM_OKHTTP, "A workaround to use the same template folder for both 'jvm-okhttp3' and 'jvm-okhttp4'."); - setLibrary(JVM_OKHTTP); - - // jvm specific supporting files - supportingFiles.add(new SupportingFile("infrastructure/Errors.kt.mustache", infrastructureFolder, "Errors.kt")); - supportingFiles.add(new SupportingFile("infrastructure/ResponseExtensions.kt.mustache", infrastructureFolder, "ResponseExtensions.kt")); - supportingFiles.add(new SupportingFile("infrastructure/ApiResponse.kt.mustache", infrastructureFolder, "ApiResponse.kt")); - } - - private void processMultiplatformLibrary(final String infrastructureFolder) { - commonJvmMultiplatformSupportingFiles(infrastructureFolder); - additionalProperties.put(MULTIPLATFORM, true); - setDateLibrary(DateLibrary.STRING.value); - setRequestDateConverter(RequestDateConverter.TO_STRING.value); - - // multiplatform default includes - defaultIncludes.add("io.ktor.client.request.forms.InputProvider"); - defaultIncludes.add(packageName + ".infrastructure.Base64ByteArray"); - defaultIncludes.add(packageName + ".infrastructure.OctetByteArray"); - - // multiplatform type mapping - typeMapping.put("number", "kotlin.Double"); - typeMapping.put("file", "OctetByteArray"); - typeMapping.put("binary", "OctetByteArray"); - typeMapping.put("ByteArray", "Base64ByteArray"); - typeMapping.put("object", "kotlin.String"); // kotlin.Any not serializable - - // multiplatform specific supporting files - supportingFiles.add(new SupportingFile("infrastructure/Base64ByteArray.kt.mustache", infrastructureFolder, "Base64ByteArray.kt")); - supportingFiles.add(new SupportingFile("infrastructure/Bytes.kt.mustache", infrastructureFolder, "Bytes.kt")); - supportingFiles.add(new SupportingFile("infrastructure/HttpResponse.kt.mustache", infrastructureFolder, "HttpResponse.kt")); - supportingFiles.add(new SupportingFile("infrastructure/OctetByteArray.kt.mustache", infrastructureFolder, "OctetByteArray.kt")); - - // multiplatform specific auth - supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.kt.mustache", authFolder, "ApiKeyAuth.kt")); - supportingFiles.add(new SupportingFile("auth/Authentication.kt.mustache", authFolder, "Authentication.kt")); - supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.kt.mustache", authFolder, "HttpBasicAuth.kt")); - supportingFiles.add(new SupportingFile("auth/HttpBearerAuth.kt.mustache", authFolder, "HttpBearerAuth.kt")); - supportingFiles.add(new SupportingFile("auth/OAuth.kt.mustache", authFolder, "OAuth.kt")); - - // multiplatform specific testing files - supportingFiles.add(new SupportingFile("commonTest/Coroutine.kt.mustache", "src/commonTest/kotlin/util", "Coroutine.kt")); - supportingFiles.add(new SupportingFile("iosTest/Coroutine.kt.mustache", "src/iosTest/kotlin/util", "Coroutine.kt")); - supportingFiles.add(new SupportingFile("jsTest/Coroutine.kt.mustache", "src/jsTest/kotlin/util", "Coroutine.kt")); - supportingFiles.add(new SupportingFile("jvmTest/Coroutine.kt.mustache", "src/jvmTest/kotlin/util", "Coroutine.kt")); - } - - - private void commonJvmMultiplatformSupportingFiles(String infrastructureFolder) { - supportingFiles.add(new SupportingFile("infrastructure/ApiClient.kt.mustache", infrastructureFolder, "ApiClient.kt")); - supportingFiles.add(new SupportingFile("infrastructure/ApiAbstractions.kt.mustache", infrastructureFolder, "ApiAbstractions.kt")); - supportingFiles.add(new SupportingFile("infrastructure/PartConfig.kt.mustache", infrastructureFolder, "PartConfig.kt")); - supportingFiles.add(new SupportingFile("infrastructure/RequestConfig.kt.mustache", infrastructureFolder, "RequestConfig.kt")); - supportingFiles.add(new SupportingFile("infrastructure/RequestMethod.kt.mustache", infrastructureFolder, "RequestMethod.kt")); - } - - private void commonSupportingFiles() { - supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - if (getLibrary().equals(MULTIPLATFORM)) { - supportingFiles.add(new SupportingFile("build.gradle.kts.mustache", "", "build.gradle.kts")); - supportingFiles.add(new SupportingFile("settings.gradle.kts.mustache", "", "settings.gradle.kts")); - } else if (getLibrary().equals(JVM_VOLLEY)) { - supportingFiles.add(new SupportingFile("build.mustache", "", "build.gradle")); - supportingFiles.add(new SupportingFile("gradle.properties.mustache", "", "gradle.properties")); - supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); - supportingFiles.add(new SupportingFile("manifest.mustache", "", "src/main/AndroidManifest.xml")); - } else { - supportingFiles.add(new SupportingFile("build.gradle.mustache", "", "build.gradle")); - supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); - } - - // gradle wrapper supporting files - supportingFiles.add(new SupportingFile("gradlew.mustache", "", "gradlew")); - supportingFiles.add(new SupportingFile("gradlew.bat.mustache", "", "gradlew.bat")); - supportingFiles.add(new SupportingFile("gradle-wrapper.properties.mustache", "gradle.wrapper".replace(".", File.separator), "gradle-wrapper.properties")); - supportingFiles.add(new SupportingFile("gradle-wrapper.jar", "gradle.wrapper".replace(".", File.separator), "gradle-wrapper.jar")); - } - - @Override - public TreeMap postProcessModels(TreeMap models) { - TreeMap objects = super.postProcessModels(models); - - for (CodegenSchema cm: objects.values()) { - if (getGenerateRoomModels()) { - cm.vendorExtensions.put("x-has-data-class-body", true); - } - - // escape the variable base name for use as a string literal - List vars = Stream.of( - cm.optionalProperties.values().stream().collect(Collectors.toList()), - cm.requiredProperties.values().stream().collect(Collectors.toList()) - ) - .flatMap(List::stream) - .collect(Collectors.toList()); - - for (CodegenSchema var : vars) { - if (var.jsonPathPiece != null) { - var.vendorExtensions.put(VENDOR_EXTENSION_BASE_NAME_LITERAL, var.jsonPathPiece.original.replace("$", "\\$")); - } - } - } - - return objects; - } - - private boolean usesRetrofit2Library() { - return getLibrary() != null && getLibrary().contains(JVM_RETROFIT2); - } - - private static boolean isMultipartType(List> consumes) { - Map firstType = consumes.get(0); - if (firstType != null) { - return "multipart/form-data".equals(firstType.get("mediaType")); - } - return false; - } - - @Override - public void postProcess() { - LOGGER.info("################################################################################"); - LOGGER.info("# Thanks for using OpenAPI JSON Schema Generator. #"); - LOGGER.info("# Please consider donation to help us maintain this project \uD83D\uDE4F #"); - LOGGER.info("# https://github.com/sponsors/spacether #"); - LOGGER.info("# #"); - LOGGER.info("# This generator's contributed by Jim Schubert (https://github.com/jimschubert)#"); - LOGGER.info("# Please support his work directly via https://patreon.com/jimschubert \uD83D\uDE4F #"); - LOGGER.info("################################################################################"); - } -} diff --git a/src/main/resources/META-INF/services/org.openapijsonschematools.codegen.generators.Generator b/src/main/resources/META-INF/services/org.openapijsonschematools.codegen.generators.Generator index cead914ce38..9009c3c5eb4 100644 --- a/src/main/resources/META-INF/services/org.openapijsonschematools.codegen.generators.Generator +++ b/src/main/resources/META-INF/services/org.openapijsonschematools.codegen.generators.Generator @@ -1,5 +1,2 @@ -org.openapijsonschematools.codegen.generators.KotlinClientGenerator org.openapijsonschematools.codegen.generators.JavaClientGenerator -org.openapijsonschematools.codegen.generators.JavaJerseyServerGenerator -org.openapijsonschematools.codegen.generators.JMeterClientGenerator org.openapijsonschematools.codegen.generators.PythonClientGenerator diff --git a/src/main/resources/kotlin-client/README.mustache b/src/main/resources/kotlin-client/README.mustache deleted file mode 100644 index 45bf156f8a0..00000000000 --- a/src/main/resources/kotlin-client/README.mustache +++ /dev/null @@ -1,92 +0,0 @@ -# {{packageName}} - Kotlin client library for {{appName}} - -## Requires - -{{#jvm}} -* Kotlin 1.4.30 -* Gradle 6.8.3 -{{/jvm}} -{{#multiplatform}} -* Kotlin 1.5.10 -{{/multiplatform}} - -## Build - -{{#jvm}} -First, create the gradle wrapper script: - -``` -gradle wrapper -``` - -Then, run: - -{{/jvm}} -``` -./gradlew check assemble -``` - -This runs all tests and packages the library. - -## Features/Implementation Notes - -* Supports JSON inputs/outputs, File inputs, and Form inputs. -* Supports collection formats for query parameters: csv, tsv, ssv, pipes. -* Some Kotlin and Java types are fully qualified to avoid conflicts with types defined in OpenAPI definitions. -{{#jvm}}* Implementation of ApiClient is intended to reduce method counts, specifically to benefit Android targets.{{/jvm}} - -{{#generateApiDocs}} - -## Documentation for API Endpoints - -All URIs are relative to *{{{basePath}}}* - -Class | Method | HTTP request | Description ------------- | ------------- | ------------- | ------------- -{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{{summary}}} -{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} -{{/generateApiDocs}} - -{{#generateModelDocs}} - -## Documentation for Models - -{{#modelPackage}} -{{#models}}{{#model}} - [{{{modelPackage}}}.{{{classname}}}]({{modelDocPath}}{{{classname}}}.md) -{{/model}}{{/models}} -{{/modelPackage}} -{{^modelPackage}} -No model defined in this package -{{/modelPackage}} -{{/generateModelDocs}} - -{{! TODO: optional documentation for authorization? }} -## Documentation for Authorization - -{{^authMethods}} -All endpoints do not require authorization. -{{/authMethods}} -{{#authMethods}} -{{#last}} -Authentication schemes defined for the API: -{{/last}} -{{/authMethods}} -{{#authMethods}} - -### {{name}} - -{{#isApiKey}}- **Type**: API key -- **API key parameter name**: {{keyParamName}} -- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} -{{/isApiKey}} -{{#isBasic}}- **Type**: HTTP basic authentication -{{/isBasic}} -{{#isOAuth}}- **Type**: OAuth -- **Flow**: {{flow}} -- **Authorization URL**: {{authorizationUrl}} -- **Scopes**: {{^scopes}}N/A{{/scopes}} -{{#scopes}} - {{scope}}: {{description}} -{{/scopes}} -{{/isOAuth}} - -{{/authMethods}} diff --git a/src/main/resources/kotlin-client/api_doc.mustache b/src/main/resources/kotlin-client/api_doc.mustache deleted file mode 100644 index 951de3c0595..00000000000 --- a/src/main/resources/kotlin-client/api_doc.mustache +++ /dev/null @@ -1,87 +0,0 @@ -# {{classname}}{{#description}} -{{.}}{{/description}} - -All URIs are relative to *{{basePath}}* - -Method | HTTP request | Description -------------- | ------------- | ------------- -{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{summary}} -{{/operation}}{{/operations}} - -{{#operations}} -{{#operation}} - -# **{{operationId}}** -> {{#returnType}}{{.}} {{/returnType}}{{operationId}}({{#allParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}) - -{{summary}}{{#notes}} - -{{.}}{{/notes}} - -### Example -```kotlin -// Import classes: -//import {{{packageName}}}.infrastructure.* -//import {{{modelPackage}}}.* - -{{! TODO: Auth method documentation examples}} -val apiInstance = {{{classname}}}() -{{#allParams}} -val {{{paramName}}} : {{{dataType}}} = {{{example}}} // {{{dataType}}} | {{{description}}} -{{/allParams}} -try { - {{#returnType}}val result : {{{returnType}}}{{#nullableReturnType}}?{{/nullableReturnType}} = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}){{#returnType}} - println(result){{/returnType}} -} catch (e: ClientException) { - println("4xx response calling {{{classname}}}#{{{operationId}}}") - e.printStackTrace() -} catch (e: ServerException) { - println("5xx response calling {{{classname}}}#{{{operationId}}}") - e.printStackTrace() -} -``` - -### Parameters -{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} -Name | Type | Description | Notes -------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} -{{#allParams}} **{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isFile}}**{{dataType}}**{{/isFile}}{{^isFile}}{{#generateModelDocs}}[**{{dataType}}**]({{baseType}}.md){{/generateModelDocs}}{{^generateModelDocs}}**{{dataType}}**{{/generateModelDocs}}{{/isFile}}{{/isPrimitiveType}}| {{description}} |{{^required}} [optional]{{/required}}{{#defaultValue}} [default to {{.}}]{{/defaultValue}}{{#allowableValues}} [enum: {{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}]{{/allowableValues}} -{{/allParams}} - -### Return type - -{{#returnType}}{{#returnTypeIsPrimitive}}**{{returnType}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}{{#generateModelDocs}}[**{{returnType}}**]({{returnBaseType}}.md){{/generateModelDocs}}{{^generateModelDocs}}**{{returnType}}**{{/generateModelDocs}}{{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}null (empty response body){{/returnType}} - -### Authorization - -{{^authMethods}}No authorization required{{/authMethods}} -{{#authMethods}} -{{#isApiKey}} -Configure {{name}}: - ApiClient.apiKey["{{keyParamName}}"] = "" - ApiClient.apiKeyPrefix["{{keyParamName}}"] = "" -{{/isApiKey}} -{{#isBasic}} -{{#isBasicBasic}} -Configure {{name}}: - ApiClient.username = "" - ApiClient.password = "" -{{/isBasicBasic}} -{{#isBasicBearer}} -Configure {{name}}: - ApiClient.accessToken = "" -{{/isBasicBearer}} -{{/isBasic}} -{{#isOAuth}} -Configure {{name}}: - ApiClient.accessToken = "" -{{/isOAuth}} -{{/authMethods}} - -### HTTP request headers - - - **Content-Type**: {{#consumes}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} - - **Accept**: {{#produces}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/produces}}{{^produces}}Not defined{{/produces}} - -{{/operation}} -{{/operations}} diff --git a/src/main/resources/kotlin-client/build.gradle.mustache b/src/main/resources/kotlin-client/build.gradle.mustache deleted file mode 100644 index 5716f8656c3..00000000000 --- a/src/main/resources/kotlin-client/build.gradle.mustache +++ /dev/null @@ -1,160 +0,0 @@ -group '{{groupId}}' -version '{{artifactVersion}}' -{{^omitGradleWrapper}} - -wrapper { - gradleVersion = '7.5' - distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" -} -{{/omitGradleWrapper}} - -buildscript { - ext.kotlin_version = '1.6.10' - {{#jvm-ktor}} - ext.ktor_version = '2.0.3' - {{/jvm-ktor}} - {{#jvm-retrofit2}} - ext.retrofitVersion = '2.9.0' - {{/jvm-retrofit2}} - {{#useRxJava}} - ext.rxJavaVersion = '1.3.8' - {{/useRxJava}} - {{#useRxJava2}} - ext.rxJava2Version = '2.2.21' - {{/useRxJava2}} - {{#useRxJava3}} - ext.rxJava3Version = '3.0.12' - {{/useRxJava3}} - - repositories { - maven { url "https://repo1.maven.org/maven2" } - } - dependencies { - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - {{#kotlinx_serialization}} - classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version" - {{/kotlinx_serialization}} - } -} - -apply plugin: 'kotlin' -{{#moshiCodeGen}} -apply plugin: 'kotlin-kapt' -{{/moshiCodeGen}} -{{#parcelizeModels}} -apply plugin: 'kotlin-parcelize' -{{/parcelizeModels}} -{{#kotlinx_serialization}} -apply plugin: 'kotlinx-serialization' -{{/kotlinx_serialization}} -{{#idea}} -apply plugin: 'idea' -{{/idea}} - -repositories { - maven { url "https://repo1.maven.org/maven2" } -} - -test { - useJUnitPlatform() -} -{{#idea}} - -idea { - module { - sourceDirs += file('src/main/kotlin') - testSourceDirs += file('src/test/kotlin') - } -} -{{/idea}} - -dependencies { - implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - {{^doNotUseRxAndCoroutines}} - {{#useCoroutines}} - implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.3" - {{/useCoroutines}} - {{/doNotUseRxAndCoroutines}} - {{#moshi}} - {{^moshiCodeGen}} - implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - implementation "com.squareup.moshi:moshi-kotlin:1.13.0" - implementation "com.squareup.moshi:moshi-adapters:1.13.0" - {{/moshiCodeGen}} - {{#moshiCodeGen}} - implementation "com.squareup.moshi:moshi:1.13.0" - implementation "com.squareup.moshi:moshi-adapters:1.13.0" - kapt "com.squareup.moshi:moshi-kotlin-codegen:1.13.0" - {{/moshiCodeGen}} - {{/moshi}} - {{#gson}} - implementation "com.google.code.gson:gson:2.9.0" - {{/gson}} - {{#jackson}} - implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - implementation "com.fasterxml.jackson.module:jackson-module-kotlin:2.13.3" - implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.13.3" - {{/jackson}} - {{#kotlinx_serialization}} - implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.3" - {{/kotlinx_serialization}} - {{#jvm-ktor}} - implementation "io.ktor:ktor-client-core:$ktor_version" - implementation "io.ktor:ktor-client-content-negotiation:$ktor_version" - {{#gson}} - implementation "io.ktor:ktor-serialization-gson:$ktor_version" - implementation "io.ktor:ktor-client-gson:$ktor_version" - {{/gson}} - {{#jackson}} - implementation "io.ktor:ktor-client-jackson:$ktor_version" - implementation "io.ktor:ktor-serialization-jackson:$ktor_version" - {{/jackson}} - {{/jvm-ktor}} - {{#jvm-okhttp3}} - implementation "com.squareup.okhttp3:okhttp:3.12.13" - {{/jvm-okhttp3}} - {{#jvm-okhttp4}} - implementation "com.squareup.okhttp3:okhttp:4.10.0" - {{/jvm-okhttp4}} - {{#threetenbp}} - implementation "org.threeten:threetenbp:1.5.1" - {{/threetenbp}} - {{#jvm-retrofit2}} - {{#hasOAuthMethods}} - implementation "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.2" - {{/hasOAuthMethods}} - implementation "com.squareup.okhttp3:logging-interceptor:4.10.0" - {{#useRxJava}} - implementation "io.reactivex:rxjava:$rxJavaVersion" - implementation "com.squareup.retrofit2:adapter-rxjava:$retrofitVersion" - {{/useRxJava}} - {{#useRxJava2}} - implementation "io.reactivex.rxjava2:rxjava:$rxJava2Version" - implementation "com.squareup.retrofit2:adapter-rxjava2:$retrofitVersion" - {{/useRxJava2}} - {{#useRxJava3}} - implementation "io.reactivex.rxjava3:rxjava:$rxJava3Version" - implementation "com.squareup.retrofit2:adapter-rxjava3:2.9.0" - {{/useRxJava3}} - implementation "com.squareup.retrofit2:retrofit:$retrofitVersion" - {{#gson}} - implementation "com.squareup.retrofit2:converter-gson:$retrofitVersion" - {{/gson}} - {{#moshi}} - implementation "com.squareup.retrofit2:converter-moshi:$retrofitVersion" - {{/moshi}} - {{#kotlinx_serialization}} - implementation "com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:0.8.0" - {{/kotlinx_serialization}} - implementation "com.squareup.retrofit2:converter-scalars:$retrofitVersion" - {{/jvm-retrofit2}} - testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" -} -{{#kotlinx_serialization}} - -tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach { - kotlinOptions { - freeCompilerArgs += "-Xopt-in=kotlinx.serialization.ExperimentalSerializationApi" - } -} -{{/kotlinx_serialization}} diff --git a/src/main/resources/kotlin-client/class_doc.mustache b/src/main/resources/kotlin-client/class_doc.mustache deleted file mode 100644 index 623e317aa5f..00000000000 --- a/src/main/resources/kotlin-client/class_doc.mustache +++ /dev/null @@ -1,15 +0,0 @@ -# {{classname}} - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -{{#vars}}**{{name}}** | {{#isEnum}}[**inline**](#{{datatypeWithEnum}}){{/isEnum}}{{^isEnum}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{refClass}}.md){{/isPrimitiveType}}{{/isEnum}} | {{description}} | {{^required}} [optional]{{/required}}{{#isReadOnly}} [readonly]{{/isReadOnly}} -{{/vars}} -{{#vars}}{{#isEnum}} - -{{!NOTE: see java's resources "pojo_doc.mustache" once enums are fully implemented}} -## Enum: {{baseName}} -Name | Value ----- | -----{{#allowableValues}} -{{name}} | {{#values}}{{.}}{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}} -{{/isEnum}}{{/vars}} diff --git a/src/main/resources/kotlin-client/data_class.mustache b/src/main/resources/kotlin-client/data_class.mustache deleted file mode 100644 index 8d2c28acd4a..00000000000 --- a/src/main/resources/kotlin-client/data_class.mustache +++ /dev/null @@ -1,147 +0,0 @@ -{{^multiplatform}} -{{#gson}} -import com.google.gson.annotations.SerializedName -{{/gson}} -{{#moshi}} -import com.squareup.moshi.Json -{{#moshiCodeGen}} -import com.squareup.moshi.JsonClass -{{/moshiCodeGen}} -{{/moshi}} -{{#jackson}} -import com.fasterxml.jackson.annotation.JsonProperty -{{#discriminator}} -import com.fasterxml.jackson.annotation.JsonSubTypes -import com.fasterxml.jackson.annotation.JsonTypeInfo -{{/discriminator}} -{{/jackson}} -{{#kotlinx_serialization}} -import {{#serializableModel}}kotlinx.serialization.Serializable as KSerializable{{/serializableModel}}{{^serializableModel}}kotlinx.serialization.Serializable{{/serializableModel}} -import kotlinx.serialization.SerialName -import kotlinx.serialization.Contextual -{{#enumUnknownDefaultCase}} -import kotlinx.serialization.KSerializer -import kotlinx.serialization.Serializer -import kotlinx.serialization.builtins.serializer -import kotlinx.serialization.encoding.Decoder -import kotlinx.serialization.encoding.Encoder -{{/enumUnknownDefaultCase}} -{{#hasEnums}} -{{/hasEnums}} -{{/kotlinx_serialization}} -{{#parcelizeModels}} -import android.os.Parcelable -import kotlinx.parcelize.Parcelize -{{/parcelizeModels}} -{{/multiplatform}} -{{#multiplatform}} -import kotlinx.serialization.* -import kotlinx.serialization.descriptors.* -import kotlinx.serialization.encoding.* -{{/multiplatform}} -{{#serializableModel}} -import java.io.Serializable -{{/serializableModel}} -{{#generateRoomModels}} -import {{roomModelPackage}}.{{classname}}RoomModel -import {{packageName}}.infrastructure.ITransformForStorage -{{/generateRoomModels}} - -/** - * {{{description}}} - * -{{#allVars}} - * @param {{{name}}} {{{description}}} -{{/allVars}} - */ -{{#parcelizeModels}} -@Parcelize -{{/parcelizeModels}} -{{#multiplatform}}{{^discriminator}}@Serializable{{/discriminator}}{{/multiplatform}}{{#kotlinx_serialization}}{{#serializableModel}}@KSerializable{{/serializableModel}}{{^serializableModel}}@Serializable{{/serializableModel}}{{/kotlinx_serialization}}{{#moshi}}{{#moshiCodeGen}}@JsonClass(generateAdapter = true){{/moshiCodeGen}}{{/moshi}}{{#jackson}}{{#discriminator}}{{>typeInfoAnnotation}}{{/discriminator}}{{/jackson}} -{{#isDeprecated}} -@Deprecated(message = "This schema is deprecated.") -{{/isDeprecated}} -{{#nonPublicApi}}internal {{/nonPublicApi}}{{#discriminator}}interface{{/discriminator}}{{^discriminator}}data class{{/discriminator}} {{classname}}{{^discriminator}} ( - -{{#allVars}} -{{#required}}{{>data_class_req_var}}{{/required}}{{^required}}{{>data_class_opt_var}}{{/required}}{{^-last}},{{/-last}} - -{{/allVars}} -){{/discriminator}}{{#parent}}{{^serializableModel}}{{^parcelizeModels}} : {{{parent}}}{{#isMap}}(){{/isMap}}{{#isArray}}(){{/isArray}}{{/parcelizeModels}}{{/serializableModel}}{{/parent}}{{#parent}}{{#serializableModel}}{{^parcelizeModels}} : {{{parent}}}{{#isMap}}(){{/isMap}}{{#isArray}}(){{/isArray}}, Serializable{{/parcelizeModels}}{{/serializableModel}}{{/parent}}{{#parent}}{{^serializableModel}}{{#parcelizeModels}} : {{{parent}}}{{#isMap}}(){{/isMap}}{{#isArray}}(){{/isArray}}, Parcelable{{/parcelizeModels}}{{/serializableModel}}{{/parent}}{{#parent}}{{#serializableModel}}{{#parcelizeModels}} : {{{parent}}}{{#isMap}}(){{/isMap}}{{#isArray}}(){{/isArray}}, Serializable, Parcelable{{/parcelizeModels}}{{/serializableModel}}{{/parent}}{{^parent}}{{#serializableModel}}{{^parcelizeModels}} : Serializable{{/parcelizeModels}}{{/serializableModel}}{{/parent}}{{^parent}}{{^serializableModel}}{{#parcelizeModels}} : Parcelable{{/parcelizeModels}}{{/serializableModel}}{{/parent}}{{^parent}}{{#serializableModel}}{{#parcelizeModels}} : Serializable, Parcelable{{/parcelizeModels}}{{/serializableModel}}{{/parent}}{{#generateRoomModels}}{{#parent}}, {{/parent}}{{^discriminator}}{{^parent}}:{{/parent}} ITransformForStorage<{{classname}}RoomModel>{{/discriminator}}{{/generateRoomModels}}{{#vendorExtensions.x-has-data-class-body}} { -{{/vendorExtensions.x-has-data-class-body}} -{{#generateRoomModels}} - companion object { } - {{^discriminator}}override fun toRoomModel(): {{classname}}RoomModel = - {{classname}}RoomModel(roomTableId = 0, - {{#allVars}}{{#items.isPrimitiveType}}{{#isArray}}{{#isList}}{{name}} = this.{{name}},{{/isList}}{{/isArray}}{{/items.isPrimitiveType}}{{^isEnum}}{{^isArray}}{{name}} = this.{{name}},{{/isArray}}{{/isEnum}}{{#isEnum}}{{^isArray}}{{name}} = this.{{name}},{{/isArray}}{{/isEnum}} - {{/allVars}} - ){{/discriminator}} -{{/generateRoomModels}} -{{#serializableModel}} - {{#nonPublicApi}}internal {{/nonPublicApi}}companion object { - private const val serialVersionUID: Long = 123 - } -{{/serializableModel}} -{{#discriminator}}{{#vars}}{{#required}} -{{>interface_req_var}}{{/required}}{{^required}} -{{>interface_opt_var}}{{/required}}{{/vars}}{{/discriminator}} -{{#hasEnums}} -{{#vars}} -{{#isEnum}} - /** - * {{{description}}} - * - * Values: {{#allowableValues}}{{#enumVars}}{{&name}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}} - */ - {{^multiplatform}} - {{#kotlinx_serialization}} - {{#serializableModel}}@KSerializable{{/serializableModel}}{{^serializableModel}}@Serializable{{#enumUnknownDefaultCase}}(with = {{classname}}Serializer::class){{/enumUnknownDefaultCase}}{{/serializableModel}} - {{/kotlinx_serialization}} - {{/multiplatform}} - {{#multiplatform}} - @Serializable - {{/multiplatform}} - {{#nonPublicApi}}internal {{/nonPublicApi}}enum class {{{nameInCamelCase}}}(val value: {{^isContainer}}{{dataType}}{{/isContainer}}{{#isContainer}}kotlin.String{{/isContainer}}) { - {{#allowableValues}} - {{#enumVars}} - {{^multiplatform}} - {{#moshi}} - @Json(name = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} - {{/moshi}} - {{#gson}} - @SerializedName(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} - {{/gson}} - {{#jackson}} - @JsonProperty(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} - {{/jackson}} - {{#kotlinx_serialization}} - @SerialName(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} - {{/kotlinx_serialization}} - {{/multiplatform}} - {{#multiplatform}} - @SerialName(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} - {{/multiplatform}} - {{/enumVars}} - {{/allowableValues}} - }{{#kotlinx_serialization}}{{#enumUnknownDefaultCase}} - - @Serializer(forClass = {{{nameInCamelCase}}}::class) - internal object {{nameInCamelCase}}Serializer : KSerializer<{{nameInCamelCase}}> { - override val descriptor = {{{dataType}}}.serializer().descriptor - - override fun deserialize(decoder: Decoder): {{nameInCamelCase}} { - val value = decoder.decodeSerializableValue({{{dataType}}}.serializer()) - return {{nameInCamelCase}}.values().firstOrNull { it.value == value } - ?: {{nameInCamelCase}}.{{#allowableValues}}{{#enumVars}}{{#-last}}{{&name}}{{/-last}}{{/enumVars}}{{/allowableValues}} - } - - override fun serialize(encoder: Encoder, value: {{nameInCamelCase}}) { - encoder.encodeSerializableValue({{{dataType}}}.serializer(), value.value) - } - }{{/enumUnknownDefaultCase}}{{/kotlinx_serialization}} -{{/isEnum}} -{{/vars}} -{{/hasEnums}} -{{#vendorExtensions.x-has-data-class-body}} -} -{{/vendorExtensions.x-has-data-class-body}} diff --git a/src/main/resources/kotlin-client/data_class_opt_var.mustache b/src/main/resources/kotlin-client/data_class_opt_var.mustache deleted file mode 100644 index f0198c9e6b1..00000000000 --- a/src/main/resources/kotlin-client/data_class_opt_var.mustache +++ /dev/null @@ -1,21 +0,0 @@ -{{#description}} - /* {{{.}}} */ -{{/description}} - {{^multiplatform}} - {{#moshi}} - @Json(name = "{{{vendorExtensions.x-base-name-literal}}}") - {{/moshi}} - {{#gson}} - @SerializedName("{{{vendorExtensions.x-base-name-literal}}}") - {{/gson}} - {{#jackson}} - @field:JsonProperty("{{{vendorExtensions.x-base-name-literal}}}") - {{/jackson}} - {{#kotlinx_serialization}} - {{^isEnum}}{{^isArray}}{{^isPrimitiveType}}{{^isModel}}@Contextual {{/isModel}}{{/isPrimitiveType}}{{/isArray}}{{/isEnum}}@SerialName(value = "{{{vendorExtensions.x-base-name-literal}}}") - {{/kotlinx_serialization}} - {{/multiplatform}} - {{#deprecated}} - @Deprecated(message = "This property is deprecated.") - {{/deprecated}} - {{#multiplatform}}@SerialName(value = "{{{vendorExtensions.x-base-name-literal}}}") {{/multiplatform}}{{#isInherited}}override {{/isInherited}}{{>modelMutable}} {{{name}}}: {{#isArray}}{{#isList}}{{#uniqueItems}}kotlin.collections.{{#modelMutable}}Mutable{{/modelMutable}}Set{{/uniqueItems}}{{^uniqueItems}}kotlin.collections.{{#modelMutable}}Mutable{{/modelMutable}}List{{/uniqueItems}}{{/isList}}{{^isList}}kotlin.Array{{/isList}}<{{^items.isEnum}}{{^items.isPrimitiveType}}{{^items.isModel}}{{#kotlinx_serialization}}@Contextual {{/kotlinx_serialization}}{{/items.isModel}}{{/items.isPrimitiveType}}{{{items.dataType}}}{{/items.isEnum}}{{#items.isEnum}}{{classname}}.{{{nameInCamelCase}}}{{/items.isEnum}}>{{/isArray}}{{^isEnum}}{{^isArray}}{{{dataType}}}{{/isArray}}{{/isEnum}}{{#isEnum}}{{^isArray}}{{classname}}.{{{nameInCamelCase}}}{{/isArray}}{{/isEnum}}? = {{^defaultValue}}null{{/defaultValue}}{{#defaultValue}}{{^isNumber}}{{{defaultValue}}}{{/isNumber}}{{#isNumber}}{{^multiplatform}}{{{dataType}}}("{{{defaultValue}}}"){{/multiplatform}}{{#multiplatform}}({{{defaultValue}}}).toDouble(){{/multiplatform}}{{/isNumber}}{{/defaultValue}} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/data_class_req_var.mustache b/src/main/resources/kotlin-client/data_class_req_var.mustache deleted file mode 100644 index 07d765fdb7a..00000000000 --- a/src/main/resources/kotlin-client/data_class_req_var.mustache +++ /dev/null @@ -1,21 +0,0 @@ -{{#description}} - /* {{{.}}} */ -{{/description}} - {{^multiplatform}} - {{#moshi}} - @Json(name = "{{{vendorExtensions.x-base-name-literal}}}") - {{/moshi}} - {{#gson}} - @SerializedName("{{{vendorExtensions.x-base-name-literal}}}") - {{/gson}} - {{#jackson}} - @field:JsonProperty("{{{vendorExtensions.x-base-name-literal}}}") - {{/jackson}} - {{#kotlinx_serialization}} - {{^isEnum}}{{^isArray}}{{^isPrimitiveType}}{{^isModel}}@Contextual {{/isModel}}{{/isPrimitiveType}}{{/isArray}}{{/isEnum}}@SerialName(value = "{{{vendorExtensions.x-base-name-literal}}}") - {{/kotlinx_serialization}} - {{/multiplatform}} - {{#deprecated}} - @Deprecated(message = "This property is deprecated.") - {{/deprecated}} - {{#multiplatform}}@SerialName(value = "{{{vendorExtensions.x-base-name-literal}}}") @Required {{/multiplatform}}{{#isInherited}}override {{/isInherited}}{{>modelMutable}} {{{name}}}: {{#isArray}}{{#isList}}{{#isUniqueItems}}kotlin.collections.{{#modelMutable}}Mutable{{/modelMutable}}Set{{/isUniqueItems}}{{^isUniqueItems}}kotlin.collections.{{#modelMutable}}Mutable{{/modelMutable}}List{{/isUniqueItems}}{{/isList}}{{^isList}}kotlin.Array{{/isList}}<{{^items.isEnum}}{{^items.isPrimitiveType}}{{^items.isModel}}{{#kotlinx_serialization}}@Contextual {{/kotlinx_serialization}}{{/items.isModel}}{{/items.isPrimitiveType}}{{{items.dataType}}}{{/items.isEnum}}{{#items.isEnum}}{{classname}}.{{{nameInCamelCase}}}{{/items.isEnum}}>{{/isArray}}{{^isEnum}}{{^isArray}}{{{dataType}}}{{/isArray}}{{/isEnum}}{{#isEnum}}{{^isArray}}{{classname}}.{{{nameInCamelCase}}}{{/isArray}}{{/isEnum}}{{#isNullable}}?{{/isNullable}}{{#defaultValue}} = {{^isNumber}}{{{defaultValue}}}{{/isNumber}}{{#isNumber}}{{^multiplatform}}{{{dataType}}}("{{{defaultValue}}}"){{/multiplatform}}{{#multiplatform}}({{{defaultValue}}}).toDouble(){{/multiplatform}}{{/isNumber}}{{/defaultValue}} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/enum_class.mustache b/src/main/resources/kotlin-client/enum_class.mustache deleted file mode 100644 index 4d11f8f2653..00000000000 --- a/src/main/resources/kotlin-client/enum_class.mustache +++ /dev/null @@ -1,104 +0,0 @@ -{{^multiplatform}} -{{#gson}} -import com.google.gson.annotations.SerializedName -{{/gson}} -{{#moshi}} -import com.squareup.moshi.Json -{{/moshi}} -{{#jackson}} -import com.fasterxml.jackson.annotation.JsonProperty -{{/jackson}} -{{#kotlinx_serialization}} -import kotlinx.serialization.SerialName -import kotlinx.serialization.Serializable -{{#enumUnknownDefaultCase}} -import kotlinx.serialization.KSerializer -import kotlinx.serialization.Serializer -import kotlinx.serialization.builtins.serializer -import kotlinx.serialization.encoding.Decoder -import kotlinx.serialization.encoding.Encoder -{{/enumUnknownDefaultCase}} -{{/kotlinx_serialization}} -{{/multiplatform}} -{{#multiplatform}} -import kotlinx.serialization.* -{{/multiplatform}} - -/** - * {{{description}}} - * - * Values: {{#allowableValues}}{{#enumVars}}{{&name}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}} - */ -{{#multiplatform}}@Serializable{{/multiplatform}}{{#kotlinx_serialization}}@Serializable{{#enumUnknownDefaultCase}}(with = {{classname}}Serializer::class){{/enumUnknownDefaultCase}}{{/kotlinx_serialization}} -{{#nonPublicApi}}internal {{/nonPublicApi}}enum class {{classname}}(val value: {{{dataType}}}) { -{{#allowableValues}}{{#enumVars}} - {{^multiplatform}} - {{#moshi}} - @Json(name = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) - {{/moshi}} - {{#gson}} - @SerializedName(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) - {{/gson}} - {{#jackson}} - @JsonProperty(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) - {{/jackson}} - {{#kotlinx_serialization}} - @SerialName(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) - {{/kotlinx_serialization}} - {{/multiplatform}} - {{#multiplatform}} - @SerialName(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) - {{/multiplatform}} - {{#isArray}} - {{#isList}} - {{&name}}(listOf({{{value}}})){{^-last}},{{/-last}}{{#-last}};{{/-last}} - {{/isList}} - {{^isList}} - {{&name}}(arrayOf({{{value}}})){{^-last}},{{/-last}}{{#-last}};{{/-last}} - {{/isList}} - {{/isArray}} - {{^isArray}} - {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} - {{/isArray}} -{{/enumVars}}{{/allowableValues}} - /** - * Override toString() to avoid using the enum variable name as the value, and instead use - * the actual value defined in the API spec file. - * - * This solves a problem when the variable name and its value are different, and ensures that - * the client sends the correct enum values to the server always. - */ - override fun toString(): String = value{{^isString}}.toString(){{/isString}} - - companion object { - /** - * Converts the provided [data] to a [String] on success, null otherwise. - */ - fun encode(data: kotlin.Any?): kotlin.String? = if (data is {{classname}}) "$data" else null - - /** - * Returns a valid [{{classname}}] for [data], null otherwise. - */ - fun decode(data: kotlin.Any?): {{classname}}? = data?.let { - val normalizedData = "$it".lowercase() - values().firstOrNull { value -> - it == value || normalizedData == "$value".lowercase() - } - } - } -}{{#kotlinx_serialization}}{{#enumUnknownDefaultCase}} - -@Serializer(forClass = {{classname}}::class) -internal object {{classname}}Serializer : KSerializer<{{classname}}> { - override val descriptor = {{{dataType}}}.serializer().descriptor - - override fun deserialize(decoder: Decoder): {{classname}} { - val value = decoder.decodeSerializableValue({{{dataType}}}.serializer()) - return {{classname}}.values().firstOrNull { it.value == value } - ?: {{classname}}.{{#allowableValues}}{{#enumVars}}{{#-last}}{{&name}}{{/-last}}{{/enumVars}}{{/allowableValues}} - } - - override fun serialize(encoder: Encoder, value: {{classname}}) { - encoder.encodeSerializableValue({{{dataType}}}.serializer(), value.value) - } -}{{/enumUnknownDefaultCase}}{{/kotlinx_serialization}} diff --git a/src/main/resources/kotlin-client/enum_doc.mustache b/src/main/resources/kotlin-client/enum_doc.mustache deleted file mode 100644 index fcb3d7e61aa..00000000000 --- a/src/main/resources/kotlin-client/enum_doc.mustache +++ /dev/null @@ -1,7 +0,0 @@ -# {{classname}} - -## Enum - -{{#allowableValues}}{{#enumVars}} - * `{{name}}` (value: `{{{value}}}`) -{{/enumVars}}{{/allowableValues}} diff --git a/src/main/resources/kotlin-client/gradle-wrapper.jar b/src/main/resources/kotlin-client/gradle-wrapper.jar deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/src/main/resources/kotlin-client/gradle-wrapper.properties.mustache b/src/main/resources/kotlin-client/gradle-wrapper.properties.mustache deleted file mode 100644 index 8cf6eb5ad22..00000000000 --- a/src/main/resources/kotlin-client/gradle-wrapper.properties.mustache +++ /dev/null @@ -1,5 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.3-all.zip -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/src/main/resources/kotlin-client/gradlew.bat.mustache b/src/main/resources/kotlin-client/gradlew.bat.mustache deleted file mode 100644 index 107acd32c4e..00000000000 --- a/src/main/resources/kotlin-client/gradlew.bat.mustache +++ /dev/null @@ -1,89 +0,0 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/src/main/resources/kotlin-client/gradlew.mustache b/src/main/resources/kotlin-client/gradlew.mustache deleted file mode 100644 index 4f906e0c811..00000000000 --- a/src/main/resources/kotlin-client/gradlew.mustache +++ /dev/null @@ -1,185 +0,0 @@ -#!/usr/bin/env sh - -# -# Copyright 2015 the original author or authors. -# -# 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. -# - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn () { - echo "$*" -} - -die () { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=`expr $i + 1` - done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -exec "$JAVACMD" "$@" diff --git a/src/main/resources/kotlin-client/infrastructure/ApiAbstractions.kt.mustache b/src/main/resources/kotlin-client/infrastructure/ApiAbstractions.kt.mustache deleted file mode 100644 index c8b2269da95..00000000000 --- a/src/main/resources/kotlin-client/infrastructure/ApiAbstractions.kt.mustache +++ /dev/null @@ -1,23 +0,0 @@ -package {{packageName}}.infrastructure - -{{#nonPublicApi}}internal {{/nonPublicApi}}typealias MultiValueMap = MutableMap> - -{{#nonPublicApi}}internal {{/nonPublicApi}}fun collectionDelimiter(collectionFormat: String) = when(collectionFormat) { - "csv" -> "," - "tsv" -> "\t" - "pipe" -> "|" - "space" -> " " - else -> "" -} - -{{#nonPublicApi}}internal {{/nonPublicApi}}val defaultMultiValueConverter: (item: Any?) -> String = { item -> "$item" } - -{{#nonPublicApi}}internal {{/nonPublicApi}}fun toMultiValue(items: Array, collectionFormat: String, map: (item: T) -> String = defaultMultiValueConverter) - = toMultiValue(items.asIterable(), collectionFormat, map) - -{{#nonPublicApi}}internal {{/nonPublicApi}}fun toMultiValue(items: Iterable, collectionFormat: String, map: (item: T) -> String = defaultMultiValueConverter): List { - return when(collectionFormat) { - "multi" -> items.map(map) - else -> listOf(items.joinToString(separator = collectionDelimiter(collectionFormat), transform = map)) - } -} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/infrastructure/PartConfig.kt.mustache b/src/main/resources/kotlin-client/infrastructure/PartConfig.kt.mustache deleted file mode 100644 index f70c18eff46..00000000000 --- a/src/main/resources/kotlin-client/infrastructure/PartConfig.kt.mustache +++ /dev/null @@ -1,11 +0,0 @@ -package {{packageName}}.infrastructure - -/** - * Defines a config object for a given part of a multi-part request. - * NOTE: Headers is a Map because rfc2616 defines - * multi-valued headers as csv-only. - */ -{{#nonPublicApi}}internal {{/nonPublicApi}}data class PartConfig( - val headers: MutableMap = mutableMapOf(), - val body: T? = null -) diff --git a/src/main/resources/kotlin-client/infrastructure/RequestConfig.kt.mustache b/src/main/resources/kotlin-client/infrastructure/RequestConfig.kt.mustache deleted file mode 100644 index ef1b0517e78..00000000000 --- a/src/main/resources/kotlin-client/infrastructure/RequestConfig.kt.mustache +++ /dev/null @@ -1,17 +0,0 @@ -package {{packageName}}.infrastructure - -/** - * Defines a config object for a given request. - * NOTE: This object doesn't include 'body' because it - * allows for caching of the constructed object - * for many request definitions. - * NOTE: Headers is a Map because rfc2616 defines - * multi-valued headers as csv-only. - */ -{{#nonPublicApi}}internal {{/nonPublicApi}}data class RequestConfig( - val method: RequestMethod, - val path: String, - val headers: MutableMap = mutableMapOf(), - val query: MutableMap> = mutableMapOf(), - val body: T? = null -) \ No newline at end of file diff --git a/src/main/resources/kotlin-client/infrastructure/RequestMethod.kt.mustache b/src/main/resources/kotlin-client/infrastructure/RequestMethod.kt.mustache deleted file mode 100644 index 8c7c162f477..00000000000 --- a/src/main/resources/kotlin-client/infrastructure/RequestMethod.kt.mustache +++ /dev/null @@ -1,8 +0,0 @@ -package {{packageName}}.infrastructure - -/** - * Provides enumerated HTTP verbs - */ -{{#nonPublicApi}}internal {{/nonPublicApi}}enum class RequestMethod { - GET, DELETE, HEAD, OPTIONS, PATCH, POST, PUT -} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/interface_opt_var.mustache b/src/main/resources/kotlin-client/interface_opt_var.mustache deleted file mode 100644 index 344a6c251d8..00000000000 --- a/src/main/resources/kotlin-client/interface_opt_var.mustache +++ /dev/null @@ -1,18 +0,0 @@ -{{#description}} - /* {{{.}}} */ -{{/description}} - {{^multiplatform}} - {{#moshi}} - @Json(name = "{{{vendorExtensions.x-base-name-literal}}}") - {{/moshi}} - {{#gson}} - @get:SerializedName("{{{vendorExtensions.x-base-name-literal}}}") - {{/gson}} - {{#jackson}} - @get:JsonProperty("{{{vendorExtensions.x-base-name-literal}}}") - {{/jackson}} - {{#kotlinx_serialization}} - {{^isEnum}}{{^isArray}}{{^isPrimitiveType}}{{^isModel}}@Contextual {{/isModel}}{{/isPrimitiveType}}{{/isArray}}{{/isEnum}}@SerialName(value = "{{{vendorExtensions.x-base-name-literal}}}") - {{/kotlinx_serialization}} - {{/multiplatform}} - {{#multiplatform}}@SerialName(value = "{{{vendorExtensions.x-base-name-literal}}}") {{/multiplatform}}{{>modelMutable}} {{{name}}}: {{#isArray}}{{#isList}}kotlin.collections.{{#modelMutable}}Mutable{{/modelMutable}}List{{/isList}}{{^isList}}kotlin.Array{{/isList}}<{{^items.isEnum}}{{^items.isPrimitiveType}}{{^items.isModel}}{{#kotlinx_serialization}}@Contextual {{/kotlinx_serialization}}{{/items.isModel}}{{/items.isPrimitiveType}}{{{items.dataType}}}{{/items.isEnum}}{{#items.isEnum}}{{classname}}.{{{nameInCamelCase}}}{{/items.isEnum}}>{{/isArray}}{{^isEnum}}{{^isArray}}{{{dataType}}}{{/isArray}}{{/isEnum}}{{#isEnum}}{{^isArray}}{{classname}}.{{{nameInCamelCase}}}{{/isArray}}{{/isEnum}}? \ No newline at end of file diff --git a/src/main/resources/kotlin-client/interface_req_var.mustache b/src/main/resources/kotlin-client/interface_req_var.mustache deleted file mode 100644 index 743069ff554..00000000000 --- a/src/main/resources/kotlin-client/interface_req_var.mustache +++ /dev/null @@ -1,18 +0,0 @@ -{{#description}} - /* {{{.}}} */ -{{/description}} - {{^multiplatform}} - {{#moshi}} - @Json(name = "{{{vendorExtensions.x-base-name-literal}}}") - {{/moshi}} - {{#gson}} - @get:SerializedName("{{{vendorExtensions.x-base-name-literal}}}") - {{/gson}} - {{#jackson}} - @get:JsonProperty("{{{vendorExtensions.x-base-name-literal}}}") - {{/jackson}} - {{#kotlinx_serialization}} - {{^isEnum}}{{^isArray}}{{^isPrimitiveType}}{{^isModel}}@Contextual {{/isModel}}{{/isPrimitiveType}}{{/isArray}}{{/isEnum}}@SerialName(value = "{{{vendorExtensions.x-base-name-literal}}}") - {{/kotlinx_serialization}} - {{/multiplatform}} - {{#multiplatform}}@SerialName(value = "{{{vendorExtensions.x-base-name-literal}}}") @Required {{/multiplatform}}{{>modelMutable}} {{{name}}}: {{#isArray}}{{#isList}}kotlin.collections.{{#modelMutable}}Mutable{{/modelMutable}}List{{/isList}}{{^isList}}kotlin.Array{{/isList}}<{{^items.isEnum}}{{^items.isPrimitiveType}}{{^items.isModel}}{{#kotlinx_serialization}}@Contextual {{/kotlinx_serialization}}{{/items.isModel}}{{/items.isPrimitiveType}}{{{items.dataType}}}{{/items.isEnum}}{{#items.isEnum}}{{classname}}.{{{nameInCamelCase}}}{{/items.isEnum}}>{{/isArray}}{{^isEnum}}{{^isArray}}{{{dataType}}}{{/isArray}}{{/isEnum}}{{#isEnum}}{{^isArray}}{{classname}}.{{{nameInCamelCase}}}{{/isArray}}{{/isEnum}}{{#isNullable}}?{{/isNullable}} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/jvm-common/infrastructure/AtomicBooleanAdapter.kt.mustache b/src/main/resources/kotlin-client/jvm-common/infrastructure/AtomicBooleanAdapter.kt.mustache deleted file mode 100644 index 098ff54c6a1..00000000000 --- a/src/main/resources/kotlin-client/jvm-common/infrastructure/AtomicBooleanAdapter.kt.mustache +++ /dev/null @@ -1,21 +0,0 @@ -package {{packageName}}.infrastructure - -import kotlinx.serialization.KSerializer -import kotlinx.serialization.Serializer -import kotlinx.serialization.encoding.Decoder -import kotlinx.serialization.encoding.Encoder -import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor -import kotlinx.serialization.descriptors.PrimitiveKind -import kotlinx.serialization.descriptors.SerialDescriptor -import java.util.concurrent.atomic.AtomicBoolean - -@Serializer(forClass = AtomicBoolean::class) -{{#nonPublicApi}}internal {{/nonPublicApi}}object AtomicBooleanAdapter : KSerializer { - override fun serialize(encoder: Encoder, value: AtomicBoolean) { - encoder.encodeBoolean(value.get()) - } - - override fun deserialize(decoder: Decoder): AtomicBoolean = AtomicBoolean(decoder.decodeBoolean()) - - override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("AtomicBoolean", PrimitiveKind.BOOLEAN) -} diff --git a/src/main/resources/kotlin-client/jvm-common/infrastructure/AtomicIntegerAdapter.kt.mustache b/src/main/resources/kotlin-client/jvm-common/infrastructure/AtomicIntegerAdapter.kt.mustache deleted file mode 100644 index 6e16b5b78a6..00000000000 --- a/src/main/resources/kotlin-client/jvm-common/infrastructure/AtomicIntegerAdapter.kt.mustache +++ /dev/null @@ -1,21 +0,0 @@ -package {{packageName}}.infrastructure - -import kotlinx.serialization.KSerializer -import kotlinx.serialization.Serializer -import kotlinx.serialization.encoding.Decoder -import kotlinx.serialization.encoding.Encoder -import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor -import kotlinx.serialization.descriptors.PrimitiveKind -import kotlinx.serialization.descriptors.SerialDescriptor -import java.util.concurrent.atomic.AtomicInteger - -@Serializer(forClass = AtomicInteger::class) -{{#nonPublicApi}}internal {{/nonPublicApi}}object AtomicIntegerAdapter : KSerializer { - override fun serialize(encoder: Encoder, value: AtomicInteger) { - encoder.encodeInt(value.get()) - } - - override fun deserialize(decoder: Decoder): AtomicInteger = AtomicInteger(decoder.decodeInt()) - - override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("AtomicInteger", PrimitiveKind.INT) -} diff --git a/src/main/resources/kotlin-client/jvm-common/infrastructure/AtomicLongAdapter.kt.mustache b/src/main/resources/kotlin-client/jvm-common/infrastructure/AtomicLongAdapter.kt.mustache deleted file mode 100644 index bc2142c676a..00000000000 --- a/src/main/resources/kotlin-client/jvm-common/infrastructure/AtomicLongAdapter.kt.mustache +++ /dev/null @@ -1,21 +0,0 @@ -package {{packageName}}.infrastructure - -import kotlinx.serialization.KSerializer -import kotlinx.serialization.Serializer -import kotlinx.serialization.encoding.Decoder -import kotlinx.serialization.encoding.Encoder -import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor -import kotlinx.serialization.descriptors.PrimitiveKind -import kotlinx.serialization.descriptors.SerialDescriptor -import java.util.concurrent.atomic.AtomicLong - -@Serializer(forClass = AtomicLong::class) -{{#nonPublicApi}}internal {{/nonPublicApi}}object AtomicLongAdapter : KSerializer { - override fun serialize(encoder: Encoder, value: AtomicLong) { - encoder.encodeLong(value.get()) - } - - override fun deserialize(decoder: Decoder): AtomicLong = AtomicLong(decoder.decodeLong()) - - override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("AtomicLong", PrimitiveKind.LONG) -} diff --git a/src/main/resources/kotlin-client/jvm-common/infrastructure/BigDecimalAdapter.kt.mustache b/src/main/resources/kotlin-client/jvm-common/infrastructure/BigDecimalAdapter.kt.mustache deleted file mode 100644 index fd08ed4a04c..00000000000 --- a/src/main/resources/kotlin-client/jvm-common/infrastructure/BigDecimalAdapter.kt.mustache +++ /dev/null @@ -1,38 +0,0 @@ -package {{packageName}}.infrastructure - -{{#kotlinx_serialization}} -import kotlinx.serialization.KSerializer -import kotlinx.serialization.Serializer -import kotlinx.serialization.encoding.Decoder -import kotlinx.serialization.encoding.Encoder -import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor -import kotlinx.serialization.descriptors.PrimitiveKind -import kotlinx.serialization.descriptors.SerialDescriptor -{{/kotlinx_serialization}} -{{#moshi}} -import com.squareup.moshi.FromJson -import com.squareup.moshi.ToJson -{{/moshi}} -import java.math.BigDecimal - -{{#kotlinx_serialization}} -@Serializer(forClass = BigDecimal::class) -{{#nonPublicApi}}internal {{/nonPublicApi}}object BigDecimalAdapter : KSerializer { - override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("BigDecimal", PrimitiveKind.STRING) - override fun deserialize(decoder: Decoder): BigDecimal = BigDecimal(decoder.decodeString()) - override fun serialize(encoder: Encoder, value: BigDecimal) = encoder.encodeString(value.toPlainString()) -} -{{/kotlinx_serialization}} -{{#moshi}} -{{#nonPublicApi}}internal {{/nonPublicApi}}class BigDecimalAdapter { - @ToJson - fun toJson(value: BigDecimal): String { - return value.toPlainString() - } - - @FromJson - fun fromJson(value: String): BigDecimal { - return BigDecimal(value) - } -} -{{/moshi}} diff --git a/src/main/resources/kotlin-client/jvm-common/infrastructure/BigIntegerAdapter.kt.mustache b/src/main/resources/kotlin-client/jvm-common/infrastructure/BigIntegerAdapter.kt.mustache deleted file mode 100644 index 5110e25b1d6..00000000000 --- a/src/main/resources/kotlin-client/jvm-common/infrastructure/BigIntegerAdapter.kt.mustache +++ /dev/null @@ -1,43 +0,0 @@ -package {{packageName}}.infrastructure - -{{#kotlinx_serialization}} -import kotlinx.serialization.KSerializer -import kotlinx.serialization.Serializer -import kotlinx.serialization.encoding.Decoder -import kotlinx.serialization.encoding.Encoder -import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor -import kotlinx.serialization.descriptors.PrimitiveKind -import kotlinx.serialization.descriptors.SerialDescriptor -{{/kotlinx_serialization}} -{{#moshi}} -import com.squareup.moshi.FromJson -import com.squareup.moshi.ToJson -{{/moshi}} -import java.math.BigInteger - -{{#kotlinx_serialization}} -@Serializer(forClass = BigInteger::class) -{{#nonPublicApi}}internal {{/nonPublicApi}}object BigIntegerAdapter : KSerializer { - override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("BigInteger", PrimitiveKind.STRING) - override fun deserialize(decoder: Decoder): BigInteger { - return BigInteger(decoder.decodeString()) - } - - override fun serialize(encoder: Encoder, value: BigInteger) { - encoder.encodeString(value.toString()) - } -} -{{/kotlinx_serialization}} -{{#moshi}} -{{#nonPublicApi}}internal {{/nonPublicApi}}class BigIntegerAdapter { - @ToJson - fun toJson(value: BigInteger): String { - return value.toString() - } - - @FromJson - fun fromJson(value: String): BigInteger { - return BigInteger(value) - } -} -{{/moshi}} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/jvm-common/infrastructure/ByteArrayAdapter.kt.mustache b/src/main/resources/kotlin-client/jvm-common/infrastructure/ByteArrayAdapter.kt.mustache deleted file mode 100644 index 9f56848226c..00000000000 --- a/src/main/resources/kotlin-client/jvm-common/infrastructure/ByteArrayAdapter.kt.mustache +++ /dev/null @@ -1,50 +0,0 @@ -package {{packageName}}.infrastructure - -{{#moshi}} -import com.squareup.moshi.FromJson -import com.squareup.moshi.ToJson -{{/moshi}} -{{#gson}} -import com.google.gson.TypeAdapter -import com.google.gson.stream.JsonReader -import com.google.gson.stream.JsonWriter -import com.google.gson.stream.JsonToken.NULL -import java.io.IOException -{{/gson}} - -{{#moshi}} -{{#nonPublicApi}}internal {{/nonPublicApi}}class ByteArrayAdapter { - @ToJson - fun toJson(data: ByteArray): String = String(data) - - @FromJson - fun fromJson(data: String): ByteArray = data.toByteArray() -} -{{/moshi}} -{{#gson}} -{{#nonPublicApi}}internal {{/nonPublicApi}}class ByteArrayAdapter : TypeAdapter() { - @Throws(IOException::class) - override fun write(out: JsonWriter?, value: ByteArray?) { - if (value == null) { - out?.nullValue() - } else { - out?.value(String(value)) - } - } - - @Throws(IOException::class) - override fun read(out: JsonReader?): ByteArray? { - out ?: return null - - when (out.peek()) { - NULL -> { - out.nextNull() - return null - } - else -> { - return out.nextString().toByteArray() - } - } - } -} -{{/gson}} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/jvm-common/infrastructure/LocalDateAdapter.kt.mustache b/src/main/resources/kotlin-client/jvm-common/infrastructure/LocalDateAdapter.kt.mustache deleted file mode 100644 index cdcf444ec32..00000000000 --- a/src/main/resources/kotlin-client/jvm-common/infrastructure/LocalDateAdapter.kt.mustache +++ /dev/null @@ -1,86 +0,0 @@ -package {{packageName}}.infrastructure - -{{#moshi}} -import com.squareup.moshi.FromJson -import com.squareup.moshi.ToJson -{{/moshi}} -{{#gson}} -import com.google.gson.TypeAdapter -import com.google.gson.stream.JsonReader -import com.google.gson.stream.JsonWriter -import com.google.gson.stream.JsonToken.NULL -import java.io.IOException -{{/gson}} -{{#kotlinx_serialization}} -import kotlinx.serialization.KSerializer -import kotlinx.serialization.Serializer -import kotlinx.serialization.encoding.Decoder -import kotlinx.serialization.encoding.Encoder -import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor -import kotlinx.serialization.descriptors.PrimitiveKind -import kotlinx.serialization.descriptors.SerialDescriptor -{{/kotlinx_serialization}} -{{^threetenbp}} -import java.time.LocalDate -import java.time.format.DateTimeFormatter -{{/threetenbp}} -{{#threetenbp}} -import org.threeten.bp.LocalDate -import org.threeten.bp.format.DateTimeFormatter -{{/threetenbp}} - -{{#moshi}} -{{#nonPublicApi}}internal {{/nonPublicApi}}class LocalDateAdapter { - @ToJson - fun toJson(value: LocalDate): String { - return DateTimeFormatter.ISO_LOCAL_DATE.format(value) - } - - @FromJson - fun fromJson(value: String): LocalDate { - return LocalDate.parse(value, DateTimeFormatter.ISO_LOCAL_DATE) - } - -} -{{/moshi}} -{{#gson}} -{{#nonPublicApi}}internal {{/nonPublicApi}}class LocalDateAdapter(private val formatter: DateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE) : TypeAdapter() { - @Throws(IOException::class) - override fun write(out: JsonWriter?, value: LocalDate?) { - if (value == null) { - out?.nullValue() - } else { - out?.value(formatter.format(value)) - } - } - - @Throws(IOException::class) - override fun read(out: JsonReader?): LocalDate? { - out ?: return null - - when (out.peek()) { - NULL -> { - out.nextNull() - return null - } - else -> { - return LocalDate.parse(out.nextString(), formatter) - } - } - } -} -{{/gson}} -{{#kotlinx_serialization}} -@Serializer(forClass = LocalDate::class) -{{#nonPublicApi}}internal {{/nonPublicApi}}object LocalDateAdapter : KSerializer { - override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("LocalDate", PrimitiveKind.STRING) - - override fun serialize(encoder: Encoder, value: LocalDate) { - encoder.encodeString(DateTimeFormatter.ISO_LOCAL_DATE.format(value)) - } - - override fun deserialize(decoder: Decoder): LocalDate { - return LocalDate.parse(decoder.decodeString(), DateTimeFormatter.ISO_LOCAL_DATE) - } -} -{{/kotlinx_serialization}} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/jvm-common/infrastructure/LocalDateTimeAdapter.kt.mustache b/src/main/resources/kotlin-client/jvm-common/infrastructure/LocalDateTimeAdapter.kt.mustache deleted file mode 100644 index 8d793d1ff42..00000000000 --- a/src/main/resources/kotlin-client/jvm-common/infrastructure/LocalDateTimeAdapter.kt.mustache +++ /dev/null @@ -1,86 +0,0 @@ -package {{packageName}}.infrastructure - -{{#moshi}} -import com.squareup.moshi.FromJson -import com.squareup.moshi.ToJson -{{/moshi}} -{{#gson}} -import com.google.gson.TypeAdapter -import com.google.gson.stream.JsonReader -import com.google.gson.stream.JsonWriter -import com.google.gson.stream.JsonToken.NULL -import java.io.IOException -{{/gson}} -{{#kotlinx_serialization}} -import kotlinx.serialization.KSerializer -import kotlinx.serialization.Serializer -import kotlinx.serialization.encoding.Decoder -import kotlinx.serialization.encoding.Encoder -import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor -import kotlinx.serialization.descriptors.PrimitiveKind -import kotlinx.serialization.descriptors.SerialDescriptor -{{/kotlinx_serialization}} -{{^threetenbp}} -import java.time.LocalDateTime -import java.time.format.DateTimeFormatter -{{/threetenbp}} -{{#threetenbp}} -import org.threeten.bp.LocalDateTime -import org.threeten.bp.format.DateTimeFormatter -{{/threetenbp}} - -{{#moshi}} -{{#nonPublicApi}}internal {{/nonPublicApi}}class LocalDateTimeAdapter { - @ToJson - fun toJson(value: LocalDateTime): String { - return DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(value) - } - - @FromJson - fun fromJson(value: String): LocalDateTime { - return LocalDateTime.parse(value, DateTimeFormatter.ISO_LOCAL_DATE_TIME) - } - -} -{{/moshi}} -{{#gson}} -{{#nonPublicApi}}internal {{/nonPublicApi}}class LocalDateTimeAdapter(private val formatter: DateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME) : TypeAdapter() { - @Throws(IOException::class) - override fun write(out: JsonWriter?, value: LocalDateTime?) { - if (value == null) { - out?.nullValue() - } else { - out?.value(formatter.format(value)) - } - } - - @Throws(IOException::class) - override fun read(out: JsonReader?): LocalDateTime? { - out ?: return null - - when (out.peek()) { - NULL -> { - out.nextNull() - return null - } - else -> { - return LocalDateTime.parse(out.nextString(), formatter) - } - } - } -} -{{/gson}} -{{#kotlinx_serialization}} -@Serializer(forClass = LocalDateTime::class) -{{#nonPublicApi}}internal {{/nonPublicApi}}object LocalDateTimeAdapter : KSerializer { - override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("LocalDateTime", PrimitiveKind.STRING) - - override fun serialize(encoder: Encoder, value: LocalDateTime) { - encoder.encodeString(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(value)) - } - - override fun deserialize(decoder: Decoder): LocalDateTime { - return LocalDateTime.parse(decoder.decodeString(), DateTimeFormatter.ISO_LOCAL_DATE_TIME) - } -} -{{/kotlinx_serialization}} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/jvm-common/infrastructure/OffsetDateTimeAdapter.kt.mustache b/src/main/resources/kotlin-client/jvm-common/infrastructure/OffsetDateTimeAdapter.kt.mustache deleted file mode 100644 index fff7ded5c28..00000000000 --- a/src/main/resources/kotlin-client/jvm-common/infrastructure/OffsetDateTimeAdapter.kt.mustache +++ /dev/null @@ -1,86 +0,0 @@ -package {{packageName}}.infrastructure - -{{#moshi}} -import com.squareup.moshi.FromJson -import com.squareup.moshi.ToJson -{{/moshi}} -{{#gson}} -import com.google.gson.TypeAdapter -import com.google.gson.stream.JsonReader -import com.google.gson.stream.JsonWriter -import com.google.gson.stream.JsonToken.NULL -import java.io.IOException -{{/gson}} -{{#kotlinx_serialization}} -import kotlinx.serialization.KSerializer -import kotlinx.serialization.Serializer -import kotlinx.serialization.encoding.Decoder -import kotlinx.serialization.encoding.Encoder -import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor -import kotlinx.serialization.descriptors.PrimitiveKind -import kotlinx.serialization.descriptors.SerialDescriptor -{{/kotlinx_serialization}} -{{^threetenbp}} -import java.time.OffsetDateTime -import java.time.format.DateTimeFormatter -{{/threetenbp}} -{{#threetenbp}} -import org.threeten.bp.OffsetDateTime -import org.threeten.bp.format.DateTimeFormatter -{{/threetenbp}} - -{{#moshi}} -{{#nonPublicApi}}internal {{/nonPublicApi}}class OffsetDateTimeAdapter { - @ToJson - fun toJson(value: OffsetDateTime): String { - return DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(value) - } - - @FromJson - fun fromJson(value: String): OffsetDateTime { - return OffsetDateTime.parse(value, DateTimeFormatter.ISO_OFFSET_DATE_TIME) - } - -} -{{/moshi}} -{{#gson}} -{{#nonPublicApi}}internal {{/nonPublicApi}}class OffsetDateTimeAdapter(private val formatter: DateTimeFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME) : TypeAdapter() { - @Throws(IOException::class) - override fun write(out: JsonWriter?, value: OffsetDateTime?) { - if (value == null) { - out?.nullValue() - } else { - out?.value(formatter.format(value)) - } - } - - @Throws(IOException::class) - override fun read(out: JsonReader?): OffsetDateTime? { - out ?: return null - - when (out.peek()) { - NULL -> { - out.nextNull() - return null - } - else -> { - return OffsetDateTime.parse(out.nextString(), formatter) - } - } - } -} -{{/gson}} -{{#kotlinx_serialization}} -@Serializer(forClass = OffsetDateTime::class) -{{#nonPublicApi}}internal {{/nonPublicApi}}object OffsetDateTimeAdapter : KSerializer { - override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("OffsetDateTime", PrimitiveKind.STRING) - - override fun serialize(encoder: Encoder, value: OffsetDateTime) { - encoder.encodeString(DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(value)) - } - - override fun deserialize(decoder: Decoder): OffsetDateTime { - return OffsetDateTime.parse(decoder.decodeString(), DateTimeFormatter.ISO_OFFSET_DATE_TIME) - } -} -{{/kotlinx_serialization}} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/jvm-common/infrastructure/Serializer.kt.mustache b/src/main/resources/kotlin-client/jvm-common/infrastructure/Serializer.kt.mustache deleted file mode 100644 index 31200465728..00000000000 --- a/src/main/resources/kotlin-client/jvm-common/infrastructure/Serializer.kt.mustache +++ /dev/null @@ -1,136 +0,0 @@ -package {{packageName}}.infrastructure - -{{#moshi}} -import com.squareup.moshi.Moshi -{{#enumUnknownDefaultCase}} -import com.squareup.moshi.adapters.EnumJsonAdapter -{{/enumUnknownDefaultCase}} -{{^moshiCodeGen}} -import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory -{{/moshiCodeGen}} -{{/moshi}} -{{#gson}} -import com.google.gson.Gson -import com.google.gson.GsonBuilder -{{^threetenbp}} -import java.time.LocalDate -import java.time.LocalDateTime -import java.time.OffsetDateTime -{{/threetenbp}} -{{#threetenbp}} -import org.threeten.bp.LocalDate -import org.threeten.bp.LocalDateTime -import org.threeten.bp.OffsetDateTime -{{/threetenbp}} -import java.util.UUID -{{/gson}} -{{#jackson}} -import com.fasterxml.jackson.databind.ObjectMapper -import com.fasterxml.jackson.databind.SerializationFeature -import com.fasterxml.jackson.annotation.JsonInclude -import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper -{{/jackson}} -{{#kotlinx_serialization}} -import java.math.BigDecimal -import java.math.BigInteger -{{^threetenbp}} -import java.time.LocalDate -import java.time.LocalDateTime -import java.time.OffsetDateTime -{{/threetenbp}} -{{#threetenbp}} -import org.threeten.bp.LocalDate -import org.threeten.bp.LocalDateTime -import org.threeten.bp.OffsetDateTime -{{/threetenbp}} -import java.util.UUID -import kotlinx.serialization.json.Json -import kotlinx.serialization.modules.SerializersModule -import java.net.URI -import java.net.URL -import java.util.concurrent.atomic.AtomicBoolean -import java.util.concurrent.atomic.AtomicInteger -import java.util.concurrent.atomic.AtomicLong -{{/kotlinx_serialization}} - -{{#nonPublicApi}}internal {{/nonPublicApi}}object Serializer { -{{#moshi}} - @JvmStatic - val moshiBuilder: Moshi.Builder = Moshi.Builder() - .add(OffsetDateTimeAdapter()) - .add(LocalDateTimeAdapter()) - .add(LocalDateAdapter()) - .add(UUIDAdapter()) - .add(ByteArrayAdapter()) - .add(URIAdapter()) - {{^moshiCodeGen}} - .add(KotlinJsonAdapterFactory()) - {{/moshiCodeGen}} - .add(BigDecimalAdapter()) - .add(BigIntegerAdapter()) - - @JvmStatic - val moshi: Moshi by lazy { -{{#enumUnknownDefaultCase}} - SerializerHelper.addEnumUnknownDefaultCase(moshiBuilder) -{{/enumUnknownDefaultCase}} - moshiBuilder.build() - } -{{/moshi}} -{{#gson}} - @JvmStatic - val gsonBuilder: GsonBuilder = GsonBuilder() - .registerTypeAdapter(OffsetDateTime::class.java, OffsetDateTimeAdapter()) - .registerTypeAdapter(LocalDateTime::class.java, LocalDateTimeAdapter()) - .registerTypeAdapter(LocalDate::class.java, LocalDateAdapter()) - .registerTypeAdapter(ByteArray::class.java, ByteArrayAdapter()) - - @JvmStatic - val gson: Gson by lazy { - gsonBuilder.create() - } -{{/gson}} -{{#jackson}} - @JvmStatic - val jacksonObjectMapper: ObjectMapper = jacksonObjectMapper() - .findAndRegisterModules() - .setSerializationInclusion(JsonInclude.Include.NON_ABSENT) - .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) -{{/jackson}} -{{#kotlinx_serialization}} - @Deprecated("Use Serializer.kotlinxSerializationAdapters instead", replaceWith = ReplaceWith("Serializer.kotlinxSerializationAdapters")) - @JvmStatic - val kotlinSerializationAdapters: SerializersModule - get() { return kotlinxSerializationAdapters } - - @JvmStatic - val kotlinxSerializationAdapters = SerializersModule { - contextual(BigDecimal::class, BigDecimalAdapter) - contextual(BigInteger::class, BigIntegerAdapter) - contextual(LocalDate::class, LocalDateAdapter) - contextual(LocalDateTime::class, LocalDateTimeAdapter) - contextual(OffsetDateTime::class, OffsetDateTimeAdapter) - contextual(UUID::class, UUIDAdapter) - contextual(AtomicInteger::class, AtomicIntegerAdapter) - contextual(AtomicLong::class, AtomicLongAdapter) - contextual(AtomicBoolean::class, AtomicBooleanAdapter) - contextual(URI::class, URIAdapter) - contextual(URL::class, URLAdapter) - contextual(StringBuilder::class, StringBuilderAdapter) - } - - @Deprecated("Use Serializer.kotlinxSerializationJson instead", replaceWith = ReplaceWith("Serializer.kotlinxSerializationJson")) - @JvmStatic - val jvmJson: Json - get() { return kotlinxSerializationJson } - - @JvmStatic - val kotlinxSerializationJson: Json by lazy { - Json { - serializersModule = kotlinxSerializationAdapters - ignoreUnknownKeys = true - isLenient = true - } - } -{{/kotlinx_serialization}} -} diff --git a/src/main/resources/kotlin-client/jvm-common/infrastructure/SerializerHelper.kt.mustache b/src/main/resources/kotlin-client/jvm-common/infrastructure/SerializerHelper.kt.mustache deleted file mode 100644 index fbf67a75dde..00000000000 --- a/src/main/resources/kotlin-client/jvm-common/infrastructure/SerializerHelper.kt.mustache +++ /dev/null @@ -1,50 +0,0 @@ -package {{packageName}}.infrastructure - -{{#moshi}} -import com.squareup.moshi.Moshi -{{#enumUnknownDefaultCase}} -import com.squareup.moshi.adapters.EnumJsonAdapter -{{/enumUnknownDefaultCase}} -{{/moshi}} - -{{#nonPublicApi}}internal {{/nonPublicApi}}object SerializerHelper { -{{#moshi}} - fun addEnumUnknownDefaultCase(moshiBuilder: Moshi.Builder): Moshi.Builder { - return moshiBuilder -{{#enumUnknownDefaultCase}} -{{#models}} -{{#model}} -{{#isEnum}} -{{#allowableValues}} -{{#enumVars}} -{{#-last}} - .add({{modelPackage}}.{{classname}}::class.java, EnumJsonAdapter.create({{modelPackage}}.{{classname}}::class.java) - .withUnknownFallback({{modelPackage}}.{{classname}}.{{&name}})) -{{/-last}} -{{/enumVars}} -{{/allowableValues}} -{{/isEnum}} -{{^isEnum}} -{{^isAlias}} -{{#hasEnums}} -{{#vars}} -{{#isEnum}} -{{#allowableValues}} -{{#enumVars}} -{{#-last}} - .add({{modelPackage}}.{{classname}}.{{{nameInCamelCase}}}::class.java, EnumJsonAdapter.create({{modelPackage}}.{{classname}}.{{{nameInCamelCase}}}::class.java) - .withUnknownFallback({{modelPackage}}.{{classname}}.{{{nameInCamelCase}}}.{{&name}})) -{{/-last}} -{{/enumVars}} -{{/allowableValues}} -{{/isEnum}} -{{/vars}} -{{/hasEnums}} -{{/isAlias}} -{{/isEnum}} -{{/model}} -{{/models}} -{{/enumUnknownDefaultCase}} - } -{{/moshi}} -} diff --git a/src/main/resources/kotlin-client/jvm-common/infrastructure/StringBuilderAdapter.kt.mustache b/src/main/resources/kotlin-client/jvm-common/infrastructure/StringBuilderAdapter.kt.mustache deleted file mode 100644 index 3d536703071..00000000000 --- a/src/main/resources/kotlin-client/jvm-common/infrastructure/StringBuilderAdapter.kt.mustache +++ /dev/null @@ -1,20 +0,0 @@ -package {{packageName}}.infrastructure - -import kotlinx.serialization.KSerializer -import kotlinx.serialization.Serializer -import kotlinx.serialization.encoding.Decoder -import kotlinx.serialization.encoding.Encoder -import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor -import kotlinx.serialization.descriptors.PrimitiveKind -import kotlinx.serialization.descriptors.SerialDescriptor - -@Serializer(forClass = StringBuilder::class) -{{#nonPublicApi}}internal {{/nonPublicApi}}object StringBuilderAdapter : KSerializer { - override fun serialize(encoder: Encoder, value: StringBuilder) { - encoder.encodeString(value.toString()) - } - - override fun deserialize(decoder: Decoder): StringBuilder = StringBuilder(decoder.decodeString()) - - override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("StringBuilder", PrimitiveKind.STRING) -} diff --git a/src/main/resources/kotlin-client/jvm-common/infrastructure/URIAdapter.kt.mustache b/src/main/resources/kotlin-client/jvm-common/infrastructure/URIAdapter.kt.mustache deleted file mode 100644 index 2fae6a3b6bc..00000000000 --- a/src/main/resources/kotlin-client/jvm-common/infrastructure/URIAdapter.kt.mustache +++ /dev/null @@ -1,38 +0,0 @@ -package {{packageName}}.infrastructure - -{{#kotlinx_serialization}} -import kotlinx.serialization.KSerializer -import kotlinx.serialization.Serializer -import kotlinx.serialization.encoding.Decoder -import kotlinx.serialization.encoding.Encoder -import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor -import kotlinx.serialization.descriptors.PrimitiveKind -import kotlinx.serialization.descriptors.SerialDescriptor -{{/kotlinx_serialization}} -{{#moshi}} -import com.squareup.moshi.FromJson -import com.squareup.moshi.ToJson -{{/moshi}} -import java.net.URI - -{{#moshi}} -{{#nonPublicApi}}internal {{/nonPublicApi}}class URIAdapter { - @ToJson - fun toJson(uri: URI) = uri.toString() - - @FromJson - fun fromJson(s: String): URI = URI.create(s) -} -{{/moshi}} -{{#kotlinx_serialization}} -@Serializer(forClass = URI::class) -{{#nonPublicApi}}internal {{/nonPublicApi}}object URIAdapter : KSerializer { - override fun serialize(encoder: Encoder, value: URI) { - encoder.encodeString(value.toASCIIString()) - } - - override fun deserialize(decoder: Decoder): URI = URI(decoder.decodeString()) - - override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("URI", PrimitiveKind.STRING) -} -{{/kotlinx_serialization}} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/jvm-common/infrastructure/URLAdapter.kt.mustache b/src/main/resources/kotlin-client/jvm-common/infrastructure/URLAdapter.kt.mustache deleted file mode 100644 index b437ff89ae0..00000000000 --- a/src/main/resources/kotlin-client/jvm-common/infrastructure/URLAdapter.kt.mustache +++ /dev/null @@ -1,21 +0,0 @@ -package {{packageName}}.infrastructure - -import kotlinx.serialization.KSerializer -import kotlinx.serialization.Serializer -import kotlinx.serialization.encoding.Decoder -import kotlinx.serialization.encoding.Encoder -import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor -import kotlinx.serialization.descriptors.PrimitiveKind -import kotlinx.serialization.descriptors.SerialDescriptor -import java.net.URL - -@Serializer(forClass = URL::class) -{{#nonPublicApi}}internal {{/nonPublicApi}}object URLAdapter : KSerializer { - override fun serialize(encoder: Encoder, value: URL) { - encoder.encodeString(value.toExternalForm()) - } - - override fun deserialize(decoder: Decoder): URL = URL(decoder.decodeString()) - - override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("URL", PrimitiveKind.STRING) -} diff --git a/src/main/resources/kotlin-client/jvm-common/infrastructure/UUIDAdapter.kt.mustache b/src/main/resources/kotlin-client/jvm-common/infrastructure/UUIDAdapter.kt.mustache deleted file mode 100644 index d0ec45c471d..00000000000 --- a/src/main/resources/kotlin-client/jvm-common/infrastructure/UUIDAdapter.kt.mustache +++ /dev/null @@ -1,40 +0,0 @@ -package {{packageName}}.infrastructure - -{{#kotlinx_serialization}} -import kotlinx.serialization.KSerializer -import kotlinx.serialization.Serializer -import kotlinx.serialization.encoding.Decoder -import kotlinx.serialization.encoding.Encoder -import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor -import kotlinx.serialization.descriptors.PrimitiveKind -import kotlinx.serialization.descriptors.SerialDescriptor -{{/kotlinx_serialization}} -{{#moshi}} -import com.squareup.moshi.FromJson -import com.squareup.moshi.ToJson -{{/moshi}} -import java.util.UUID - -{{#moshi}} -{{#nonPublicApi}}internal {{/nonPublicApi}}class UUIDAdapter { - @ToJson - fun toJson(uuid: UUID) = uuid.toString() - - @FromJson - fun fromJson(s: String): UUID = UUID.fromString(s) -} -{{/moshi}} -{{#kotlinx_serialization}} -@Serializer(forClass = UUID::class) -{{#nonPublicApi}}internal {{/nonPublicApi}}object UUIDAdapter : KSerializer { - override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("UUID", PrimitiveKind.STRING) - - override fun serialize(encoder: Encoder, value: UUID) { - encoder.encodeString(value.toString()) - } - - override fun deserialize(decoder: Decoder): UUID { - return UUID.fromString(decoder.decodeString()) - } -} -{{/kotlinx_serialization}} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/jvm-common/infrastructure/proguard-rules.pro.mustache b/src/main/resources/kotlin-client/jvm-common/infrastructure/proguard-rules.pro.mustache deleted file mode 100644 index 6da4eba5060..00000000000 --- a/src/main/resources/kotlin-client/jvm-common/infrastructure/proguard-rules.pro.mustache +++ /dev/null @@ -1,11 +0,0 @@ --keepattributes *Annotation*, InnerClasses --dontnote kotlinx.serialization.AnnotationsKt # core serialization annotations - -# kotlinx-serialization-json specific. Add this if you have java.lang.NoClassDefFoundError kotlinx.serialization.json.JsonObjectSerializer --keepclassmembers class kotlinx.serialization.json.** { *** Companion; } --keepclasseswithmembers class kotlinx.serialization.json.** { kotlinx.serialization.KSerializer serializer(...); } - -# project specific. --keep,includedescriptorclasses class {{modelPackage}}.**$$serializer { *; } --keepclassmembers class {{modelPackage}}.** { *** Companion; } --keepclasseswithmembers class {{modelPackage}}.** { kotlinx.serialization.KSerializer serializer(...); } diff --git a/src/main/resources/kotlin-client/libraries/jvm-ktor/api.mustache b/src/main/resources/kotlin-client/libraries/jvm-ktor/api.mustache deleted file mode 100644 index 168401c6743..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-ktor/api.mustache +++ /dev/null @@ -1,97 +0,0 @@ -{{>licenseInfo}} -package {{apiPackage}} - -{{#imports}}import {{import}} -{{/imports}} - -import {{packageName}}.infrastructure.* -import io.ktor.client.HttpClientConfig -import io.ktor.client.request.forms.formData -import io.ktor.client.engine.HttpClientEngine -import io.ktor.http.ParametersBuilder -{{#gson}} -import com.google.gson.Gson -import com.google.gson.GsonBuilder -import java.text.DateFormat -{{/gson}} -{{#jackson}} -import com.fasterxml.jackson.databind.ObjectMapper -{{/jackson}} - -{{#operations}} - {{#nonPublicApi}}internal {{/nonPublicApi}}open class {{classname}}( - baseUrl: String = ApiClient.BASE_URL, - httpClientEngine: HttpClientEngine? = null, - httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, - {{#gson}} - jsonBlock: GsonBuilder.() -> Unit = ApiClient.JSON_DEFAULT, - {{/gson}} - {{#jackson}} - jsonBlock: ObjectMapper.() -> Unit = ApiClient.JSON_DEFAULT, - {{/jackson}} - ) : ApiClient(baseUrl, httpClientEngine, httpClientConfig, jsonBlock) { - - {{#operation}} - /** - * {{summary}} - * {{notes}} - {{#allParams}} * @param {{{paramName}}} {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} - {{/allParams}} * @return {{{returnType}}}{{^returnType}}void{{/returnType}} - */ - {{#returnType}} - @Suppress("UNCHECKED_CAST") - {{/returnType}} - open suspend fun {{operationId}}({{#allParams}}{{{paramName}}}: {{{dataType}}}{{^required}}?{{/required}}{{^-last}}, {{/-last}}{{/allParams}}): HttpResponse<{{{returnType}}}{{^returnType}}Unit{{/returnType}}> { - - val localVariableAuthNames = listOf({{#authMethods}}"{{name}}"{{^-last}}, {{/-last}}{{/authMethods}}) - - val localVariableBody = {{#hasBodyParam}}{{#bodyParam}}{{{paramName}}}{{/bodyParam}}{{/hasBodyParam}} - {{^hasBodyParam}} - {{#hasFormParams}} - {{#isMultipart}} - formData { - {{#formParams}} - {{{paramName}}}?.apply { append("{{{baseName}}}", {{{paramName}}}) } - {{/formParams}} - } - {{/isMultipart}} - {{^isMultipart}} - ParametersBuilder().also { - {{#formParams}} - {{{paramName}}}?.apply { it.append("{{{baseName}}}", {{{paramName}}}.toString()) } - {{/formParams}} - }.build() - {{/isMultipart}} - {{/hasFormParams}} - {{^hasFormParams}} - io.ktor.client.utils.EmptyContent - {{/hasFormParams}} - {{/hasBodyParam}} - - val localVariableQuery = mutableMapOf>() - {{#queryParams}} - {{{paramName}}}?.apply { localVariableQuery["{{baseName}}"] = {{#isContainer}}toMultiValue(this, "{{collectionFormat}}"){{/isContainer}}{{^isContainer}}listOf("${{{paramName}}}"){{/isContainer}} } - {{/queryParams}} - - val localVariableHeaders = mutableMapOf() - {{#headerParams}} - {{{paramName}}}?.apply { localVariableHeaders["{{baseName}}"] = {{#isContainer}}this.joinToString(separator = collectionDelimiter("{{collectionFormat}}")){{/isContainer}}{{^isContainer}}this.toString(){{/isContainer}} } - {{/headerParams}} - - val localVariableConfig = RequestConfig( - RequestMethod.{{httpMethod}}, - "{{path}}"{{#pathParams}}.replace("{" + "{{baseName}}" + "}", "${{{paramName}}}"){{/pathParams}}, - query = localVariableQuery, - headers = localVariableHeaders - ) - - return {{#hasBodyParam}}jsonRequest{{/hasBodyParam}}{{^hasBodyParam}}{{#hasFormParams}}{{#isMultipart}}multipartFormRequest{{/isMultipart}}{{^isMultipart}}urlEncodedFormRequest{{/isMultipart}}{{/hasFormParams}}{{^hasFormParams}}request{{/hasFormParams}}{{/hasBodyParam}}( - localVariableConfig, - localVariableBody, - localVariableAuthNames - ).wrap() - } - - {{/operation}} - } -{{/operations}} diff --git a/src/main/resources/kotlin-client/libraries/jvm-ktor/auth/ApiKeyAuth.kt.mustache b/src/main/resources/kotlin-client/libraries/jvm-ktor/auth/ApiKeyAuth.kt.mustache deleted file mode 100644 index 618fd7a8890..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-ktor/auth/ApiKeyAuth.kt.mustache +++ /dev/null @@ -1,16 +0,0 @@ -package {{packageName}}.auth - -class ApiKeyAuth(private val location: String, val paramName: String) : Authentication { - var apiKey: String? = null - var apiKeyPrefix: String? = null - - override fun apply(query: MutableMap>, headers: MutableMap) { - val key: String = apiKey ?: return - val prefix: String? = apiKeyPrefix - val value: String = if (prefix != null) "$prefix $key" else key - when (location) { - "query" -> query[paramName] = listOf(value) - "header" -> headers[paramName] = value - } - } -} diff --git a/src/main/resources/kotlin-client/libraries/jvm-ktor/auth/Authentication.kt.mustache b/src/main/resources/kotlin-client/libraries/jvm-ktor/auth/Authentication.kt.mustache deleted file mode 100644 index 1aab9156d98..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-ktor/auth/Authentication.kt.mustache +++ /dev/null @@ -1,13 +0,0 @@ -package {{packageName}}.auth - -interface Authentication { - - /** - * Apply authentication settings to header and query params. - * - * @param query Query parameters. - * @param headers Header parameters. - */ - fun apply(query: MutableMap>, headers: MutableMap) - -} diff --git a/src/main/resources/kotlin-client/libraries/jvm-ktor/auth/HttpBasicAuth.kt.mustache b/src/main/resources/kotlin-client/libraries/jvm-ktor/auth/HttpBasicAuth.kt.mustache deleted file mode 100644 index 26325424e5d..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-ktor/auth/HttpBasicAuth.kt.mustache +++ /dev/null @@ -1,17 +0,0 @@ -package {{packageName}}.auth - -import io.ktor.util.InternalAPI -import io.ktor.util.encodeBase64 - -class HttpBasicAuth : Authentication { - var username: String? = null - var password: String? = null - - @OptIn(InternalAPI::class) - override fun apply(query: MutableMap>, headers: MutableMap) { - if (username == null && password == null) return - val str = (username ?: "") + ":" + (password ?: "") - val auth = str.encodeBase64() - headers["Authorization"] = "Basic $auth" - } -} diff --git a/src/main/resources/kotlin-client/libraries/jvm-ktor/auth/HttpBearerAuth.kt.mustache b/src/main/resources/kotlin-client/libraries/jvm-ktor/auth/HttpBearerAuth.kt.mustache deleted file mode 100644 index 982389d0960..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-ktor/auth/HttpBearerAuth.kt.mustache +++ /dev/null @@ -1,14 +0,0 @@ -package {{packageName}}.auth - -class HttpBearerAuth(private val scheme: String?) : Authentication { - var bearerToken: String? = null - - override fun apply(query: MutableMap>, headers: MutableMap) { - val token: String = bearerToken ?: return - headers["Authorization"] = (if (scheme != null) upperCaseBearer(scheme)!! + " " else "") + token - } - - private fun upperCaseBearer(scheme: String): String? { - return if ("bearer".equals(scheme, ignoreCase = true)) "Bearer" else scheme - } -} diff --git a/src/main/resources/kotlin-client/libraries/jvm-ktor/auth/OAuth.kt.mustache b/src/main/resources/kotlin-client/libraries/jvm-ktor/auth/OAuth.kt.mustache deleted file mode 100644 index 98bb449a609..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-ktor/auth/OAuth.kt.mustache +++ /dev/null @@ -1,10 +0,0 @@ -package {{packageName}}.auth - -class OAuth : Authentication { - var accessToken: String? = null - - override fun apply(query: MutableMap>, headers: MutableMap) { - val token: String = accessToken ?: return - headers["Authorization"] = "Bearer $token" - } -} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/libraries/jvm-ktor/infrastructure/ApiClient.kt.mustache b/src/main/resources/kotlin-client/libraries/jvm-ktor/infrastructure/ApiClient.kt.mustache deleted file mode 100644 index fad229d7836..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-ktor/infrastructure/ApiClient.kt.mustache +++ /dev/null @@ -1,228 +0,0 @@ -package {{packageName}}.infrastructure - - -import io.ktor.client.HttpClient -import io.ktor.client.HttpClientConfig -import io.ktor.client.engine.HttpClientEngine -import io.ktor.client.plugins.contentnegotiation.ContentNegotiation -import io.ktor.client.request.forms.FormDataContent -import io.ktor.client.request.forms.MultiPartFormDataContent -import io.ktor.client.request.header -import io.ktor.client.request.parameter -import io.ktor.client.request.request -import io.ktor.client.request.setBody -import io.ktor.client.statement.HttpResponse -import io.ktor.http.HttpHeaders -import io.ktor.http.HttpMethod -import io.ktor.http.Parameters -import io.ktor.http.URLBuilder -import io.ktor.http.content.PartData -import io.ktor.http.encodeURLQueryComponent -import io.ktor.http.encodedPath -import io.ktor.http.takeFrom -{{#gson}} -import io.ktor.serialization.gson.* -import com.google.gson.GsonBuilder -import java.text.DateFormat -{{/gson}} -{{#jackson}} -import io.ktor.serialization.jackson.* -import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper -import com.fasterxml.jackson.databind.ObjectMapper -import com.fasterxml.jackson.databind.SerializationFeature -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule -import com.fasterxml.jackson.core.util.DefaultIndenter -import com.fasterxml.jackson.core.util.DefaultPrettyPrinter -{{/jackson}} -import org.openapijsonschematools.client.auth.ApiKeyAuth -import org.openapijsonschematools.client.auth.Authentication -import org.openapijsonschematools.client.auth.HttpBasicAuth -import org.openapijsonschematools.client.auth.HttpBearerAuth -import org.openapijsonschematools.client.auth.OAuth -import {{packageName}}.auth.* - -{{#nonPublicApi}}internal {{/nonPublicApi}}open class ApiClient( - private val baseUrl: String, - httpClientEngine: HttpClientEngine?, - httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, - {{#gson}} - jsonBlock: GsonBuilder.() -> Unit = JSON_DEFAULT, - {{/gson}} - {{#jackson}} - jsonBlock: ObjectMapper.() -> Unit = JSON_DEFAULT, - {{/jackson}} -) { - - private val clientConfig: (HttpClientConfig<*>) -> Unit by lazy { - { - it.install(ContentNegotiation) { - {{#gson}} - gson { jsonBlock() } - {{/gson}} - {{#jackson}} - jackson { jsonBlock() } - {{/jackson}} - } - httpClientConfig?.invoke(it) - } - } - - private val client: HttpClient by lazy { - httpClientEngine?.let { HttpClient(it, clientConfig) } ?: HttpClient(clientConfig) - } - - {{#hasAuthMethods}} - private val authentications: kotlin.collections.Map by lazy { - mapOf({{#authMethods}}{{#isBasic}}{{#isBasicBasic}} - "{{name}}" to HttpBasicAuth(){{/isBasicBasic}}{{^isBasicBasic}} - "{{name}}" to HttpBearerAuth("{{scheme}}"){{/isBasicBasic}}{{/isBasic}}{{#isApiKey}} - "{{name}}" to ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"){{/isApiKey}}{{#isOAuth}} - "{{name}}" to OAuth(){{/isOAuth}}{{^-last}}, {{/-last}}{{/authMethods}}) - } - {{/hasAuthMethods}} - {{^hasAuthMethods}} - private val authentications: kotlin.collections.Map? = null - {{/hasAuthMethods}} - - {{#nonPublicApi}}internal {{/nonPublicApi}}companion object { - const val BASE_URL = "{{{basePath}}}" - {{#gson}} - val JSON_DEFAULT : GsonBuilder.() -> Unit = { - setDateFormat(DateFormat.LONG) - setPrettyPrinting() - } - {{/gson}} - {{#jackson}} - val JSON_DEFAULT: ObjectMapper.() -> Unit = { - configure(SerializationFeature.INDENT_OUTPUT, true) - setDefaultPrettyPrinter(DefaultPrettyPrinter().apply { - indentArraysWith(DefaultPrettyPrinter.FixedSpaceIndenter.instance) - indentObjectsWith(DefaultIndenter(" ", "\n")) - }) - registerModule(JavaTimeModule()) - } - {{/jackson}} - protected val UNSAFE_HEADERS = listOf(HttpHeaders.ContentType) - } - - /** - * Set the username for the first HTTP basic authentication. - * - * @param username Username - */ - fun setUsername(username: String) { - val auth = authentications.values.firstOrNull { it is HttpBasicAuth } as HttpBasicAuth? - ?: throw Exception("No HTTP basic authentication configured") - auth.username = username - } - - /** - * Set the password for the first HTTP basic authentication. - * - * @param password Password - */ - fun setPassword(password: String) { - val auth = authentications.values.firstOrNull { it is HttpBasicAuth } as HttpBasicAuth? - ?: throw Exception("No HTTP basic authentication configured") - auth.password = password - } - - /** - * Set the API key value for the first API key authentication. - * - * @param apiKey API key - * @param paramName The name of the API key parameter, or null or set the first key. - */ - fun setApiKey(apiKey: String, paramName: String? = null) { - val auth = authentications.values.firstOrNull { it is ApiKeyAuth && (paramName == null || paramName == it.paramName)} as ApiKeyAuth? - ?: throw Exception("No API key authentication configured") - auth.apiKey = apiKey - } - - /** - * Set the API key prefix for the first API key authentication. - * - * @param apiKeyPrefix API key prefix - * @param paramName The name of the API key parameter, or null or set the first key. - */ - fun setApiKeyPrefix(apiKeyPrefix: String, paramName: String? = null) { - val auth = authentications.values.firstOrNull { it is ApiKeyAuth && (paramName == null || paramName == it.paramName) } as ApiKeyAuth? - ?: throw Exception("No API key authentication configured") - auth.apiKeyPrefix = apiKeyPrefix - } - - /** - * Set the access token for the first OAuth2 authentication. - * - * @param accessToken Access token - */ - fun setAccessToken(accessToken: String) { - val auth = authentications.values.firstOrNull { it is OAuth } as OAuth? - ?: throw Exception("No OAuth2 authentication configured") - auth.accessToken = accessToken - } - - /** - * Set the access token for the first Bearer authentication. - * - * @param bearerToken The bearer token. - */ - fun setBearerToken(bearerToken: String) { - val auth = authentications.values.firstOrNull { it is HttpBearerAuth } as HttpBearerAuth? - ?: throw Exception("No Bearer authentication configured") - auth.bearerToken = bearerToken - } - - protected suspend fun multipartFormRequest(requestConfig: RequestConfig, body: kotlin.collections.List?, authNames: kotlin.collections.List): HttpResponse { - return request(requestConfig, MultiPartFormDataContent(body ?: listOf()), authNames) - } - - protected suspend fun urlEncodedFormRequest(requestConfig: RequestConfig, body: Parameters?, authNames: kotlin.collections.List): HttpResponse { - return request(requestConfig, FormDataContent(body ?: Parameters.Empty), authNames) - } - - protected suspend fun jsonRequest(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse = request(requestConfig, body, authNames) - - protected suspend fun request(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse { - requestConfig.updateForAuth(authNames) - val headers = requestConfig.headers - - return client.request { - this.url { - this.takeFrom(URLBuilder(baseUrl)) - appendPath(requestConfig.path.trimStart('/').split('/')) - requestConfig.query.forEach { query -> - query.value.forEach { value -> - parameter(query.key, value) - } - } - } - this.method = requestConfig.method.httpMethod - headers.filter { header -> !UNSAFE_HEADERS.contains(header.key) }.forEach { header -> this.header(header.key, header.value) } - if (requestConfig.method in listOf(RequestMethod.PUT, RequestMethod.POST, RequestMethod.PATCH)) - setBody(body) - } - } - - private fun RequestConfig.updateForAuth(authNames: kotlin.collections.List) { - for (authName in authNames) { - val auth = authentications?.get(authName) ?: throw Exception("Authentication undefined: $authName") - auth.apply(query, headers) - } - } - - private fun URLBuilder.appendPath(components: kotlin.collections.List): URLBuilder = apply { - encodedPath = encodedPath.trimEnd('/') + components.joinToString("/", prefix = "/") { it.encodeURLQueryComponent() } - } - - private val RequestMethod.httpMethod: HttpMethod - get() = when (this) { - RequestMethod.DELETE -> HttpMethod.Delete - RequestMethod.GET -> HttpMethod.Get - RequestMethod.HEAD -> HttpMethod.Head - RequestMethod.PATCH -> HttpMethod.Patch - RequestMethod.PUT -> HttpMethod.Put - RequestMethod.POST -> HttpMethod.Post - RequestMethod.OPTIONS -> HttpMethod.Options - } -} diff --git a/src/main/resources/kotlin-client/libraries/jvm-ktor/infrastructure/HttpResponse.kt.mustache b/src/main/resources/kotlin-client/libraries/jvm-ktor/infrastructure/HttpResponse.kt.mustache deleted file mode 100644 index 87a68f3084e..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-ktor/infrastructure/HttpResponse.kt.mustache +++ /dev/null @@ -1,51 +0,0 @@ -package {{packageName}}.infrastructure - -import io.ktor.http.Headers -import io.ktor.http.isSuccess -import io.ktor.util.reflect.TypeInfo -import io.ktor.util.reflect.typeInfo - -{{#nonPublicApi}}internal {{/nonPublicApi}}open class HttpResponse(val response: io.ktor.client.statement.HttpResponse, val provider: BodyProvider) { - val status: Int = response.status.value - val success: Boolean = response.status.isSuccess() - val headers: Map> = response.headers.mapEntries() - suspend fun body(): T = provider.body(response) - suspend fun typedBody(type: TypeInfo): V = provider.typedBody(response, type) - - {{#nonPublicApi}}internal {{/nonPublicApi}}companion object { - private fun Headers.mapEntries(): Map> { - val result = mutableMapOf>() - entries().forEach { result[it.key] = it.value } - return result - } - } -} - -{{#nonPublicApi}}internal {{/nonPublicApi}}interface BodyProvider { - suspend fun body(response: io.ktor.client.statement.HttpResponse): T - suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V -} - -{{#nonPublicApi}}internal {{/nonPublicApi}}class TypedBodyProvider(private val type: TypeInfo) : BodyProvider { - @Suppress("UNCHECKED_CAST") - override suspend fun body(response: io.ktor.client.statement.HttpResponse): T = - response.call.body(type) as T - - @Suppress("UNCHECKED_CAST") - override suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V = - response.call.body(type) as V -} - -{{#nonPublicApi}}internal {{/nonPublicApi}}class MappedBodyProvider(private val provider: BodyProvider, private val block: S.() -> T) : BodyProvider { - override suspend fun body(response: io.ktor.client.statement.HttpResponse): T = - block(provider.body(response)) - - override suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V = - provider.typedBody(response, type) -} - -{{#nonPublicApi}}internal {{/nonPublicApi}}inline fun io.ktor.client.statement.HttpResponse.wrap(): HttpResponse = - HttpResponse(this, TypedBodyProvider(typeInfo())) - -{{#nonPublicApi}}internal {{/nonPublicApi}}fun HttpResponse.map(block: T.() -> V): HttpResponse = - HttpResponse(response, MappedBodyProvider(provider, block)) diff --git a/src/main/resources/kotlin-client/libraries/jvm-okhttp/api.mustache b/src/main/resources/kotlin-client/libraries/jvm-okhttp/api.mustache deleted file mode 100644 index 5c467a1b884..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-okhttp/api.mustache +++ /dev/null @@ -1,240 +0,0 @@ -{{>licenseInfo}} -package {{apiPackage}} - -import java.io.IOException -import okhttp3.OkHttpClient -import okhttp3.HttpUrl - -{{#imports}}import {{import}} -{{/imports}} - -{{^multiplatform}} -{{#gson}} -import com.google.gson.annotations.SerializedName -{{/gson}} -{{#moshi}} -import com.squareup.moshi.Json -{{/moshi}} -{{#jackson}} -import com.fasterxml.jackson.annotation.JsonProperty -{{/jackson}} -{{#kotlinx_serialization}} -import kotlinx.serialization.SerialName -import kotlinx.serialization.Serializable -{{/kotlinx_serialization}} -{{/multiplatform}} -{{#multiplatform}} -import kotlinx.serialization.* -{{/multiplatform}} - -{{^doNotUseRxAndCoroutines}} -{{#useCoroutines}} -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.withContext -{{/useCoroutines}} -{{/doNotUseRxAndCoroutines}} -import {{packageName}}.infrastructure.ApiClient -import {{packageName}}.infrastructure.ApiResponse -import {{packageName}}.infrastructure.ClientException -import {{packageName}}.infrastructure.ClientError -import {{packageName}}.infrastructure.ServerException -import {{packageName}}.infrastructure.ServerError -import {{packageName}}.infrastructure.MultiValueMap -import {{packageName}}.infrastructure.PartConfig -import {{packageName}}.infrastructure.RequestConfig -import {{packageName}}.infrastructure.RequestMethod -import {{packageName}}.infrastructure.ResponseType -import {{packageName}}.infrastructure.Success -import {{packageName}}.infrastructure.toMultiValue - -{{#operations}} -{{#nonPublicApi}}internal {{/nonPublicApi}}class {{classname}}(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = ApiClient.defaultClient) : ApiClient(basePath, client) { - companion object { - @JvmStatic - val defaultBasePath: String by lazy { - System.getProperties().getProperty(ApiClient.baseUrlKey, "{{{basePath}}}") - } - } - - {{#operation}} - {{#allParams}} - {{#isEnum}} - /** - * enum for parameter {{paramName}} - */ - {{#nonPublicApi}}internal {{/nonPublicApi}}enum class {{enumName}}_{{operationId}}(val value: {{^isContainer}}{{dataType}}{{/isContainer}}{{#isContainer}}kotlin.String{{/isContainer}}) { - {{^enumUnknownDefaultCase}} - {{#allowableValues}} - {{#enumVars}} - {{^multiplatform}} - {{#moshi}} - @Json(name = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}){{^-last}},{{/-last}} - {{/moshi}} - {{#gson}} - @SerializedName(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}){{^-last}},{{/-last}} - {{/gson}} - {{#jackson}} - @JsonProperty(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}){{^-last}},{{/-last}} - {{/jackson}} - {{#kotlinx_serialization}} - @SerialName(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}){{^-last}},{{/-last}} - {{/kotlinx_serialization}} - {{/multiplatform}} - {{#multiplatform}} - @SerialName(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}){{^-last}},{{/-last}} - {{/multiplatform}} - {{/enumVars}} - {{/allowableValues}} - {{/enumUnknownDefaultCase}} - {{#enumUnknownDefaultCase}} - {{#allowableValues}} - {{#enumVars}} - {{^-last}} - {{^multiplatform}} - {{#moshi}} - @Json(name = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}), - {{/moshi}} - {{#gson}} - @SerializedName(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}), - {{/gson}} - {{#jackson}} - @JsonProperty(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}), - {{/jackson}} - {{#kotlinx_serialization}} - @SerialName(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}), - {{/kotlinx_serialization}} - {{/multiplatform}} - {{#multiplatform}} - @SerialName(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}), - {{/multiplatform}} - {{/-last}} - {{/enumVars}} - {{/allowableValues}} - {{/enumUnknownDefaultCase}} - } - - {{/isEnum}} - {{/allParams}} - /** - * {{summary}} - * {{notes}} - {{#allParams}}* @param {{{paramName}}} {{description}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{#required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}{{/required}} - {{/allParams}}* @return {{#returnType}}{{{returnType}}}{{#nullableReturnType}} or null{{/nullableReturnType}}{{/returnType}}{{^returnType}}void{{/returnType}} - * @throws IllegalStateException If the request is not correctly configured - * @throws IOException Rethrows the OkHttp execute method exception - * @throws UnsupportedOperationException If the API returns an informational or redirection response - * @throws ClientException If the API returns a client error response - * @throws ServerException If the API returns a server error response - */{{#returnType}} - @Suppress("UNCHECKED_CAST"){{/returnType}} - @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) - {{#isDeprecated}} - @Deprecated(message = "This operation is deprecated.") - {{/isDeprecated}} - {{^doNotUseRxAndCoroutines}}{{#useCoroutines}}suspend {{/useCoroutines}}{{/doNotUseRxAndCoroutines}}fun {{operationId}}({{#allParams}}{{{paramName}}}: {{#isEnum}}{{#isContainer}}kotlin.collections.List<{{enumName}}_{{operationId}}>{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{#required}}{{#defaultValue}} = {{^isNumber}}{{#isEnum}}{{enumName}}_{{operationId}}.{{enumDefaultValue}}{{/isEnum}}{{^isEnum}}{{{defaultValue}}}{{/isEnum}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{/required}}{{^required}}?{{#defaultValue}} = {{^isNumber}}{{#isEnum}}{{enumName}}_{{operationId}}.{{enumDefaultValue}}{{/isEnum}}{{^isEnum}}{{{defaultValue}}}{{/isEnum}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{^defaultValue}} = null{{/defaultValue}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) : {{#returnType}}{{{returnType}}}{{#nullableReturnType}}?{{/nullableReturnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}}{{^doNotUseRxAndCoroutines}}{{#useCoroutines}} = withContext(Dispatchers.IO){{/useCoroutines}}{{/doNotUseRxAndCoroutines}} { - {{#isDeprecated}} - @Suppress("DEPRECATION") - {{/isDeprecated}} - val localVarResponse = {{operationId}}WithHttpInfo({{#allParams}}{{{paramName}}} = {{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}) - - return{{^doNotUseRxAndCoroutines}}{{#useCoroutines}}@withContext{{/useCoroutines}}{{/doNotUseRxAndCoroutines}} when (localVarResponse.responseType) { - ResponseType.Success -> {{#returnType}}(localVarResponse as Success<*>).data as {{{returnType}}}{{#nullableReturnType}}?{{/nullableReturnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}} - ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") - ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") - ResponseType.ClientError -> { - val localVarError = localVarResponse as ClientError<*> - throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) - } - ResponseType.ServerError -> { - val localVarError = localVarResponse as ServerError<*> - throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) - } - } - } - - /** - * {{summary}} - * {{notes}} - {{#allParams}}* @param {{{paramName}}} {{description}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{#required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}{{/required}} - {{/allParams}}* @return ApiResponse<{{#returnType}}{{{returnType}}}?{{/returnType}}{{^returnType}}Unit?{{/returnType}}> - * @throws IllegalStateException If the request is not correctly configured - * @throws IOException Rethrows the OkHttp execute method exception - */{{#returnType}} - @Suppress("UNCHECKED_CAST"){{/returnType}} - @Throws(IllegalStateException::class, IOException::class) - {{#isDeprecated}} - @Deprecated(message = "This operation is deprecated.") - {{/isDeprecated}} - {{^doNotUseRxAndCoroutines}}{{#useCoroutines}}suspend {{/useCoroutines}}{{/doNotUseRxAndCoroutines}}fun {{operationId}}WithHttpInfo({{#allParams}}{{{paramName}}}: {{#isEnum}}{{#isContainer}}kotlin.collections.List<{{enumName}}_{{operationId}}>{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}?{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) : ApiResponse<{{#returnType}}{{{returnType}}}?{{/returnType}}{{^returnType}}Unit?{{/returnType}}>{{^doNotUseRxAndCoroutines}}{{#useCoroutines}} = withContext(Dispatchers.IO){{/useCoroutines}}{{/doNotUseRxAndCoroutines}} { - {{#isDeprecated}} - @Suppress("DEPRECATION") - {{/isDeprecated}} - val localVariableConfig = {{operationId}}RequestConfig({{#allParams}}{{{paramName}}} = {{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}) - - return{{^doNotUseRxAndCoroutines}}{{#useCoroutines}}@withContext{{/useCoroutines}}{{/doNotUseRxAndCoroutines}} request<{{#hasBodyParam}}{{#bodyParams}}{{{dataType}}}{{/bodyParams}}{{/hasBodyParam}}{{^hasBodyParam}}{{^hasFormParams}}Unit{{/hasFormParams}}{{#hasFormParams}}Map>{{/hasFormParams}}{{/hasBodyParam}}, {{{returnType}}}{{^returnType}}Unit{{/returnType}}>( - localVariableConfig - ) - } - - /** - * To obtain the request config of the operation {{operationId}} - * - {{#allParams}}* @param {{{paramName}}} {{description}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{#required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}{{/required}} - {{/allParams}}* @return RequestConfig - */ - {{#isDeprecated}} - @Deprecated(message = "This operation is deprecated.") - {{/isDeprecated}} - fun {{operationId}}RequestConfig({{#allParams}}{{{paramName}}}: {{#isEnum}}{{#isContainer}}kotlin.collections.List<{{enumName}}_{{operationId}}>{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}?{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) : RequestConfig<{{#hasBodyParam}}{{#bodyParams}}{{{dataType}}}{{/bodyParams}}{{/hasBodyParam}}{{^hasBodyParam}}{{^hasFormParams}}Unit{{/hasFormParams}}{{#hasFormParams}}Map>{{/hasFormParams}}{{/hasBodyParam}}> { - val localVariableBody = {{#hasBodyParam}}{{! - }}{{#bodyParams}}{{{paramName}}}{{/bodyParams}}{{/hasBodyParam}}{{^hasBodyParam}}{{! - }}{{^hasFormParams}}null{{/hasFormParams}}{{! - }}{{#hasFormParams}}mapOf({{#formParams}} - "{{{baseName}}}" to PartConfig(body = {{{paramName}}}{{#isEnum}}.value{{/isEnum}}, headers = mutableMapOf({{#contentType}}"Content-Type" to "{{contentType}}"{{/contentType}})),{{! - }}{{/formParams}}){{/hasFormParams}}{{! - }}{{/hasBodyParam}} - val localVariableQuery: MultiValueMap = {{^hasQueryParams}}mutableMapOf() -{{/hasQueryParams}}{{#hasQueryParams}}mutableMapOf>() - .apply { - {{#queryParams}} - {{^required}} - if ({{{paramName}}} != null) { - put("{{baseName}}", {{#isContainer}}toMultiValue({{{paramName}}}.toList(), "{{collectionFormat}}"){{/isContainer}}{{^isContainer}}listOf({{#isDateTime}}parseDateToQueryString({{{paramName}}}){{/isDateTime}}{{#isDate}}parseDateToQueryString({{{paramName}}}){{/isDate}}{{^isDateTime}}{{^isDate}}{{{paramName}}}.toString(){{/isDate}}{{/isDateTime}}){{/isContainer}}) - } - {{/required}} - {{#required}} - {{#isNullable}} - if ({{{paramName}}} != null) { - put("{{baseName}}", {{#isContainer}}toMultiValue({{{paramName}}}.toList(), "{{collectionFormat}}"){{/isContainer}}{{^isContainer}}listOf({{#isDateTime}}parseDateToQueryString({{{paramName}}}){{/isDateTime}}{{#isDate}}parseDateToQueryString({{{paramName}}}){{/isDate}}{{^isDateTime}}{{^isDate}}{{{paramName}}}.toString(){{/isDate}}{{/isDateTime}}){{/isContainer}}) - } - {{/isNullable}} - {{^isNullable}} - put("{{baseName}}", {{#isContainer}}toMultiValue({{{paramName}}}.toList(), "{{collectionFormat}}"){{/isContainer}}{{^isContainer}}listOf({{#isDateTime}}parseDateToQueryString({{{paramName}}}){{/isDateTime}}{{#isDate}}parseDateToQueryString({{{paramName}}}){{/isDate}}{{^isDateTime}}{{^isDate}}{{{paramName}}}.toString(){{/isDate}}{{/isDateTime}}){{/isContainer}}) - {{/isNullable}} - {{/required}} - {{/queryParams}} - } - {{/hasQueryParams}} - val localVariableHeaders: MutableMap = mutableMapOf({{#hasFormParams}}"Content-Type" to {{^consumes}}"multipart/form-data"{{/consumes}}{{#consumes.0}}"{{{mediaType}}}"{{/consumes.0}}{{/hasFormParams}}) - {{#headerParams}} - {{{paramName}}}{{^required}}?{{/required}}.apply { localVariableHeaders["{{baseName}}"] = {{#isContainer}}this.joinToString(separator = collectionDelimiter("{{collectionFormat}}")){{/isContainer}}{{^isContainer}}this.toString(){{/isContainer}} } - {{/headerParams}} - {{^hasFormParams}}{{#hasConsumes}}{{#consumes}}localVariableHeaders["Content-Type"] = "{{{mediaType}}}" - {{/consumes}}{{/hasConsumes}}{{/hasFormParams}}{{#hasProduces}}localVariableHeaders["Accept"] = "{{#produces}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/produces}}" -{{/hasProduces}} - - return RequestConfig( - method = RequestMethod.{{httpMethod}}, - path = "{{path}}"{{#pathParams}}.replace("{"+"{{baseName}}"+"}", encodeURIComponent({{#isContainer}}{{paramName}}.joinToString(","){{/isContainer}}{{^isContainer}}{{{paramName}}}{{#isEnum}}.value{{/isEnum}}.toString(){{/isContainer}})){{/pathParams}}, - query = localVariableQuery, - headers = localVariableHeaders, - body = localVariableBody - ) - } - - {{/operation}} - - private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = - HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments{{#jvm-okhttp3}}(){{/jvm-okhttp3}}[0] -} -{{/operations}} diff --git a/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ApiClient.kt.mustache b/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ApiClient.kt.mustache deleted file mode 100644 index b0c5f045795..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ApiClient.kt.mustache +++ /dev/null @@ -1,462 +0,0 @@ -package {{packageName}}.infrastructure - -{{#supportAndroidApiLevel25AndBelow}} -import android.os.Build -{{/supportAndroidApiLevel25AndBelow}} -import okhttp3.OkHttpClient -import okhttp3.RequestBody -{{#jvm-okhttp3}} -import okhttp3.MediaType -{{/jvm-okhttp3}} -{{#jvm-okhttp4}} -import okhttp3.RequestBody.Companion.asRequestBody -import okhttp3.RequestBody.Companion.toRequestBody -{{/jvm-okhttp4}} -import okhttp3.FormBody -{{#jvm-okhttp3}} -import okhttp3.HttpUrl -{{/jvm-okhttp3}} -{{#jvm-okhttp4}} -import okhttp3.HttpUrl.Companion.toHttpUrlOrNull -{{/jvm-okhttp4}} -import okhttp3.ResponseBody -{{#jvm-okhttp4}} -import okhttp3.MediaType.Companion.toMediaTypeOrNull -{{/jvm-okhttp4}} -import okhttp3.Request -import okhttp3.Headers -{{#jvm-okhttp4}} -import okhttp3.Headers.Companion.toHeaders -{{/jvm-okhttp4}} -import okhttp3.MultipartBody -import okhttp3.Call -import okhttp3.Callback -import okhttp3.Response -{{#jvm-okhttp3}} -import okhttp3.internal.Util.EMPTY_REQUEST -{{/jvm-okhttp3}} -{{#jvm-okhttp4}} -import okhttp3.internal.EMPTY_REQUEST -{{/jvm-okhttp4}} -import java.io.BufferedWriter -import java.io.File -import java.io.FileWriter -import java.io.IOException -import java.net.URLConnection -{{^threetenbp}} -import java.time.LocalDate -import java.time.LocalDateTime -import java.time.LocalTime -import java.time.OffsetDateTime -import java.time.OffsetTime -{{/threetenbp}} -import java.util.Locale -{{#useCoroutines}} -import kotlin.coroutines.resume -import kotlin.coroutines.resumeWithException -import kotlinx.coroutines.suspendCancellableCoroutine -{{/useCoroutines}} -{{#kotlinx_serialization}} -import kotlinx.serialization.decodeFromString -import kotlinx.serialization.encodeToString -{{/kotlinx_serialization}} -{{#threetenbp}} -import org.threeten.bp.LocalDate -import org.threeten.bp.LocalDateTime -import org.threeten.bp.LocalTime -import org.threeten.bp.OffsetDateTime -import org.threeten.bp.OffsetTime -{{/threetenbp}} -{{#gson}} -import com.google.gson.reflect.TypeToken -{{/gson}} -{{#jackson}} -import com.fasterxml.jackson.core.type.TypeReference -{{/jackson}} -{{#moshi}} -import com.squareup.moshi.adapter -{{/moshi}} - -{{#nonPublicApi}}internal {{/nonPublicApi}}open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClient) { - {{#nonPublicApi}}internal {{/nonPublicApi}}companion object { - protected const val ContentType = "Content-Type" - protected const val Accept = "Accept" - protected const val Authorization = "Authorization" - protected const val JsonMediaType = "application/json" - protected const val FormDataMediaType = "multipart/form-data" - protected const val FormUrlEncMediaType = "application/x-www-form-urlencoded" - protected const val XmlMediaType = "application/xml" - - val apiKey: MutableMap = mutableMapOf() - val apiKeyPrefix: MutableMap = mutableMapOf() - var username: String? = null - var password: String? = null - var accessToken: String? = null - const val baseUrlKey = "{{packageName}}.baseUrl" - - @JvmStatic - val defaultClient: OkHttpClient by lazy { - builder.build() - } - - @JvmStatic - val builder: OkHttpClient.Builder = OkHttpClient.Builder() - } - - /** - * Guess Content-Type header from the given file (defaults to "application/octet-stream"). - * - * @param file The given file - * @return The guessed Content-Type - */ - protected fun guessContentTypeFromFile(file: File): String { - val contentType = URLConnection.guessContentTypeFromName(file.name) - return contentType ?: "application/octet-stream" - } - - protected inline fun requestBody(content: T, mediaType: String?): RequestBody = - when { - {{#jvm-okhttp3}} - content is File -> RequestBody.create(MediaType.parse(mediaType ?: guessContentTypeFromFile(content)), content) - {{/jvm-okhttp3}} - {{#jvm-okhttp4}} - content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) - {{/jvm-okhttp4}} - mediaType == FormDataMediaType -> - MultipartBody.Builder() - .setType(MultipartBody.FORM) - .apply { - // content's type *must* be Map> - @Suppress("UNCHECKED_CAST") - (content as Map>).forEach { (name, part) -> - if (part.body is File) { - val partHeaders = part.headers.toMutableMap() + - ("Content-Disposition" to "form-data; name=\"$name\"; filename=\"${part.body.name}\"") - {{#jvm-okhttp3}} - val fileMediaType = MediaType.parse(guessContentTypeFromFile(part.body)) - addPart( - Headers.of(partHeaders), - RequestBody.create(fileMediaType, part.body) - ) - {{/jvm-okhttp3}} - {{#jvm-okhttp4}} - val fileMediaType = guessContentTypeFromFile(part.body).toMediaTypeOrNull() - addPart( - partHeaders.toHeaders(), - part.body.asRequestBody(fileMediaType) - ) - {{/jvm-okhttp4}} - } else { - val partHeaders = part.headers.toMutableMap() + - ("Content-Disposition" to "form-data; name=\"$name\"") - {{#jvm-okhttp3}} - addPart( - Headers.of(partHeaders), - RequestBody.create(null, parameterToString(part.body)) - ) - {{/jvm-okhttp3}} - {{#jvm-okhttp4}} - addPart( - partHeaders.toHeaders(), - parameterToString(part.body).toRequestBody(null) - ) - {{/jvm-okhttp4}} - } - } - }.build() - mediaType == FormUrlEncMediaType -> { - FormBody.Builder().apply { - // content's type *must* be Map> - @Suppress("UNCHECKED_CAST") - (content as Map>).forEach { (name, part) -> - add(name, parameterToString(part.body)) - } - }.build() - } - mediaType == null || mediaType.startsWith("application/") && mediaType.endsWith("json") -> - {{#jvm-okhttp3}} - if (content == null) { - EMPTY_REQUEST - } else { - RequestBody.create( - {{#moshi}} - MediaType.parse(mediaType ?: JsonMediaType), Serializer.moshi.adapter(T::class.java).toJson(content) - {{/moshi}} - {{#gson}} - MediaType.parse(mediaType ?: JsonMediaType), Serializer.gson.toJson(content, T::class.java) - {{/gson}} - {{#jackson}} - MediaType.parse(mediaType ?: JsonMediaType), Serializer.jacksonObjectMapper.writeValueAsString(content) - {{/jackson}} - {{#kotlinx_serialization}} - MediaType.parse(mediaType ?: JsonMediaType), Serializer.kotlinxSerializationJson.encodeToString(content) - {{/kotlinx_serialization}} - ) - } - {{/jvm-okhttp3}} - {{#jvm-okhttp4}} - if (content == null) { - EMPTY_REQUEST - } else { - {{#moshi}} - Serializer.moshi.adapter(T::class.java).toJson(content) - {{/moshi}} - {{#gson}} - Serializer.gson.toJson(content, T::class.java) - {{/gson}} - {{#jackson}} - Serializer.jacksonObjectMapper.writeValueAsString(content) - {{/jackson}} - {{#kotlinx_serialization}} - Serializer.kotlinxSerializationJson.encodeToString(content) - {{/kotlinx_serialization}} - .toRequestBody((mediaType ?: JsonMediaType).toMediaTypeOrNull()) - } - {{/jvm-okhttp4}} - mediaType == XmlMediaType -> throw UnsupportedOperationException("xml not currently supported.") - // TODO: this should be extended with other serializers - else -> throw UnsupportedOperationException("requestBody currently only supports JSON body and File body.") - } - - {{#moshi}} - @OptIn(ExperimentalStdlibApi::class) - {{/moshi}} - protected inline fun responseBody(body: ResponseBody?, mediaType: String? = JsonMediaType): T? { - if(body == null) { - return null - } - if (T::class.java == File::class.java) { - // return tempFile - {{^supportAndroidApiLevel25AndBelow}} - // Attention: if you are developing an android app that supports API Level 25 and bellow, please check flag supportAndroidApiLevel25AndBelow in https://openapi-generator.tech/docs/generators/kotlin#config-options - val tempFile = java.nio.file.Files.createTempFile("tmp.{{packageName}}", null).toFile() - {{/supportAndroidApiLevel25AndBelow}} - {{#supportAndroidApiLevel25AndBelow}} - val tempFile = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - java.nio.file.Files.createTempFile("tmp.net.medicineone.teleconsultationandroid.openapi.openapicommon", null).toFile() - } else { - @Suppress("DEPRECATION") - createTempFile("tmp.net.medicineone.teleconsultationandroid.openapi.openapicommon", null) - } - {{/supportAndroidApiLevel25AndBelow}} - tempFile.deleteOnExit() - body.byteStream().use { inputStream -> - tempFile.outputStream().use { tempFileOutputStream -> - inputStream.copyTo(tempFileOutputStream) - } - } - return tempFile as T - } - val bodyContent = body.string() - if (bodyContent.isEmpty()) { - return null - } - return when { - mediaType==null || (mediaType.startsWith("application/") && mediaType.endsWith("json")) -> - {{#moshi}}Serializer.moshi.adapter().fromJson(bodyContent){{/moshi}}{{! - }}{{#gson}}Serializer.gson.fromJson(bodyContent, (object: TypeToken(){}).getType()){{/gson}}{{! - }}{{#jackson}}Serializer.jacksonObjectMapper.readValue(bodyContent, object: TypeReference() {}){{/jackson}}{{! - }}{{#kotlinx_serialization}}Serializer.kotlinxSerializationJson.decodeFromString(bodyContent){{/kotlinx_serialization}} - else -> throw UnsupportedOperationException("responseBody currently only supports JSON body.") - } - } - - {{#hasAuthMethods}} - protected fun updateAuthParams(requestConfig: RequestConfig) { - {{#authMethods}} - {{#isApiKey}} - {{#isKeyInHeader}} - if (requestConfig.headers["{{keyParamName}}"].isNullOrEmpty()) { - {{/isKeyInHeader}} - {{#isKeyInQuery}} - if (requestConfig.query["{{keyParamName}}"].isNullOrEmpty()) { - {{/isKeyInQuery}} - if (apiKey["{{keyParamName}}"] != null) { - if (apiKeyPrefix["{{keyParamName}}"] != null) { - {{#isKeyInHeader}} - requestConfig.headers["{{keyParamName}}"] = apiKeyPrefix["{{keyParamName}}"]!! + " " + apiKey["{{keyParamName}}"]!! - {{/isKeyInHeader}} - {{#isKeyInQuery}} - requestConfig.query["{{keyParamName}}"] = apiKeyPrefix["{{keyParamName}}"]!! + " " + apiKey["{{keyParamName}}"]!! - {{/isKeyInQuery}} - } else { - {{#isKeyInHeader}} - requestConfig.headers["{{keyParamName}}"] = apiKey["{{keyParamName}}"]!! - {{/isKeyInHeader}} - {{#isKeyInQuery}} - requestConfig.query["{{keyParamName}}"] = apiKey["{{keyParamName}}"]!! - {{/isKeyInQuery}} - } - } - } - {{/isApiKey}} - {{#isBasic}} - {{#isBasicBasic}} - if (requestConfig.headers[Authorization].isNullOrEmpty()) { - username?.let { username -> - password?.let { password -> - requestConfig.headers[Authorization] = okhttp3.Credentials.basic(username, password) - } - } - } - {{/isBasicBasic}} - {{#isBasicBearer}} - if (requestConfig.headers[Authorization].isNullOrEmpty()) { - accessToken?.let { accessToken -> - requestConfig.headers[Authorization] = "Bearer $accessToken" - } - } - {{/isBasicBearer}} - {{/isBasic}} - {{#isOAuth}} - if (requestConfig.headers[Authorization].isNullOrEmpty()) { - accessToken?.let { accessToken -> - requestConfig.headers[Authorization] = "Bearer $accessToken " - } - } - {{/isOAuth}} - {{/authMethods}} - } - {{/hasAuthMethods}} - - protected {{#useCoroutines}}suspend {{/useCoroutines}}inline fun request(requestConfig: RequestConfig): ApiResponse { - {{#jvm-okhttp3}} - val httpUrl = HttpUrl.parse(baseUrl) ?: throw IllegalStateException("baseUrl is invalid.") - {{/jvm-okhttp3}} - {{#jvm-okhttp4}} - val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") - {{/jvm-okhttp4}} - {{#hasAuthMethods}} - - // take authMethod from operation - updateAuthParams(requestConfig) - {{/hasAuthMethods}} - - val url = httpUrl.newBuilder() - .addEncodedPathSegments(requestConfig.path.trimStart('/')) - .apply { - requestConfig.query.forEach { query -> - query.value.forEach { queryValue -> - addQueryParameter(query.key, queryValue) - } - } - }.build() - - // take content-type/accept from spec or set to default (application/json) if not defined - if (requestConfig.headers[ContentType].isNullOrEmpty()) { - requestConfig.headers[ContentType] = JsonMediaType - } - if (requestConfig.headers[Accept].isNullOrEmpty()) { - requestConfig.headers[Accept] = JsonMediaType - } - val headers = requestConfig.headers - - if(headers[ContentType].isNullOrEmpty()) { - throw kotlin.IllegalStateException("Missing Content-Type header. This is required.") - } - - if(headers[Accept].isNullOrEmpty()) { - throw kotlin.IllegalStateException("Missing Accept header. This is required.") - } - - // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) - - val request = when (requestConfig.method) { - RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) - RequestMethod.GET -> Request.Builder().url(url) - RequestMethod.HEAD -> Request.Builder().url(url).head() - RequestMethod.PATCH -> Request.Builder().url(url).patch(requestBody(requestConfig.body, contentType)) - RequestMethod.PUT -> Request.Builder().url(url).put(requestBody(requestConfig.body, contentType)) - RequestMethod.POST -> Request.Builder().url(url).post(requestBody(requestConfig.body, contentType)) - RequestMethod.OPTIONS -> Request.Builder().url(url).method("OPTIONS", null) - }.apply { - headers.forEach { header -> addHeader(header.key, header.value) } - }.build() - - {{#useCoroutines}} - val response: Response = suspendCancellableCoroutine { continuation -> - val call = client.newCall(request) - continuation.invokeOnCancellation { call.cancel() } - call.enqueue(object : Callback { - override fun onFailure(call: Call, e: IOException) { - continuation.resumeWithException(e) - } - override fun onResponse(call: Call, response: Response) { - continuation.resume(response) - } - }) - } - {{/useCoroutines}} - {{^useCoroutines}} - val response = client.newCall(request).execute() - {{/useCoroutines}} - - val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.getDefault()) - - // TODO: handle specific mapping types. e.g. Map> - return when { - response.isRedirect -> Redirection( - response.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, - response.headers{{#jvm-okhttp3}}(){{/jvm-okhttp3}}.toMultimap() - ) - response.isInformational -> Informational( - response.message{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, - response.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, - response.headers{{#jvm-okhttp3}}(){{/jvm-okhttp3}}.toMultimap() - ) - response.isSuccessful -> Success( - responseBody(response.body{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, accept), - response.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, - response.headers{{#jvm-okhttp3}}(){{/jvm-okhttp3}}.toMultimap() - ) - response.isClientError -> ClientError( - response.message{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, - response.body{{#jvm-okhttp3}}(){{/jvm-okhttp3}}?.string(), - response.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, - response.headers{{#jvm-okhttp3}}(){{/jvm-okhttp3}}.toMultimap() - ) - else -> ServerError( - response.message{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, - response.body{{#jvm-okhttp3}}(){{/jvm-okhttp3}}?.string(), - response.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, - response.headers{{#jvm-okhttp3}}(){{/jvm-okhttp3}}.toMultimap() - ) - } - } - - protected fun parameterToString(value: Any?): String = when (value) { - null -> "" - is Array<*> -> toMultiValue(value, "csv").toString() - is Iterable<*> -> toMultiValue(value, "csv").toString() - is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime -> - parseDateToQueryString(value) - else -> value.toString() - } - - protected inline fun parseDateToQueryString(value : T): String { - {{#toJson}} - /* - .replace("\"", "") converts the json object string to an actual string for the query parameter. - The moshi or gson adapter allows a more generic solution instead of trying to use a native - formatter. It also easily allows to provide a simple way to define a custom date format pattern - inside a gson/moshi adapter. - */ - {{#moshi}} - return Serializer.moshi.adapter(T::class.java).toJson(value).replace("\"", "") - {{/moshi}} - {{#gson}} - return Serializer.gson.toJson(value, T::class.java).replace("\"", "") - {{/gson}} - {{#jackson}} - return Serializer.jacksonObjectMapper.writeValueAsString(value).replace("\"", "") - {{/jackson}} - {{#kotlinx_serialization}} - return Serializer.kotlinxSerializationJson.encodeToString(value).replace("\"", "") - {{/kotlinx_serialization}} - {{/toJson}} - {{^toJson}} - return value.toString() - {{/toJson}} - } -} diff --git a/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ApiResponse.kt.mustache b/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ApiResponse.kt.mustache deleted file mode 100644 index d529ad5599f..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ApiResponse.kt.mustache +++ /dev/null @@ -1,43 +0,0 @@ -package {{packageName}}.infrastructure - -{{#nonPublicApi}}internal {{/nonPublicApi}}enum class ResponseType { - Success, Informational, Redirection, ClientError, ServerError -} - -{{#nonPublicApi}}internal {{/nonPublicApi}}interface Response - -{{#nonPublicApi}}internal {{/nonPublicApi}}abstract class ApiResponse(val responseType: ResponseType): Response { - abstract val statusCode: Int - abstract val headers: Map> -} - -{{#nonPublicApi}}internal {{/nonPublicApi}}class Success( - val data: T{{#nullableReturnType}}?{{/nullableReturnType}}, - override val statusCode: Int = -1, - override val headers: Map> = mapOf() -): ApiResponse(ResponseType.Success) - -{{#nonPublicApi}}internal {{/nonPublicApi}}class Informational( - val statusText: String, - override val statusCode: Int = -1, - override val headers: Map> = mapOf() -) : ApiResponse(ResponseType.Informational) - -{{#nonPublicApi}}internal {{/nonPublicApi}}class Redirection( - override val statusCode: Int = -1, - override val headers: Map> = mapOf() -) : ApiResponse(ResponseType.Redirection) - -{{#nonPublicApi}}internal {{/nonPublicApi}}class ClientError( - val message: String? = null, - val body: Any? = null, - override val statusCode: Int = -1, - override val headers: Map> = mapOf() -) : ApiResponse(ResponseType.ClientError) - -{{#nonPublicApi}}internal {{/nonPublicApi}}class ServerError( - val message: String? = null, - val body: Any? = null, - override val statusCode: Int = -1, - override val headers: Map> -): ApiResponse(ResponseType.ServerError) diff --git a/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/Errors.kt.mustache b/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/Errors.kt.mustache deleted file mode 100644 index 7c428ad655f..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/Errors.kt.mustache +++ /dev/null @@ -1,18 +0,0 @@ -@file:Suppress("unused") -package {{packageName}}.infrastructure - -import java.lang.RuntimeException - -{{#nonPublicApi}}internal {{/nonPublicApi}}open class ClientException(message: kotlin.String? = null, val statusCode: Int = -1, val response: Response? = null) : RuntimeException(message) { - - {{#nonPublicApi}}internal {{/nonPublicApi}}companion object { - private const val serialVersionUID: Long = 123L - } -} - -{{#nonPublicApi}}internal {{/nonPublicApi}}open class ServerException(message: kotlin.String? = null, val statusCode: Int = -1, val response: Response? = null) : RuntimeException(message) { - - {{#nonPublicApi}}internal {{/nonPublicApi}}companion object { - private const val serialVersionUID: Long = 456L - } -} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ResponseExtensions.kt.mustache b/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ResponseExtensions.kt.mustache deleted file mode 100644 index d301ca6f23d..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ResponseExtensions.kt.mustache +++ /dev/null @@ -1,24 +0,0 @@ -package {{packageName}}.infrastructure - -import okhttp3.Response - -/** - * Provides an extension to evaluation whether the response is a 1xx code - */ -{{#nonPublicApi}}internal {{/nonPublicApi}}val Response.isInformational : Boolean get() = this.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}} in 100..199 - -/** - * Provides an extension to evaluation whether the response is a 3xx code - */ -@Suppress("EXTENSION_SHADOWED_BY_MEMBER") -{{#nonPublicApi}}internal {{/nonPublicApi}}val Response.isRedirect : Boolean get() = this.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}} in 300..399 - -/** - * Provides an extension to evaluation whether the response is a 4xx code - */ -{{#nonPublicApi}}internal {{/nonPublicApi}}val Response.isClientError : Boolean get() = this.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}} in 400..499 - -/** - * Provides an extension to evaluation whether the response is a 5xx (Standard) through 999 (non-standard) code - */ -{{#nonPublicApi}}internal {{/nonPublicApi}}val Response.isServerError : Boolean get() = this.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}} in 500..999 diff --git a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/api.mustache b/src/main/resources/kotlin-client/libraries/jvm-retrofit2/api.mustache deleted file mode 100644 index 3626029f764..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/api.mustache +++ /dev/null @@ -1,165 +0,0 @@ -package {{apiPackage}} - -import {{packageName}}.infrastructure.CollectionFormats.* -import retrofit2.http.* -{{#doNotUseRxAndCoroutines}} -import retrofit2.Call -{{/doNotUseRxAndCoroutines}} -{{^doNotUseRxAndCoroutines}} -{{#useCoroutines}} -import retrofit2.Response -{{/useCoroutines}} -{{/doNotUseRxAndCoroutines}} -import okhttp3.RequestBody -{{#isResponseFile}} -import okhttp3.ResponseBody -{{/isResponseFile}} -{{#isMultipart}} -import okhttp3.MultipartBody -{{/isMultipart}} -{{^doNotUseRxAndCoroutines}} -{{#useRxJava}} -import rx.Observable -{{/useRxJava}} -{{#useRxJava2}} -import io.reactivex.Single -{{/useRxJava2}} -{{#useRxJava3}} -import io.reactivex.rxjava3.core.Single -{{/useRxJava3}} -{{^returnType}} -{{#useRxJava2}} -import io.reactivex.Completable -{{/useRxJava2}} -{{#useRxJava3}} -import io.reactivex.rxjava3.core.Completable -{{/useRxJava3}} -{{/returnType}} -{{/doNotUseRxAndCoroutines}} -{{^multiplatform}} -{{#gson}} -import com.google.gson.annotations.SerializedName -{{/gson}} -{{#moshi}} -import com.squareup.moshi.Json -{{/moshi}} -{{#jackson}} -import com.fasterxml.jackson.annotation.JsonProperty -{{/jackson}} -{{#kotlinx_serialization}} -import kotlinx.serialization.SerialName -import kotlinx.serialization.Serializable -{{/kotlinx_serialization}} -{{/multiplatform}} -{{#multiplatform}} -import kotlinx.serialization.* -{{/multiplatform}} - -{{#imports}}import {{import}} -{{/imports}} - -{{#operations}} -{{#x-kotlin-multipart-import}} -{{^isMultipart}} -import okhttp3.MultipartBody - -{{/isMultipart}} -{{/x-kotlin-multipart-import}} -{{#operation}} -{{#isResponseFile}} -import okhttp3.ResponseBody - -{{/isResponseFile}} -{{/operation}} -interface {{classname}} { - {{#operation}} - {{#allParams}} - {{#isEnum}} - - /** - * enum for parameter {{paramName}} - */ - {{#nonPublicApi}}internal {{/nonPublicApi}}enum class {{enumName}}_{{operationId}}(val value: {{^isContainer}}{{dataType}}{{/isContainer}}{{#isContainer}}kotlin.String{{/isContainer}}) { - {{^enumUnknownDefaultCase}} - {{#allowableValues}} - {{#enumVars}} - {{^multiplatform}} - {{#moshi}} - @Json(name = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}){{^-last}},{{/-last}} - {{/moshi}} - {{#gson}} - @SerializedName(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}){{^-last}},{{/-last}} - {{/gson}} - {{#jackson}} - @JsonProperty(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}){{^-last}},{{/-last}} - {{/jackson}} - {{#kotlinx_serialization}} - @SerialName(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}){{^-last}},{{/-last}} - {{/kotlinx_serialization}} - {{/multiplatform}} - {{#multiplatform}} - @SerialName(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}){{^-last}},{{/-last}} - {{/multiplatform}} - {{/enumVars}} - {{/allowableValues}} - {{/enumUnknownDefaultCase}} - {{#enumUnknownDefaultCase}} - {{#allowableValues}} - {{#enumVars}} - {{^-last}} - {{^multiplatform}} - {{#moshi}} - @Json(name = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}), - {{/moshi}} - {{#gson}} - @SerializedName(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}), - {{/gson}} - {{#jackson}} - @JsonProperty(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}), - {{/jackson}} - {{#kotlinx_serialization}} - @SerialName(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}), - {{/kotlinx_serialization}} - {{/multiplatform}} - {{#multiplatform}} - @SerialName(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}), - {{/multiplatform}} - {{/-last}} - {{/enumVars}} - {{/allowableValues}} - {{/enumUnknownDefaultCase}} - } - - {{/isEnum}} - {{/allParams}} - /** - * {{summary}} - * {{notes}} - * Responses:{{#responses}} - * - {{code}}: {{{message}}}{{/responses}} - *{{>paramJavadoc}} - * @return {{^useCoroutines}}[Call]<{{/useCoroutines}}{{#isResponseFile}}[ResponseBody]{{/isResponseFile}}{{^isResponseFile}}{{#returnType}}[{{{.}}}]{{/returnType}}{{^returnType}}[Unit]{{/returnType}}{{/isResponseFile}}{{^useCoroutines}}>{{/useCoroutines}} - */ - {{#isDeprecated}} - @Deprecated("This api was deprecated") - {{/isDeprecated}} - {{#formParams}} - {{#-first}} - {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}} - {{/-first}} - {{/formParams}} - {{^formParams}} - {{#prioritizedContentTypes}} - {{#-first}} - @Headers({ - "Content-Type:{{{mediaType}}}" - }) - {{/-first}} - {{/prioritizedContentTypes}} - {{/formParams}} - @{{httpMethod}}("{{{path}}}") - {{^doNotUseRxAndCoroutines}}{{#useCoroutines}}suspend {{/useCoroutines}}{{/doNotUseRxAndCoroutines}}fun {{operationId}}({{^allParams}}){{/allParams}}{{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{^-last}}, {{/-last}}{{#-last}}){{/-last}}{{/allParams}}: {{^doNotUseRxAndCoroutines}}{{#useRxJava}}Observable<{{#isResponseFile}}ResponseBody{{/isResponseFile}}{{^isResponseFile}}{{{returnType}}}{{^returnType}}Unit{{/returnType}}{{/isResponseFile}}>{{/useRxJava}}{{#useRxJava2}}{{#returnType}}Single<{{#isResponseFile}}ResponseBody{{/isResponseFile}}{{^isResponseFile}}{{{returnType}}}{{/isResponseFile}}>{{/returnType}}{{^returnType}}Completable{{/returnType}}{{/useRxJava2}}{{#useRxJava3}}{{#returnType}}Single<{{#isResponseFile}}ResponseBody{{/isResponseFile}}{{^isResponseFile}}{{{returnType}}}{{/isResponseFile}}>{{/returnType}}{{^returnType}}Completable{{/returnType}}{{/useRxJava3}}{{#useCoroutines}}Response<{{#isResponseFile}}ResponseBody{{/isResponseFile}}{{^isResponseFile}}{{{returnType}}}{{^returnType}}Unit{{/returnType}}{{/isResponseFile}}>{{/useCoroutines}}{{/doNotUseRxAndCoroutines}}{{#doNotUseRxAndCoroutines}}Call<{{#isResponseFile}}ResponseBody{{/isResponseFile}}{{^isResponseFile}}{{{returnType}}}{{^returnType}}Unit{{/returnType}}{{/isResponseFile}}>{{/doNotUseRxAndCoroutines}} - - {{/operation}} -} -{{/operations}} diff --git a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/api_doc.mustache b/src/main/resources/kotlin-client/libraries/jvm-retrofit2/api_doc.mustache deleted file mode 100644 index 3c83a2edec6..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/api_doc.mustache +++ /dev/null @@ -1,83 +0,0 @@ -# {{classname}}{{#description}} -{{.}}{{/description}} - -All URIs are relative to *{{basePath}}* - -Method | HTTP request | Description -------------- | ------------- | ------------- -{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{summary}} -{{/operation}}{{/operations}} - -{{#operations}} -{{#operation}} - -{{summary}}{{#notes}} - -{{.}}{{/notes}} - -### Example -```kotlin -// Import classes: -//import {{{packageName}}}.* -//import {{{packageName}}}.infrastructure.* -//import {{{modelPackage}}}.* - -val apiClient = ApiClient() -{{#authMethods}} -{{#isBasic}} -{{#isBasicBasic}} -apiClient.setCredentials("USERNAME", "PASSWORD") -{{/isBasicBasic}} -{{#isBasicBearer}} -apiClient.setBearerToken("TOKEN") -{{/isBasicBearer}} -{{/isBasic}} -{{/authMethods}} -val webService = apiClient.createWebservice({{{classname}}}::class.java) -{{#allParams}} -val {{{paramName}}} : {{{dataType}}} = {{{example}}} // {{{dataType}}} | {{{description}}} -{{/allParams}} - -{{#useCoroutines}} -launch(Dispatchers.IO) { -{{/useCoroutines}} -{{#useCoroutines}} {{/useCoroutines}}{{#returnType}}val result : {{{returnType}}}{{#nullableReturnType}}?{{/nullableReturnType}} = {{/returnType}}webService.{{{operationId}}}({{#allParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}) -{{#useCoroutines}} -} -{{/useCoroutines}} -``` - -### Parameters -{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} -Name | Type | Description | Notes -------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} -{{#allParams}} **{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isFile}}**{{dataType}}**{{/isFile}}{{^isFile}}{{#generateModelDocs}}[**{{dataType}}**]({{baseType}}.md){{/generateModelDocs}}{{^generateModelDocs}}**{{dataType}}**{{/generateModelDocs}}{{/isFile}}{{/isPrimitiveType}}| {{description}} |{{^required}} [optional]{{/required}}{{#defaultValue}} [default to {{.}}]{{/defaultValue}}{{#allowableValues}} [enum: {{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}]{{/allowableValues}} -{{/allParams}} - -### Return type - -{{#returnType}}{{#returnTypeIsPrimitive}}**{{returnType}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}{{#generateModelDocs}}[**{{returnType}}**]({{returnBaseType}}.md){{/generateModelDocs}}{{^generateModelDocs}}**{{returnType}}**{{/generateModelDocs}}{{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}null (empty response body){{/returnType}} - -### Authorization - -{{^authMethods}}No authorization required{{/authMethods}} -{{#authMethods}} -{{#isBasic}} -{{#isBasicBasic}} -Configure {{name}}: - ApiClient().setCredentials("USERNAME", "PASSWORD") -{{/isBasicBasic}} -{{#isBasicBearer}} -Configure {{name}}: - ApiClient().setBearerToken("TOKEN") -{{/isBasicBearer}} -{{/isBasic}} -{{/authMethods}} - -### HTTP request headers - - - **Content-Type**: {{#consumes}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} - - **Accept**: {{#produces}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/produces}}{{^produces}}Not defined{{/produces}} - -{{/operation}} -{{/operations}} diff --git a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/auth/ApiKeyAuth.kt.mustache b/src/main/resources/kotlin-client/libraries/jvm-retrofit2/auth/ApiKeyAuth.kt.mustache deleted file mode 100644 index 967980ae7fb..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/auth/ApiKeyAuth.kt.mustache +++ /dev/null @@ -1,50 +0,0 @@ -package {{packageName}}.auth - -import java.io.IOException -import java.net.URI -import java.net.URISyntaxException - -import okhttp3.Interceptor -import okhttp3.Response - -class ApiKeyAuth( - private val location: String = "", - private val paramName: String = "", - private var apiKey: String = "" -) : Interceptor { - - @Throws(IOException::class) - override fun intercept(chain: Interceptor.Chain): Response { - var request = chain.request() - - if ("query" == location) { - var newQuery = request.url.toUri().query - val paramValue = "$paramName=$apiKey" - if (newQuery == null) { - newQuery = paramValue - } else { - newQuery += "&$paramValue" - } - - val newUri: URI - try { - val oldUri = request.url.toUri() - newUri = URI(oldUri.scheme, oldUri.authority, - oldUri.path, newQuery, oldUri.fragment) - } catch (e: URISyntaxException) { - throw IOException(e) - } - - request = request.newBuilder().url(newUri.toURL()).build() - } else if ("header" == location) { - request = request.newBuilder() - .addHeader(paramName, apiKey) - .build() - } else if ("cookie" == location) { - request = request.newBuilder() - .addHeader("Cookie", "$paramName=$apiKey") - .build() - } - return chain.proceed(request) - } -} diff --git a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/auth/HttpBasicAuth.kt.mustache b/src/main/resources/kotlin-client/libraries/jvm-retrofit2/auth/HttpBasicAuth.kt.mustache deleted file mode 100644 index fc122514388..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/auth/HttpBasicAuth.kt.mustache +++ /dev/null @@ -1,33 +0,0 @@ -package {{packageName}}.auth - -import java.io.IOException - -import kotlin.jvm.Throws -import okhttp3.Interceptor -import okhttp3.Interceptor.Chain -import okhttp3.Response -import okhttp3.Credentials - -class HttpBasicAuth( - private var username: String = "", - private var password: String = "" -) : Interceptor { - - fun setCredentials(username: String, password: String) { - this.username = username - this.password = password - } - - @Throws(IOException::class) - override fun intercept(chain: Chain): Response { - var request = chain.request() - - // If the request already have an authorization (eg. Basic auth), do nothing - if (request.header("Authorization") == null && username.isNotBlank() && password.isNotBlank()) { - request = request.newBuilder() - .addHeader("Authorization", Credentials.basic(username, password)) - .build() - } - return chain.proceed(request) - } -} diff --git a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/auth/HttpBearerAuth.kt.mustache b/src/main/resources/kotlin-client/libraries/jvm-retrofit2/auth/HttpBearerAuth.kt.mustache deleted file mode 100644 index 7488e6a9f57..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/auth/HttpBearerAuth.kt.mustache +++ /dev/null @@ -1,39 +0,0 @@ -package {{packageName}}.auth - -import java.io.IOException - -import okhttp3.Interceptor -import okhttp3.Interceptor.Chain -import okhttp3.Response - -class HttpBearerAuth( - private var schema: String = "", - var bearerToken: String = "" -) : Interceptor { - - @Throws(IOException::class) - override fun intercept(chain: Chain): Response { - var request = chain.request() - - // If the request already have an authorization (eg. Basic auth), do nothing - if (request.header("Authorization") == null && bearerToken.isNotBlank()) { - request = request.newBuilder() - .addHeader("Authorization", headerValue()) - .build() - } - return chain.proceed(request) - } - - private fun headerValue(): String { - return if (schema.isNotBlank()) { - "${upperCaseBearer()} $bearerToken" - } else { - bearerToken - } - } - - private fun upperCaseBearer(): String { - return if (schema.lowercase().equals("bearer")) "Bearer" else schema - } - -} diff --git a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/auth/OAuth.kt.mustache b/src/main/resources/kotlin-client/libraries/jvm-retrofit2/auth/OAuth.kt.mustache deleted file mode 100644 index 8063b6c7186..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/auth/OAuth.kt.mustache +++ /dev/null @@ -1,151 +0,0 @@ -package {{packageName}}.auth - -import java.net.HttpURLConnection.HTTP_UNAUTHORIZED -import java.net.HttpURLConnection.HTTP_FORBIDDEN - -import java.io.IOException - -import org.apache.oltu.oauth2.client.OAuthClient -import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest -import org.apache.oltu.oauth2.client.request.OAuthClientRequest -import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder -import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder -import org.apache.oltu.oauth2.common.exception.OAuthProblemException -import org.apache.oltu.oauth2.common.exception.OAuthSystemException -import org.apache.oltu.oauth2.common.message.types.GrantType -import org.apache.oltu.oauth2.common.token.BasicOAuthToken - -import okhttp3.Interceptor -import okhttp3.OkHttpClient -import okhttp3.Response - -class OAuth( - client: OkHttpClient, - var tokenRequestBuilder: TokenRequestBuilder -) : Interceptor { - - interface AccessTokenListener { - fun notify(token: BasicOAuthToken) - } - - private var oauthClient: OAuthClient = OAuthClient(OAuthOkHttpClient(client)) - - @Volatile - private var accessToken: String? = null - var authenticationRequestBuilder: AuthenticationRequestBuilder? = null - private var accessTokenListener: AccessTokenListener? = null - - constructor( - requestBuilder: TokenRequestBuilder - ) : this( - OkHttpClient(), - requestBuilder - ) - - constructor( - flow: OAuthFlow, - authorizationUrl: String, - tokenUrl: String, - scopes: String - ) : this( - OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes) - ) { - setFlow(flow) - authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl) - } - - fun setFlow(flow: OAuthFlow) { - when (flow) { - OAuthFlow.accessCode, OAuthFlow.implicit -> - tokenRequestBuilder.setGrantType(GrantType.AUTHORIZATION_CODE) - OAuthFlow.password -> - tokenRequestBuilder.setGrantType(GrantType.PASSWORD) - OAuthFlow.application -> - tokenRequestBuilder.setGrantType(GrantType.CLIENT_CREDENTIALS) - } - } - - @Throws(IOException::class) - override fun intercept(chain: Interceptor.Chain): Response { - return retryingIntercept(chain, true) - } - - @Throws(IOException::class) - private fun retryingIntercept(chain: Interceptor.Chain, updateTokenAndRetryOnAuthorizationFailure: Boolean): Response { - var request = chain.request() - - // If the request already have an authorization (eg. Basic auth), do nothing - if (request.header("Authorization") != null) { - return chain.proceed(request) - } - - // If first time, get the token - val oAuthRequest: OAuthClientRequest - if (accessToken == null) { - updateAccessToken(null) - } - - if (accessToken != null) { - // Build the request - val rb = request.newBuilder() - - val requestAccessToken = accessToken - try { - oAuthRequest = OAuthBearerClientRequest(request.url.toString()) - .setAccessToken(requestAccessToken) - .buildHeaderMessage() - } catch (e: OAuthSystemException) { - throw IOException(e) - } - - oAuthRequest.headers.entries.forEach { header -> - rb.addHeader(header.key, header.value) - } - rb.url(oAuthRequest.locationUri) - - //Execute the request - val response = chain.proceed(rb.build()) - - // 401/403 most likely indicates that access token has expired. Unless it happens two times in a row. - if ((response.code == HTTP_UNAUTHORIZED || response.code == HTTP_FORBIDDEN) && updateTokenAndRetryOnAuthorizationFailure) { - try { - if (updateAccessToken(requestAccessToken)) { - response.body?.close() - return retryingIntercept(chain, false) - } - } catch (e: Exception) { - response.body?.close() - throw e - } - } - return response - } else { - return chain.proceed(chain.request()) - } - } - - /** - * Returns true if the access token has been updated - */ - @Throws(IOException::class) - @Synchronized - fun updateAccessToken(requestAccessToken: String?): Boolean { - if (accessToken == null || accessToken.equals(requestAccessToken)) { - return try { - val accessTokenResponse = oauthClient.accessToken(this.tokenRequestBuilder.buildBodyMessage()) - if (accessTokenResponse != null && accessTokenResponse.accessToken != null) { - accessToken = accessTokenResponse.accessToken - accessTokenListener?.notify(accessTokenResponse.oAuthToken as BasicOAuthToken) - !accessToken.equals(requestAccessToken) - } else { - false - } - } catch (e: OAuthSystemException) { - throw IOException(e) - } catch (e: OAuthProblemException) { - throw IOException(e) - } - } - return true - } -} diff --git a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/auth/OAuthFlow.kt.mustache b/src/main/resources/kotlin-client/libraries/jvm-retrofit2/auth/OAuthFlow.kt.mustache deleted file mode 100644 index 05ad3f7e547..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/auth/OAuthFlow.kt.mustache +++ /dev/null @@ -1,5 +0,0 @@ -package {{packageName}}.auth - -enum class OAuthFlow { - accessCode, implicit, password, application -} diff --git a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/auth/OAuthOkHttpClient.kt.mustache b/src/main/resources/kotlin-client/libraries/jvm-retrofit2/auth/OAuthOkHttpClient.kt.mustache deleted file mode 100644 index 0731e92a890..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/auth/OAuthOkHttpClient.kt.mustache +++ /dev/null @@ -1,61 +0,0 @@ -package {{packageName}}.auth - -import java.io.IOException - -import org.apache.oltu.oauth2.client.HttpClient -import org.apache.oltu.oauth2.client.request.OAuthClientRequest -import org.apache.oltu.oauth2.client.response.OAuthClientResponse -import org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory -import org.apache.oltu.oauth2.common.exception.OAuthProblemException -import org.apache.oltu.oauth2.common.exception.OAuthSystemException - -import okhttp3.OkHttpClient -import okhttp3.Request -import okhttp3.MediaType.Companion.toMediaTypeOrNull -import okhttp3.RequestBody -import okhttp3.RequestBody.Companion.toRequestBody - - -class OAuthOkHttpClient( - private var client: OkHttpClient = OkHttpClient() -) : HttpClient { - - @Throws(OAuthSystemException::class, OAuthProblemException::class) - override fun execute( - request: OAuthClientRequest, - headers: Map?, - requestMethod: String, - responseClass: Class?): T { - - var mediaType = "application/json".toMediaTypeOrNull() - val requestBuilder = Request.Builder().url(request.locationUri) - - headers?.forEach { entry -> - if (entry.key.equals("Content-Type", true)) { - mediaType = entry.value.toMediaTypeOrNull() - } else { - requestBuilder.addHeader(entry.key, entry.value) - } - } - - val body: RequestBody? = if (request.body != null) request.body.toRequestBody(mediaType) else null - requestBuilder.method(requestMethod, body) - - try { - val response = client.newCall(requestBuilder.build()).execute() - return OAuthClientResponseFactory.createCustomResponse( - response.body?.string(), - response.body?.contentType()?.toString(), - response.code, - response.headers.toMultimap(), - responseClass) - } catch (e: IOException) { - throw OAuthSystemException(e) - } - } - - override fun shutdown() { - // Nothing to do here - } - -} diff --git a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/bodyParams.mustache b/src/main/resources/kotlin-client/libraries/jvm-retrofit2/bodyParams.mustache deleted file mode 100644 index 15ec80cdbad..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/bodyParams.mustache +++ /dev/null @@ -1 +0,0 @@ -{{#isBodyParam}}@Body {{{paramName}}}: {{{dataType}}}{{^required}}? = null{{/required}}{{/isBodyParam}} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/explodedQueryParam.mustache b/src/main/resources/kotlin-client/libraries/jvm-retrofit2/explodedQueryParam.mustache deleted file mode 100644 index 3aaa4e67fbf..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/explodedQueryParam.mustache +++ /dev/null @@ -1 +0,0 @@ -@Query("{{baseName}}") {{{baseName}}}: {{#collectionFormat}}{{#isCollectionFormatMulti}}{{{dataType}}}{{/isCollectionFormatMulti}}{{^isCollectionFormatMulti}}{{{collectionFormat.toUpperCase}}}Params{{/isCollectionFormatMulti}}{{/collectionFormat}}{{^collectionFormat}}{{{dataType}}}{{/collectionFormat}}{{#required}}{{#defaultValue}} = {{^isNumber}}{{{defaultValue}}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{/required}}{{^required}}?{{#defaultValue}} = {{^isNumber}}{{{defaultValue}}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{^defaultValue}} = null{{/defaultValue}}{{/required}} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/formParams.mustache b/src/main/resources/kotlin-client/libraries/jvm-retrofit2/formParams.mustache deleted file mode 100644 index 66d904c740c..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/formParams.mustache +++ /dev/null @@ -1 +0,0 @@ -{{#isFormParam}}{{^isFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{baseName}}") {{{paramName}}}: {{{dataType}}}{{#required}}{{#defaultValue}} = {{^isNumber}}{{{defaultValue}}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{/required}}{{^required}}?{{#defaultValue}} = {{^isNumber}}{{{defaultValue}}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{^defaultValue}} = null{{/defaultValue}}{{/required}}{{/isFile}}{{#isFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field("{{baseName}}"){{/isMultipart}} {{{paramName}}}: MultipartBody.Part{{^required}}? = null{{/required}}{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/headerParams.mustache b/src/main/resources/kotlin-client/libraries/jvm-retrofit2/headerParams.mustache deleted file mode 100644 index 70bf5ef3b3e..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/headerParams.mustache +++ /dev/null @@ -1 +0,0 @@ -{{#isHeaderParam}}@Header("{{baseName}}") {{{paramName}}}: {{#isEnum}}{{enumName}}_{{operationId}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{#required}}{{#defaultValue}} = {{^isNumber}}{{#isEnum}}{{enumName}}_{{operationId}}.{{enumDefaultValue}}{{/isEnum}}{{^isEnum}}{{{defaultValue}}}{{/isEnum}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{/required}}{{^required}}?{{#defaultValue}} = {{^isNumber}}{{#isEnum}}{{enumName}}_{{operationId}}.{{enumDefaultValue}}{{/isEnum}}{{^isEnum}}{{{defaultValue}}}{{/isEnum}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{^defaultValue}} = null{{/defaultValue}}{{/required}}{{/isHeaderParam}} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/infrastructure/ApiClient.kt.mustache b/src/main/resources/kotlin-client/libraries/jvm-retrofit2/infrastructure/ApiClient.kt.mustache deleted file mode 100644 index 4b48bdcb7da..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/infrastructure/ApiClient.kt.mustache +++ /dev/null @@ -1,333 +0,0 @@ -package {{packageName}}.infrastructure - -{{#hasOAuthMethods}} -import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder -import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder -import {{packageName}}.auth.OAuth -import {{packageName}}.auth.OAuth.AccessTokenListener -import {{packageName}}.auth.OAuthFlow -{{/hasOAuthMethods}} -{{#hasAuthMethods}} -{{#authMethods}} -{{#isBasic}} -{{#isBasicBasic}} -import {{packageName}}.auth.HttpBasicAuth -{{/isBasicBasic}} -{{#isBasicBearer}} -import {{packageName}}.auth.HttpBearerAuth -{{/isBasicBearer}} -{{/isBasic}} -{{#isApiKey}} -import {{packageName}}.auth.ApiKeyAuth -{{/isApiKey}} -{{/authMethods}} -{{/hasAuthMethods}} - -import okhttp3.Call -import okhttp3.Interceptor -import okhttp3.OkHttpClient -import retrofit2.Retrofit -import okhttp3.logging.HttpLoggingInterceptor -import retrofit2.Converter -import retrofit2.converter.scalars.ScalarsConverterFactory -{{#useRxJava}} -import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory -{{/useRxJava}} -{{#useRxJava2}} -import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory -{{/useRxJava2}} -{{#useRxJava3}} -import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory -{{/useRxJava3}} -{{#gson}} -import com.google.gson.Gson -import com.google.gson.GsonBuilder -import retrofit2.converter.gson.GsonConverterFactory -{{/gson}} -{{#moshi}} -import com.squareup.moshi.Moshi -import retrofit2.converter.moshi.MoshiConverterFactory -{{/moshi}} - -{{#kotlinx_serialization}} -import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory -import {{packageName}}.infrastructure.Serializer.kotlinxSerializationJson -import okhttp3.MediaType.Companion.toMediaType -{{/kotlinx_serialization}} - -{{#nonPublicApi}}internal {{/nonPublicApi}}class ApiClient( - private var baseUrl: String = defaultBasePath, - private val okHttpClientBuilder: OkHttpClient.Builder? = null{{^kotlinx_serialization}}, - private val serializerBuilder: {{#gson}}Gson{{/gson}}{{#moshi}}Moshi.{{/moshi}}Builder = Serializer.{{#gson}}gson{{/gson}}{{#moshi}}moshi{{/moshi}}Builder{{/kotlinx_serialization}}, - private val callFactory : Call.Factory? = null, - private val converterFactory: Converter.Factory? = null, -) { - private val apiAuthorizations = mutableMapOf() - var logger: ((String) -> Unit)? = null - - private val retrofitBuilder: Retrofit.Builder by lazy { - Retrofit.Builder() - .baseUrl(baseUrl) - .addConverterFactory(ScalarsConverterFactory.create()) - {{#gson}} - .addConverterFactory(GsonConverterFactory.create(serializerBuilder.create())) - {{/gson}} - {{#useRxJava}} - .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) - {{/useRxJava}} - {{#useRxJava2}} - .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) - {{/useRxJava2}}{{#useRxJava3}} - .addCallAdapterFactory(RxJava3CallAdapterFactory.create()) - {{/useRxJava3}} - {{#moshi}} - .addConverterFactory(MoshiConverterFactory.create(serializerBuilder.build())) - {{/moshi}} - {{#kotlinx_serialization}} - .addConverterFactory(kotlinxSerializationJson.asConverterFactory("application/json".toMediaType())) - {{/kotlinx_serialization}} - .apply { - if (converterFactory != null) { - addConverterFactory(converterFactory) - } - } - } - - private val clientBuilder: OkHttpClient.Builder by lazy { - okHttpClientBuilder ?: defaultClientBuilder - } - - private val defaultClientBuilder: OkHttpClient.Builder by lazy { - OkHttpClient() - .newBuilder() - .addInterceptor(HttpLoggingInterceptor { message -> logger?.invoke(message) } - .apply { level = HttpLoggingInterceptor.Level.BODY } - ) - } - - init { - normalizeBaseUrl() - } - - {{#hasAuthMethods}} - constructor( - baseUrl: String = defaultBasePath, - okHttpClientBuilder: OkHttpClient.Builder? = null, - {{^kotlinx_serialization}}serializerBuilder: {{#gson}}Gson{{/gson}}{{#moshi}}Moshi.{{/moshi}}Builder = Serializer.{{#gson}}gson{{/gson}}{{#moshi}}moshi{{/moshi}}Builder,{{/kotlinx_serialization}} - authNames: Array - ) : this(baseUrl, okHttpClientBuilder{{^kotlinx_serialization}}, serializerBuilder{{/kotlinx_serialization}}) { - authNames.forEach { authName -> - val auth = when (authName) { - {{#authMethods}}"{{name}}" -> {{#isBasic}}{{#isBasicBasic}}HttpBasicAuth(){{/isBasicBasic}}{{#isBasicBearer}}HttpBearerAuth("{{scheme}}"){{/isBasicBearer}}{{/isBasic}}{{#isApiKey}}ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{#isKeyInQuery}}"query"{{/isKeyInQuery}}{{#isKeyInCookie}}"cookie"{{/isKeyInCookie}}, "{{keyParamName}}"){{/isApiKey}}{{#isOAuth}}OAuth(OAuthFlow.{{flow}}, "{{authorizationUrl}}", "{{tokenUrl}}", "{{#scopes}}{{scope}}{{^-last}}, {{/-last}}{{/scopes}}"){{/isOAuth}}{{/authMethods}} - else -> throw RuntimeException("auth name $authName not found in available auth names") - } - addAuthorization(authName, auth) - } - } - - {{#authMethods}} - {{#isBasic}} - {{#isBasicBasic}} - constructor( - baseUrl: String = defaultBasePath, - okHttpClientBuilder: OkHttpClient.Builder? = null, - {{^kotlinx_serialization}}serializerBuilder: {{#gson}}Gson{{/gson}}{{#moshi}}Moshi.{{/moshi}}Builder = Serializer.{{#gson}}gson{{/gson}}{{#moshi}}moshi{{/moshi}}Builder,{{/kotlinx_serialization}} - authName: String, - username: String, - password: String - ) : this(baseUrl, okHttpClientBuilder, {{^kotlinx_serialization}}serializerBuilder, {{/kotlinx_serialization}}arrayOf(authName)) { - setCredentials(username, password) - } - - {{/isBasicBasic}} - {{#isBasicBearer}} - constructor( - baseUrl: String = defaultBasePath, - okHttpClientBuilder: OkHttpClient.Builder? = null, - {{^kotlinx_serialization}}serializerBuilder: {{#gson}}Gson{{/gson}}{{#moshi}}Moshi.{{/moshi}}Builder = Serializer.{{#gson}}gson{{/gson}}{{#moshi}}moshi{{/moshi}}Builder,{{/kotlinx_serialization}} - authName: String, - bearerToken: String - ) : this(baseUrl, okHttpClientBuilder, {{^kotlinx_serialization}}serializerBuilder, {{/kotlinx_serialization}}arrayOf(authName)) { - setBearerToken(bearerToken) - } - - {{/isBasicBearer}} - {{/isBasic}} - {{/authMethods}} - {{#hasOAuthMethods}} - constructor( - baseUrl: String = defaultBasePath, - okHttpClientBuilder: OkHttpClient.Builder? = null, - {{^kotlinx_serialization}}serializerBuilder: {{#gson}}Gson{{/gson}}{{#moshi}}Moshi.{{/moshi}}Builder = Serializer.{{#gson}}gson{{/gson}}{{#moshi}}moshi{{/moshi}}Builder,{{/kotlinx_serialization}} - authName: String, - clientId: String, - secret: String, - username: String, - password: String - ) : this(baseUrl, okHttpClientBuilder, {{^kotlinx_serialization}}serializerBuilder, {{/kotlinx_serialization}}arrayOf(authName)) { - getTokenEndPoint() - ?.setClientId(clientId) - ?.setClientSecret(secret) - ?.setUsername(username) - ?.setPassword(password) - } - - {{/hasOAuthMethods}} - {{#authMethods}} - {{#isBasic}} - {{#isBasicBasic}} - fun setCredentials(username: String, password: String): ApiClient { - apiAuthorizations.values.runOnFirst { - setCredentials(username, password) - } - {{#hasOAuthMethods}} - apiAuthorizations.values.runOnFirst { - tokenRequestBuilder.setUsername(username).setPassword(password) - } - {{/hasOAuthMethods}} - return this - } - - {{/isBasicBasic}} - {{^isBasicBasic}} - {{#hasOAuthMethods}} - fun setCredentials(username: String, password: String): ApiClient { - apiAuthorizations.values.runOnFirst { - tokenRequestBuilder.setUsername(username).setPassword(password) - } - return this - } - {{/hasOAuthMethods}} - {{/isBasicBasic}} - {{#isBasicBearer}} - fun setBearerToken(bearerToken: String): ApiClient { - apiAuthorizations.values.runOnFirst { - this.bearerToken = bearerToken - } - return this - } - - {{/isBasicBearer}} - {{/isBasic}} - {{/authMethods}} - {{/hasAuthMethods}} - {{#hasOAuthMethods}} - /** - * Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one) - * @return Token request builder - */ - fun getTokenEndPoint(): TokenRequestBuilder? { - var result: TokenRequestBuilder? = null - apiAuthorizations.values.runOnFirst { - result = tokenRequestBuilder - } - return result - } - - /** - * Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one) - * @return Authentication request builder - */ - fun getAuthorizationEndPoint(): AuthenticationRequestBuilder? { - var result: AuthenticationRequestBuilder? = null - apiAuthorizations.values.runOnFirst { - result = authenticationRequestBuilder - } - return result - } - - /** - * Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one) - * @param accessToken Access token - * @return ApiClient - */ - fun setAccessToken(accessToken: String): ApiClient { - apiAuthorizations.values.runOnFirst { - setAccessToken(accessToken) - } - return this - } - - /** - * Helper method to configure the oauth accessCode/implicit flow parameters - * @param clientId Client ID - * @param clientSecret Client secret - * @param redirectURI Redirect URI - * @return ApiClient - */ - fun configureAuthorizationFlow(clientId: String, clientSecret: String, redirectURI: String): ApiClient { - apiAuthorizations.values.runOnFirst { - tokenRequestBuilder - .setClientId(clientId) - .setClientSecret(clientSecret) - .setRedirectURI(redirectURI) - authenticationRequestBuilder - ?.setClientId(clientId) - ?.setRedirectURI(redirectURI) - } - return this - } - - /** - * Configures a listener which is notified when a new access token is received. - * @param accessTokenListener Access token listener - * @return ApiClient - */ - fun registerAccessTokenListener(accessTokenListener: AccessTokenListener): ApiClient { - apiAuthorizations.values.runOnFirst { - registerAccessTokenListener(accessTokenListener) - } - return this - } - - {{/hasOAuthMethods}} - /** - * Adds an authorization to be used by the client - * @param authName Authentication name - * @param authorization Authorization interceptor - * @return ApiClient - */ - fun addAuthorization(authName: String, authorization: Interceptor): ApiClient { - if (apiAuthorizations.containsKey(authName)) { - throw RuntimeException("auth name $authName already in api authorizations") - } - apiAuthorizations[authName] = authorization - clientBuilder.addInterceptor(authorization) - return this - } - - fun setLogger(logger: (String) -> Unit): ApiClient { - this.logger = logger - return this - } - - fun createService(serviceClass: Class): S { - val usedCallFactory = this.callFactory ?: clientBuilder.build() - return retrofitBuilder.callFactory(usedCallFactory).build().create(serviceClass) - } - - private fun normalizeBaseUrl() { - if (!baseUrl.endsWith("/")) { - baseUrl += "/" - } - } - - private inline fun Iterable.runOnFirst(callback: U.() -> Unit) { - for (element in this) { - if (element is U) { - callback.invoke(element) - break - } - } - } - - companion object { - @JvmStatic - protected val baseUrlKey = "{{packageName}}.baseUrl" - - @JvmStatic - val defaultBasePath: String by lazy { - System.getProperties().getProperty(baseUrlKey, "{{{basePath}}}") - } - } -} diff --git a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/infrastructure/CollectionFormats.kt.mustache b/src/main/resources/kotlin-client/libraries/jvm-retrofit2/infrastructure/CollectionFormats.kt.mustache deleted file mode 100644 index 659f2df4851..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/infrastructure/CollectionFormats.kt.mustache +++ /dev/null @@ -1,56 +0,0 @@ -package {{packageName}}.infrastructure - -class CollectionFormats { - - open class CSVParams { - - var params: List - - constructor(params: List) { - this.params = params - } - - constructor(vararg params: String) { - this.params = listOf(*params) - } - - override fun toString(): String { - return params.joinToString(",") - } - } - - open class SSVParams : CSVParams { - - constructor(params: List) : super(params) - - constructor(vararg params: String) : super(*params) - - override fun toString(): String { - return params.joinToString(" ") - } - } - - class TSVParams : CSVParams { - - constructor(params: List) : super(params) - - constructor(vararg params: String) : super(*params) - - override fun toString(): String { - return params.joinToString("\t") - } - } - - class PIPESParams : CSVParams { - - constructor(params: List) : super(params) - - constructor(vararg params: String) : super(*params) - - override fun toString(): String { - return params.joinToString("|") - } - } - - class SPACEParams : SSVParams() -} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/infrastructure/ResponseExt.kt.mustache b/src/main/resources/kotlin-client/libraries/jvm-retrofit2/infrastructure/ResponseExt.kt.mustache deleted file mode 100644 index a5edf4ee809..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/infrastructure/ResponseExt.kt.mustache +++ /dev/null @@ -1,35 +0,0 @@ -package {{packageName}}.infrastructure - -{{#moshi}} -import com.squareup.moshi.JsonDataException -import com.squareup.moshi.Moshi -{{/moshi}} -{{#gson}} -import com.google.gson.GsonBuilder -import com.google.gson.JsonParseException -{{/gson}} -import retrofit2.Response - -{{#moshi}} -@Throws(JsonDataException::class) -inline fun Response<*>.getErrorResponse(serializerBuilder: Moshi.Builder = Serializer.moshiBuilder): T? { - val serializer = serializerBuilder.build() - val parser = serializer.adapter(T::class.java) - val response = errorBody()?.string() - if (response != null) { - return parser.fromJson(response) - } - return null -} -{{/moshi}} -{{#gson}} -@Throws(JsonParseException::class) -inline fun Response<*>.getErrorResponse(serializerBuilder: GsonBuilder = Serializer.gsonBuilder): T? { - val serializer = serializerBuilder.create() - val reader = errorBody()?.charStream() - if (reader != null) { - return serializer.fromJson(reader, T::class.java) - } - return null -} -{{/gson}} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/paramJavadoc.mustache b/src/main/resources/kotlin-client/libraries/jvm-retrofit2/paramJavadoc.mustache deleted file mode 100644 index fe821c41b4d..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/paramJavadoc.mustache +++ /dev/null @@ -1,5 +0,0 @@ -{{#allParams}}{{#isDeepObject}} - * @param {{{paramName}}} {{description}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{#required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}{{/required}}{{/isDeepObject}}{{^isDeepObject}}{{#isExplode}}{{#hasVars}}{{#vars}} - * @param {{{baseName}}} {{description}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{#required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}{{/required}}{{/vars}}{{/hasVars}}{{^hasVars}} - * @param {{{paramName}}} {{description}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{#required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}{{/required}}{{/hasVars}}{{/isExplode}}{{^isExplode}} - * @param {{{paramName}}} {{description}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{#required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}{{/required}}{{/isExplode}}{{/isDeepObject}}{{/allParams}} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/pathParams.mustache b/src/main/resources/kotlin-client/libraries/jvm-retrofit2/pathParams.mustache deleted file mode 100644 index 685c514e6a9..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/pathParams.mustache +++ /dev/null @@ -1 +0,0 @@ -{{#isPathParam}}@Path("{{baseName}}") {{{paramName}}}: {{{dataType}}}{{#required}}{{#defaultValue}} = {{^isNumber}}{{{defaultValue}}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{/required}}{{^required}}?{{#defaultValue}} = {{^isNumber}}{{{defaultValue}}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{^defaultValue}} = null{{/defaultValue}}{{/required}}{{/isPathParam}} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/queryParam.mustache b/src/main/resources/kotlin-client/libraries/jvm-retrofit2/queryParam.mustache deleted file mode 100644 index 0fdab94eed2..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/queryParam.mustache +++ /dev/null @@ -1 +0,0 @@ -@Query("{{baseName}}") {{{paramName}}}: {{#collectionFormat}}{{#isCollectionFormatMulti}}{{{dataType}}}{{/isCollectionFormatMulti}}{{^isCollectionFormatMulti}}{{{collectionFormat.toUpperCase}}}Params{{/isCollectionFormatMulti}}{{/collectionFormat}}{{^collectionFormat}}{{#isEnum}}{{enumName}}_{{operationId}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{/collectionFormat}}{{#required}}{{#defaultValue}} = {{^isNumber}}{{#isEnum}}{{enumName}}_{{operationId}}.{{enumDefaultValue}}{{/isEnum}}{{^isEnum}}{{{defaultValue}}}{{/isEnum}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{/required}}{{^required}}?{{#defaultValue}} = {{^isNumber}}{{#isEnum}}{{enumName}}_{{operationId}}.{{enumDefaultValue}}{{/isEnum}}{{^isEnum}}{{{defaultValue}}}{{/isEnum}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{^defaultValue}} = null{{/defaultValue}}{{/required}} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/queryParams.mustache b/src/main/resources/kotlin-client/libraries/jvm-retrofit2/queryParams.mustache deleted file mode 100644 index ab229cf40e4..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-retrofit2/queryParams.mustache +++ /dev/null @@ -1 +0,0 @@ -{{#isQueryParam}}{{#isDeepObject}}{{>queryParam}}{{/isDeepObject}}{{^isDeepObject}}{{#isExplode}}{{#hasVars}}{{#vars}}{{>explodedQueryParam}}{{^-last}}, {{/-last}}{{/vars}}{{/hasVars}}{{^hasVars}}{{>queryParam}}{{/hasVars}}{{/isExplode}}{{^isExplode}}{{>queryParam}}{{/isExplode}}{{/isDeepObject}}{{/isQueryParam}} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/libraries/jvm-volley/README.mustache b/src/main/resources/kotlin-client/libraries/jvm-volley/README.mustache deleted file mode 100644 index ea684b99848..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-volley/README.mustache +++ /dev/null @@ -1,232 +0,0 @@ -# {{packageName}} - Kotlin client library for {{appName}} - - -A kotlin client for Android using the currently recommended http client, Volley. See https://developer.android.com/training/volley - -- Currently sends GsonRequests -- Currently only supports Gson as a serializer - will throw an exception if a different serializer is chosen -- Defaults the source location to src/main/java as per standard Android builds - - -## Design - -Volley is a queue/request based layer on top of http url stack specific to Android. Android favours dependency injection and -a layered architecture, and IO performed off the main thread to maintain UI responsiveness, with a preferred technique of -kotlin co-routines. The code gen library reflects these factors. - -- Api calls use co-routines, and execute them using volley callbacks to avoid tying up a thread. -- Facilitate dependency injection, with default implementations available. -- Generate a requestFactory that can be overridden -- Allow the passing of the RequestFactory per tag (api client) or per operation (an extra parameter is created on operations with non-global security), with per operation auth overriding global security. -- DI scoping of the Request Factory and pre-generated auth header factories allow for thread safe and secure setting of credentials. -- Lazy header factories allow for refreshing tokens etc -- Factoring of header factories to the Request Factory allow ambient provision of credentials. Code gen library is credential storage agnostic. -- Header factories allow the merging of generated headers from open api spec with dynamically added headers - -- Injection of http url stack to allow custom http stacks. Default implementation is best practice singleton -- Data classes used for serialisation to reflect volley's preference - an immutable request that once queued can't be tampered with. - -- Reuse model class and other jvm common infrastructure - -- Optional generation of room database models, and transform methods to these from open api models -- Room and api models can be extended with additional extension properties. - -## Future improvements -- Option to generate image requests on certain conditionals e.g content-type gif etc -- Support for kotlin serialization. -- Multi part form parameters and support for file inputs - -## Usage -Hilt Dependency injection example - with default values for parameters overridden. -``` - @Provides - internal fun provideSomeApi( - context: Context, - restService: IRestService, - configurationService: IConfigurationService, - sessionService: ISessionService - ): SomeApi { - return SomeApi( - context = context, - requestQueue = restService.getRequestQueue(), - requestFactory = RequestFactory(listOf(createSessionHeaderFactory(sessionService), createTraceHeaderFactory()), - postProcessors = listOf(retryPolicySetter)), - basePath = configurationService.getBaseUrl() - ) - } -``` -Here is the constructor so you can see the defaults -```class SomeApi ( -val context: Context, -val requestQueue: Lazy = lazy(initializer = { - Volley.newRequestQueue(context.applicationContext) - }), - val requestFactory: IRequestFactory = RequestFactory(), - val basePath: String = "https://yourbasepath.from_input_parameter.com/api", - private val postProcessors :List <(Request<*>) -> Unit> = listOf()) { -``` - -### Overriding defaults -The above constructor for each api allows the following to be customized -- A custom context, so either a singleton request queue or different scope can be created - see -https://developer.android.com/training/volley/requestqueue#singleton -- An overrideable request queue - which in turn can have a custom http url stack passed to it -- An overrideable request factory constructor call, or a request factory that can be overridden by a custom template, with -custom header factory, request post processors and custom gson adapters injected. - -#### Overriding request generation -Request generation can be overridden by -- Overriding the entire request factory template -- Supplying custom header factories - methods that take any possible parameters but return a map of headers -- Supplying custom request post processors - methods that take and return the request object - -Header factory examples can be found in the auth section, as these are implemented as header factories. eg -``` -val basicAuthHeaderFactoryBuilder = { username: String?, password: String? -> -{ mapOf("Authorization" to "Basic " + Base64.encodeToString("${username ?: ""}:${password ?: ""}".toByteArray(), Base64.DEFAULT))} -} -``` -In this case it's a lambda function (a factory method) that takes an username and password, and returns a map of headers. Other -generated code will supply the username and password. In this case it results in a map of just one key/value pair, but -it could be multiple. The important part is it's returning a map - and that the surrounding code -will can bind the inputs to it at some point. - -Here is a different example that supplies tracing header values -``` -/** - * Create a lambda of tracing headers to be injected into an API's [RequestFactory]. - */ -private fun createTraceHeaderFactory(): () -> Map = { - mapOf( - HttpHeaderType.b3_traceId.rawValue to UUIDExtensions.asTraceId(UUID.randomUUID()), - HttpHeaderType.b3_spanId.rawValue to UUIDExtensions.asSpanId(UUID.randomUUID()), - HttpHeaderType.b3_sampled.rawValue to "1" - ) -} -``` -Finally a post processor example -``` - /** - * Configure a [DefaultRetryPolicy] to be injected into the [RequestFactory] with a maximum number of retries of zero. - */ - private val retryPolicySetter = { request: Request<*> -> - Unit.apply { - request.setRetryPolicy( - DefaultRetryPolicy( - RestService.DEFAULT_TIMEOUT_MS, - 0, - DefaultRetryPolicy.DEFAULT_BACKOFF_MULT - ) - ) - } - } -``` - -### Serialization -#### Gson and Polymorphic types -The GsonRequest object can be passed custom type adapters -``` -class GsonRequest( - method: Int, - url: String, - private val body: Any?, - private val headers: Map?, - private val params: MutableMap?, - private val contentTypeForBody: String?, - private val encodingForParams: String?, - private val gsonAdapters: Map?, - private val type: Type, - private val listener: Response.Listener, - errorListener: Response.ErrorListener -) : Request(method, url, errorListener) { - - val gsonBuilder: GsonBuilder = GsonBuilder() - .registerTypeAdapter(OffsetDateTime::class.java, OffsetDateTimeAdapter()) - .registerTypeAdapter(LocalDateTime::class.java, LocalDateTimeAdapter()) - .registerTypeAdapter(LocalDate::class.java, LocalDateAdapter()) - .registerTypeAdapter(ByteArray::class.java, ByteArrayAdapter()) - -``` -## Requires - -{{#jvm}} -* Kotlin 1.4.30 -* Gradle 6.8.3 -{{/jvm}} -{{#multiplatform}} -* Kotlin 1.5.10 -{{/multiplatform}} - -## Build - -{{#jvm}} -First, create the gradle wrapper script: - -``` -gradle wrapper -``` - -Then, run: - -{{/jvm}} -``` -./gradlew check assemble -``` - -This runs all tests and packages the library. - -{{#generateApiDocs}} - -## Documentation for API Endpoints - -All URIs are relative to *{{{basePath}}}* - -Class | Method | HTTP request | Description ------------- | ------------- | ------------- | ------------- -{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{{summary}}}{{/summary}} -{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} -{{/generateApiDocs}} - -{{#generateModelDocs}} - -## Documentation for Models - -{{#modelPackage}} -{{#models}}{{#model}} - [{{{modelPackage}}}.{{{classname}}}]({{modelDocPath}}{{{classname}}}.md) -{{/model}}{{/models}} -{{/modelPackage}} -{{^modelPackage}} -No model defined in this package -{{/modelPackage}} -{{/generateModelDocs}} - -{{! TODO: optional documentation for authorization? }} -## Documentation for Authorization - -{{^authMethods}} -All endpoints do not require authorization. -{{/authMethods}} -{{#authMethods}} -{{#last}} -Authentication schemes defined for the API: -{{/last}} -{{/authMethods}} -{{#authMethods}} - -### {{name}} - -{{#isApiKey}}- **Type**: API key -- **API key parameter name**: {{keyParamName}} -- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} -{{/isApiKey}} -{{#isBasic}}- **Type**: HTTP basic authentication -{{/isBasic}} -{{#isOAuth}}- **Type**: OAuth -- **Flow**: {{flow}} -- **Authorization URL**: {{authorizationUrl}} -- **Scopes**: {{^scopes}}N/A{{/scopes}} -{{#scopes}} - {{scope}}: {{description}} -{{/scopes}} -{{/isOAuth}} - -{{/authMethods}} diff --git a/src/main/resources/kotlin-client/libraries/jvm-volley/api.mustache b/src/main/resources/kotlin-client/libraries/jvm-volley/api.mustache deleted file mode 100644 index 515c3c6efba..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-volley/api.mustache +++ /dev/null @@ -1,116 +0,0 @@ -package {{apiPackage}} - -import android.content.Context -import com.android.volley.DefaultRetryPolicy -import com.android.volley.Request -import com.android.volley.RequestQueue -import com.android.volley.Response -import com.android.volley.toolbox.BaseHttpStack -import com.android.volley.toolbox.Volley -import java.util.* -import kotlin.coroutines.resume -import kotlin.coroutines.resumeWithException -import kotlin.coroutines.suspendCoroutine -import com.google.gson.reflect.TypeToken - -import {{packageName}}.request.IRequestFactory -import {{packageName}}.request.RequestFactory -import {{packageName}}.infrastructure.CollectionFormats.* - -{{#imports}}import {{import}} -{{/imports}} - -{{#operations}} -/* -* If you wish to use a custom http stack with your client you -* can pass that to the request queue like: -* Volley.newRequestQueue(context.applicationContext, myCustomHttpStack) -*/ -class {{classname}} ( - private val context: Context, - private val requestQueue: Lazy = lazy(initializer = { - Volley.newRequestQueue(context.applicationContext) - }), - private val requestFactory: IRequestFactory = RequestFactory(), - private val basePath: String = "{{{basePath}}}", - private val postProcessors :List <(Request<*>) -> Unit> = listOf()) { - - {{#operation}} - /** - * {{summary}} - * {{notes}} - {{#allParams}}* @param {{{paramName}}} {{description}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{#required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}{{/required}} - {{/allParams}}* @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} - */ - {{#isDeprecated}} - @Deprecated("This api was deprecated") - {{/isDeprecated}} - suspend fun {{operationId}}({{^allParams}}){{/allParams}}{{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{^-last}}, {{/-last}}{{#-last}}{{#operationAuthMethod}}, opAuthHeaderFactory = () -> map{{/operationAuthMethod}}){{/-last}}{{/allParams}}: {{#returnType}}{{{returnType}}}?{{/returnType}}{{^returnType}}Unit{{/returnType}} { - {{#bodyParam}} - val body: Any? = {{paramName}} - {{/bodyParam}} - {{^bodyParam}} - val body: Any? = null - {{/bodyParam}} - - val contentTypes : Array = arrayOf({{#consumes}}"{{{mediaType}}}"{{^-last}},{{/-last}}{{/consumes}}) - val contentType: String = if (contentTypes.isNotEmpty()) { contentTypes.first() } else { "application/json" } - - // Do some work or avoid some work based on what we know about the model, - // before we delegate to a pluggable request factory template - // The request factory template contains only pure code and no templates - // to make it easy to override with your own. - - // create path and map variables - val path = "{{{path}}}"{{#pathParams}}.replace("{" + "{{baseName}}" + "}", {{#isContainer}}{{paramName}}.joinToString(","){{/isContainer}}{{^isContainer}}IRequestFactory.escapeString({{{paramName}}}.toString()){{/isContainer}}){{/pathParams}} - - val formParams = mapOf({{^formParams}}){{/formParams}}{{#formParams}} - "{{baseName}}" to IRequestFactory.parameterToString({{paramName}}){{^-last}},{{/-last}}{{#-last}} - ){{/-last}}{{/formParams}} - - - // TODO: Cater for allowing empty values - // TODO, if its apikey auth, then add the header names here and the hardcoded auth key - // Only support hard coded apikey in query param auth for when we do this first path - val queryParams = mapOf({{^queryParams}}){{/queryParams}}{{#queryParams}} - "{{baseName}}" to IRequestFactory.parameterToString({{paramName}}){{^-last}},{{/-last}}{{#-last}} - ){{/-last}}{{/queryParams}} - .filter { it.value.isNotEmpty() } - - val headerParams: Map = mapOf({{^headerParams}}){{/headerParams}}{{#headerParams}} - "{{baseName}}" to IRequestFactory.parameterToString({{paramName}}){{^-last}},{{/-last}}{{#-last}} - ){{/-last}}{{/headerParams}} - - return suspendCoroutine { continuation -> - val responseListener = Response.Listener<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Unit{{/returnType}}> { response -> - continuation.resume(response) - } - - val errorListener = Response.ErrorListener { error -> - continuation.resumeWithException(error) - } - - val responseType = object : TypeToken<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Unit{{/returnType}}>() {}.type - - // Call the correct request builder based on whether we have a return type or a body. - // All other switching on types must be done in code inside the builder - val request: Request<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Unit{{/returnType}}> = requestFactory.build( - Request.Method.{{httpMethod}}, - "$basePath$path", - body, - headerParams, - queryParams, - formParams, - contentType, - responseType, - responseListener, - errorListener) - - postProcessors.forEach { it.invoke(request) } - - requestQueue.value.add(request) - } - } - {{/operation}} -} -{{/operations}} diff --git a/src/main/resources/kotlin-client/libraries/jvm-volley/api_doc.mustache b/src/main/resources/kotlin-client/libraries/jvm-volley/api_doc.mustache deleted file mode 100644 index f7bf73ae31d..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-volley/api_doc.mustache +++ /dev/null @@ -1,83 +0,0 @@ -# {{classname}}{{#description}} -{{description}}{{/description}} - -All URIs are relative to *{{basePath}}* - -Method | HTTP request | Description -------------- | ------------- | ------------- -{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} -{{/operation}}{{/operations}} - -{{#operations}} -{{#operation}} - -{{summary}}{{#notes}} - -{{notes}}{{/notes}} - -### Example -```kotlin -// Import classes: -//import {{{packageName}}}.* -//import {{{packageName}}}.infrastructure.* -//import {{{modelPackage}}}.* - -val apiClient = ApiClient() -{{#authMethods}} -{{#isBasic}} -{{#isBasicBasic}} -apiClient.setCredentials("USERNAME", "PASSWORD") -{{/isBasicBasic}} -{{#isBasicBearer}} -apiClient.setBearerToken("TOKEN") -{{/isBasicBearer}} -{{/isBasic}} -{{/authMethods}} -val webService = apiClient.createWebservice({{{classname}}}::class.java) -{{#allParams}} -val {{{paramName}}} : {{{dataType}}} = {{{example}}} // {{{dataType}}} | {{{description}}} -{{/allParams}} - -{{#useCoroutines}} -launch(Dispatchers.IO) { -{{/useCoroutines}} -{{#useCoroutines}} {{/useCoroutines}}{{#returnType}}val result : {{{returnType}}}{{#nullableReturnType}}?{{/nullableReturnType}} = {{/returnType}}webService.{{{operationId}}}({{#allParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}) -{{#useCoroutines}} -} -{{/useCoroutines}} -``` - -### Parameters -{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} -Name | Type | Description | Notes -------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} -{{#allParams}} **{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isFile}}**{{dataType}}**{{/isFile}}{{^isFile}}{{#generateModelDocs}}[**{{dataType}}**]({{baseType}}.md){{/generateModelDocs}}{{^generateModelDocs}}**{{dataType}}**{{/generateModelDocs}}{{/isFile}}{{/isPrimitiveType}}| {{description}} |{{^required}} [optional]{{/required}}{{#defaultValue}} [default to {{defaultValue}}]{{/defaultValue}}{{#allowableValues}} [enum: {{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}]{{/allowableValues}} -{{/allParams}} - -### Return type - -{{#returnType}}{{#returnTypeIsPrimitive}}**{{returnType}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}{{#generateModelDocs}}[**{{returnType}}**]({{returnBaseType}}.md){{/generateModelDocs}}{{^generateModelDocs}}**{{returnType}}**{{/generateModelDocs}}{{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}null (empty response body){{/returnType}} - -### Authorization - -{{^authMethods}}No authorization required{{/authMethods}} -{{#authMethods}} -{{#isBasic}} -{{#isBasicBasic}} -Configure {{name}}: - ApiClient().setCredentials("USERNAME", "PASSWORD") -{{/isBasicBasic}} -{{#isBasicBearer}} -Configure {{name}}: - ApiClient().setBearerToken("TOKEN") -{{/isBasicBearer}} -{{/isBasic}} -{{/authMethods}} - -### HTTP request headers - - - **Content-Type**: {{#consumes}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} - - **Accept**: {{#produces}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/produces}}{{^produces}}Not defined{{/produces}} - -{{/operation}} -{{/operations}} diff --git a/src/main/resources/kotlin-client/libraries/jvm-volley/auth/apikeyauth.mustache b/src/main/resources/kotlin-client/libraries/jvm-volley/auth/apikeyauth.mustache deleted file mode 100644 index 919da64ce3d..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-volley/auth/apikeyauth.mustache +++ /dev/null @@ -1,16 +0,0 @@ - // Api Key auth supports query header and cookie. - // Query is supported in the path generation only with a hardcoded value. - // TODO: Not sure about cookie auth form - // If implementing api key in query parameter use the ^isKeyInHeader property - - val apiKeyAuthHeaderFactoryBuilder = { - paramName: String, apiKeyPrefix: String?, apiKey: String? -> { - mapOf(paramName to - if (apiKeyPrefix != null) { - "$apiKeyPrefix $apiKey" - } else { - apiKey!! - } - ) - } - } diff --git a/src/main/resources/kotlin-client/libraries/jvm-volley/auth/authentication.mustache b/src/main/resources/kotlin-client/libraries/jvm-volley/auth/authentication.mustache deleted file mode 100644 index 707a8c25fe3..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-volley/auth/authentication.mustache +++ /dev/null @@ -1,15 +0,0 @@ -companion object Authentication { - // Where a header factory requires parameters a client will need to bind these - // TODO Generate appropriate header factories based on settings - {{#authMethods}} -{{#isApiKey}} -{{>auth/apikeyauth}} -{{/isApiKey}} -{{#isBasic}} -{{>auth/httpbasicauth}} -{{/isBasic}} -{{#isOAuth}} - // TODO: Oauth not implemented yet - comment out below as OAuth does not exist -{{/isOAuth}} - {{/authMethods}} - } diff --git a/src/main/resources/kotlin-client/libraries/jvm-volley/auth/httpbasicauth.mustache b/src/main/resources/kotlin-client/libraries/jvm-volley/auth/httpbasicauth.mustache deleted file mode 100644 index f4cf1e11fe6..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-volley/auth/httpbasicauth.mustache +++ /dev/null @@ -1,3 +0,0 @@ -val basicAuthHeaderFactoryBuilder = { username: String?, password: String? -> - { mapOf("Authorization" to "Basic " + Base64.encodeToString("${username ?: ""}:${password ?: ""}".toByteArray(), Base64.DEFAULT))} -} diff --git a/src/main/resources/kotlin-client/libraries/jvm-volley/auth/oauth.mustache b/src/main/resources/kotlin-client/libraries/jvm-volley/auth/oauth.mustache deleted file mode 100644 index 78ffc6a2d7c..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-volley/auth/oauth.mustache +++ /dev/null @@ -1,5 +0,0 @@ -val basicAuthHeaderFactoryBuilder = { username: String?, password: String? -> -{ - throw NotImplementedError("OAuth security scheme header factory not impemented yet - see open api generator auth/oauth.mustache") - mapOf("" to "")} -} diff --git a/src/main/resources/kotlin-client/libraries/jvm-volley/bodyParams.mustache b/src/main/resources/kotlin-client/libraries/jvm-volley/bodyParams.mustache deleted file mode 100644 index 886aecf65e3..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-volley/bodyParams.mustache +++ /dev/null @@ -1 +0,0 @@ -{{#isBodyParam}}{{{paramName}}}: {{{dataType}}}{{^required}}? = null{{/required}}{{/isBodyParam}} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/libraries/jvm-volley/build.mustache b/src/main/resources/kotlin-client/libraries/jvm-volley/build.mustache deleted file mode 100644 index 3b15fd5dfa1..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-volley/build.mustache +++ /dev/null @@ -1,111 +0,0 @@ -{{#useAndroidMavenGradlePlugin}} -group = '{{groupId}}' -project.version = '{{artifactVersion}}' -{{/useAndroidMavenGradlePlugin}} - -buildscript { - - ext.kotlin_version = '1.5.10' - ext.swagger_annotations_version = "1.6.2" - ext.gson_version = "2.8.6" - ext.volley_version = "1.2.0" - ext.junit_version = "4.13.2" - ext.robolectric_version = "4.5.1" - ext.concurrent_unit_version = "0.4.6" - - repositories { - mavenLocal() - google() - maven { - url 'https://dl.google.com/dl/android/maven2' - } - mavenCentral() - } - dependencies { - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - classpath 'com.android.tools.build:gradle:4.0.2' - {{#useAndroidMavenGradlePlugin}} - classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5' - {{/useAndroidMavenGradlePlugin}} - } -} - -allprojects { - repositories { - google() - mavenCentral() - } -} - -apply plugin: 'com.android.library' -apply plugin: 'kotlin-android' -{{#useAndroidMavenGradlePlugin}} -apply plugin: 'com.github.dcendents.android-maven' -{{/useAndroidMavenGradlePlugin}} - -android { - compileSdkVersion 30 - defaultConfig { - minSdkVersion 21 - targetSdkVersion 30 - } - compileOptions { - coreLibraryDesugaringEnabled true - sourceCompatibility JavaVersion.VERSION_1_8 - targetCompatibility JavaVersion.VERSION_1_8 - } - lintOptions { - abortOnError false - } - - // Rename the aar correctly - libraryVariants.all { variant -> - variant.outputs.all { output -> - if (outputFile != null && outputFileName.endsWith('.aar')) { - outputFileName = "${archivesBaseName}-${version}.aar" - } - } - } - - testOptions { - unitTests.returnDefaultValues = true - } -} - -dependencies { - coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5' - implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" - implementation "io.swagger:swagger-annotations:$swagger_annotations_version" - implementation "com.google.code.gson:gson:$gson_version" - implementation "com.android.volley:volley:${volley_version}" - testImplementation "junit:junit:$junit_version" - testImplementation "org.robolectric:robolectric:${robolectric_version}" - testImplementation "net.jodah:concurrentunit:${concurrent_unit_version}" - {{#generateRoomModels}} - annotationProcessor "androidx.room:room-runtime:2.3.0" - implementation "androidx.room:room-runtime:2.3.0" - {{/generateRoomModels}} -} - -afterEvaluate { - android.libraryVariants.all { variant -> - def task = project.tasks.create "jar${variant.name.capitalize()}", Jar - task.description = "Create jar artifact for ${variant.name}" - task.dependsOn variant.javaCompile - task.from variant.javaCompile.destinationDir - task.destinationDirectory = project.file("${project.buildDir}/outputs/jar") - task.archiveFileName = "${project.name}-${variant.baseName}-${version}.jar" - artifacts.add('archives', task); - } -} - -{{#useAndroidMavenGradlePlugin}} -task sourcesJar(type: Jar) { - from android.sourceSets.main.java.srcDirs - classifier = 'sources' -} - -artifacts { - archives sourcesJar -} -{{/useAndroidMavenGradlePlugin}} diff --git a/src/main/resources/kotlin-client/libraries/jvm-volley/formParams.mustache b/src/main/resources/kotlin-client/libraries/jvm-volley/formParams.mustache deleted file mode 100644 index 98427cd4817..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-volley/formParams.mustache +++ /dev/null @@ -1 +0,0 @@ -{{#isFormParam}}{{{paramName}}}: {{{dataType}}}{{#required}}{{#defaultValue}} = {{^isNumber}}{{{defaultValue}}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{/required}}{{^required}}?{{#defaultValue}} = {{^isNumber}}{{{defaultValue}}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{^defaultValue}} = null{{/defaultValue}}{{/required}}{{/isFormParam}} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/libraries/jvm-volley/gradle.properties.mustache b/src/main/resources/kotlin-client/libraries/jvm-volley/gradle.properties.mustache deleted file mode 100644 index f7a5f347d68..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-volley/gradle.properties.mustache +++ /dev/null @@ -1,4 +0,0 @@ -android.useAndroidX=true -{{#generateRoomModels}} -android.enableJetifier=true -{{/generateRoomModels}} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/libraries/jvm-volley/headerParams.mustache b/src/main/resources/kotlin-client/libraries/jvm-volley/headerParams.mustache deleted file mode 100644 index 3e5c64b2cd8..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-volley/headerParams.mustache +++ /dev/null @@ -1 +0,0 @@ -{{#isHeaderParam}}{{{paramName}}}: {{{dataType}}}{{#required}}{{#defaultValue}} = {{^isNumber}}{{{defaultValue}}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{/required}}{{^required}}?{{#defaultValue}} = {{^isNumber}}{{{defaultValue}}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{^defaultValue}} = null{{/defaultValue}}{{/required}}{{/isHeaderParam}} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/libraries/jvm-volley/infrastructure/CollectionFormats.kt.mustache b/src/main/resources/kotlin-client/libraries/jvm-volley/infrastructure/CollectionFormats.kt.mustache deleted file mode 100644 index 659f2df4851..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-volley/infrastructure/CollectionFormats.kt.mustache +++ /dev/null @@ -1,56 +0,0 @@ -package {{packageName}}.infrastructure - -class CollectionFormats { - - open class CSVParams { - - var params: List - - constructor(params: List) { - this.params = params - } - - constructor(vararg params: String) { - this.params = listOf(*params) - } - - override fun toString(): String { - return params.joinToString(",") - } - } - - open class SSVParams : CSVParams { - - constructor(params: List) : super(params) - - constructor(vararg params: String) : super(*params) - - override fun toString(): String { - return params.joinToString(" ") - } - } - - class TSVParams : CSVParams { - - constructor(params: List) : super(params) - - constructor(vararg params: String) : super(*params) - - override fun toString(): String { - return params.joinToString("\t") - } - } - - class PIPESParams : CSVParams { - - constructor(params: List) : super(params) - - constructor(vararg params: String) : super(*params) - - override fun toString(): String { - return params.joinToString("|") - } - } - - class SPACEParams : SSVParams() -} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/libraries/jvm-volley/infrastructure/ITransformForStorage.mustache b/src/main/resources/kotlin-client/libraries/jvm-volley/infrastructure/ITransformForStorage.mustache deleted file mode 100644 index 83b5fa369ab..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-volley/infrastructure/ITransformForStorage.mustache +++ /dev/null @@ -1,9 +0,0 @@ -{{>licenseInfo}} -package {{packageName}}.infrastructure - -import {{roomModelPackage}}.* - -// TODO ITransformForStorage -interface ITransformForStorage { - fun toRoomModel(): T -} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/libraries/jvm-volley/manifest.mustache b/src/main/resources/kotlin-client/libraries/jvm-volley/manifest.mustache deleted file mode 100644 index 1ea918bad73..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-volley/manifest.mustache +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/src/main/resources/kotlin-client/libraries/jvm-volley/pathParams.mustache b/src/main/resources/kotlin-client/libraries/jvm-volley/pathParams.mustache deleted file mode 100644 index 4cc7de2240b..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-volley/pathParams.mustache +++ /dev/null @@ -1 +0,0 @@ -{{#isPathParam}}{{{paramName}}}: {{{dataType}}}{{#required}}{{#defaultValue}} = {{^isNumber}}{{{defaultValue}}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{/required}}{{^required}}?{{#defaultValue}} = {{^isNumber}}{{{defaultValue}}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{^defaultValue}} = null{{/defaultValue}}{{/required}}{{/isPathParam}} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/libraries/jvm-volley/queryParams.mustache b/src/main/resources/kotlin-client/libraries/jvm-volley/queryParams.mustache deleted file mode 100644 index da0a0c0930a..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-volley/queryParams.mustache +++ /dev/null @@ -1 +0,0 @@ -{{#isQueryParam}}{{{paramName}}}: {{#collectionFormat}}{{#isCollectionFormatMulti}}{{{dataType}}}{{/isCollectionFormatMulti}}{{^isCollectionFormatMulti}}{{{collectionFormat.toUpperCase}}}Params{{/isCollectionFormatMulti}}{{/collectionFormat}}{{^collectionFormat}}{{{dataType}}}{{/collectionFormat}}{{#required}}{{#defaultValue}} = {{^isNumber}}{{{defaultValue}}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{/required}}{{^required}}?{{#defaultValue}} = {{^isNumber}}{{{defaultValue}}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{^defaultValue}} = null{{/defaultValue}}{{/required}}{{/isQueryParam}} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/libraries/jvm-volley/request/GsonRequest.mustache b/src/main/resources/kotlin-client/libraries/jvm-volley/request/GsonRequest.mustache deleted file mode 100644 index e87f7413aab..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-volley/request/GsonRequest.mustache +++ /dev/null @@ -1,119 +0,0 @@ -package {{packageName}}.request - -import com.android.volley.NetworkResponse -import com.android.volley.ParseError -import com.android.volley.Request -import com.android.volley.Response -import com.android.volley.toolbox.HttpHeaderParser -import com.google.gson.Gson -import com.google.gson.GsonBuilder -import com.google.gson.JsonSyntaxException -import java.io.UnsupportedEncodingException -import java.nio.charset.Charset -import java.net.HttpURLConnection -import java.lang.reflect.Type -import java.time.LocalDate -import java.time.LocalDateTime -import java.time.OffsetDateTime - -import {{packageName}}.infrastructure.OffsetDateTimeAdapter -import {{packageName}}.infrastructure.LocalDateTimeAdapter -import {{packageName}}.infrastructure.LocalDateAdapter -import {{packageName}}.infrastructure.ByteArrayAdapter - -class GsonRequest( - method: Int, - url: String, - private val body: Any?, - private val headers: Map?, - private val params: MutableMap?, - private val contentTypeForBody: String?, - private val encodingForParams: String?, - private val gsonAdapters: Map?, - private val type: Type, - private val listener: Response.Listener, - errorListener: Response.ErrorListener -) : Request(method, url, errorListener) { - - val gsonBuilder: GsonBuilder = GsonBuilder() - .registerTypeAdapter(OffsetDateTime::class.java, OffsetDateTimeAdapter()) - .registerTypeAdapter(LocalDateTime::class.java, LocalDateTimeAdapter()) - .registerTypeAdapter(LocalDate::class.java, LocalDateAdapter()) - .registerTypeAdapter(ByteArray::class.java, ByteArrayAdapter()) - .apply { - gsonAdapters?.forEach { - this.registerTypeAdapter(it.key, it.value) - } - } - - val gson: Gson by lazy { - gsonBuilder.create() - } - - private var response: NetworkResponse? = null - - override fun deliverResponse(response: T?) { - listener.onResponse(response) - } - - override fun getParams(): MutableMap? = params ?: super.getParams() - - override fun getBodyContentType(): String = contentTypeForBody ?: super.getBodyContentType() - - override fun getParamsEncoding(): String = encodingForParams ?: super.getParamsEncoding() - - override fun getHeaders(): MutableMap { - val combined = HashMap() - combined.putAll(super.getHeaders()) - if (headers != null) { - combined.putAll(headers) - } - return combined - } - - override fun getBody(): ByteArray? { - if (body != null) { - return gson.toJson(body).toByteArray(Charsets.UTF_8) - } - return super.getBody() - } - - override fun parseNetworkResponse(response: NetworkResponse?): Response { - return try { - this.response = copyTo(response) - val json = String( - response?.data ?: ByteArray(0), - Charset.forName(HttpHeaderParser.parseCharset(response?.headers)) - ) - Response.success( - gson.fromJson(json, type), - HttpHeaderParser.parseCacheHeaders(response) - ) - } catch (e: UnsupportedEncodingException) { - Response.error(ParseError(e)) - } catch (e: JsonSyntaxException) { - Response.error(ParseError(e)) - } - } - - private fun copyTo(response: NetworkResponse?): NetworkResponse { - return if (response != null) { - NetworkResponse( - response.statusCode, - response.data, - response.notModified, - response.networkTimeMs, - response.allHeaders - ) - } else { - // Return an empty response. - NetworkResponse( - HttpURLConnection.HTTP_BAD_METHOD, - ByteArray(0), - false, - 0, - emptyList() - ) - } - } -} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/libraries/jvm-volley/request/IRequestFactory.mustache b/src/main/resources/kotlin-client/libraries/jvm-volley/request/IRequestFactory.mustache deleted file mode 100644 index d46fe90c620..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-volley/request/IRequestFactory.mustache +++ /dev/null @@ -1,64 +0,0 @@ -package {{packageName}}.request - -import com.android.volley.Request -import com.android.volley.Response -import java.io.UnsupportedEncodingException -import java.lang.reflect.Type -import java.net.URLEncoder -import java.text.ParseException -import java.text.SimpleDateFormat -import java.util.* -import java.time.format.DateTimeFormatter -import java.time.OffsetDateTime -import java.time.LocalDate - - -interface IRequestFactory { - - companion object { - /** - * ISO 8601 date time format. - * @see https://en.wikipedia.org/wiki/ISO_8601 - */ - fun formatDateTime(datetime: OffsetDateTime) = DateTimeFormatter.ISO_INSTANT.format(datetime) - fun formatDate(date: LocalDate) = DateTimeFormatter.ISO_LOCAL_DATE.format(date) - - fun escapeString(str: String): String { - return try { - URLEncoder.encode(str, "UTF-8") - } catch (e: UnsupportedEncodingException) { - str - } - } - - fun parameterToString(param: Any?) = - when (param) { - null -> "" - is OffsetDateTime -> formatDateTime(param) - is Collection<*> -> { - val b = StringBuilder() - for (o in param) { - if (b.isNotEmpty()) { - b.append(",") - } - b.append(o.toString()) - } - b.toString() - } - else -> param.toString() - } - } - - - fun build( - method: Int, - url : String, - body: Any?, - headers: Map?, - queryParams: Map?, - formParams: Map?, - contentTypeForBody: String?, - type: Type, - responseListener: Response.Listener, - errorListener: Response.ErrorListener): Request -} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/libraries/jvm-volley/request/RequestFactory.mustache b/src/main/resources/kotlin-client/libraries/jvm-volley/request/RequestFactory.mustache deleted file mode 100644 index e9bc5d21283..00000000000 --- a/src/main/resources/kotlin-client/libraries/jvm-volley/request/RequestFactory.mustache +++ /dev/null @@ -1,69 +0,0 @@ -// Knowing the details of an operation it will produce a call to a Volley Request constructor -package {{packageName}}.request - - -import com.android.volley.Request -import com.android.volley.Response -{{#hasAuthMethods}} -import android.util.Base64 -{{/hasAuthMethods}} -import {{packageName}}.request.IRequestFactory.Companion.escapeString -import java.lang.reflect.Type -import java.util.Locale -import java.util.UUID - -class RequestFactory(private val headerFactories : List<() -> Map> = listOf(), private val postProcessors :List <(Request<*>) -> Unit> = listOf(), private val gsonAdapters: Map = mapOf()): IRequestFactory { -{{#hasAuthMethods}} - - {{>auth/authentication}} -{{/hasAuthMethods}} - - /** - * {@inheritDoc} - */ - @Suppress("UNCHECKED_CAST") - override fun build( - method: Int, - url: String, - body: Any?, - headers: Map?, - queryParams: Map?, - formParams: Map?, - contentTypeForBody: String?, - type: Type, - responseListener: Response.Listener, - errorListener: Response.ErrorListener - ): Request { - val afterMarketHeaders = (headers?.toMutableMap() ?: mutableMapOf()) - // Factory built and aftermarket - // Merge the after market headers on top of the base ones in case we are overriding per call auth - val allHeaders = headerFactories.fold(afterMarketHeaders) { acc, factory -> (acc + factory.invoke()).toMutableMap() } - - // If we decide to support auth parameters in the url, then you will reference them by supplying a url string - // with known variable name refernces in the string. We will then apply - val updatedUrl = if (!queryParams.isNullOrEmpty()) { - queryParams.asSequence().fold("$url?") {acc, param -> - "$acc${escapeString(param.key)}=${escapeString(param.value)}&" - }.trimEnd('&') - } else { - url - } - - val request = GsonRequest( - method, - updatedUrl, - body, - allHeaders, - formParams?.toMutableMap(), - contentTypeForBody, - null, - gsonAdapters, - type, - responseListener, - errorListener) - - postProcessors.forEach{ it.invoke(request)} - - return request - } -} diff --git a/src/main/resources/kotlin-client/libraries/multiplatform/api.mustache b/src/main/resources/kotlin-client/libraries/multiplatform/api.mustache deleted file mode 100644 index 4ee453f2969..00000000000 --- a/src/main/resources/kotlin-client/libraries/multiplatform/api.mustache +++ /dev/null @@ -1,95 +0,0 @@ -{{>licenseInfo}} -package {{apiPackage}} - -{{#imports}}import {{import}} -{{/imports}} - -import {{packageName}}.infrastructure.* -import io.ktor.client.HttpClientConfig -import io.ktor.client.request.forms.formData -import io.ktor.client.engine.HttpClientEngine -import kotlinx.serialization.json.Json -import io.ktor.http.ParametersBuilder -import kotlinx.serialization.* -import kotlinx.serialization.descriptors.* -import kotlinx.serialization.encoding.* - -{{#operations}} -{{#nonPublicApi}}internal {{/nonPublicApi}}open class {{classname}}( - baseUrl: String = ApiClient.BASE_URL, - httpClientEngine: HttpClientEngine? = null, - httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, - jsonSerializer: Json = ApiClient.JSON_DEFAULT -) : ApiClient(baseUrl, httpClientEngine, httpClientConfig, jsonSerializer) { - - {{#operation}} - /** - * {{summary}} - * {{notes}} - {{#allParams}} * @param {{{paramName}}} {{description}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{#required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}{{/required}} - {{/allParams}} * @return {{{returnType}}}{{^returnType}}void{{/returnType}} - */ - {{#returnType}} - @Suppress("UNCHECKED_CAST") - {{/returnType}} - open suspend fun {{operationId}}({{#allParams}}{{{paramName}}}: {{{dataType}}}{{#required}}{{#defaultValue}} = {{^isNumber}}{{{defaultValue}}}{{/isNumber}}{{#isNumber}}{{{defaultValue}}}.toDouble(){{/isNumber}}{{/defaultValue}}{{/required}}{{^required}}?{{#defaultValue}} = {{^isNumber}}{{{defaultValue}}}{{/isNumber}}{{#isNumber}}{{{defaultValue}}}.toDouble(){{/isNumber}}{{/defaultValue}}{{^defaultValue}} = null{{/defaultValue}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}): HttpResponse<{{{returnType}}}{{^returnType}}Unit{{/returnType}}> { - - val localVariableAuthNames = listOf({{#authMethods}}"{{name}}"{{^-last}}, {{/-last}}{{/authMethods}}) - - val localVariableBody = {{#hasBodyParam}}{{#bodyParam}}{{#isArray}}{{operationIdCamelCase}}Request({{{paramName}}}{{^isList}}.asList(){{/isList}}){{/isArray}}{{^isArray}}{{#isMap}}{{operationIdCamelCase}}Request({{{paramName}}}){{/isMap}}{{^isMap}}{{{paramName}}}{{/isMap}}{{/isArray}}{{/bodyParam}}{{/hasBodyParam}} - {{^hasBodyParam}} - {{#hasFormParams}} - {{#isMultipart}} - formData { - {{#formParams}} - {{{paramName}}}?.apply { append("{{{baseName}}}", {{{paramName}}}) } - {{/formParams}} - } - {{/isMultipart}} - {{^isMultipart}} - ParametersBuilder().also { - {{#formParams}} - {{{paramName}}}?.apply { it.append("{{{baseName}}}", {{{paramName}}}.toString()) } - {{/formParams}} - }.build() - {{/isMultipart}} - {{/hasFormParams}} - {{^hasFormParams}} - io.ktor.client.utils.EmptyContent - {{/hasFormParams}} - {{/hasBodyParam}} - - val localVariableQuery = mutableMapOf>(){{#queryParams}} - {{{paramName}}}?.apply { localVariableQuery["{{baseName}}"] = {{#isContainer}}toMultiValue(this, "{{collectionFormat}}"){{/isContainer}}{{^isContainer}}listOf("${{{paramName}}}"){{/isContainer}} }{{/queryParams}} - val localVariableHeaders = mutableMapOf(){{#headerParams}} - {{{paramName}}}?.apply { localVariableHeaders["{{baseName}}"] = {{#isContainer}}this.joinToString(separator = collectionDelimiter("{{collectionFormat}}")){{/isContainer}}{{^isContainer}}this.toString(){{/isContainer}} }{{/headerParams}} - - val localVariableConfig = RequestConfig( - RequestMethod.{{httpMethod}}, - "{{path}}"{{#pathParams}}.replace("{" + "{{baseName}}" + "}", {{#isContainer}}{{paramName}}.joinToString(","){{/isContainer}}{{^isContainer}}"${{{paramName}}}"{{/isContainer}}){{/pathParams}}, - query = localVariableQuery, - headers = localVariableHeaders - ) - - return {{#hasBodyParam}}jsonRequest{{/hasBodyParam}}{{^hasBodyParam}}{{#hasFormParams}}{{#isMultipart}}multipartFormRequest{{/isMultipart}}{{^isMultipart}}urlEncodedFormRequest{{/isMultipart}}{{/hasFormParams}}{{^hasFormParams}}request{{/hasFormParams}}{{/hasBodyParam}}( - localVariableConfig, - localVariableBody, - localVariableAuthNames - ).{{#isArray}}wrap<{{operationIdCamelCase}}Response>().map { value{{^isList}}.toTypedArray(){{/isList}} }{{/isArray}}{{^isArray}}{{#isMap}}wrap<{{operationIdCamelCase}}Response>().map { value }{{/isMap}}{{^isMap}}wrap(){{/isMap}}{{/isArray}} - } - -{{#hasBodyParam}} -{{#bodyParam}} -{{#isArray}}{{>serial_wrapper_request_list}}{{/isArray}}{{#isMap}}{{>serial_wrapper_request_map}}{{/isMap}} -{{/bodyParam}} -{{/hasBodyParam}} -{{#isArray}} -{{>serial_wrapper_response_list}} -{{/isArray}} -{{#isMap}} -{{>serial_wrapper_response_map}} -{{/isMap}} - - {{/operation}} -} -{{/operations}} diff --git a/src/main/resources/kotlin-client/libraries/multiplatform/auth/ApiKeyAuth.kt.mustache b/src/main/resources/kotlin-client/libraries/multiplatform/auth/ApiKeyAuth.kt.mustache deleted file mode 100644 index 618fd7a8890..00000000000 --- a/src/main/resources/kotlin-client/libraries/multiplatform/auth/ApiKeyAuth.kt.mustache +++ /dev/null @@ -1,16 +0,0 @@ -package {{packageName}}.auth - -class ApiKeyAuth(private val location: String, val paramName: String) : Authentication { - var apiKey: String? = null - var apiKeyPrefix: String? = null - - override fun apply(query: MutableMap>, headers: MutableMap) { - val key: String = apiKey ?: return - val prefix: String? = apiKeyPrefix - val value: String = if (prefix != null) "$prefix $key" else key - when (location) { - "query" -> query[paramName] = listOf(value) - "header" -> headers[paramName] = value - } - } -} diff --git a/src/main/resources/kotlin-client/libraries/multiplatform/auth/Authentication.kt.mustache b/src/main/resources/kotlin-client/libraries/multiplatform/auth/Authentication.kt.mustache deleted file mode 100644 index 1aab9156d98..00000000000 --- a/src/main/resources/kotlin-client/libraries/multiplatform/auth/Authentication.kt.mustache +++ /dev/null @@ -1,13 +0,0 @@ -package {{packageName}}.auth - -interface Authentication { - - /** - * Apply authentication settings to header and query params. - * - * @param query Query parameters. - * @param headers Header parameters. - */ - fun apply(query: MutableMap>, headers: MutableMap) - -} diff --git a/src/main/resources/kotlin-client/libraries/multiplatform/auth/HttpBasicAuth.kt.mustache b/src/main/resources/kotlin-client/libraries/multiplatform/auth/HttpBasicAuth.kt.mustache deleted file mode 100644 index 26325424e5d..00000000000 --- a/src/main/resources/kotlin-client/libraries/multiplatform/auth/HttpBasicAuth.kt.mustache +++ /dev/null @@ -1,17 +0,0 @@ -package {{packageName}}.auth - -import io.ktor.util.InternalAPI -import io.ktor.util.encodeBase64 - -class HttpBasicAuth : Authentication { - var username: String? = null - var password: String? = null - - @OptIn(InternalAPI::class) - override fun apply(query: MutableMap>, headers: MutableMap) { - if (username == null && password == null) return - val str = (username ?: "") + ":" + (password ?: "") - val auth = str.encodeBase64() - headers["Authorization"] = "Basic $auth" - } -} diff --git a/src/main/resources/kotlin-client/libraries/multiplatform/auth/HttpBearerAuth.kt.mustache b/src/main/resources/kotlin-client/libraries/multiplatform/auth/HttpBearerAuth.kt.mustache deleted file mode 100644 index 982389d0960..00000000000 --- a/src/main/resources/kotlin-client/libraries/multiplatform/auth/HttpBearerAuth.kt.mustache +++ /dev/null @@ -1,14 +0,0 @@ -package {{packageName}}.auth - -class HttpBearerAuth(private val scheme: String?) : Authentication { - var bearerToken: String? = null - - override fun apply(query: MutableMap>, headers: MutableMap) { - val token: String = bearerToken ?: return - headers["Authorization"] = (if (scheme != null) upperCaseBearer(scheme)!! + " " else "") + token - } - - private fun upperCaseBearer(scheme: String): String? { - return if ("bearer".equals(scheme, ignoreCase = true)) "Bearer" else scheme - } -} diff --git a/src/main/resources/kotlin-client/libraries/multiplatform/auth/OAuth.kt.mustache b/src/main/resources/kotlin-client/libraries/multiplatform/auth/OAuth.kt.mustache deleted file mode 100644 index 98bb449a609..00000000000 --- a/src/main/resources/kotlin-client/libraries/multiplatform/auth/OAuth.kt.mustache +++ /dev/null @@ -1,10 +0,0 @@ -package {{packageName}}.auth - -class OAuth : Authentication { - var accessToken: String? = null - - override fun apply(query: MutableMap>, headers: MutableMap) { - val token: String = accessToken ?: return - headers["Authorization"] = "Bearer $token" - } -} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/libraries/multiplatform/build.gradle.kts.mustache b/src/main/resources/kotlin-client/libraries/multiplatform/build.gradle.kts.mustache deleted file mode 100644 index 797279d5d44..00000000000 --- a/src/main/resources/kotlin-client/libraries/multiplatform/build.gradle.kts.mustache +++ /dev/null @@ -1,101 +0,0 @@ -import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget - -plugins { - kotlin("multiplatform"){{^omitGradlePluginVersions}} version "1.6.0" // kotlin_version{{/omitGradlePluginVersions}} - kotlin("plugin.serialization"){{^omitGradlePluginVersions}} version "1.6.0" // kotlin_version{{/omitGradlePluginVersions}} -} - -group = "{{groupId}}" -version = "{{artifactVersion}}" - -val kotlin_version = "1.6.10" -val coroutines_version = "1.6.3" -val serialization_version = "1.3.3" -val ktor_version = "2.0.3" - -repositories { - mavenCentral() -} - -kotlin { - jvm() - ios { binaries { framework { freeCompilerArgs += "-Xobjc-generics" } } } - js { - browser() - nodejs() - } - - sourceSets { - val commonMain by getting { - dependencies { - implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version") - implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:$serialization_version") - - api("io.ktor:ktor-client-core:$ktor_version") - api("io.ktor:ktor-client-serialization:$ktor_version") - api("io.ktor:ktor-client-content-negotiation:$ktor_version") - api("io.ktor:ktor-serialization-kotlinx-json:$ktor_version") - } - } - - val commonTest by getting { - dependencies { - implementation(kotlin("test")) - implementation("io.ktor:ktor-client-mock:$ktor_version") - } - } - - val jvmMain by getting { - dependencies { - implementation(kotlin("stdlib-jdk7")) - implementation("io.ktor:ktor-client-cio-jvm:$ktor_version") - } - } - - val jvmTest by getting { - dependencies { - implementation(kotlin("test-junit")) - } - } - - val iosMain by getting { - dependencies { - api("io.ktor:ktor-client-ios:$ktor_version") - } - } - - val iosTest by getting - - val jsMain by getting { - dependencies { - api("io.ktor:ktor-client-js:$ktor_version") - } - } - - val jsTest by getting - - all { - languageSettings.apply { - useExperimentalAnnotation("kotlin.Experimental") - } - } - } -} - -tasks { - register("iosTest") { - val device = project.findProperty("device")?.toString() ?: "iPhone 8" - dependsOn("linkDebugTestIosX64") - group = JavaBasePlugin.VERIFICATION_GROUP - description = "Execute unit tests on ${device} simulator" - doLast { - val binary = kotlin.targets.getByName("iosX64").binaries.getTest("DEBUG") - exec { - commandLine("xcrun", "simctl", "spawn", device, binary.outputFile) - } - } - } - register("test") { - dependsOn("allTests") - } -} diff --git a/src/main/resources/kotlin-client/libraries/multiplatform/commonTest/Coroutine.kt.mustache b/src/main/resources/kotlin-client/libraries/multiplatform/commonTest/Coroutine.kt.mustache deleted file mode 100644 index c3bd8b18461..00000000000 --- a/src/main/resources/kotlin-client/libraries/multiplatform/commonTest/Coroutine.kt.mustache +++ /dev/null @@ -1,13 +0,0 @@ -{{>licenseInfo}} - -package util - -import kotlinx.coroutines.CoroutineScope - -/** -* Block the current thread until execution of the given coroutine is complete. -* -* @param block The coroutine code. -* @return The result of the coroutine. -*/ -internal expect fun runTest(block: suspend CoroutineScope.() -> T): T diff --git a/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/ApiClient.kt.mustache b/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/ApiClient.kt.mustache deleted file mode 100644 index bc5d9b19508..00000000000 --- a/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/ApiClient.kt.mustache +++ /dev/null @@ -1,183 +0,0 @@ -package {{packageName}}.infrastructure - -import io.ktor.client.HttpClient -import io.ktor.client.HttpClientConfig -import io.ktor.client.engine.HttpClientEngine -import io.ktor.client.plugins.contentnegotiation.ContentNegotiation -import io.ktor.serialization.kotlinx.json.* -import io.ktor.client.request.* -import io.ktor.client.request.forms.FormDataContent -import io.ktor.client.request.forms.MultiPartFormDataContent -import io.ktor.client.request.header -import io.ktor.client.request.parameter -import io.ktor.client.statement.HttpResponse -import io.ktor.http.* -import io.ktor.http.content.PartData -import kotlin.Unit -import kotlinx.serialization.json.Json - -import {{packageName}}.auth.* - -{{#nonPublicApi}}internal {{/nonPublicApi}}open class ApiClient( - private val baseUrl: String, - httpClientEngine: HttpClientEngine?, - httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, - private val jsonBlock: Json -) { - - private val clientConfig: (HttpClientConfig<*>) -> Unit by lazy { - { - it.install(ContentNegotiation) { json(jsonBlock) } - httpClientConfig?.invoke(it) - } - } - - private val client: HttpClient by lazy { - httpClientEngine?.let { HttpClient(it, clientConfig) } ?: HttpClient(clientConfig) - } - - {{#hasAuthMethods}} - private val authentications: kotlin.collections.Map by lazy { - mapOf({{#authMethods}}{{#isBasic}}{{#isBasicBasic}} - "{{name}}" to HttpBasicAuth(){{/isBasicBasic}}{{^isBasicBasic}} - "{{name}}" to HttpBearerAuth("{{scheme}}"){{/isBasicBasic}}{{/isBasic}}{{#isApiKey}} - "{{name}}" to ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"){{/isApiKey}}{{#isOAuth}} - "{{name}}" to OAuth(){{/isOAuth}}{{^-last}}, {{/-last}}{{/authMethods}}) - } - {{/hasAuthMethods}} - {{^hasAuthMethods}} - private val authentications: kotlin.collections.Map? = null - {{/hasAuthMethods}} - - {{#nonPublicApi}}internal {{/nonPublicApi}}companion object { - const val BASE_URL = "{{{basePath}}}" - val JSON_DEFAULT = Json { - ignoreUnknownKeys = true - prettyPrint = true - isLenient = true - } - protected val UNSAFE_HEADERS = listOf(HttpHeaders.ContentType) - } - - /** - * Set the username for the first HTTP basic authentication. - * - * @param username Username - */ - fun setUsername(username: String) { - val auth = authentications?.values?.firstOrNull { it is HttpBasicAuth } as HttpBasicAuth? - ?: throw Exception("No HTTP basic authentication configured") - auth.username = username - } - - /** - * Set the password for the first HTTP basic authentication. - * - * @param password Password - */ - fun setPassword(password: String) { - val auth = authentications?.values?.firstOrNull { it is HttpBasicAuth } as HttpBasicAuth? - ?: throw Exception("No HTTP basic authentication configured") - auth.password = password - } - - /** - * Set the API key value for the first API key authentication. - * - * @param apiKey API key - * @param paramName The name of the API key parameter, or null or set the first key. - */ - fun setApiKey(apiKey: String, paramName: String? = null) { - val auth = authentications?.values?.firstOrNull { it is ApiKeyAuth && (paramName == null || paramName == it.paramName)} as ApiKeyAuth? - ?: throw Exception("No API key authentication configured") - auth.apiKey = apiKey - } - - /** - * Set the API key prefix for the first API key authentication. - * - * @param apiKeyPrefix API key prefix - * @param paramName The name of the API key parameter, or null or set the first key. - */ - fun setApiKeyPrefix(apiKeyPrefix: String, paramName: String? = null) { - val auth = authentications?.values?.firstOrNull { it is ApiKeyAuth && (paramName == null || paramName == it.paramName) } as ApiKeyAuth? - ?: throw Exception("No API key authentication configured") - auth.apiKeyPrefix = apiKeyPrefix - } - - /** - * Set the access token for the first OAuth2 authentication. - * - * @param accessToken Access token - */ - fun setAccessToken(accessToken: String) { - val auth = authentications?.values?.firstOrNull { it is OAuth } as OAuth? - ?: throw Exception("No OAuth2 authentication configured") - auth.accessToken = accessToken - } - - /** - * Set the access token for the first Bearer authentication. - * - * @param bearerToken The bearer token. - */ - fun setBearerToken(bearerToken: String) { - val auth = authentications?.values?.firstOrNull { it is HttpBearerAuth } as HttpBearerAuth? - ?: throw Exception("No Bearer authentication configured") - auth.bearerToken = bearerToken - } - - protected suspend fun multipartFormRequest(requestConfig: RequestConfig, body: kotlin.collections.List?, authNames: kotlin.collections.List): HttpResponse { - return request(requestConfig, MultiPartFormDataContent(body ?: listOf()), authNames) - } - - protected suspend fun urlEncodedFormRequest(requestConfig: RequestConfig, body: Parameters?, authNames: kotlin.collections.List): HttpResponse { - return request(requestConfig, FormDataContent(body ?: Parameters.Empty), authNames) - } - - protected suspend fun jsonRequest(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse = request(requestConfig, body, authNames) - - protected suspend fun request(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse { - requestConfig.updateForAuth(authNames) - val headers = requestConfig.headers - - return client.request { - this.url { - this.takeFrom(URLBuilder(baseUrl)) - appendPath(requestConfig.path.trimStart('/').split('/')) - requestConfig.query.forEach { query -> - query.value.forEach { value -> - parameter(query.key, value) - } - } - } - this.method = requestConfig.method.httpMethod - headers.filter { header -> !UNSAFE_HEADERS.contains(header.key) }.forEach { header -> this.header(header.key, header.value) } - if (requestConfig.method in listOf(RequestMethod.PUT, RequestMethod.POST, RequestMethod.PATCH)) - this.setBody(body) - - } - } - - private fun RequestConfig.updateForAuth(authNames: kotlin.collections.List) { - for (authName in authNames) { - val auth = authentications?.get(authName) ?: throw Exception("Authentication undefined: $authName") - auth.apply(query, headers) - } - } - - private fun URLBuilder.appendPath(components: kotlin.collections.List): URLBuilder = apply { - encodedPath = encodedPath.trimEnd('/') + components.joinToString("/", prefix = "/") { it.encodeURLQueryComponent() } - } - - private val RequestMethod.httpMethod: HttpMethod - get() = when (this) { - RequestMethod.DELETE -> HttpMethod.Delete - RequestMethod.GET -> HttpMethod.Get - RequestMethod.HEAD -> HttpMethod.Head - RequestMethod.PATCH -> HttpMethod.Patch - RequestMethod.PUT -> HttpMethod.Put - RequestMethod.POST -> HttpMethod.Post - RequestMethod.OPTIONS -> HttpMethod.Options - } -} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/Base64ByteArray.kt.mustache b/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/Base64ByteArray.kt.mustache deleted file mode 100644 index c3122bd2a59..00000000000 --- a/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/Base64ByteArray.kt.mustache +++ /dev/null @@ -1,30 +0,0 @@ -package {{packageName}}.infrastructure - -import kotlinx.serialization.* -import kotlinx.serialization.descriptors.* -import kotlinx.serialization.encoding.* - -@Serializable -class Base64ByteArray(val value: ByteArray) { - @Serializer(Base64ByteArray::class) - companion object : KSerializer { - override val descriptor = PrimitiveSerialDescriptor("Base64ByteArray", PrimitiveKind.STRING) - override fun serialize(encoder: Encoder, obj: Base64ByteArray) = encoder.encodeString(obj.value.encodeBase64()) - override fun deserialize(decoder: Decoder) = Base64ByteArray(decoder.decodeString().decodeBase64Bytes()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - other as Base64ByteArray - return value.contentEquals(other.value) - } - - override fun hashCode(): Int { - return value.contentHashCode() - } - - override fun toString(): String { - return "Base64ByteArray(${hex(value)})" - } -} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/Bytes.kt.mustache b/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/Bytes.kt.mustache deleted file mode 100644 index 39825fbe388..00000000000 --- a/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/Bytes.kt.mustache +++ /dev/null @@ -1,100 +0,0 @@ -package {{packageName}}.infrastructure - -import io.ktor.utils.io.core.* -import kotlin.experimental.and - -private val digits = "0123456789abcdef".toCharArray() -private const val BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" -private const val BASE64_MASK: Byte = 0x3f -private const val BASE64_PAD = '=' -private val BASE64_INVERSE_ALPHABET = IntArray(256) { BASE64_ALPHABET.indexOf(it.toChar()) } - -private fun String.toCharArray(): CharArray = CharArray(length) { get(it) } -private fun ByteArray.clearFrom(from: Int) = (from until size).forEach { this[it] = 0 } -private fun Int.toBase64(): Char = BASE64_ALPHABET[this] -private fun Byte.fromBase64(): Byte = BASE64_INVERSE_ALPHABET[toInt() and 0xff].toByte() and BASE64_MASK -internal fun ByteArray.encodeBase64(): String = buildPacket { writeFully(this@encodeBase64) }.encodeBase64() -internal fun String.decodeBase64Bytes(): ByteArray = buildPacket { dropLastWhile { it == BASE64_PAD } }.decodeBase64Bytes().readBytes() - -/** - * Encode [bytes] as a HEX string with no spaces, newlines and `0x` prefixes. - * - * Taken from https://github.com/ktorio/ktor/blob/master/ktor-utils/common/src/io/ktor/util/Crypto.kt - */ -internal fun hex(bytes: ByteArray): String { - val result = CharArray(bytes.size * 2) - var resultIndex = 0 - val digits = digits - - for (element in bytes) { - val b = element.toInt() and 0xff - result[resultIndex++] = digits[b shr 4] - result[resultIndex++] = digits[b and 0x0f] - } - - return result.concatToString() -} - -/** - * Decode bytes from HEX string. It should be no spaces and `0x` prefixes. - * - * Taken from https://github.com/ktorio/ktor/blob/master/ktor-utils/common/src/io/ktor/util/Crypto.kt - */ -internal fun hex(s: String): ByteArray { - val result = ByteArray(s.length / 2) - for (idx in result.indices) { - val srcIdx = idx * 2 - val high = s[srcIdx].toString().toInt(16) shl 4 - val low = s[srcIdx + 1].toString().toInt(16) - result[idx] = (high or low).toByte() - } - - return result -} - -/** - * Encode [ByteReadPacket] in base64 format. - * - * Taken from https://github.com/ktorio/ktor/blob/424d1d2cfaa3281302c60af9500f738c8c2fc846/ktor-utils/common/src/io/ktor/util/Base64.kt - */ -private fun ByteReadPacket.encodeBase64(): String = buildString { - val data = ByteArray(3) - while (remaining > 0) { - val read = readAvailable(data) - data.clearFrom(read) - - val padSize = (data.size - read) * 8 / 6 - val chunk = ((data[0].toInt() and 0xFF) shl 16) or - ((data[1].toInt() and 0xFF) shl 8) or - (data[2].toInt() and 0xFF) - - for (index in data.size downTo padSize) { - val char = (chunk shr (6 * index)) and BASE64_MASK.toInt() - append(char.toBase64()) - } - - repeat(padSize) { append(BASE64_PAD) } - } -} - -/** - * Decode [ByteReadPacket] from base64 format - * - * Taken from https://github.com/ktorio/ktor/blob/424d1d2cfaa3281302c60af9500f738c8c2fc846/ktor-utils/common/src/io/ktor/util/Base64.kt - */ -private fun ByteReadPacket.decodeBase64Bytes(): Input = buildPacket { - val data = ByteArray(4) - - while (remaining > 0) { - val read = readAvailable(data) - - val chunk = data.foldIndexed(0) { index, result, current -> - result or (current.fromBase64().toInt() shl ((3 - index) * 6)) - } - - for (index in data.size - 2 downTo (data.size - read)) { - val origin = (chunk shr (8 * index)) and 0xff - writeByte(origin.toByte()) - } - } -} diff --git a/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/HttpResponse.kt.mustache b/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/HttpResponse.kt.mustache deleted file mode 100644 index 87a68f3084e..00000000000 --- a/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/HttpResponse.kt.mustache +++ /dev/null @@ -1,51 +0,0 @@ -package {{packageName}}.infrastructure - -import io.ktor.http.Headers -import io.ktor.http.isSuccess -import io.ktor.util.reflect.TypeInfo -import io.ktor.util.reflect.typeInfo - -{{#nonPublicApi}}internal {{/nonPublicApi}}open class HttpResponse(val response: io.ktor.client.statement.HttpResponse, val provider: BodyProvider) { - val status: Int = response.status.value - val success: Boolean = response.status.isSuccess() - val headers: Map> = response.headers.mapEntries() - suspend fun body(): T = provider.body(response) - suspend fun typedBody(type: TypeInfo): V = provider.typedBody(response, type) - - {{#nonPublicApi}}internal {{/nonPublicApi}}companion object { - private fun Headers.mapEntries(): Map> { - val result = mutableMapOf>() - entries().forEach { result[it.key] = it.value } - return result - } - } -} - -{{#nonPublicApi}}internal {{/nonPublicApi}}interface BodyProvider { - suspend fun body(response: io.ktor.client.statement.HttpResponse): T - suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V -} - -{{#nonPublicApi}}internal {{/nonPublicApi}}class TypedBodyProvider(private val type: TypeInfo) : BodyProvider { - @Suppress("UNCHECKED_CAST") - override suspend fun body(response: io.ktor.client.statement.HttpResponse): T = - response.call.body(type) as T - - @Suppress("UNCHECKED_CAST") - override suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V = - response.call.body(type) as V -} - -{{#nonPublicApi}}internal {{/nonPublicApi}}class MappedBodyProvider(private val provider: BodyProvider, private val block: S.() -> T) : BodyProvider { - override suspend fun body(response: io.ktor.client.statement.HttpResponse): T = - block(provider.body(response)) - - override suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V = - provider.typedBody(response, type) -} - -{{#nonPublicApi}}internal {{/nonPublicApi}}inline fun io.ktor.client.statement.HttpResponse.wrap(): HttpResponse = - HttpResponse(this, TypedBodyProvider(typeInfo())) - -{{#nonPublicApi}}internal {{/nonPublicApi}}fun HttpResponse.map(block: T.() -> V): HttpResponse = - HttpResponse(response, MappedBodyProvider(provider, block)) diff --git a/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/OctetByteArray.kt.mustache b/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/OctetByteArray.kt.mustache deleted file mode 100644 index d77a0bcbb48..00000000000 --- a/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/OctetByteArray.kt.mustache +++ /dev/null @@ -1,30 +0,0 @@ -package {{packageName}}.infrastructure - -import kotlinx.serialization.* -import kotlinx.serialization.descriptors.* -import kotlinx.serialization.encoding.* - -@Serializable -class OctetByteArray(val value: ByteArray) { - @Serializer(OctetByteArray::class) - companion object : KSerializer { - override val descriptor = PrimitiveSerialDescriptor("OctetByteArray", PrimitiveKind.STRING) - override fun serialize(encoder: Encoder, obj: OctetByteArray) = encoder.encodeString(hex(obj.value)) - override fun deserialize(decoder: Decoder) = OctetByteArray(hex(decoder.decodeString())) - } - - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - other as OctetByteArray - return value.contentEquals(other.value) - } - - override fun hashCode(): Int { - return value.contentHashCode() - } - - override fun toString(): String { - return "OctetByteArray(${hex(value)})" - } -} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/libraries/multiplatform/iosTest/Coroutine.kt.mustache b/src/main/resources/kotlin-client/libraries/multiplatform/iosTest/Coroutine.kt.mustache deleted file mode 100644 index 351c0120b7b..00000000000 --- a/src/main/resources/kotlin-client/libraries/multiplatform/iosTest/Coroutine.kt.mustache +++ /dev/null @@ -1,8 +0,0 @@ -{{>licenseInfo}} - -package util - -import kotlinx.coroutines.CoroutineScope -import kotlin.coroutines.EmptyCoroutineContext - -internal actual fun runTest(block: suspend CoroutineScope.() -> T): T = kotlinx.coroutines.runBlocking(EmptyCoroutineContext, block) diff --git a/src/main/resources/kotlin-client/libraries/multiplatform/jsTest/Coroutine.kt.mustache b/src/main/resources/kotlin-client/libraries/multiplatform/jsTest/Coroutine.kt.mustache deleted file mode 100644 index 2bea4861f67..00000000000 --- a/src/main/resources/kotlin-client/libraries/multiplatform/jsTest/Coroutine.kt.mustache +++ /dev/null @@ -1,7 +0,0 @@ -package util - -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.promise - -actual fun runTest(block: suspend (scope : CoroutineScope) -> T): dynamic = GlobalScope.promise { block(this) } \ No newline at end of file diff --git a/src/main/resources/kotlin-client/libraries/multiplatform/jvmTest/Coroutine.kt.mustache b/src/main/resources/kotlin-client/libraries/multiplatform/jvmTest/Coroutine.kt.mustache deleted file mode 100644 index 351c0120b7b..00000000000 --- a/src/main/resources/kotlin-client/libraries/multiplatform/jvmTest/Coroutine.kt.mustache +++ /dev/null @@ -1,8 +0,0 @@ -{{>licenseInfo}} - -package util - -import kotlinx.coroutines.CoroutineScope -import kotlin.coroutines.EmptyCoroutineContext - -internal actual fun runTest(block: suspend CoroutineScope.() -> T): T = kotlinx.coroutines.runBlocking(EmptyCoroutineContext, block) diff --git a/src/main/resources/kotlin-client/libraries/multiplatform/pom.mustache b/src/main/resources/kotlin-client/libraries/multiplatform/pom.mustache deleted file mode 100644 index 179205c3fec..00000000000 --- a/src/main/resources/kotlin-client/libraries/multiplatform/pom.mustache +++ /dev/null @@ -1,64 +0,0 @@ - - 4.0.0 - {{groupId}} - {{artifactId}} - {{artifactVersion}} - {{appName}} - pom - - UTF-8 - - - - - maven-dependency-plugin - - - package - - copy-dependencies - - - ${project.build.directory} - - - - - - org.codehaus.mojo - exec-maven-plugin - 1.2.1 - - - bundle-clean - clean - - exec - - - /bin/bash - - gradlew - clean - - - - - bundle-test - integration-test - - exec - - - /bin/bash - - gradlew - build - - - - - - - - diff --git a/src/main/resources/kotlin-client/libraries/multiplatform/serial_wrapper_request_list.mustache b/src/main/resources/kotlin-client/libraries/multiplatform/serial_wrapper_request_list.mustache deleted file mode 100644 index f3b0464445e..00000000000 --- a/src/main/resources/kotlin-client/libraries/multiplatform/serial_wrapper_request_list.mustache +++ /dev/null @@ -1,10 +0,0 @@ - @Serializable - private class {{operationIdCamelCase}}Request(val value: List<{{#bodyParam}}{{baseType}}{{/bodyParam}}>) { - @Serializer({{operationIdCamelCase}}Request::class) - {{#nonPublicApi}}internal {{/nonPublicApi}}companion object : KSerializer<{{operationIdCamelCase}}Request> { - private val serializer: KSerializer> = serializer>() - override val descriptor = serializer.descriptor - override fun serialize(encoder: Encoder, obj: {{operationIdCamelCase}}Request) = serializer.serialize(encoder, obj.value) - override fun deserialize(decoder: Decoder) = {{operationIdCamelCase}}Request(serializer.deserialize(decoder)) - } - } \ No newline at end of file diff --git a/src/main/resources/kotlin-client/libraries/multiplatform/serial_wrapper_request_map.mustache b/src/main/resources/kotlin-client/libraries/multiplatform/serial_wrapper_request_map.mustache deleted file mode 100644 index a287882728d..00000000000 --- a/src/main/resources/kotlin-client/libraries/multiplatform/serial_wrapper_request_map.mustache +++ /dev/null @@ -1,10 +0,0 @@ - @Serializable - private class {{operationIdCamelCase}}Request(val value: Map) { - @Serializer({{operationIdCamelCase}}Request::class) - {{#nonPublicApi}}internal {{/nonPublicApi}}companion object : KSerializer<{{operationIdCamelCase}}Request> { - private val serializer: KSerializer> = serializer>() - override val descriptor = serializer.descriptor - override fun serialize(encoder: Encoder, obj: {{operationIdCamelCase}}Request) = serializer.serialize(encoder, obj.value) - override fun deserialize(decoder: Decoder) = {{operationIdCamelCase}}Request(serializer.deserialize(decoder)) - } - } \ No newline at end of file diff --git a/src/main/resources/kotlin-client/libraries/multiplatform/serial_wrapper_response_list.mustache b/src/main/resources/kotlin-client/libraries/multiplatform/serial_wrapper_response_list.mustache deleted file mode 100644 index 227d6a351f2..00000000000 --- a/src/main/resources/kotlin-client/libraries/multiplatform/serial_wrapper_response_list.mustache +++ /dev/null @@ -1,10 +0,0 @@ - @Serializable - private class {{operationIdCamelCase}}Response(val value: List<{{returnBaseType}}>) { - @Serializer({{operationIdCamelCase}}Response::class) - {{#nonPublicApi}}internal {{/nonPublicApi}}companion object : KSerializer<{{operationIdCamelCase}}Response> { - private val serializer: KSerializer> = serializer>() - override val descriptor = serializer.descriptor - override fun serialize(encoder: Encoder, obj: {{operationIdCamelCase}}Response) = serializer.serialize(encoder, obj.value) - override fun deserialize(decoder: Decoder) = {{operationIdCamelCase}}Response(serializer.deserialize(decoder)) - } - } \ No newline at end of file diff --git a/src/main/resources/kotlin-client/libraries/multiplatform/serial_wrapper_response_map.mustache b/src/main/resources/kotlin-client/libraries/multiplatform/serial_wrapper_response_map.mustache deleted file mode 100644 index a6bdd6c166a..00000000000 --- a/src/main/resources/kotlin-client/libraries/multiplatform/serial_wrapper_response_map.mustache +++ /dev/null @@ -1,10 +0,0 @@ - @Serializable - private class {{operationIdCamelCase}}Response(val value: Map) { - @Serializer({{operationIdCamelCase}}Response::class) - {{#nonPublicApi}}internal {{/nonPublicApi}}companion object : KSerializer<{{operationIdCamelCase}}Response> { - private val serializer: KSerializer> = serializer>() - override val descriptor = serializer.descriptor - override fun serialize(encoder: Encoder, obj: {{operationIdCamelCase}}Response) = serializer.serialize(encoder, obj.value) - override fun deserialize(decoder: Decoder) = {{operationIdCamelCase}}Response(serializer.deserialize(decoder)) - } - } \ No newline at end of file diff --git a/src/main/resources/kotlin-client/libraries/multiplatform/settings.gradle.kts.mustache b/src/main/resources/kotlin-client/libraries/multiplatform/settings.gradle.kts.mustache deleted file mode 100644 index b8fd6c4c41f..00000000000 --- a/src/main/resources/kotlin-client/libraries/multiplatform/settings.gradle.kts.mustache +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = "{{artifactId}}" \ No newline at end of file diff --git a/src/main/resources/kotlin-client/licenseInfo.mustache b/src/main/resources/kotlin-client/licenseInfo.mustache deleted file mode 100644 index d344667db12..00000000000 --- a/src/main/resources/kotlin-client/licenseInfo.mustache +++ /dev/null @@ -1,19 +0,0 @@ -/** - * {{{appName}}} - * - * {{{appDescription}}} - * - * {{#version}}The version of the OpenAPI document: {{{.}}}{{/version}} - * {{#infoEmail}}Contact: {{{.}}}{{/infoEmail}} - * - * Please note: - * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * Do not edit this file manually. - */ - -@file:Suppress( - "ArrayInDataClass", - "EnumEntryName", - "RemoveRedundantQualifierName", - "UnusedImport" -) diff --git a/src/main/resources/kotlin-client/model.mustache b/src/main/resources/kotlin-client/model.mustache deleted file mode 100644 index abd168abce8..00000000000 --- a/src/main/resources/kotlin-client/model.mustache +++ /dev/null @@ -1,11 +0,0 @@ -{{>licenseInfo}} -package {{modelPackage}} - -{{#imports}}import {{import}} -{{/imports}} - -{{#models}} -{{#model}} -{{#isEnum}}{{>enum_class}}{{/isEnum}}{{^isEnum}}{{#isAlias}}typealias {{classname}} = {{{dataType}}}{{/isAlias}}{{^isAlias}}{{>data_class}}{{/isAlias}}{{/isEnum}} -{{/model}} -{{/models}} diff --git a/src/main/resources/kotlin-client/modelMutable.mustache b/src/main/resources/kotlin-client/modelMutable.mustache deleted file mode 100644 index 4c7f3900717..00000000000 --- a/src/main/resources/kotlin-client/modelMutable.mustache +++ /dev/null @@ -1 +0,0 @@ -{{#modelMutable}}var{{/modelMutable}}{{^modelMutable}}val{{/modelMutable}} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/model_doc.mustache b/src/main/resources/kotlin-client/model_doc.mustache deleted file mode 100644 index e3b71842118..00000000000 --- a/src/main/resources/kotlin-client/model_doc.mustache +++ /dev/null @@ -1,3 +0,0 @@ -{{#models}}{{#model}} -{{#isEnum}}{{>enum_doc}}{{/isEnum}}{{^isEnum}}{{>class_doc}}{{/isEnum}} -{{/model}}{{/models}} diff --git a/src/main/resources/kotlin-client/model_room.mustache b/src/main/resources/kotlin-client/model_room.mustache deleted file mode 100644 index bb43e6bf87e..00000000000 --- a/src/main/resources/kotlin-client/model_room.mustache +++ /dev/null @@ -1,38 +0,0 @@ -{{>licenseInfo}} -package {{roomModelPackage}} - -import androidx.room.Entity -import androidx.room.Ignore -import androidx.room.PrimaryKey -import {{modelPackage}}.* - -{{#models}} -{{#model}} - -@Entity(tableName = "{{classname}}") -/** -* Room model for {{{description}}} -{{#allVars}} -* @param {{{name}}} {{{description}}} -{{/allVars}} -*/ -data class {{classname}}RoomModel ( - @PrimaryKey(autoGenerate = true) var roomTableId: Int, - {{#allVars}}{{#items.isPrimitiveType}}var {{{name}}}: {{#isArray}}{{#isList}}kotlin.collections.List{{/isList}}{{^isList}}kotlin.Array{{/isList}}<{{^items.isEnum}}{{{items.dataType}}}{{/items.isEnum}}{{#items.isEnum}}{{classname}}.{{{nameInCamelCase}}}{{/items.isEnum}}>{{>model_room_init_var}}{{/isArray}}, - {{/items.isPrimitiveType}}{{/allVars}} - {{#allVars}}{{^isEnum}}{{^isArray}}var {{{name}}}: {{{dataType}}}{{>model_room_init_var}}, - {{/isArray}}{{/isEnum}}{{/allVars}} - {{#allVars}}{{#isEnum}}{{^isArray}}var {{{name}}}: {{classname}}.{{{nameInCamelCase}}}{{>model_room_init_var}}, - {{/isArray}}{{/isEnum}}{{/allVars}}) { -{{#allVars}}{{#isArray}}{{#isList}}{{^items.isPrimitiveType}} - @Ignore - {{^isNullable}}{{#required}}lateinit {{/required}}{{/isNullable}}var {{{name}}}: {{#isArray}}{{#isList}}kotlin.collections.List{{/isList}}{{^isList}}kotlin.Array{{/isList}}<{{^items.isEnum}}{{^items.isPrimitiveType}}{{^items.isModel}}{{/items.isModel}}{{/items.isPrimitiveType}}{{{items.dataType}}}{{/items.isEnum}}{{#items.isEnum}}{{classname}}.{{{nameInCamelCase}}}{{/items.isEnum}}>{{>model_room_init_var}}{{/isArray}} -{{/items.isPrimitiveType}}{{/isList}}{{/isArray}}{{/allVars}} - {{^discriminator}}companion object { } - - fun toApiModel(): {{classname}} = {{classname}}( - {{#allVars}}{{name}} = this.{{name}}, - {{/allVars}}){{/discriminator}} -} -{{/model}} -{{/models}} diff --git a/src/main/resources/kotlin-client/model_room_init_var.mustache b/src/main/resources/kotlin-client/model_room_init_var.mustache deleted file mode 100644 index 3e6f299d3d6..00000000000 --- a/src/main/resources/kotlin-client/model_room_init_var.mustache +++ /dev/null @@ -1 +0,0 @@ -{{#isNullable}}?{{/isNullable}}{{^required}}{{^isNullable}}?{{/isNullable}}{{/required}}{{#defaultvalue}} = {{defaultvalue}}{{/defaultvalue}}{{^defaultvalue}}{{#isNullable}} = null{{/isNullable}}{{^required}}{{^isNullable}} = null{{/isNullable}}{{/required}}{{/defaultvalue}} \ No newline at end of file diff --git a/src/main/resources/kotlin-client/settings.gradle.mustache b/src/main/resources/kotlin-client/settings.gradle.mustache deleted file mode 100644 index 2a789fe8d04..00000000000 --- a/src/main/resources/kotlin-client/settings.gradle.mustache +++ /dev/null @@ -1,2 +0,0 @@ -{{#multiplatform}}enableFeaturePreview('GRADLE_METADATA'){{/multiplatform}} -rootProject.name = '{{artifactId}}' \ No newline at end of file diff --git a/src/main/resources/kotlin-client/typeInfoAnnotation.mustache b/src/main/resources/kotlin-client/typeInfoAnnotation.mustache deleted file mode 100644 index 6b3cb83b0f8..00000000000 --- a/src/main/resources/kotlin-client/typeInfoAnnotation.mustache +++ /dev/null @@ -1,6 +0,0 @@ -@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "{{{discriminator.propertyBaseName}}}", visible = true) -@JsonSubTypes( -{{#discriminator.mappedModels}} - JsonSubTypes.Type(value = {{modelName}}::class, name = "{{^vendorExtensions.x-discriminator-value}}{{mappingName}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{vendorExtensions.x-discriminator-value}}}{{/vendorExtensions.x-discriminator-value}}"){{^-last}},{{/-last}} -{{/discriminator.mappedModels}} -) \ No newline at end of file diff --git a/src/test/java/org/openapijsonschematools/codegen/clicommands/GenerateBatchTest.java b/src/test/java/org/openapijsonschematools/codegen/clicommands/GenerateBatchTest.java index fc6e3debe59..02f99bf3e2d 100644 --- a/src/test/java/org/openapijsonschematools/codegen/clicommands/GenerateBatchTest.java +++ b/src/test/java/org/openapijsonschematools/codegen/clicommands/GenerateBatchTest.java @@ -79,7 +79,7 @@ public void testDeserializerWithJsonInclude(String file) throws IOException { assertNotNull(workflowSettings); assertNotNull(generatorSettings); - assertEquals(generatorSettings.getGeneratorName(), "jaxrs-jersey"); + assertEquals(generatorSettings.getGeneratorName(), "java"); assertEquals(workflowSettings.getOutputDir(), "outputDir"); assertEquals(workflowSettings.getInputSpec(), SPEC_FILE); assertTrue(generatorSettings.getAdditionalProperties().size() >= 7); diff --git a/src/test/java/org/openapijsonschematools/codegen/generatorrunner/DefaultGeneratorRunnerTest.java b/src/test/java/org/openapijsonschematools/codegen/generatorrunner/DefaultGeneratorRunnerTest.java index 6c152b95399..b096e780a4b 100644 --- a/src/test/java/org/openapijsonschematools/codegen/generatorrunner/DefaultGeneratorRunnerTest.java +++ b/src/test/java/org/openapijsonschematools/codegen/generatorrunner/DefaultGeneratorRunnerTest.java @@ -393,8 +393,8 @@ public void testBuiltinLibraryTemplates() throws IOException { File output = target.toFile(); try { final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("kotlin") - .setLibrary("jvm-okhttp4") + .setGeneratorName("python") + .setLibrary("urllib3") .setInputSpec("src/test/resources/3_0/petstore.yaml") .setSkipOverwrite(false) .setOutputDir(target.toAbsolutePath().toString()); @@ -412,19 +412,19 @@ public void testBuiltinLibraryTemplates() throws IOException { List files = generator.opts(clientOptInput).generate(); - Assert.assertEquals(files.size(), 27); + Assert.assertEquals(files.size(), 57); // GeneratorRunner should report a library templated file as a generated file - TestUtils.ensureContainsFile(files, output, "src/main/kotlin/org/openapijsonschematools/client/infrastructure/Errors.kt"); + TestUtils.ensureContainsFile(files, output, "src/openapi_client/exceptions.py"); // Generated file should exist on the filesystem after generation - File generatedFile = new File(output, "src/main/kotlin/org/openapijsonschematools/client/infrastructure/Errors.kt"); + File generatedFile = new File(output, "src/openapi_client/exceptions.py"); Assert.assertTrue(generatedFile.exists()); // Generated file should contain some expected text - TestUtils.assertFileContains(generatedFile.toPath(), "package org.openapijsonschematools.client.infrastructure", - "open class ClientException", - "open class ServerException"); + TestUtils.assertFileContains(generatedFile.toPath(), "class OpenApiException(Exception):", + "class ApiTypeError(OpenApiException, TypeError):", + "class ApiValueError(OpenApiException, ValueError):"); } finally { output.delete(); } @@ -436,7 +436,7 @@ public void testBuiltinNonLibraryTemplates() throws IOException { File output = target.toFile(); try { final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("kotlin") + .setGeneratorName("python") .setInputSpec("src/test/resources/3_0/petstore.yaml") .setSkipOverwrite(false) .setOutputDir(target.toAbsolutePath().toString()); @@ -454,7 +454,7 @@ public void testBuiltinNonLibraryTemplates() throws IOException { List files = generator.opts(clientOptInput).generate(); - Assert.assertEquals(files.size(), 27); + Assert.assertEquals(files.size(), 57); // GeneratorRunner should report README.md as a generated file TestUtils.ensureContainsFile(files, output, "README.md"); @@ -464,10 +464,10 @@ public void testBuiltinNonLibraryTemplates() throws IOException { Assert.assertTrue(readme.exists()); // README.md should contain some expected text - TestUtils.assertFileContains(readme.toPath(), "# org.openapijsonschematools.client - Kotlin client library for OpenAPI Petstore", - "## Requires", - "## Build", - "## Features/Implementation Notes"); + TestUtils.assertFileContains(readme.toPath(), "# openapi-client", + "## Requirements", + "## Installation", + "## Endpoints"); } finally { output.delete(); } @@ -480,7 +480,7 @@ public void testCustomLibraryTemplates() throws IOException { File output = target.toFile(); try { // Create custom template - File customTemplate = new File(templates.toFile(), "libraries/jvm-okhttp/infrastructure/Errors.kt.mustache"); + File customTemplate = new File(templates.toFile(), "exceptions.hbs"); new File(customTemplate.getParent()).mkdirs(); StringBuilder sb = new StringBuilder(); sb.append("// {{someKey}}").append("\n"); @@ -498,10 +498,10 @@ public void testCustomLibraryTemplates() throws IOException { StandardOpenOption.CREATE); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("kotlin") + .setGeneratorName("python") .addAdditionalProperty("someKey", "testCustomLibraryTemplates") .setTemplateDir(templates.toAbsolutePath().toString()) - .setLibrary("jvm-okhttp4") + .setLibrary("urllib3") .setInputSpec("src/test/resources/3_0/petstore.yaml") .setSkipOverwrite(false) .setOutputDir(target.toAbsolutePath().toString()); @@ -519,13 +519,13 @@ public void testCustomLibraryTemplates() throws IOException { List files = generator.opts(clientOptInput).generate(); - Assert.assertEquals(files.size(), 27); + Assert.assertEquals(files.size(), 57); // GeneratorRunner should report a library templated file as a generated file - TestUtils.ensureContainsFile(files, output, "src/main/kotlin/org/openapijsonschematools/client/infrastructure/Errors.kt"); + TestUtils.ensureContainsFile(files, output, "src/openapi_client/exceptions.py"); // Generated file should exist on the filesystem after generation - File readme = new File(output, "src/main/kotlin/org/openapijsonschematools/client/infrastructure/Errors.kt"); + File readme = new File(output, "src/openapi_client/exceptions.py"); Assert.assertTrue(readme.exists()); // Generated file should contain our custom templated text @@ -546,14 +546,14 @@ public void testCustomNonLibraryTemplates() throws IOException { File output = target.toFile(); try { // Create custom template - File customTemplate = new File(templates.toFile(), "README.mustache"); + File customTemplate = new File(templates.toFile(), "README.hbs"); new File(customTemplate.getParent()).mkdirs(); Files.write(customTemplate.toPath(), "# {{someKey}}".getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("kotlin") + .setGeneratorName("python") .addAdditionalProperty("someKey", "testCustomNonLibraryTemplates") .setTemplateDir(templates.toAbsolutePath().toString()) .setInputSpec("src/test/resources/3_0/petstore.yaml") @@ -573,7 +573,7 @@ public void testCustomNonLibraryTemplates() throws IOException { List files = generator.opts(clientOptInput).generate(); - Assert.assertEquals(files.size(), 27); + Assert.assertEquals(files.size(), 57); // GeneratorRunner should report README.md as a generated file TestUtils.ensureContainsFile(files, output, "README.md"); diff --git a/src/test/resources/batch/jaxrs-datelib-j8-json-include.yaml b/src/test/resources/batch/jaxrs-datelib-j8-json-include.yaml index 121076c9652..4c6b51c3a9a 100644 --- a/src/test/resources/batch/jaxrs-datelib-j8-json-include.yaml +++ b/src/test/resources/batch/jaxrs-datelib-j8-json-include.yaml @@ -1,6 +1,6 @@ --- "!include": common/jaxrs-datelib-j8.json -generatorName: jaxrs-jersey +generatorName: java inputSpec: batch/specs/petstore.yaml outputDir: outputDir additionalProperties: diff --git a/src/test/resources/batch/jaxrs-datelib-j8-nested-include-property-merge.yaml b/src/test/resources/batch/jaxrs-datelib-j8-nested-include-property-merge.yaml index ee1b4250b6d..bcf5f1527ac 100644 --- a/src/test/resources/batch/jaxrs-datelib-j8-nested-include-property-merge.yaml +++ b/src/test/resources/batch/jaxrs-datelib-j8-nested-include-property-merge.yaml @@ -1,6 +1,6 @@ --- "!include": common/jaxrs-datelib-j8.yaml -generatorName: jaxrs-jersey +generatorName: java # We expect this property to be ignored because it exists in the importing file outputDir: outputDir-should-be-ignored inputSpec: batch/specs/petstore.yaml diff --git a/src/test/resources/batch/jaxrs-datelib-j8-nested-include.json b/src/test/resources/batch/jaxrs-datelib-j8-nested-include.json index f41d8a3a6d9..028491cb7c6 100644 --- a/src/test/resources/batch/jaxrs-datelib-j8-nested-include.json +++ b/src/test/resources/batch/jaxrs-datelib-j8-nested-include.json @@ -1,6 +1,6 @@ { "!include": "common/jaxrs-datelib-j8.json", - "generatorName": "jaxrs-jersey", + "generatorName": "java", "outputDir": "outputDir", "additionalProperties": { "hideGenerationTimestamp": true, diff --git a/src/test/resources/batch/jaxrs-datelib-j8-nested-include.yaml b/src/test/resources/batch/jaxrs-datelib-j8-nested-include.yaml index 7a42dd928db..815c14eca10 100644 --- a/src/test/resources/batch/jaxrs-datelib-j8-nested-include.yaml +++ b/src/test/resources/batch/jaxrs-datelib-j8-nested-include.yaml @@ -1,6 +1,6 @@ --- "!include": common/jaxrs-datelib-j8.yaml -generatorName: jaxrs-jersey +generatorName: java outputDir: outputDir additionalProperties: hideGenerationTimestamp: true diff --git a/src/test/resources/batch/jaxrs-datelib-j8-yaml-include.json b/src/test/resources/batch/jaxrs-datelib-j8-yaml-include.json index bb8957cf653..8b5e145362c 100644 --- a/src/test/resources/batch/jaxrs-datelib-j8-yaml-include.json +++ b/src/test/resources/batch/jaxrs-datelib-j8-yaml-include.json @@ -1,6 +1,6 @@ { "!include": "common/jaxrs-datelib-j8.yaml", - "generatorName": "jaxrs-jersey", + "generatorName": "java", "inputSpec": "batch/specs/petstore.yaml", "outputDir": "outputDir", "additionalProperties": { diff --git a/src/test/resources/batch/jaxrs-datelib-j8.json b/src/test/resources/batch/jaxrs-datelib-j8.json index c3f03859f04..7b3a184a0a6 100644 --- a/src/test/resources/batch/jaxrs-datelib-j8.json +++ b/src/test/resources/batch/jaxrs-datelib-j8.json @@ -1,6 +1,6 @@ { "!include": "common/jaxrs-datelib-j8.json", - "generatorName": "jaxrs-jersey", + "generatorName": "java", "inputSpec": "batch/specs/petstore.yaml", "outputDir": "outputDir", "additionalProperties": { diff --git a/src/test/resources/batch/jaxrs-datelib-j8.yaml b/src/test/resources/batch/jaxrs-datelib-j8.yaml index bab10df8dd1..a5ce186eb83 100644 --- a/src/test/resources/batch/jaxrs-datelib-j8.yaml +++ b/src/test/resources/batch/jaxrs-datelib-j8.yaml @@ -1,6 +1,6 @@ --- "!include": common/jaxrs-datelib-j8.yaml -generatorName: jaxrs-jersey +generatorName: java inputSpec: batch/specs/petstore.yaml outputDir: outputDir additionalProperties: