Merge remote-tracking branch 'origin/master' into 6.0.x

This commit is contained in:
William Cheng 2021-02-12 18:48:20 +08:00
commit b4f4d7434b
750 changed files with 34048 additions and 10711 deletions

View File

@ -9,7 +9,7 @@
<div align="center">
[Master](https://github.com/OpenAPITools/openapi-generator/tree/master) (`5.0.1`):
[Master](https://github.com/OpenAPITools/openapi-generator/tree/master) (`5.1.0`):
[![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/master.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator)
[![Integration Test2](https://circleci.com/gh/OpenAPITools/openapi-generator.svg?style=shield)](https://circleci.com/gh/OpenAPITools/openapi-generator)
[![Run Status](https://api.shippable.com/projects/5af6bf74e790f4070084a115/badge?branch=master)](https://app.shippable.com/github/OpenAPITools/openapi-generator)
@ -18,14 +18,6 @@
[![Bitrise](https://img.shields.io/bitrise/4a2b10a819d12b67/master?label=bitrise%3A%20Swift+4,5&token=859FMDR8QHwabCzwvZK6vQ)](https://app.bitrise.io/app/4a2b10a819d12b67)
[![GitHub Workflow Status (branch)](https://img.shields.io/github/workflow/status/openapitools/openapi-generator/Check%20Supported%20Java%20Versions/master?label=Check%20Supported%20Java%20Versions&logo=github&logoColor=green)](https://github.com/OpenAPITools/openapi-generator/actions?query=workflow%3A%22Check+Supported+Java+Versions%22)
[5.1.x](https://github.com/OpenAPITools/openapi-generator/tree/5.1.x) (`5.1.x`):
[![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/5.1.x.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator)
[![Integration Test2](https://circleci.com/gh/OpenAPITools/openapi-generator/tree/5.1.x.svg?style=shield)](https://circleci.com/gh/OpenAPITools/openapi-generator)
[![Run Status](https://api.shippable.com/projects/5af6bf74e790f4070084a115/badge?branch=5.1.x)](https://app.shippable.com/github/OpenAPITools/openapi-generator)
[![Windows Test](https://ci.appveyor.com/api/projects/status/github/openapitools/openapi-generator?branch=5.1.x&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/openapi-generator-wh2wu)
[![JDK11 Build](https://cloud.drone.io/api/badges/OpenAPITools/openapi-generator/status.svg?ref=refs/heads/5.1.x)](https://cloud.drone.io/OpenAPITools/openapi-generator)
[![Bitrise](https://img.shields.io/bitrise/4a2b10a819d12b67/5.1.x?label=bitrise%3A%20Swift+4,5&token=859FMDR8QHwabCzwvZK6vQ)](https://app.bitrise.io/app/4a2b10a819d12b67)
[6.0.x](https://github.com/OpenAPITools/openapi-generator/tree/6.0.x) (`6.0.x`):
[![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/6.0.x.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator)
[![Integration Test2](https://circleci.com/gh/OpenAPITools/openapi-generator/tree/6.0.x.svg?style=shield)](https://circleci.com/gh/OpenAPITools/openapi-generator)
@ -77,9 +69,9 @@ OpenAPI Generator allows generation of API client libraries (SDK generation), se
| | Languages/Frameworks |
| -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C**, **C#** (.net 2.0, 3.5 or later, .NET Standard 1.3 - 2.0, .NET Core 2.0), **C++** (cpp-restsdk, Qt5, Tizen), **Clojure**, **Crystal**, **Dart**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java, Rest-assured, Spring 5 Web Client, MicroProfile Rest Client), **k6**, **Kotlin**, **Lua**, **Nim**, **Node.js/JavaScript** (ES5, ES6, AngularJS with Google Closure Compiler annotations, Flow types, Apollo GraphQL DataStore), **Objective-C**, **OCaml**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (rust, rust-server), **Scala** (akka, http4s, scalaz, sttp, swagger-async-httpclient), **Swift** (2.x, 3.x, 4.x, 5.x), **Typescript** (AngularJS, Angular (2.x - 8.x), Aurelia, Axios, Fetch, Inversify, jQuery, Nestjs, Node, Rxjs) |
| **API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C**, **C#** (.net 2.0, 3.5 or later, .NET Standard 1.3 - 2.0, .NET Core 2.0, .NET 5.0), **C++** (cpp-restsdk, Qt5, Tizen, Unreal Engine 4), **Clojure**, **Crystal**, **Dart**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java, Rest-assured, Spring 5 Web Client, MicroProfile Rest Client), **k6**, **Kotlin**, **Lua**, **Nim**, **Node.js/JavaScript** (ES5, ES6, AngularJS with Google Closure Compiler annotations, Flow types, Apollo GraphQL DataStore), **Objective-C**, **OCaml**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (hyper, reqwest, rust-server), **Scala** (akka, http4s, scalaz, sttp, swagger-async-httpclient), **Swift** (2.x, 3.x, 4.x, 5.x), **Typescript** (AngularJS, Angular (2.x - 11.x), Aurelia, Axios, Fetch, Inversify, jQuery, Nestjs, Node, redux-query, Rxjs) |
| **Server stubs** | **Ada**, **C#** (ASP.NET Core, NancyFx), **C++** (Pistache, Restbed, Qt5 QHTTPEngine), **Erlang**, **F#** (Giraffe), **Go** (net/http, Gin), **Haskell** (Servant), **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, Jersey, RestEasy, Play Framework, [PKMST](https://github.com/ProKarma-Inc/pkmst-getting-started-examples), [Vert.x](https://vertx.io/)), **Kotlin** (Spring Boot, Ktor, Vertx), **PHP** (Laravel, Lumen, Slim, Silex, [Symfony](https://symfony.com/), [Zend Expressive](https://github.com/zendframework/zend-expressive)), **Python** (Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust** (rust-server), **Scala** (Akka, [Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), [Play](https://www.playframework.com/), Scalatra) |
| **API documentation generators** | **HTML**, **Confluence Wiki**, **Asciidoc** |
| **API documentation generators** | **HTML**, **Confluence Wiki**, **Asciidoc**, **Markdown**, **PlantUML** |
| **Configuration files** | [**Apache2**](https://httpd.apache.org/) |
| **Others** | **GraphQL**, **JMeter**, **Ktorm**, **MySQL Schema**, **Protocol Buffer** |
@ -121,8 +113,7 @@ The OpenAPI Specification has undergone 3 revisions since initial creation in 20
| --------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ------------------------------------------------- |
| 6.0.0 (upcoming major release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/6.0.0-SNAPSHOT/) | Nov/Dec 2021 | Minor release with breaking changes (no fallback) |
| 5.1.0 (upcoming minor release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/5.1.0-SNAPSHOT/) | Mar/Apr 2021 | Minor release with breaking changes (with fallback) |
| 5.0.1 (upcoming patch release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/5.0.1-SNAPSHOT/) | Jan/Feb 2021 | Patch release with enhancements, bug fixes, etc |
| [5.0.0](https://github.com/OpenAPITools/openapi-generator/releases/tag/v5.0.0) (latest stable release) | 21.12.2020 | Major release with breaking changes (no fallback) |
| [5.0.1](https://github.com/OpenAPITools/openapi-generator/releases/tag/v5.0.1) (latest stable release) | 06.02.2021 | Patch release with enhancements, bug fixes, etc |
| [4.3.1](https://github.com/OpenAPITools/openapi-generator/releases/tag/v4.3.1) | 06.05.2020 | Patch release (enhancements, bug fixes, etc) |
OpenAPI Spec compatibility: 1.0, 1.1, 1.2, 2.0, 3.0
@ -179,16 +170,16 @@ See the different versions of the [openapi-generator-cli](https://mvnrepository.
<!-- RELEASE_VERSION -->
If you're looking for the latest stable version, you can grab it directly from Maven.org (Java 8 runtime at a minimum):
JAR location: `https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.0/openapi-generator-cli-5.0.0.jar`
JAR location: `https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.1/openapi-generator-cli-5.0.1.jar`
For **Mac/Linux** users:
```sh
wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.0/openapi-generator-cli-5.0.0.jar -O openapi-generator-cli.jar
wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.1/openapi-generator-cli-5.0.1.jar -O openapi-generator-cli.jar
```
For **Windows** users, you will need to install [wget](http://gnuwin32.sourceforge.net/packages/wget.htm) or you can use Invoke-WebRequest in PowerShell (3.0+), e.g.
```
Invoke-WebRequest -OutFile openapi-generator-cli.jar https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.0/openapi-generator-cli-5.0.0.jar
Invoke-WebRequest -OutFile openapi-generator-cli.jar https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.1/openapi-generator-cli-5.0.1.jar
```
After downloading the JAR, run `java -jar openapi-generator-cli.jar help` to show the usage.
@ -413,7 +404,7 @@ openapi-generator-cli version
To use a specific version of "openapi-generator-cli"
```sh
openapi-generator-cli version-manager set 5.0.0
openapi-generator-cli version-manager set 5.0.1
```
Or install it as dev-dependency:
@ -437,7 +428,7 @@ java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generat
(if you're on Windows, replace the last command with `java -jar modules\openapi-generator-cli\target\openapi-generator-cli.jar generate -i https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g php -o c:\temp\php_api_client`)
<!-- RELEASE_VERSION -->
You can also download the JAR (latest release) directly from [maven.org](https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.0/openapi-generator-cli-5.0.0.jar)
You can also download the JAR (latest release) directly from [maven.org](https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.1/openapi-generator-cli-5.0.1.jar)
<!-- /RELEASE_VERSION -->
To get a list of **general** options available, please run `java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar help generate`
@ -450,10 +441,10 @@ To get a list of PHP specified options (which can be passed to the generator wit
You can build a client against the [Petstore API](https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/3_0/petstore.yaml) as follows:
```sh
./bin/java-petstore-okhttp-gson.sh
./bin/generate-samples.sh ./bin/configs/java-okhttp-gson.yaml
```
(On Windows, run `.\bin\windows\java-petstore-okhttp-gson.bat` instead)
(On Windows, please install [GIT Bash for Windows](https://gitforwindows.org/) to run the command above)
This script uses the default library, which is `okhttp-gson`. It will run the generator with this command:
@ -461,6 +452,8 @@ This script uses the default library, which is `okhttp-gson`. It will run the ge
java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generate \
-i https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/3_0/petstore.yaml \
-g java \
-t modules/openapi-generator/src/main/resources/Java \
--additional-properties artifactId=petstore-okhttp-gson,hideGenerationTimestamp:true \
-o samples/client/petstore/java/okhttp-gson
```
@ -526,13 +519,7 @@ cd samples/client/petstore/java/okhttp-gson
mvn package
```
Other languages have petstore samples, too:
- [Swift5](https://github.com/OpenAPITools/openapi-generator/tree/master/samples/client/petstore/swift5)
- [Ruby](https://github.com/OpenAPITools/openapi-generator/tree/master/samples/client/petstore/ruby)
- [Kotlin](https://github.com/OpenAPITools/openapi-generator/tree/master/samples/client/petstore/kotlin)
... and more.
Other generators have [samples](https://github.com/OpenAPITools/openapi-generator/tree/master/samples) too.
### [3.1 - Customization](#table-of-contents)
@ -629,6 +616,7 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- [Kubernetes](https://kubernetes.io)
- [Linode](https://www.linode.com/)
- [Logicdrop](https://www.logicdrop.com)
- [Lumeris](https://www.lumeris.com)
- [LVM Versicherungen](https://www.lvm.de)
- [MailSlurp](https://www.mailslurp.com)
- [Médiavision](https://www.mediavision.fr/)
@ -808,6 +796,7 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- 2020-10-31 - [[B2] OpenAPI Specification으로 타입-세이프하게 API 개발하기: 희망편 VS 절망편](https://www.youtube.com/watch?v=J4JHLESAiFk) by 최태건 at [FEConf 2020](https://2020.feconf.kr/)
- 2020-11-05 - [Automated REST-Api Code Generation: Wie IT-Systeme miteinander sprechen](https://www.massiveart.com/blog/automated-rest-api-code-generation-wie-it-systeme-miteinander-sprechen) by Stefan Rottensteiner at [MASSIVE ART Blog](https://www.massiveart.com/blog)
- 2020-12-01 - [OpenAPI GeneratorでGoのAPIサーバー/クライアントコードを自動生成する](https://qiita.com/saki-engineering/items/b20d8b6074c4da9664a5) by [@saki-engineering](https://qiita.com/saki-engineering)
- 2020-12-04 - [Scaling the Test Coverage of OpenAPI Generator for 30+ Programming Languages](https://www.youtube.com/watch?v=7Lke9dHRqT0) by [William Cheng](https://github.com/wing328) at [Open Source Summit Japan + Automotive Linux Summit 2020](https://events.linuxfoundation.org/archive/2020/open-source-summit-japan/) ([Slides](https://speakerdeck.com/wing328/scaling-the-test-coverage-of-openapi-generator-for-30-plus-programming-languages))
- 2020-12-09 - [プロジェクトにOpenAPI Generatorで自動生成された型付きAPI Clientを導入した話](https://qiita.com/yoshifujiT/items/905c18700ede23f40840) by [@yoshifujiT](https://github.com/yoshifujiT)
- 2020-12-15 - [Next.js + NestJS + GraphQLで変化に追従するフロントエンドへ 〜 ショッピングクーポンの事例紹介](https://techblog.yahoo.co.jp/entry/2020121530052952/) by [小倉 陸](https://github.com/ogugu9) at [Yahoo! JAPAN Tech Blog](https://techblog.yahoo.co.jp/)
- 2021-01-08 - [Hello, New API Part 1](https://www.nginx.com/blog/hello-new-api-part-1/) by [Jeremy Schulman](https://www.nginx.com/people/jeremy-schulman/) at [Major League Baseball](https://www.mlb.com)

View File

@ -1,9 +1,7 @@
# for .net standard
generatorName: csharp-netcore
outputDir: samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0
# TODO switch to http signature spec after fixing compilation issues
#inputSpec: modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml
templateDir: modules/openapi-generator/src/main/resources/csharp-netcore
additionalProperties:
packageGuid: '{321C8C3F-0156-40C1-AE42-D59761FB9B6C}'

View File

@ -1,6 +1,7 @@
generatorName: typescript-nestjs
outputDir: samples/client/petstore/typescript-nestjs-v6-provided-in-root/builds/default
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/typescript-nestjs
additionalProperties:
nestVersion: 6.0.0
"npmName": "@openapitools/typescript-nestjs-petstore"

View File

@ -1,6 +1,6 @@
---
# csharp-netcore test files and image for upload
- filename: "samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Api/PetApiTests.cs"
sha256: b74ef9eefa4b41fd3233e083fe2355babf25a77f9073d28e1aa81ae2e0a5f1d0
sha256: aceebba316148a2a803a15ef4e13bbd0b0a1b8d15006cd88adb9b39a620ee451
- filename: "samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/linux-logo.png"
sha256: 0a67c32728197e942b13bdda064b73793f12f5c795f1e5cf35a3adf69c973230

View File

@ -21,7 +21,7 @@ Our tooling supports the following types of configuration:
## Tool-specific Declarations
The READMEs for the [CLI](https://openapi-generator.tech/docs/usage#generate), [Gradle Plugin](https://github.com/OpenAPITools/openapi-generator/tree/master/modules/openapi-generator-maven-plugin), [Maven Plugin](https://github.com/OpenAPITools/openapi-generator/tree/master/modules/openapi-generator-maven-plugin), and [SBT Plugin](https://github.com/OpenAPITools/sbt-openapi-generator/blob/master/README.md) may have top-level or tooling specific options which appear to duplicate 'config options' or 'global properties'. Each may also expose user-facing properties slightly differently from the other tools. This may occur due to:
The READMEs for the [CLI](https://openapi-generator.tech/docs/usage#generate), [Gradle Plugin](https://github.com/OpenAPITools/openapi-generator/tree/master/modules/openapi-generator-gradle-plugin), [Maven Plugin](https://github.com/OpenAPITools/openapi-generator/tree/master/modules/openapi-generator-maven-plugin), and [SBT Plugin](https://github.com/OpenAPITools/sbt-openapi-generator/blob/master/README.md) may have top-level or tooling specific options which appear to duplicate 'config options' or 'global properties'. Each may also expose user-facing properties slightly differently from the other tools. This may occur due to:
* Conventions used by the underlying tooling
* Limitations in underlying frameworks which define how properties must be declared

View File

@ -94,7 +94,7 @@ The following generators are available:
* [java-pkmst](generators/java-pkmst.md)
* [java-play-framework](generators/java-play-framework.md)
* [java-undertow-server](generators/java-undertow-server.md)
* [java-vertx](generators/java-vertx.md)
* [java-vertx (deprecated)](generators/java-vertx.md)
* [java-vertx-web (beta)](generators/java-vertx-web.md)
* [jaxrs-cxf](generators/jaxrs-cxf.md)
* [jaxrs-cxf-cdi](generators/jaxrs-cxf-cdi.md)

View File

@ -206,7 +206,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|XMLStructureDefinitions|✗|OAS2,OAS3
|MultiServer|✓|OAS3
|ParameterizedServer|✓|OAS3
|ParameterStyling||OAS3
|ParameterStyling||OAS3
|Callbacks|✗|OAS3
|LinkObjects|✗|OAS3

View File

@ -41,8 +41,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl
| Type/Alias | Instantiated By |
| ---------- | --------------- |
|array|List|
|map|Map|
## LANGUAGE PRIMITIVES

View File

@ -36,8 +36,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl
| Type/Alias | Instantiated By |
| ---------- | --------------- |
|array|List|
|map|Map|
## LANGUAGE PRIMITIVES

View File

@ -34,8 +34,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl
| Type/Alias | Instantiated By |
| ---------- | --------------- |
|array|List|
|map|Map|
## LANGUAGE PRIMITIVES

View File

@ -32,8 +32,8 @@ These options may be applied as additional-properties (cli) or configOptions (pl
| Type/Alias | Imports |
| ---------- | ------- |
|BigDecimal|java.math.BigDecimal|
|Date|java.util.Date|
|DateTime|java.time.LocalDateTime|
|Date|java.time.LocalDate|
|DateTime|java.time.OffsetDateTime|
|File|java.io.File|
|LocalDate|java.time.LocalDate|
|LocalDateTime|java.time.LocalDateTime|

View File

@ -26,8 +26,8 @@ These options may be applied as additional-properties (cli) or configOptions (pl
| Type/Alias | Imports |
| ---------- | ------- |
|BigDecimal|java.math.BigDecimal|
|Date|java.util.Date|
|DateTime|java.time.LocalDateTime|
|Date|java.time.LocalDate|
|DateTime|java.time.OffsetDateTime|
|File|java.io.File|
|LocalDate|java.time.LocalDate|
|LocalDateTime|java.time.LocalDateTime|

View File

@ -34,8 +34,8 @@ These options may be applied as additional-properties (cli) or configOptions (pl
| Type/Alias | Imports |
| ---------- | ------- |
|BigDecimal|java.math.BigDecimal|
|Date|java.util.Date|
|DateTime|java.time.LocalDateTime|
|Date|java.time.LocalDate|
|DateTime|java.time.OffsetDateTime|
|File|java.io.File|
|LocalDate|java.time.LocalDate|
|LocalDateTime|java.time.LocalDateTime|

View File

@ -27,8 +27,8 @@ These options may be applied as additional-properties (cli) or configOptions (pl
| Type/Alias | Imports |
| ---------- | ------- |
|BigDecimal|java.math.BigDecimal|
|Date|java.util.Date|
|DateTime|java.time.LocalDateTime|
|Date|java.time.LocalDate|
|DateTime|java.time.OffsetDateTime|
|File|java.io.File|
|LocalDate|java.time.LocalDate|
|LocalDateTime|java.time.LocalDateTime|

View File

@ -22,7 +22,7 @@ npm install @openapitools/openapi-generator-cli -g
To install a specific version of the tool, pass the version during installation:
<!-- RELEASE_VERSION -->
```bash
openapi-generator-cli version-manager set 4.3.1
openapi-generator-cli version-manager set 5.0.1
```
<!-- /RELEASE_VERSION -->
To install the tool as a dev dependency in your current project:
@ -80,18 +80,18 @@ docker run --rm \
<!-- RELEASE_VERSION -->
If you're looking for the latest stable version, you can grab it directly from Maven.org (Java 8 runtime at a minimum):
JAR location: `https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/4.3.1/openapi-generator-cli-4.3.1.jar`
JAR location: `https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.1/openapi-generator-cli-5.0.1.jar`
For **Mac/Linux** users:
```bash
wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/4.3.1/openapi-generator-cli-4.3.1.jar -O openapi-generator-cli.jar
wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.1/openapi-generator-cli-5.0.1.jar -O openapi-generator-cli.jar
```
For **Windows** users, you will need to install [wget](http://gnuwin32.sourceforge.net/packages/wget.htm) or you can use Invoke-WebRequest in PowerShell (3.0+), e.g.
```powershell
Invoke-WebRequest -OutFile openapi-generator-cli.jar https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/4.3.1/openapi-generator-cli-4.3.1.jar
Invoke-WebRequest -OutFile openapi-generator-cli.jar https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.1/openapi-generator-cli-5.0.1.jar
```
<!-- /RELEASE_VERSION -->

View File

@ -24,7 +24,7 @@ package org.openapitools.codegen.api;
*
* @deprecated as of 5.0, replaced by {@link TemplatingExecutor}.
*/
@Deprecated()
@Deprecated
public interface TemplatingGenerator extends TemplatingExecutor {
}

View File

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

View File

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

View File

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

View File

@ -25,7 +25,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
*/
@Controller
public class HomeController {
@RequestMapping(value = "/")
@RequestMapping("/")
public String index() {
return "redirect:index.html";
}

View File

@ -153,7 +153,7 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
typeMapping.put("ByteArray", "kotlin.ByteArray");
typeMapping.put("number", "java.math.BigDecimal");
typeMapping.put("decimal", "java.math.BigDecimal");
typeMapping.put("date-time", "java.time.LocalDateTime");
typeMapping.put("date-time", "java.time.OffsetDateTime");
typeMapping.put("date", "java.time.LocalDate");
typeMapping.put("file", "java.io.File");
typeMapping.put("array", "kotlin.Array");
@ -163,7 +163,7 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
typeMapping.put("object", "kotlin.Any");
typeMapping.put("binary", "kotlin.ByteArray");
typeMapping.put("Date", "java.time.LocalDate");
typeMapping.put("DateTime", "java.time.LocalDateTime");
typeMapping.put("DateTime", "java.time.OffsetDateTime");
instantiationTypes.put("array", "kotlin.collections.ArrayList");
instantiationTypes.put("list", "kotlin.collections.ArrayList");
@ -174,9 +174,9 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
importMapping.put("UUID", "java.util.UUID");
importMapping.put("URI", "java.net.URI");
importMapping.put("File", "java.io.File");
importMapping.put("Date", "java.util.Date");
importMapping.put("Date", "java.time.LocalDate");
importMapping.put("Timestamp", "java.sql.Timestamp");
importMapping.put("DateTime", "java.time.LocalDateTime");
importMapping.put("DateTime", "java.time.OffsetDateTime");
importMapping.put("LocalDateTime", "java.time.LocalDateTime");
importMapping.put("LocalDate", "java.time.LocalDate");
importMapping.put("LocalTime", "java.time.LocalTime");

View File

@ -898,4 +898,19 @@ public class CLibcurlClientCodegen extends DefaultCodegen implements CodegenConf
}
}
}
@Override
public void postProcess() {
System.out.println("################################################################################");
System.out.println("# Thanks for using OpenAPI Generator. #");
System.out.println("# Please consider donation to help us maintain this project \uD83D\uDE4F #");
System.out.println("# https://opencollective.com/openapi_generator/donate #");
System.out.println("# #");
System.out.println("# This generator is contributed by Hemant Zope (https://github.com/zhemant) #");
System.out.println("# and Niklas Werner (https://github.com/PowerOfCreation). #");
System.out.println("# Please support their work directly \uD83D\uDE4F #");
System.out.println("# > Hemant Zope - https://www.patreon.com/zhemant #");
System.out.println("# > Niklas Werner - https://paypal.me/wernerdevelopment #");
System.out.println("################################################################################");
}
}

View File

@ -46,6 +46,7 @@ public class CppQt5ClientCodegen extends CppQt5AbstractCodegen implements Codege
.includeSecurityFeatures(SecurityFeature.BasicAuth)
.includeSecurityFeatures(SecurityFeature.ApiKey)
.includeSecurityFeatures(SecurityFeature.BearerToken)
.includeGlobalFeatures(GlobalFeature.ParameterStyling)
);
// set the output folder here

View File

@ -141,14 +141,13 @@ public class DartClientCodegen extends DefaultCodegen {
"double",
"dynamic"
);
instantiationTypes.put("array", "List");
instantiationTypes.put("map", "Map");
typeMapping = new HashMap<>();
typeMapping.put("Array", "List");
typeMapping.put("array", "List");
typeMapping.put("map", "Map");
typeMapping.put("List", "List");
typeMapping.put("set", "Set");
typeMapping.put("boolean", "bool");
typeMapping.put("string", "String");
typeMapping.put("char", "String");
@ -468,9 +467,10 @@ public class DartClientCodegen extends DefaultCodegen {
@Override
public String toDefaultValue(Schema schema) {
if (ModelUtils.isMapSchema(schema)) {
if (ModelUtils.isMapSchema(schema) || ModelUtils.isSet(schema)) {
return "const {}";
} else if (ModelUtils.isArraySchema(schema)) {
}
if (ModelUtils.isArraySchema(schema)) {
return "const []";
}
@ -494,7 +494,8 @@ public class DartClientCodegen extends DefaultCodegen {
if (ModelUtils.isArraySchema(target)) {
Schema<?> items = getSchemaItems((ArraySchema) schema);
return getSchemaType(target) + "<" + getTypeDeclaration(items) + ">";
} else if (ModelUtils.isMapSchema(target)) {
}
if (ModelUtils.isMapSchema(target)) {
// Note: ModelUtils.isMapSchema(p) returns true when p is a composed schema that also defines
// additionalproperties: true
Schema<?> inner = getAdditionalProperties(target);

View File

@ -127,6 +127,9 @@ public class DartDioClientCodegen extends DartClientCodegen {
public String toDefaultValue(Schema schema) {
if (schema.getDefault() != null) {
if (ModelUtils.isArraySchema(schema)) {
if (ModelUtils.isSet(schema)) {
return "SetBuilder()";
}
return "ListBuilder()";
}
if (ModelUtils.isMapSchema(schema)) {
@ -318,6 +321,7 @@ public class DartDioClientCodegen extends DartClientCodegen {
if (param.isContainer) {
final Map<String, Object> serializer = new HashMap<>();
serializer.put("isArray", param.isArray);
serializer.put("uniqueItems", param.uniqueItems);
serializer.put("isMap", param.isMap);
serializer.put("baseType", param.baseType);
serializers.add(serializer);
@ -347,7 +351,8 @@ public class DartDioClientCodegen extends DartClientCodegen {
if (op.returnContainer != null) {
final Map<String, Object> serializer = new HashMap<>();
serializer.put("isArray", Objects.equals("array", op.returnContainer));
serializer.put("isArray", Objects.equals("array", op.returnContainer) || Objects.equals("set", op.returnContainer));
serializer.put("uniqueItems", op.uniqueItems);
serializer.put("isMap", Objects.equals("map", op.returnContainer));
serializer.put("baseType", op.returnBaseType);
serializers.add(serializer);

View File

@ -155,7 +155,7 @@ public class FsharpFunctionsServerCodegen extends AbstractFSharpCodegen {
return outputFolder + File.separator + sourceFolder + File.separator + "impl";
}
@Override()
@Override
public String toModelImport(String name) {
return packageName + "." + modelPackage() + "." + name;
}

View File

@ -229,7 +229,7 @@ public class FsharpGiraffeServerCodegen extends AbstractFSharpCodegen {
return outputFolder + File.separator + sourceFolder + File.separator + "impl";
}
@Override()
@Override
public String toModelImport(String name) {
return packageName + "." + modelPackage() + "." + name;
}

View File

@ -24,9 +24,14 @@ import io.swagger.v3.oas.models.PathItem.HttpMethod;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.servers.Server;
import org.openapitools.codegen.*;
import org.openapitools.codegen.meta.GeneratorMetadata;
import org.openapitools.codegen.meta.Stability;
import org.openapitools.codegen.meta.features.DocumentationFeature;
import org.openapitools.codegen.utils.URLPathUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.net.URL;
import java.util.List;
@ -37,6 +42,7 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JavaVertXServerCodegen extends AbstractJavaCodegen {
private static final Logger LOGGER = LoggerFactory.getLogger(JavaVertXServerCodegen.class);
protected String resourceFolder = "src/main/resources";
protected String rootPackage = "org.openapitools.server.api";
@ -61,6 +67,10 @@ public class JavaVertXServerCodegen extends AbstractJavaCodegen {
modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme));
generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata)
.stability(Stability.DEPRECATED)
.build();
// set the output folder here
outputFolder = "generated-code" + File.separator + "javaVertXServer";
@ -134,6 +144,8 @@ public class JavaVertXServerCodegen extends AbstractJavaCodegen {
public void processOpts() {
super.processOpts();
LOGGER.warn("IMPORTANT: This generator has been deprecated. Please use `java-vertx-web` instead");
apiTestTemplateFiles.clear();
importMapping.remove("JsonCreator");

View File

@ -125,17 +125,9 @@ public class KotlinSpringServerCodegen extends AbstractKotlinCodegen
typeMapping.put("array", "kotlin.collections.List");
typeMapping.put("list", "kotlin.collections.List");
typeMapping.put("date", "java.time.LocalDate");
typeMapping.put("date-time", "java.time.OffsetDateTime");
typeMapping.put("Date", "java.time.LocalDate");
typeMapping.put("DateTime", "java.time.OffsetDateTime");
// use resource for file handling
typeMapping.put("file", "org.springframework.core.io.Resource");
importMapping.put("Date", "java.time.LocalDate");
importMapping.put("DateTime", "java.time.OffsetDateTime");
addOption(TITLE, "server title name or client service name", title);
addOption(BASE_PACKAGE, "base package (invokerPackage) for generated code", basePackage);
addOption(SERVER_PORT, "configuration the port in which the sever is to run on", serverPort);

View File

@ -581,4 +581,16 @@ public class LuaClientCodegen extends DefaultCodegen implements CodegenConfig {
return name;
}
@Override
public void postProcess() {
System.out.println("################################################################################");
System.out.println("# Thanks for using OpenAPI Generator. #");
System.out.println("# Please consider donation to help us maintain this project \uD83D\uDE4F #");
System.out.println("# https://opencollective.com/openapi_generator/donate #");
System.out.println("# #");
System.out.println("# This generator is contributed by daurnimator (https://github.com/daurnimator)#");
System.out.println("# Pls support his work directly via https://github.com/sponsors/daurnimator \uD83D\uDE4F #");
System.out.println("################################################################################");
}
}

View File

@ -1107,4 +1107,16 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig
example += ")";
return example;
}
@Override
public void postProcess() {
System.out.println("################################################################################");
System.out.println("# Thanks for using OpenAPI Generator. #");
System.out.println("# Please consider donation to help us maintain this project \uD83D\uDE4F #");
System.out.println("# https://opencollective.com/openapi_generator/donate #");
System.out.println("# #");
System.out.println("# swift5 generator is contributed by Bruno Coelho (https://github.com/4brunu). #");
System.out.println("# Please support his work directly via https://paypal.com/paypalme/4brunu \uD83D\uDE4F #");
System.out.println("################################################################################");
}
}

View File

@ -1,6 +1,8 @@
{{>licenseInfo}}
pragma Warnings (Off, "*is not referenced");
with Swagger.Streams;
package body {{package}}.Clients is
pragma Style_Checks ("-mr");
{{#apiInfo}}
{{#apis}}
{{#operations}}

View File

@ -4,6 +4,7 @@
with {{package}}.Models;
with Swagger.Clients;
package {{package}}.Clients is
pragma Style_Checks ("-mr");
type Client_Type is new Swagger.Clients.Client_Type with null record;

View File

@ -3,12 +3,11 @@ abstract project Config is
type Yes_No is ("yes", "no");
type Library_Type_Type is ("relocatable", "static");
type Library_Type_Type is ("relocatable", "static", "static-pic");
type Mode_Type is ("distrib", "debug", "optimize", "profile");
Mode : Mode_Type := external ("MODE", "debug");
type Build_Type is ("distrib", "debug", "optimize", "profile", "coverage");
Mode : Build_Type := external ("BUILD", "debug");
Coverage : Yes_No := External ("COVERAGE", "no");
Processors := External ("PROCESSORS", "1");
package Builder is
@ -29,7 +28,12 @@ abstract project Config is
when "debug" =>
for Default_Switches ("Ada") use defaults & warnings
& ("-gnata", "-gnatVaMI", "-gnaty3abcefhiklmnprstxM99");
& ("-gnata", "-gnatVaMI", "-gnaty3abcefhiklmnprstxM127");
when "coverage" =>
for Default_Switches ("Ada") use defaults & warnings
& ("-gnata", "-gnatVaMI", "-gnaty3abcefhiklmnprstxM127",
"-fprofile-arcs", "-ftest-coverage");
when "optimize" =>
for Default_Switches ("Ada") use defaults & warnings
@ -37,13 +41,7 @@ abstract project Config is
when "profile" =>
for Default_Switches ("Ada") use defaults & warnings & ("-pg");
end case;
case Coverage is
when "yes" =>
for Default_Switches ("ada") use Compiler'Default_Switches ("Ada") &
("-fprofile-arcs", "-ftest-coverage");
when others =>
end case;
end compiler;
@ -69,16 +67,13 @@ abstract project Config is
when "optimize" =>
for Default_Switches ("Ada") use ("-Wl,--gc-sections");
when "coverage" =>
for Default_Switches ("ada") use ("-fprofile-arcs");
when others =>
null;
end case;
case Coverage is
when "yes" =>
for Default_Switches ("ada") use Linker'Default_Switches ("ada") &
("-fprofile-arcs");
when others =>
end case;
end linker;
package Ide is

View File

@ -2,7 +2,7 @@
-- {{{appDescription}}}
--
-- {{#version}}The version of the OpenAPI document: {{{version}}}{{/version}}
-- {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}}
--{{#infoEmail}} Contact: {{{infoEmail}}}{{/infoEmail}}
--
-- NOTE: This package is auto generated by OpenAPI-Generator {{{generatorVersion}}}.
-- https://openapi-generator.tech

View File

@ -1,6 +1,9 @@
{{>licenseInfo}}
package body {{package}}.Models is
pragma Style_Checks ("-mr");
pragma Warnings (Off, "*use clause for package*");
use Swagger.Streams;

View File

@ -4,6 +4,7 @@
with Swagger.Streams;
with Ada.Containers.Vectors;
package {{package}}.Models is
pragma Style_Checks ("-mr");
{{#orderedModels}}{{#model}}{{^isArray}}
{{#title}} -- ------------------------------

View File

@ -1,7 +1,12 @@
{{>licenseInfo}}
pragma Warnings (Off, "*is not referenced");
with Swagger.Streams;
with Swagger.Servers.Operation;
package body {{package}}.Skeletons is
pragma Style_Checks ("-mr");
pragma Warnings (Off, "*use clause for package*");
use Swagger.Streams;
package body Skeleton is
@ -58,7 +63,7 @@ package body {{package}}.Skeletons is
{{#hasParams}}
{{#hasBodyParam}}
Swagger.Servers.Read (Req, Input);
{{#bodyParams}}{{#vendorExtensions.x-is-model-type}}
{{#bodyParams}}{{#vendorExtensions.x-is-model-type}}
{{package}}.Models.Deserialize (Input, "{{baseName}}", {{paramName}});{{/vendorExtensions.x-is-model-type}}{{^vendorExtensions.x-is-model-type}}{{#isFile}}
-- TODO: Serialize (Input.Stream, "{{basename}}", {{paramName}});{{/isFile}}{{^isFile}}{{^isLong}}
Deserialize (Input, "{{baseName}}", {{paramName}});{{/isLong}}{{#isLong}}

View File

@ -1,10 +1,14 @@
{{>licenseInfo}}
{{#imports}}with {{import}};
{{/imports}}
pragma Warnings (Off, "*is not referenced");
pragma Warnings (Off, "*no entities of*are referenced");
with Swagger.Servers;
with {{package}}.Models;
with Security.Permissions;
package {{package}}.Skeletons is
pragma Style_Checks ("-mr");
pragma Warnings (Off, "*use clause for package*");
use {{package}}.Models;
type Server_Type is limited interface;
{{#authMethods}}{{#scopes}}

View File

@ -15,6 +15,7 @@ with Swagger.Servers;
with {{package}}.Models;
with {{package}}.Skeletons;
package {{package}}.Servers is
pragma Warnings (Off, "*use clause for package*");
use {{package}}.Models;
type Server_Type is limited new {{package}}.Skeletons.Server_Type with null record;

View File

@ -1,6 +1,6 @@
{{>licenseInfo}}
package {{invokerPackage}}.model;
package {{modelPackage}};
import {{invokerPackage}}.ApiException;
import java.util.Objects;

View File

@ -18,6 +18,10 @@ import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.Charset;
import java.time.Duration;
{{#java8}}
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
{{/java8}}
import java.util.Collection;
import java.util.Collections;
import java.util.List;
@ -57,6 +61,11 @@ public class ApiClient {
if (value == null) {
return "";
}
{{#java8}}
if (value instanceof OffsetDateTime) {
return ((OffsetDateTime) value).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
}
{{/java8}}
return value.toString();
}
@ -87,7 +96,7 @@ public class ApiClient {
if (name == null || name.isEmpty() || value == null) {
return Collections.emptyList();
}
return Collections.singletonList(new Pair(urlEncode(name), urlEncode(value.toString())));
return Collections.singletonList(new Pair(urlEncode(name), urlEncode(valueToString(value))));
}
/**
@ -156,6 +165,7 @@ public class ApiClient {
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
mapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
mapper.registerModule(new JavaTimeModule());
{{#openApiNullable}}
JsonNullableModule jnm = new JsonNullableModule();

View File

@ -330,16 +330,16 @@
<java.version>{{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}}</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<gson-fire-version>1.8.4</gson-fire-version>
<swagger-core-version>1.5.24</swagger-core-version>
<okhttp-version>3.14.7</okhttp-version>
<gson-fire-version>1.8.5</gson-fire-version>
<swagger-core-version>1.6.2</swagger-core-version>
<okhttp-version>4.9.1</okhttp-version>
<gson-version>2.8.6</gson-version>
<commons-lang3-version>3.10</commons-lang3-version>
<commons-lang3-version>3.11</commons-lang3-version>
{{#joda}}
<jodatime-version>2.9.9</jodatime-version>
<jodatime-version>2.10.9</jodatime-version>
{{/joda}}
{{#threetenbp}}
<threetenbp-version>1.4.3</threetenbp-version>
<threetenbp-version>1.5.0</threetenbp-version>
{{/threetenbp}}
<javax-annotation-version>1.3.2</javax-annotation-version>
<junit-version>4.13.1</junit-version>

View File

@ -576,7 +576,7 @@
*/
{{/emitJSDoc}} exports.parseDate = function(str) {
if (isNaN(str)) {
return new Date(str.replace(/T/i, ' '));
return new Date(str.replace(/(\d)(T)(\d)/i, '$1 $3'));
}
return new Date(+str);
};

View File

@ -556,7 +556,7 @@ class ApiClient {
*/{{/emitJSDoc}}
static parseDate(str) {
if (isNaN(str)) {
return new Date(str);
return new Date(str.replace(/(\d)(T)(\d)/i, '$1 $3'));
}
return new Date(+str);
}

View File

@ -139,15 +139,73 @@ void {{classname}}::abortRequests(){
emit abortRequestsSignal();
}
QString {{classname}}::getParamStylePrefix(QString style){
if(style == "matrix"){
return ";";
}else if(style == "label"){
return ".";
}else if(style == "form"){
return "&";
}else if(style == "simple"){
return "";
}else if(style == "spaceDelimited"){
return "&";
}else if(style == "pipeDelimited"){
return "&";
}else
return "none";
}
QString {{classname}}::getParamStyleSuffix(QString style){
if(style == "matrix"){
return "=";
}else if(style == "label"){
return "";
}else if(style == "form"){
return "=";
}else if(style == "simple"){
return "";
}else if(style == "spaceDelimited"){
return "=";
}else if(style == "pipeDelimited"){
return "=";
}else
return "none";
}
QString {{classname}}::getParamStyleDelimiter(QString style, QString name, bool isExplode){
if(style == "matrix"){
return (isExplode) ? ";" + name + "=" : ",";
}else if(style == "label"){
return (isExplode) ? "." : ",";
}else if(style == "form"){
return (isExplode) ? "&" + name + "=" : ",";
}else if(style == "simple"){
return ",";
}else if(style == "spaceDelimited"){
return (isExplode) ? "&" + name + "=" : " ";
}else if(style == "pipeDelimited"){
return (isExplode) ? "&" + name + "=" : "|";
}else if(style == "deepObject"){
return (isExplode) ? "&" : "none";
}else
return "none";
}
{{#operations}}
{{#operation}}
void {{classname}}::{{nickname}}({{#allParams}}const {{{dataType}}} &{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) {
QString fullPath = QString(_serverConfigs["{{nickname}}"][_serverIndices.value("{{nickname}}")].URL()+"{{{path}}}");
{{#pathParams}}
QString {{paramName}}PathParam("{");
{{paramName}}PathParam.append("{{baseName}}").append("}");
fullPath.replace({{paramName}}PathParam, QUrl::toPercentEncoding(::{{cppNamespace}}::toStringValue({{paramName}})));
{{/pathParams}}{{#authMethods}}{{#isApiKey}}{{#isKeyInHeader}}
{{#authMethods}}{{#isApiKey}}{{#isKeyInHeader}}
if(_apiKeys.contains("{{name}}")){
addHeaders("{{name}}",_apiKeys.find("{{name}}").value());
}
@ -168,18 +226,148 @@ void {{classname}}::{{nickname}}({{#allParams}}const {{{dataType}}} &{{paramName
b64.append(_username.toUtf8() + ":" + _password.toUtf8());
addHeaders("Authorization","Basic " + b64.toBase64());
}{{/isBasicBasic}}{{/authMethods}}
{{#queryParams}}{{^collectionFormat}}
{{#pathParams}}
QString {{paramName}}PathParam("{");
{{paramName}}PathParam.append("{{baseName}}").append("}");
QString pathPrefix, pathSuffix, pathDelimiter;
QString pathStyle = "{{style}}";
if(pathStyle == "")
pathStyle = "simple";
pathPrefix = getParamStylePrefix(pathStyle);
pathSuffix = getParamStyleSuffix(pathStyle);
pathDelimiter = getParamStyleDelimiter(pathStyle, "{{baseName}}", {{isExplode}});
{{^collectionFormat}}
{{^isPrimitiveType}}
QString paramString = (pathStyle == "matrix" && {{isExplode}}) ? pathPrefix : pathPrefix+"{{baseName}}"+pathSuffix;
QJsonObject parameter = {{paramName}}.asJsonObject();
qint32 count = 0;
foreach(const QString& key, parameter.keys()) {
if (count > 0) {
pathDelimiter = (pathStyle == "matrix" && {{isExplode}}) ? ";" : getParamStyleDelimiter(pathStyle, key, {{isExplode}});
paramString.append(pathDelimiter);
}
QString assignOperator = ({{isExplode}}) ? "=" : ",";
switch(parameter.value(key).type()) {
case QJsonValue::String:
{
paramString.append(key+assignOperator+parameter.value(key).toString());
break;
}
case QJsonValue::Double:
{
paramString.append(key+assignOperator+QString::number(parameter.value(key).toDouble()));
break;
}
case QJsonValue::Bool:
{
paramString.append(key+assignOperator+QVariant(parameter.value(key).toBool()).toString());
break;
}
case QJsonValue::Array:
{
paramString.append(key+assignOperator+QVariant(parameter.value(key).toArray()).toString());
break;
}
case QJsonValue::Object:
{
paramString.append(key+assignOperator+QVariant(parameter.value(key).toObject()).toString());
break;
}
case QJsonValue::Null:
case QJsonValue::Undefined:
break;
}
count++;
}
fullPath.replace({{paramName}}PathParam, QUrl::toPercentEncoding(paramString));
{{/isPrimitiveType}}
{{#isPrimitiveType}}
QString paramString = (pathStyle == "matrix") ? pathPrefix+"{{baseName}}"+pathSuffix : pathPrefix;
fullPath.replace({{paramName}}PathParam, paramString+QUrl::toPercentEncoding(::{{cppNamespace}}::toStringValue({{paramName}})));
{{/isPrimitiveType}}{{/collectionFormat}}{{#collectionFormat}}
if ({{{paramName}}}.size() > 0) {
QString paramString = (pathStyle == "matrix") ? pathPrefix+"{{baseName}}"+pathSuffix : pathPrefix;
qint32 count = 0;
foreach ({{{baseType}}} t, {{paramName}}) {
if (count > 0) {
fullPath.append(pathDelimiter);
}
fullPath.append(QUrl::toPercentEncoding(::{{cppNamespace}}::toStringValue(t)));
count++;
}
fullPath.replace({{paramName}}PathParam, paramString);
}
{{/collectionFormat}}{{/pathParams}}
{{#hasQueryParams}}
QString queryPrefix, querySuffix, queryDelimiter, queryStyle;
{{/hasQueryParams}}
{{#queryParams}}
queryStyle = "{{style}}";
if(queryStyle == "")
queryStyle = "form";
queryPrefix = getParamStylePrefix(queryStyle);
querySuffix = getParamStyleSuffix(queryStyle);
queryDelimiter = getParamStyleDelimiter(queryStyle, "{{baseName}}", {{isExplode}});
{{^collectionFormat}}
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
fullPath.append(queryPrefix);
else
fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("{{baseName}}")).append("=").append(QUrl::toPercentEncoding(::{{cppNamespace}}::toStringValue({{paramName}})));
{{/collectionFormat}}{{#collectionFormat}}
{{^isPrimitiveType}}
QString paramString = (queryStyle == "form" && {{isExplode}}) ? "" : (queryStyle == "form" && !({{isExplode}})) ? "{{baseName}}"+querySuffix : "";
QJsonObject parameter = {{paramName}}.asJsonObject();
qint32 count = 0;
foreach(const QString& key, parameter.keys()) {
if (count > 0) {
queryDelimiter = ((queryStyle == "form" || queryStyle == "deepObject") && {{isExplode}}) ? "&" : getParamStyleDelimiter(queryStyle, key, {{isExplode}});
paramString.append(queryDelimiter);
}
QString assignOperator;
if (queryStyle == "form")
assignOperator = ({{isExplode}}) ? "=" : ",";
else if (queryStyle == "deepObject")
assignOperator = ({{isExplode}}) ? "=" : "none";
switch(parameter.value(key).type()) {
case QJsonValue::String:
{
paramString.append(((queryStyle == "form") ? key : QString("{{baseName}}").append("[").append(key).append("]"))+assignOperator+parameter.value(key).toString());
break;
}
case QJsonValue::Double:
{
paramString.append(((queryStyle == "form") ? key : QString("{{baseName}}").append("[").append(key).append("]"))+assignOperator+QString::number(parameter.value(key).toDouble()));
break;
}
case QJsonValue::Bool:
{
paramString.append(((queryStyle == "form") ? key : QString("{{baseName}}").append("[").append(key).append("]"))+assignOperator+QVariant(parameter.value(key).toBool()).toString());
break;
}
case QJsonValue::Array:
{
paramString.append(((queryStyle == "form") ? key : QString("{{baseName}}").append("[").append(key).append("]"))+assignOperator+QVariant(parameter.value(key).toArray()).toString());
break;
}
case QJsonValue::Object:
{
paramString.append(((queryStyle == "form") ? key : QString("{{baseName}}").append("[").append(key).append("]"))+assignOperator+QVariant(parameter.value(key).toObject()).toString());
break;
}
case QJsonValue::Null:
case QJsonValue::Undefined:
break;
}
count++;
}
fullPath.append(paramString);
{{/isPrimitiveType}}{{#isPrimitiveType}}
fullPath.append(QUrl::toPercentEncoding("{{baseName}}")).append(querySuffix).append(QUrl::toPercentEncoding(::{{cppNamespace}}::toStringValue({{paramName}})));
{{/isPrimitiveType}}{{/collectionFormat}}{{#collectionFormat}}
if ({{{paramName}}}.size() > 0) {
if (QString("{{collectionFormat}}").indexOf("multi") == 0) {
foreach ({{{baseType}}} t, {{paramName}}) {
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
fullPath.append(queryPrefix);
else
fullPath.append("?");
fullPath.append("{{{baseName}}}=").append(::{{cppNamespace}}::toStringValue(t));
@ -188,27 +376,66 @@ void {{classname}}::{{nickname}}({{#allParams}}const {{{dataType}}} &{{paramName
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append("{{baseName}}=");
fullPath.append("?").append(queryPrefix).append("{{baseName}}").append(querySuffix);
qint32 count = 0;
foreach ({{{baseType}}} t, {{paramName}}) {
if (count > 0) {
fullPath.append(" ");
fullPath.append(({{isExplode}})? queryDelimiter : QUrl::toPercentEncoding(queryDelimiter));
}
fullPath.append(::{{cppNamespace}}::toStringValue(t));
count++;
}
} else if (QString("{{collectionFormat}}").indexOf("tsv") == 0) {
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append("{{baseName}}=");
fullPath.append("?").append(queryPrefix).append("{{baseName}}").append(querySuffix);
qint32 count = 0;
foreach ({{{baseType}}} t, {{paramName}}) {
if (count > 0) {
fullPath.append("\t");
}
fullPath.append(::{{cppNamespace}}::toStringValue(t));
count++;
}
} else if (QString("{{collectionFormat}}").indexOf("csv") == 0) {
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?").append(queryPrefix).append("{{baseName}}").append(querySuffix);
qint32 count = 0;
foreach ({{{baseType}}} t, {{paramName}}) {
if (count > 0) {
fullPath.append(queryDelimiter);
}
fullPath.append(::{{cppNamespace}}::toStringValue(t));
count++;
}
} else if (QString("{{collectionFormat}}").indexOf("pipes") == 0) {
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?").append(queryPrefix).append("{{baseName}}").append(querySuffix);
qint32 count = 0;
foreach ({{{baseType}}} t, {{paramName}}) {
if (count > 0) {
fullPath.append(queryDelimiter);
}
fullPath.append(::{{cppNamespace}}::toStringValue(t));
count++;
}
} else if (QString("{{collectionFormat}}").indexOf("deepObject") == 0) {
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?").append(queryPrefix).append("{{baseName}}").append(querySuffix);
qint32 count = 0;
foreach ({{{baseType}}} t, {{paramName}}) {
if (count > 0) {
fullPath.append(queryDelimiter);
}
fullPath.append(::{{cppNamespace}}::toStringValue(t));
count++;
}
}
}
@ -219,7 +446,18 @@ void {{classname}}::{{nickname}}({{#allParams}}const {{{dataType}}} &{{paramName
worker->setResponseCompressionEnabled(isResponseCompressionEnabled);
worker->setRequestCompressionEnabled(isRequestCompressionEnabled);{{/contentCompression}}
{{prefix}}HttpRequestInput input(fullPath, "{{httpMethod}}");
{{#formParams}}{{^isFile}}
{{#formParams}}
{{#first}}
QString formPrefix,formSuffix, formDelimiter;
QString formStyle = "{{style}}";
if(formStyle == "")
formStyle = "form";
formPrefix = getParamStylePrefix(formStyle);
formSuffix = getParamStyleSuffix(formStyle);
formDelimiter = getParamStyleDelimiter(formStyle, "{{baseName}}", {{isExplode}});
{{/first}}
{{^isFile}}
input.add_var("{{baseName}}", ::{{cppNamespace}}::toStringValue({{paramName}}));{{/isFile}}{{#isFile}}
input.add_file("{{baseName}}", {{paramName}}.local_filename, {{paramName}}.request_filename, {{paramName}}.mime_type);{{/isFile}}{{/formParams}}{{#bodyParams}}{{#isContainer}}{{#isArray}}
QJsonDocument doc(::{{cppNamespace}}::toJsonValue({{paramName}}).toArray());{{/isArray}}{{#isMap}}
@ -232,11 +470,130 @@ void {{classname}}::{{nickname}}({{#allParams}}const {{{dataType}}} &{{paramName
QByteArray output = {{paramName}}.asByteArray();{{/isFile}}
input.request_body.append(output);
{{/isContainer}}{{/bodyParams}}{{#headerParams}}
{{^collectionFormat}}{{^isPrimitiveType}}
QString headerString;
QJsonObject parameter = {{paramName}}.asJsonObject();
qint32 count = 0;
foreach(const QString& key, parameter.keys()) {
if (count > 0) {
headerString.append(",");
}
QString assignOperator = ({{isExplode}}) ? "=" : ",";
switch(parameter.value(key).type()) {
case QJsonValue::String:
{
headerString.append(key+assignOperator+parameter.value(key).toString());
break;
}
case QJsonValue::Double:
{
headerString.append(key+assignOperator+QString::number(parameter.value(key).toDouble()));
break;
}
case QJsonValue::Bool:
{
headerString.append(key+assignOperator+QVariant(parameter.value(key).toBool()).toString());
break;
}
case QJsonValue::Array:
{
headerString.append(key+assignOperator+QVariant(parameter.value(key).toArray()).toString());
break;
}
case QJsonValue::Object:
{
headerString.append(key+assignOperator+QVariant(parameter.value(key).toObject()).toString());
break;
}
case QJsonValue::Null:
case QJsonValue::Undefined:
break;
}
count++;
}
input.headers.insert("{{baseName}}", headerString);
{{/isPrimitiveType}}{{#isPrimitiveType}}
if (!::{{cppNamespace}}::toStringValue({{paramName}}).isEmpty()) {
input.headers.insert("{{baseName}}", ::{{cppNamespace}}::toStringValue({{paramName}}));
}
{{/isPrimitiveType}}{{/collectionFormat}}{{#collectionFormat}}
QString headerString;
if ({{{paramName}}}.size() > 0) {
qint32 count = 0;
foreach ({{{baseType}}} t, {{paramName}}) {
if (count > 0) {
headerString.append(",");
}
headerString.append(::{{cppNamespace}}::toStringValue(t));
count++;
}
input.headers.insert("{{baseName}}", headerString);
}
{{/collectionFormat}}
{{/headerParams}}
{{#cookieParams}}
if(QString("{{style}}").indexOf("form") == 0){
{{^collectionFormat}}{{^isPrimitiveType}}{{^isExplode}}
QString cookieString = "{{baseName}}=";
QJsonObject parameter = {{paramName}}.asJsonObject();
qint32 count = 0;
foreach(const QString& key, parameter.keys()) {
if (count > 0) {
cookieString.append(",");
}
switch(parameter.value(key).type()) {
case QJsonValue::String:
{
cookieString.append(key+","+parameter.value(key).toString());
break;
}
case QJsonValue::Double:
{
cookieString.append(key+","+QString::number(parameter.value(key).toDouble()));
break;
}
case QJsonValue::Bool:
{
cookieString.append(key+","+QVariant(parameter.value(key).toBool()).toString());
break;
}
case QJsonValue::Array:
{
cookieString.append(key+","+QVariant(parameter.value(key).toArray()).toString());
break;
}
case QJsonValue::Object:
{
cookieString.append(key+","+QVariant(parameter.value(key).toObject()).toString());
break;
}
case QJsonValue::Null:
case QJsonValue::Undefined:
break;
}
count++;
}
input.headers.insert("Cookie", cookieString);
{{/isExplode}}{{/isPrimitiveType}}{{#isPrimitiveType}}
if (!::{{cppNamespace}}::toStringValue({{paramName}}).isEmpty()) {
input.headers.insert("Cookie", "{{baseName}}="+::{{cppNamespace}}::toStringValue({{paramName}}));
}
{{/isPrimitiveType}}{{/collectionFormat}}{{#collectionFormat}}{{^isExplode}}
QString cookieString = "{{baseName}}=";
if ({{{paramName}}}.size() > 0) {
qint32 count = 0;
foreach ({{{baseType}}} t, {{paramName}}) {
if (count > 0) {
cookieString.append(",");
}
cookieString.append(::{{cppNamespace}}::toStringValue(t));
count++;
}
input.headers.insert("Cookie", cookieString);
}
{{/isExplode}}{{/collectionFormat}}
}
{{/cookieParams}}
foreach (QString key, this->defaultHeaders.keys()) { input.headers.insert(key, this->defaultHeaders.value(key)); }
connect(worker, &{{prefix}}HttpRequestWorker::on_execution_finished, this, &{{classname}}::{{nickname}}Callback);

View File

@ -43,6 +43,9 @@ public:
void enableRequestCompression();
void enableResponseCompression();
void abortRequests();
QString getParamStylePrefix(QString style);
QString getParamStyleSuffix(QString style);
QString getParamStyleDelimiter(QString style, QString name, bool isExplode);
{{#operations}}{{#operation}}
void {{nickname}}({{#allParams}}const {{{dataType}}} &{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{/operation}}{{/operations}}

View File

@ -55,7 +55,7 @@ module {{moduleName}}
{{^isContainer}}
# verify enum value
allowable_values = [{{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}]
if @api_client.config.client_side_validation && !allowable_values.include?({{{paramName}}})
if @api_client.config.client_side_validation && !allowable_values.includes?({{{paramName}}})
raise ArgumentError.new("invalid value for \"{{{paramName}}}\", must be one of #{allowable_values}")
end
{{/isContainer}}
@ -66,13 +66,13 @@ module {{moduleName}}
{{#isEnum}}
{{#collectionFormat}}
allowable_values = [{{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}]
if @api_client.config.client_side_validation && {{{paramName}}} && {{{paramName}}}.all? { |item| allowable_values.include?(item) }
if @api_client.config.client_side_validation && {{{paramName}}} && {{{paramName}}}.all? { |item| allowable_values.includes?(item) }
raise ArgumentError.new("invalid value for \"{{{paramName}}}\", must include one of #{allowable_values}")
end
{{/collectionFormat}}
{{^collectionFormat}}
allowable_values = [{{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}]
if @api_client.config.client_side_validation && {{{paramName}}} && !allowable_values.include?({{{paramName}}}])
if @api_client.config.client_side_validation && {{{paramName}}} && !allowable_values.includes?({{{paramName}}})
raise ArgumentError.new("invalid value for \"{{{paramName}}}\", must be one of #{allowable_values}")
end
{{/collectionFormat}}

View File

@ -342,7 +342,7 @@ module {{moduleName}}
:verbose => @config.debugging
}
if [:post, :patch, :put, :delete].include?(http_method)
if [:post, :patch, :put, :delete].includes?(http_method)
req_body = build_request_body(header_params, form_params, opts[:body])
req_opts.update body: req_body
if @config.debugging

View File

@ -81,7 +81,7 @@
:verbose => @config.debugging
}
if [:post, :patch, :put, :delete].include?(http_method)
if [:post, :patch, :put, :delete].includes?(http_method)
req_body = build_request_body(header_params, form_params, opts[:body])
req_opts.update body: req_body
if @config.debugging

View File

@ -73,7 +73,7 @@
# set custom cert, if provided
req_opts[:cainfo] = @config.ssl_ca_cert if @config.ssl_ca_cert
if [:post, :patch, :put, :delete].include?(http_method)
if [:post, :patch, :put, :delete].includes?(http_method)
req_body = build_request_body(header_params, form_params, opts[:body])
req_opts.update body: req_body
if @config.debugging

View File

@ -14,7 +14,7 @@
super(attributes)
{{/parent}}
self.class.openapi_types.each_pair do |key, type|
if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key)
if !attributes[self.class.attribute_map[key]]? && self.class.openapi_nullable.includes?(key)
self.send("#{key}=", nil)
elsif type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the attribute
@ -92,7 +92,7 @@
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
if value.nil?
is_nullable = self.class.openapi_nullable.include?(attr)
is_nullable = self.class.openapi_nullable.includes?(attr)
next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}"))
end

View File

@ -334,12 +334,12 @@ module {{moduleName}}
server = servers[index]
url = server[:url]
return url unless server.key? :variables
return url unless server.has_key? :variables
# go through variable and assign a value
server[:variables].each do |name, variable|
if variables.key?(name)
if (!server[:variables][name].key?(:enum_values) || server[:variables][name][:enum_values].include?(variables[name]))
if variables.has_key?(name)
if (!server[:variables][name].has_key?(:enum_values) || server[:variables][name][:enum_values].includes?(variables[name]))
url.gsub! "{" + name.to_s + "}", variables[name]
else
raise ArgumentError.new("The variable `#{name}` in the server URL has invalid value #{variables[name]}. Must be #{server[:variables][name][:enum_values]}.")

View File

@ -30,7 +30,7 @@
end
def valid?(value)
!value || allowable_values.include?(value)
!value || allowable_values.includes?(value)
end
end
@ -225,7 +225,7 @@
{{/isNullable}}
{{#maxLength}}
if {{^required}}!{{{name}}}.nil? && {{/required}}{{{name}}}.to_s.length > {{{maxLength}}}
raise ArgumentError.new("invalid value for "{{{name}}}", the character length must be smaller than or equal to {{{maxLength}}}.")
raise ArgumentError.new("invalid value for \"{{{name}}}\", the character length must be smaller than or equal to {{{maxLength}}}.")
end
{{/maxLength}}

View File

@ -75,7 +75,7 @@
end
end
openapi_one_of.include?(:AnyType) ? data : nil
openapi_one_of.includes?(:AnyType) ? data : nil
{{/discriminator}}
end
{{^discriminator}}

View File

@ -472,6 +472,19 @@ namespace {{packageName}}.Client
response = client.Execute<T>(req);
}
// if the response type is oneOf/anyOf, call FromJSON to deserialize the data
if (typeof({{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema).IsAssignableFrom(typeof(T)))
{
T instance = (T)Activator.CreateInstance(typeof(T));
MethodInfo method = typeof(T).GetMethod("FromJson");
method.Invoke(instance, new object[] { response.Content });
response.Data = instance;
}
else if (typeof(T).Name == "Stream") // for binary response
{
response.Data = (T)(object)new MemoryStream(response.RawBytes);
}
InterceptResponse(req, response);
var result = ToApiResponse(response);
@ -583,6 +596,10 @@ namespace {{packageName}}.Client
method.Invoke(instance, new object[] { response.Content });
response.Data = instance;
}
else if (typeof(T).Name == "Stream") // for binary response
{
response.Data = (T)(object)new MemoryStream(response.RawBytes);
}
InterceptResponse(req, response);

View File

@ -329,9 +329,22 @@ namespace {{packageName}}.Client
#if (NETCOREAPP3_0 || NETCOREAPP3_1 || NET5_0)
var byteCount = 0;
if (configuration.KeyPassPhrase != null)
if (KeyPassPhrase != null)
{
ecdsa.ImportEncryptedPkcs8PrivateKey(keyPassPhrase, keyBytes, out byteCount);
IntPtr unmanagedString = IntPtr.Zero;
try
{
// convert secure string to byte array
unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(KeyPassPhrase);
ecdsa.ImportEncryptedPkcs8PrivateKey(Encoding.UTF8.GetBytes(Marshal.PtrToStringUni(unmanagedString)), keyBytes, out byteCount);
}
finally
{
if (unmanagedString != IntPtr.Zero)
{
Marshal.ZeroFreeBSTR(unmanagedString);
}
}
}
else
{

View File

@ -11,10 +11,12 @@ import 'package:built_value/serializer.dart';
{{/fullImports}}
class {{classname}} {
final Dio _dio;
Serializers _serializers;
{{classname}}(this._dio, this._serializers);
final Dio _dio;
final Serializers _serializers;
const {{classname}}(this._dio, this._serializers);
{{#operation}}
/// {{{summary}}}
@ -69,7 +71,7 @@ class {{classname}} {
{{#isContainer}}
{{#isArray}}
const type = FullType(BuiltList, [FullType({{baseType}})]);
const type = FullType(Built{{#uniqueItems}}Built{{/uniqueItems}}{{^uniqueItems}}List{{/uniqueItems}}, [FullType({{baseType}})]);
final serializedBody = _serializers.serialize({{paramName}}, specifiedType: type);
{{/isArray}}
{{#isMap}}
@ -135,8 +137,7 @@ class {{classname}} {
{{/returnTypeIsPrimitive}}
{{/returnSimpleType}}
{{^returnSimpleType}}
const collectionType = {{#isMap}}BuiltMap{{/isMap}}{{^isMap}}BuiltList{{/isMap}};
const type = FullType(collectionType, [{{#isMap}}FullType(String), {{/isMap}}FullType({{{returnBaseType}}})]);
const type = FullType(Built{{#isMap}}Map{{/isMap}}{{#isArray}}{{#uniqueItems}}Set{{/uniqueItems}}{{^uniqueItems}}List{{/uniqueItems}}{{/isArray}}, [{{#isMap}}FullType(String), {{/isMap}}FullType({{{returnBaseType}}})]);
final data = _serializers.deserialize(
response.data is String
? jsonDecode(response.data as String)
@ -149,6 +150,7 @@ class {{classname}} {
return Response<{{{returnType}}}>(
data: data,
headers: response.headers,
isRedirect: response.isRedirect,
request: response.request,
redirects: response.redirects,
statusCode: response.statusCode,

View File

@ -10,31 +10,37 @@ import 'package:{{pubName}}/auth/oauth.dart';
{{#apiInfo}}{{#apis}}import 'package:{{pubName}}/api/{{classFilename}}.dart';
{{/apis}}{{/apiInfo}}
final _defaultInterceptors = [OAuthInterceptor(), BasicAuthInterceptor(), ApiKeyAuthInterceptor()];
final _defaultInterceptors = [
OAuthInterceptor(),
BasicAuthInterceptor(),
ApiKeyAuthInterceptor(),
];
class {{clientName}} {
Dio dio;
Serializers serializers;
String basePath = '{{{basePath}}}';
static const String basePath = r'{{{basePath}}}';
{{clientName}}({this.dio, Serializers serializers, String basePathOverride, List<Interceptor> interceptors}) {
if (dio == null) {
BaseOptions options = new BaseOptions(
final Dio dio;
final Serializers serializers;
{{clientName}}({
Dio dio,
Serializers serializers,
String basePathOverride,
List<Interceptor> interceptors,
}) : this.serializers = serializers ?? standardSerializers,
this.dio = dio ??
Dio(BaseOptions(
baseUrl: basePathOverride ?? basePath,
connectTimeout: 5000,
receiveTimeout: 3000,
);
this.dio = new Dio(options);
}
if (interceptors == null) {
this.dio.interceptors.addAll(_defaultInterceptors);
} else {
this.dio.interceptors.addAll(interceptors);
}
this.serializers = serializers ?? standardSerializers;
)) {
if (interceptors == null) {
this.dio.interceptors.addAll(_defaultInterceptors);
} else {
this.dio.interceptors.addAll(interceptors);
}
}
void setOAuthToken(String name, String token) {

View File

@ -4,6 +4,9 @@ import 'package:built_value/serializer.dart';
import 'package:time_machine/time_machine.dart';
class OffsetDateSerializer implements PrimitiveSerializer<OffsetDate> {
const OffsetDateSerializer();
@override
Iterable<Type> get types => BuiltList<Type>([OffsetDate]);
@ -25,6 +28,9 @@ class OffsetDateSerializer implements PrimitiveSerializer<OffsetDate> {
}
class OffsetDateTimeSerializer implements PrimitiveSerializer<OffsetDateTime> {
const OffsetDateTimeSerializer();
@override
Iterable<Type> get types => BuiltList<Type>([OffsetDateTime]);

View File

@ -18,16 +18,16 @@ part 'serializers.g.dart';
Serializers serializers = (_$serializers.toBuilder(){{#apiInfo}}{{#apis}}{{#serializers}}
..addBuilderFactory(
{{#isArray}}
const FullType(BuiltList, [FullType({{baseType}})]),
() => ListBuilder<{{baseType}}>(),
const FullType(Built{{#uniqueItems}}Set{{/uniqueItems}}{{^uniqueItems}}List{{/uniqueItems}}, [FullType({{baseType}})]),
() => {{#uniqueItems}}Set{{/uniqueItems}}{{^uniqueItems}}List{{/uniqueItems}}Builder<{{baseType}}>(),
{{/isArray}}
{{#isMap}}
const FullType(BuiltMap, [FullType(String), FullType({{baseType}})]),
() => MapBuilder<String, {{baseType}}>(),
{{/isMap}}
){{/serializers}}{{/apis}}{{/apiInfo}}{{#timeMachine}}
..add(OffsetDateSerializer())
..add(OffsetDateTimeSerializer()){{/timeMachine}}
..add(const OffsetDateSerializer())
..add(const OffsetDateTimeSerializer()){{/timeMachine}}
..add(Iso8601DateTimeSerializer()))
.build();

View File

@ -187,8 +187,8 @@ class {{{classname}}} {
if (response.body != null && response.statusCode != HttpStatus.noContent) {
{{#isArray}}
return (apiClient.deserialize(_decodeBodyBytes(response), '{{{returnType}}}') as List)
.map((item) => item as {{{returnBaseType}}})
.toList(growable: false);
.cast<{{{returnBaseType}}}>()
.{{#uniqueItems}}toSet(){{/uniqueItems}}{{^uniqueItems}}toList(growable: false){{/uniqueItems}};
{{/isArray}}
{{^isArray}}
{{#isMap}}

View File

@ -194,6 +194,12 @@ class ApiClient {
.map((v) => _deserialize(v, newTargetType, growable: growable))
.toList(growable: true == growable);
}
if (value is Set && (match = _regSet.firstMatch(targetType)) != null) {
final newTargetType = match[1];
return value
.map((v) => _deserialize(v, newTargetType, growable: growable))
.toSet();
}
if (value is Map && (match = _regMap.firstMatch(targetType)) != null) {
final newTargetType = match[1];
return Map.fromIterables(

View File

@ -26,6 +26,7 @@ const _delimiters = {'csv': ',', 'ssv': ' ', 'tsv': '\t', 'pipes': '|'};
const _dateEpochMarker = 'epoch';
final _dateFormatter = DateFormat('yyyy-MM-dd');
final _regList = RegExp(r'^List<(.*)>$');
final _regSet = RegExp(r'^Set<(.*)>$');
final _regMap = RegExp(r'^Map<String,(.*)>$');
ApiClient defaultApiClient = ApiClient();

View File

@ -156,7 +156,7 @@ class {{{classname}}} {
{{^isEnum}}
{{{name}}}: json[r'{{{baseName}}}'] == null
? null
: (json[r'{{{baseName}}}'] as List).cast<{{{items.datatype}}}>(),
: (json[r'{{{baseName}}}'] as {{#uniqueItems}}Set{{/uniqueItems}}{{^uniqueItems}}List{{/uniqueItems}}).cast<{{{items.datatype}}}>(),
{{/isEnum}}
{{/isArray}}
{{^isArray}}

View File

@ -116,6 +116,11 @@ type HttpSignatureAuth struct {
privateKey crypto.PrivateKey // The private key used to sign HTTP requests.
}
// SetPrivateKey accepts a private key string and sets it.
func (h *HttpSignatureAuth) SetPrivateKey(privateKey string) error {
return h.parsePrivateKey([]byte(privateKey))
}
// ContextWithValue validates the HttpSignatureAuth configuration parameters and returns a context
// suitable for HTTP signature. An error is returned if the HttpSignatureAuth configuration parameters
// are invalid.
@ -123,7 +128,7 @@ func (h *HttpSignatureAuth) ContextWithValue(ctx context.Context) (context.Conte
if h.KeyId == "" {
return nil, fmt.Errorf("Key ID must be specified")
}
if h.PrivateKeyPath == "" {
if h.PrivateKeyPath == "" && h.privateKey == nil {
return nil, fmt.Errorf("Private key path must be specified")
}
if _, ok := supportedSigningSchemes[h.SigningScheme]; !ok {
@ -168,7 +173,11 @@ func (h *HttpSignatureAuth) GetPublicKey() (crypto.PublicKey, error) {
}
// loadPrivateKey reads the private key from the file specified in the HttpSignatureAuth.
// The key is loaded only when privateKey is not already set.
func (h *HttpSignatureAuth) loadPrivateKey() (err error) {
if h.privateKey != nil {
return nil
}
var file *os.File
file, err = os.Open(h.PrivateKeyPath)
if err != nil {
@ -182,12 +191,18 @@ func (h *HttpSignatureAuth) loadPrivateKey() (err error) {
if err != nil {
return err
}
return h.parsePrivateKey(priv)
}
// parsePrivateKey decodes privateKey byte array to crypto.PrivateKey type.
func (h *HttpSignatureAuth) parsePrivateKey(priv []byte) error {
pemBlock, _ := pem.Decode(priv)
if pemBlock == nil {
// No PEM data has been found.
return fmt.Errorf("File '%s' does not contain PEM data", h.PrivateKeyPath)
}
var privKey []byte
var err error
if x509.IsEncryptedPEMBlock(pemBlock) {
// The PEM data is encrypted.
privKey, err = x509.DecryptPEMBlock(pemBlock, []byte(h.Passphrase))

View File

@ -2,23 +2,23 @@ group '{{groupId}}'
version '{{artifactVersion}}'
wrapper {
gradleVersion = '4.9'
gradleVersion = '6.8.2'
distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip"
}
buildscript {
ext.kotlin_version = '1.3.61'
ext.kotlin_version = '1.4.20'
{{#jvm-retrofit2}}
ext.retrofitVersion = '2.6.2'
ext.retrofitVersion = '2.7.2'
{{/jvm-retrofit2}}
{{#useRxJava}}
ext.rxJavaVersion = '1.3.8'
{{/useRxJava}}
{{#useRxJava2}}
ext.rxJava2Version = '2.2.17'
ext.rxJava2Version = '2.2.20'
{{/useRxJava2}}
{{#useRxJava3}}
ext.rxJava3Version = '3.0.4'
ext.rxJava3Version = '3.0.10'
{{/useRxJava3}}
repositories {
@ -33,6 +33,9 @@ apply plugin: 'kotlin'
{{#moshiCodeGen}}
apply plugin: 'kotlin-kapt'
{{/moshiCodeGen}}
{{#parcelizeModels}}
apply plugin: 'kotlin-parcelize'
{{/parcelizeModels}}
repositories {
maven { url "https://repo1.maven.org/maven2" }
@ -47,52 +50,36 @@ dependencies {
{{#moshi}}
{{^moshiCodeGen}}
compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
compile "com.squareup.moshi:moshi-kotlin:1.9.2"
compile "com.squareup.moshi:moshi-kotlin:1.11.0"
{{/moshiCodeGen}}
compile "com.squareup.moshi:moshi-adapters:1.9.2"
{{#moshiCodeGen}}
compile "com.squareup.moshi:moshi:1.9.2"
kapt "com.squareup.moshi:moshi-kotlin-codegen:1.9.2"
compile "com.squareup.moshi:moshi:1.11.0"
kapt "com.squareup.moshi:moshi-kotlin-codegen:1.11.0"
{{/moshiCodeGen}}
{{/moshi}}
{{#gson}}
compile "com.google.code.gson:gson:2.8.6"
{{/gson}}
{{#jackson}}
compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
compile "com.fasterxml.jackson.module:jackson-module-kotlin:2.10.2"
compile "com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.10.2"
compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.10.2"
{{/jackson}}
{{#jvm-okhttp3}}
{{^moshi}}
compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
{{/moshi}}
{{#moshi}}
{{#modeCodeGen}}
compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
{{/modeCodeGen}}
{{/moshi}}
compile "com.squareup.okhttp3:okhttp:3.12.6"
compile "com.squareup.okhttp3:okhttp:3.12.13"
{{/jvm-okhttp3}}
{{#jvm-okhttp4}}
{{^moshi}}
compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
{{/moshi}}
{{#moshi}}
{{#modeCodeGen}}
compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
{{/modeCodeGen}}
{{/moshi}}
compile "com.squareup.okhttp3:okhttp:4.2.2"
compile "com.squareup.okhttp3:okhttp:4.9.0"
{{/jvm-okhttp4}}
{{#threetenbp}}
compile "org.threeten:threetenbp:1.4.0"
compile "org.threeten:threetenbp:1.5.0"
{{/threetenbp}}
{{#jvm-retrofit2}}
{{#hasOAuthMethods}}
compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.0"
{{/hasOAuthMethods}}
compile "com.squareup.okhttp3:logging-interceptor:4.4.0"
compile "com.squareup.okhttp3:logging-interceptor:4.9.0"
{{#useRxJava}}
compile "io.reactivex:rxjava:$rxJavaVersion"
compile "com.squareup.retrofit2:adapter-rxjava:$retrofitVersion"
@ -114,5 +101,5 @@ dependencies {
{{/moshi}}
compile "com.squareup.retrofit2:converter-scalars:$retrofitVersion"
{{/jvm-retrofit2}}
testCompile "io.kotlintest:kotlintest-runner-junit5:3.1.0"
testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2"
}

View File

@ -17,7 +17,7 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo
{{/jackson}}
{{#parcelizeModels}}
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
import kotlinx.parcelize.Parcelize
{{/parcelizeModels}}
{{/multiplatform}}

View File

@ -12,5 +12,6 @@ package {{packageName}}.infrastructure
val method: RequestMethod,
val path: String,
val headers: MutableMap<String, String> = mutableMapOf(),
val query: MutableMap<String, List<String>> = mutableMapOf()
val query: MutableMap<String, List<String>> = mutableMapOf(),
val body: kotlin.Any? = null
)

View File

@ -2,7 +2,6 @@ package {{packageName}}.infrastructure
{{#moshi}}
import com.squareup.moshi.Moshi
import com.squareup.moshi.adapters.Rfc3339DateJsonAdapter
{{^moshiCodeGen}}
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
{{/moshiCodeGen}}
@ -36,7 +35,6 @@ import java.util.Date
{{#moshi}}
@JvmStatic
val moshiBuilder: Moshi.Builder = Moshi.Builder()
.add(Date::class.java, Rfc3339DateJsonAdapter().nullSafe())
.add(OffsetDateTimeAdapter())
.add(LocalDateTimeAdapter())
.add(LocalDateAdapter())
@ -54,7 +52,6 @@ import java.util.Date
{{#gson}}
@JvmStatic
val gsonBuilder: GsonBuilder = GsonBuilder()
.registerTypeAdapter(Date::class.java, DateAdapter())
.registerTypeAdapter(OffsetDateTime::class.java, OffsetDateTimeAdapter())
.registerTypeAdapter(LocalDateTime::class.java, LocalDateTimeAdapter())
.registerTypeAdapter(LocalDate::class.java, LocalDateAdapter())

View File

@ -41,6 +41,37 @@ import {{packageName}}.infrastructure.toMultiValue
@Deprecated(message = "This operation is deprecated.")
{{/isDeprecated}}
{{^doNotUseRxAndCoroutines}}{{#useCoroutines}}suspend {{/useCoroutines}}{{/doNotUseRxAndCoroutines}}fun {{operationId}}({{#allParams}}{{{paramName}}}: {{{dataType}}}{{^required}}?{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) : {{#returnType}}{{{returnType}}}{{#nullableReturnType}}?{{/nullableReturnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}} {
val localVariableConfig = {{operationId}}RequestConfig({{#allParams}}{{{paramName}}} = {{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}})
val localVarResponse = request<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Any?{{/returnType}}>(
localVariableConfig
)
return 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)
}
}
}
/**
* To obtain the request config of the operation {{operationId}}
*
{{#allParams}}* @param {{{paramName}}} {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}
{{/allParams}}* @return RequestConfig
*/
{{#isDeprecated}}
@Deprecated(message = "This operation is deprecated.")
{{/isDeprecated}}
fun {{operationId}}RequestConfig({{#allParams}}{{{paramName}}}: {{{dataType}}}{{^required}}?{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) : RequestConfig {
val localVariableBody: kotlin.Any? = {{#hasBodyParam}}{{#bodyParams}}{{{paramName}}}{{/bodyParams}}{{/hasBodyParam}}{{^hasBodyParam}}{{^hasFormParams}}null{{/hasFormParams}}{{#hasFormParams}}mapOf({{#formParams}}"{{{baseName}}}" to {{{paramName}}}{{^-last}}, {{/-last}}{{/formParams}}){{/hasFormParams}}{{/hasBodyParam}}
val localVariableQuery: MultiValueMap = {{^hasQueryParams}}mutableMapOf()
{{/hasQueryParams}}{{#hasQueryParams}}mutableMapOf<kotlin.String, List<kotlin.String>>()
@ -68,30 +99,16 @@ import {{packageName}}.infrastructure.toMultiValue
{{#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}},
method = RequestMethod.{{httpMethod}},
path = "{{path}}"{{#pathParams}}.replace("{"+"{{baseName}}"+"}", "${{{paramName}}}"){{/pathParams}},
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Any?{{/returnType}}>(
localVariableConfig,
localVariableBody
headers = localVariableHeaders,
body = localVariableBody
)
return 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)
}
}
return localVariableConfig
}
{{/operation}}

View File

@ -232,7 +232,7 @@ import org.threeten.bp.OffsetTime
}
{{/hasAuthMethods}}
protected inline fun <reified T: Any?> request(requestConfig: RequestConfig, body : Any? = null): ApiInfrastructureResponse<T?> {
protected inline fun <reified T: Any?> request(requestConfig: RequestConfig): ApiInfrastructureResponse<T?> {
{{#jvm-okhttp3}}
val httpUrl = HttpUrl.parse(baseUrl) ?: throw IllegalStateException("baseUrl is invalid.")
{{/jvm-okhttp3}}
@ -276,12 +276,12 @@ import org.threeten.bp.OffsetTime
val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase()
val request = when (requestConfig.method) {
RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(body, contentType))
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(body, contentType))
RequestMethod.PUT -> Request.Builder().url(url).put(requestBody(body, contentType))
RequestMethod.POST -> Request.Builder().url(url).post(requestBody(body, contentType))
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) }

View File

@ -1,6 +1,6 @@
{{#parcelizeModels}}
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
import kotlinx.parcelize.Parcelize
{{/parcelizeModels}}
{{#serializableModel}}

View File

@ -1,7 +1,7 @@
{{#parcelizeModels}}
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
import kotlinx.parcelize.Parcelize
{{/parcelizeModels}}
import com.google.gson.annotations.SerializedName
import com.fasterxml.jackson.annotation.JsonIgnoreProperties

View File

@ -23,8 +23,6 @@ Method | HTTP request | Description
### Example
```powershell
Import-Module -Name {{{packageName}}}
{{#hasAuthMethods}}
# general setting of the PowerShell module, e.g. base URL, authentication, etc
$Configuration = Get-Configuration

View File

@ -163,6 +163,7 @@ conf = {{{packageName}}}.Configuration(
def __init__(self, host=None,
api_key=None, api_key_prefix=None,
access_token=None,
username=None, password=None,
discard_unknown_keys=False,
disabled_client_side_validations="",
@ -190,6 +191,7 @@ conf = {{{packageName}}}.Configuration(
"""Temp file folder for downloading files
"""
# Authentication Settings
self.access_token = access_token
self.api_key = {}
if api_key:
self.api_key = api_key
@ -218,18 +220,6 @@ conf = {{{packageName}}}.Configuration(
"""The HTTP signing configuration
"""
{{/hasHttpSignatureMethods}}
{{#hasOAuthMethods}}
self.access_token = None
"""access token for OAuth/Bearer
"""
{{/hasOAuthMethods}}
{{^hasOAuthMethods}}
{{#hasBearerMethods}}
self.access_token = None
"""access token for OAuth/Bearer
"""
{{/hasBearerMethods}}
{{/hasOAuthMethods}}
self.logger = {}
"""Logging Settings
"""

View File

@ -197,13 +197,13 @@
{{/pattern}}
{{#maxItems}}
if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.length > {{{maxItems}}}
invalid_properties.push('invalid value for "{{{name}}}", number of items must be less than or equal to {{{maxItems}}}.'
invalid_properties.push('invalid value for "{{{name}}}", number of items must be less than or equal to {{{maxItems}}}.')
end
{{/maxItems}}
{{#minItems}}
if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.length < {{{minItems}}}
invalid_properties.push('invalid value for "{{{name}}}", number of items must be greater than or equal to {{{minItems}}}.'
invalid_properties.push('invalid value for "{{{name}}}", number of items must be greater than or equal to {{{minItems}}}.')
end
{{/minItems}}

View File

@ -283,7 +283,7 @@ pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}(configuration:
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text(){{#supportAsync}}.await{{/supportAsync}}?;
if local_var_status.is_success() {
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
{{^supportMultipleResponses}}
{{^returnType}}
Ok(())

View File

@ -1,5 +1,3 @@
use reqwest;
use serde_json;
use std::error;
use std::fmt;

View File

@ -216,6 +216,9 @@ export function querystring(params: HTTPQuery, prefix: string = ''): string {
.join(`&${encodeURIComponent(fullKey)}=`);
return `${encodeURIComponent(fullKey)}=${multiValue}`;
}
if (value instanceof Date) {
return `${encodeURIComponent(fullKey)}=${encodeURIComponent(value.toISOString())}`;
}
if (value instanceof Object) {
return querystring(value as HTTPQuery, fullKey);
}

View File

@ -12,12 +12,12 @@ import { {{classname}} } from './{{importPath}}';
@Module({
imports: [ HttpModule ],
exports: [
{{#apiInfo}}{{#apis}}{{classname}}{{#hasMore}},
{{/hasMore}}{{/apis}}{{/apiInfo}}
{{#apiInfo}}{{#apis}}{{classname}}{{^-last}},
{{/-last}}{{/apis}}{{/apiInfo}}
],
providers: [
{{#apiInfo}}{{#apis}}{{classname}}{{#hasMore}},
{{/hasMore}}{{/apis}}{{/apiInfo}}
{{#apiInfo}}{{#apis}}{{classname}}{{^-last}},
{{/-last}}{{/apis}}{{/apiInfo}}
]
})
export class ApiModule {

View File

@ -107,7 +107,7 @@ export class {{classname}} {
{{/isListContainer}}
{{^isListContainer}}
if ({{paramName}} !== undefined && {{paramName}} !== null) {
headers['{{baseName}}'] String({{paramName}});
headers['{{baseName}}'] = String({{paramName}});
}
{{/isListContainer}}
{{/headerParams}}
@ -147,7 +147,7 @@ export class {{classname}} {
// to determine the Accept header
let httpHeaderAccepts: string[] = [
{{#produces}}
'{{{mediaType}}}'{{#hasMore}},{{/hasMore}}
'{{{mediaType}}}'{{^-last}},{{/-last}}
{{/produces}}
];
const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts);
@ -158,7 +158,7 @@ export class {{classname}} {
// to determine the Content-Type header
const consumes: string[] = [
{{#consumes}}
'{{{mediaType}}}'{{#hasMore}},{{/hasMore}}
'{{{mediaType}}}'{{^-last}},{{/-last}}
{{/consumes}}
];
{{#bodyParam}}
@ -167,8 +167,8 @@ export class {{classname}} {
headers['Content-Type'] = httpContentTypeSelected;
}
{{/bodyParam}}
{{#hasFormParams}}
const canConsumeForm = this.canConsumeForm(consumes);
let formParams: { append(param: string, value: any): void; };
@ -176,6 +176,7 @@ export class {{classname}} {
let convertFormParamsToString = false;
{{#formParams}}
{{#isFile}}
// use FormData to transmit files using content-type "multipart/form-data"
// see https://stackoverflow.com/questions/4007969/application-x-www-form-urlencoded-or-multipart-form-data
useForm = canConsumeForm;
@ -186,8 +187,8 @@ export class {{classname}} {
} else {
// formParams = new HttpParams({encoder: new CustomHttpUrlEncodingCodec()});
}
{{#formParams}}
{{#isListContainer}}
if ({{paramName}}) {
{{#isCollectionFormatMulti}}

View File

@ -113,9 +113,9 @@ export class ObjectSerializer {
let subType: string = type.replace("Array<", ""); // Array<Type> => Type>
subType = subType.substring(0, subType.length - 1); // Type> => Type
let transformedData: any[] = [];
for (let index in data) {
let date = data[index];
transformedData.push(ObjectSerializer.serialize(date, subType));
for (let index = 0; index < data.length; index++) {
let datum = data[index];
transformedData.push(ObjectSerializer.serialize(datum, subType));
}
return transformedData;
} else if (type === "Date") {
@ -134,7 +134,7 @@ export class ObjectSerializer {
// get the map for the correct type.
let attributeTypes = typeMap[type].getAttributeTypeMap();
let instance: {[index: string]: any} = {};
for (let index in attributeTypes) {
for (let index = 0; index < attributeTypes.length; index++) {
let attributeType = attributeTypes[index];
instance[attributeType.baseName] = ObjectSerializer.serialize(data[attributeType.name], attributeType.type);
}
@ -153,9 +153,9 @@ export class ObjectSerializer {
let subType: string = type.replace("Array<", ""); // Array<Type> => Type>
subType = subType.substring(0, subType.length - 1); // Type> => Type
let transformedData: any[] = [];
for (let index in data) {
let date = data[index];
transformedData.push(ObjectSerializer.deserialize(date, subType));
for (let index = 0; index < data.length; index++) {
let datum = data[index];
transformedData.push(ObjectSerializer.deserialize(datum, subType));
}
return transformedData;
} else if (type === "Date") {
@ -170,7 +170,7 @@ export class ObjectSerializer {
}
let instance = new typeMap[type]();
let attributeTypes = typeMap[type].getAttributeTypeMap();
for (let index in attributeTypes) {
for (let index = 0; index < attributeTypes.length; index++) {
let attributeType = attributeTypes[index];
instance[attributeType.name] = ObjectSerializer.deserialize(data[attributeType.baseName], attributeType.type);
}

View File

@ -142,6 +142,45 @@ public class DartModelTest {
Assert.assertTrue(property2.isContainer);
}
@Test(description = "convert a model with set property")
public void setPropertyTest() {
final Schema model = new Schema()
.description("a sample model")
.addProperties("id", new IntegerSchema())
.addProperties("urls", new ArraySchema().items(new StringSchema()).uniqueItems(true))
.addRequiredItem("id");
final DefaultCodegen codegen = new DartClientCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "Sample");
Assert.assertEquals(cm.description, "a sample model");
Assert.assertEquals(cm.vars.size(), 2);
final CodegenProperty property1 = cm.vars.get(0);
Assert.assertEquals(property1.baseName, "id");
Assert.assertEquals(property1.dataType, "int");
Assert.assertEquals(property1.name, "id");
Assert.assertNull(property1.defaultValue);
Assert.assertEquals(property1.baseType, "int");
Assert.assertTrue(property1.required);
Assert.assertTrue(property1.isPrimitiveType);
Assert.assertFalse(property1.isContainer);
final CodegenProperty property2 = cm.vars.get(1);
Assert.assertEquals(property2.baseName, "urls");
Assert.assertEquals(property2.dataType, "Set<String>");
Assert.assertEquals(property2.name, "urls");
Assert.assertEquals(property2.baseType, "Set");
Assert.assertEquals(property2.containerType, "set");
Assert.assertFalse(property2.required);
Assert.assertTrue(property2.isPrimitiveType);
Assert.assertTrue(property2.isContainer);
}
@Test(description = "convert a model with a map property")
public void mapPropertyTest() {
final Schema model = new Schema()

View File

@ -204,6 +204,44 @@ public class DartDioModelTest {
Assert.assertTrue(property2.isContainer);
}
@Test(description = "convert a model with set property")
public void setPropertyTest() {
final Schema model = new Schema()
.description("a sample model")
.addProperties("id", new IntegerSchema())
.addProperties("urls", new ArraySchema().items(new StringSchema()).uniqueItems(true))
.addRequiredItem("id");
final DefaultCodegen codegen = new DartDioClientCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "Sample");
Assert.assertEquals(cm.description, "a sample model");
Assert.assertEquals(cm.vars.size(), 2);
final CodegenProperty property1 = cm.vars.get(0);
Assert.assertEquals(property1.baseName, "id");
Assert.assertEquals(property1.dataType, "int");
Assert.assertEquals(property1.name, "id");
Assert.assertNull(property1.defaultValue);
Assert.assertEquals(property1.baseType, "int");
Assert.assertTrue(property1.required);
Assert.assertTrue(property1.isPrimitiveType);
Assert.assertFalse(property1.isContainer);
final CodegenProperty property2 = cm.vars.get(1);
Assert.assertEquals(property2.baseName, "urls");
Assert.assertEquals(property2.dataType, "BuiltSet<String>");
Assert.assertEquals(property2.name, "urls");
Assert.assertEquals(property2.baseType, "BuiltSet");
Assert.assertEquals(property2.containerType, "set");
Assert.assertFalse(property2.required);
Assert.assertTrue(property2.isPrimitiveType);
Assert.assertTrue(property2.isContainer);
}
@Test(description = "convert a model with a map property")
public void mapPropertyTest() {
final Schema model = new Schema()

View File

@ -368,7 +368,7 @@ public class JavaJAXRSCXFExtServerCodegenTest extends JavaJaxrsBaseTest {
assertEquals(testerCodegen.getTestDataControlFile(), new File(curdir, "my/test-data-control.json"));
}
@Test()
@Test
public void testGenerateOperationBodyWithCodedTestData() throws Exception {
File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
output.deleteOnExit();
@ -412,7 +412,7 @@ public class JavaJAXRSCXFExtServerCodegenTest extends JavaJaxrsBaseTest {
checkFile(Paths.get(outputPath + "/test-data-control.json"), false);
}
@Test()
@Test
public void testGenerateOperationBodyWithJsonTestData() throws Exception {
File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
output.deleteOnExit();

View File

@ -134,6 +134,7 @@ paths:
type: array
items:
type: string
uniqueItems: true
responses:
'200':
description: successful operation
@ -143,11 +144,13 @@ paths:
type: array
items:
$ref: '#/components/schemas/Pet'
uniqueItems: true
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Pet'
uniqueItems: true
'400':
description: Invalid tag value
security:
@ -1313,6 +1316,7 @@ components:
wrapped: true
items:
type: string
uniqueItems: true
tags:
type: array
xml:
@ -1623,6 +1627,8 @@ components:
type: array
items:
type: string
minItems: 0
maxItems: 3
array_array_of_integer:
type: array
items:

29
pom.xml
View File

@ -1181,6 +1181,8 @@
</property>
</activation>
<modules>
<module>samples/client/petstore/typescript-axios/builds/with-npm-version</module>
<module>samples/client/petstore/typescript-axios/tests/default</module>
<module>samples/client/petstore/crystal</module>
<!-- servers -->
<module>samples/server/petstore/python-aiohttp</module>
@ -1222,7 +1224,6 @@
<module>samples/client/petstore/typescript-fetch/builds/es6-target</module>
<module>samples/client/petstore/typescript-fetch/builds/with-npm-version</module>
<module>samples/client/petstore/typescript-fetch/tests/default</module>
<module>samples/client/petstore/typescript-axios/tests/default</module>
<module>samples/client/petstore/typescript-node/npm</module>
<module>samples/client/petstore/typescript-rxjs/builds/with-npm-version</module>
<!-- TODO comment out below when the test for typescript-nestjs is ready
@ -1234,8 +1235,6 @@
<module>samples/client/petstore/typescript-angular-v4.3/npm</module>
<module>samples/client/petstore/typescript-angular-v6-provided-in-root</module>
<module>samples/client/petstore/typescript-angular-v7-provided-in-root</module>-->
<module>samples/client/petstore/kotlin-threetenbp/</module>
<module>samples/client/petstore/kotlin-string/</module>
</modules>
</profile>
<!-- test with JDK8 in CircleCI -->
@ -1259,8 +1258,7 @@
<module>samples/server/petstore/jaxrs-spec</module>
<module>samples/server/petstore/jaxrs-spec-interface</module>
<module>samples/server/petstore/jaxrs-spec-interface-response</module>
<module>samples/server/petstore/java-vertx/rx</module>
<module>samples/server/petstore/java-vertx/async</module>
<module>samples/server/petstore/java-vertx-web</module>
<module>samples/server/petstore/java-inflector</module>
<module>samples/server/petstore/java-pkmst</module>
<module>samples/server/petstore/java-play-framework</module>
@ -1302,7 +1300,6 @@
<module>samples/server/petstore/scala-play-server</module>
<module>samples/server/petstore/scala-akka-http-server</module>
<module>samples/server/petstore/scalatra</module>
<module>samples/server/petstore/java-vertx-web</module>
<module>samples/server/petstore/scala-finch</module>
<!--<module>samples/server/petstore/kotlin/vertx</module>-->
</modules>
@ -1378,17 +1375,21 @@
<!--<module>samples/client/petstore/elixir</module>-->
<module>samples/client/petstore/erlang-client</module>
<module>samples/client/petstore/erlang-proper</module>
<module>samples/client/petstore/kotlin</module>
<module>samples/client/petstore/kotlin-gson</module>
<module>samples/client/petstore/kotlin-jackson</module>
<module>samples/client/petstore/kotlin-json-request-string</module>
<module>samples/client/petstore/kotlin-jvm-okhttp4-coroutines</module>
<module>samples/client/petstore/kotlin-moshi-codegen</module>
<module>samples/client/petstore/kotlin-multiplatform</module>
<!--<module>samples/client/petstore/kotlin/</module>-->
<module>samples/client/petstore/kotlin-nonpublic</module>
<module>samples/client/petstore/kotlin-nullable</module>
<module>samples/client/petstore/kotlin-okhttp3</module>
<module>samples/client/petstore/kotlin-retrofit2</module>
<module>samples/client/petstore/kotlin-retrofit2-rx3</module>
<module>samples/client/petstore/kotlin-jackson/</module>
<module>samples/client/petstore/kotlin-gson/</module>
<module>samples/client/petstore/kotlin-nonpublic/</module>
<module>samples/client/petstore/kotlin-nullable/</module>
<module>samples/client/petstore/kotlin-okhttp3/</module>
<module>samples/client/petstore/kotlin-moshi-codegen/</module>
<module>samples/client/petstore/kotlin-json-request-string/</module>
<module>samples/client/petstore/kotlin-string</module>
<module>samples/client/petstore/kotlin-threetenbp</module>
<module>samples/client/petstore/kotlin-uppercase-enum</module>
<!-- servers -->
<!--<module>samples/server/petstore/erlang-server</module>-->
</modules>

View File

@ -1 +1 @@
5.0.1-SNAPSHOT
5.1.0-SNAPSHOT

View File

@ -145,18 +145,81 @@ void PFXPetApi::abortRequests(){
emit abortRequestsSignal();
}
QString PFXPetApi::getParamStylePrefix(QString style){
if(style == "matrix"){
return ";";
}else if(style == "label"){
return ".";
}else if(style == "form"){
return "&";
}else if(style == "simple"){
return "";
}else if(style == "spaceDelimited"){
return "&";
}else if(style == "pipeDelimited"){
return "&";
}else
return "none";
}
QString PFXPetApi::getParamStyleSuffix(QString style){
if(style == "matrix"){
return "=";
}else if(style == "label"){
return "";
}else if(style == "form"){
return "=";
}else if(style == "simple"){
return "";
}else if(style == "spaceDelimited"){
return "=";
}else if(style == "pipeDelimited"){
return "=";
}else
return "none";
}
QString PFXPetApi::getParamStyleDelimiter(QString style, QString name, bool isExplode){
if(style == "matrix"){
return (isExplode) ? ";" + name + "=" : ",";
}else if(style == "label"){
return (isExplode) ? "." : ",";
}else if(style == "form"){
return (isExplode) ? "&" + name + "=" : ",";
}else if(style == "simple"){
return ",";
}else if(style == "spaceDelimited"){
return (isExplode) ? "&" + name + "=" : " ";
}else if(style == "pipeDelimited"){
return (isExplode) ? "&" + name + "=" : "|";
}else if(style == "deepObject"){
return (isExplode) ? "&" : "none";
}else
return "none";
}
void PFXPetApi::addPet(const PFXPet &body) {
QString fullPath = QString(_serverConfigs["addPet"][_serverIndices.value("addPet")].URL()+"/pet");
PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager);
worker->setTimeOut(_timeOut);
worker->setWorkingDirectory(_workingDirectory);
PFXHttpRequestInput input(fullPath, "POST");
QByteArray output = body.asJson().toUtf8();
input.request_body.append(output);
foreach (QString key, this->defaultHeaders.keys()) { input.headers.insert(key, this->defaultHeaders.value(key)); }
connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::addPetCallback);
@ -188,9 +251,18 @@ void PFXPetApi::addPetCallback(PFXHttpRequestWorker *worker) {
void PFXPetApi::deletePet(const qint64 &pet_id, const QString &api_key) {
QString fullPath = QString(_serverConfigs["deletePet"][_serverIndices.value("deletePet")].URL()+"/pet/{petId}");
QString pet_idPathParam("{");
pet_idPathParam.append("petId").append("}");
fullPath.replace(pet_idPathParam, QUrl::toPercentEncoding(::test_namespace::toStringValue(pet_id)));
QString pathPrefix, pathSuffix, pathDelimiter;
QString pathStyle = "";
if(pathStyle == "")
pathStyle = "simple";
pathPrefix = getParamStylePrefix(pathStyle);
pathSuffix = getParamStyleSuffix(pathStyle);
pathDelimiter = getParamStyleDelimiter(pathStyle, "petId", false);
QString paramString = (pathStyle == "matrix") ? pathPrefix+"petId"+pathSuffix : pathPrefix;
fullPath.replace(pet_idPathParam, paramString+QUrl::toPercentEncoding(::test_namespace::toStringValue(pet_id)));
PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager);
@ -198,10 +270,11 @@ void PFXPetApi::deletePet(const qint64 &pet_id, const QString &api_key) {
worker->setWorkingDirectory(_workingDirectory);
PFXHttpRequestInput input(fullPath, "DELETE");
if (!::test_namespace::toStringValue(api_key).isEmpty()) {
input.headers.insert("api_key", ::test_namespace::toStringValue(api_key));
}
foreach (QString key, this->defaultHeaders.keys()) { input.headers.insert(key, this->defaultHeaders.value(key)); }
connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::deletePetCallback);
@ -235,11 +308,19 @@ void PFXPetApi::findPetsByStatus(const QList<QString> &status) {
QString fullPath = QString(_serverConfigs["findPetsByStatus"][_serverIndices.value("findPetsByStatus")].URL()+"/pet/findByStatus");
QString queryPrefix, querySuffix, queryDelimiter, queryStyle;
queryStyle = "form";
if(queryStyle == "")
queryStyle = "form";
queryPrefix = getParamStylePrefix(queryStyle);
querySuffix = getParamStyleSuffix(queryStyle);
queryDelimiter = getParamStyleDelimiter(queryStyle, "status", false);
if (status.size() > 0) {
if (QString("csv").indexOf("multi") == 0) {
foreach (QString t, status) {
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
fullPath.append(queryPrefix);
else
fullPath.append("?");
fullPath.append("status=").append(::test_namespace::toStringValue(t));
@ -248,27 +329,66 @@ void PFXPetApi::findPetsByStatus(const QList<QString> &status) {
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append("status=");
fullPath.append("?").append(queryPrefix).append("status").append(querySuffix);
qint32 count = 0;
foreach (QString t, status) {
if (count > 0) {
fullPath.append(" ");
fullPath.append((false)? queryDelimiter : QUrl::toPercentEncoding(queryDelimiter));
}
fullPath.append(::test_namespace::toStringValue(t));
count++;
}
} else if (QString("csv").indexOf("tsv") == 0) {
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append("status=");
fullPath.append("?").append(queryPrefix).append("status").append(querySuffix);
qint32 count = 0;
foreach (QString t, status) {
if (count > 0) {
fullPath.append("\t");
}
fullPath.append(::test_namespace::toStringValue(t));
count++;
}
} else if (QString("csv").indexOf("csv") == 0) {
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?").append(queryPrefix).append("status").append(querySuffix);
qint32 count = 0;
foreach (QString t, status) {
if (count > 0) {
fullPath.append(queryDelimiter);
}
fullPath.append(::test_namespace::toStringValue(t));
count++;
}
} else if (QString("csv").indexOf("pipes") == 0) {
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?").append(queryPrefix).append("status").append(querySuffix);
qint32 count = 0;
foreach (QString t, status) {
if (count > 0) {
fullPath.append(queryDelimiter);
}
fullPath.append(::test_namespace::toStringValue(t));
count++;
}
} else if (QString("csv").indexOf("deepObject") == 0) {
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?").append(queryPrefix).append("status").append(querySuffix);
qint32 count = 0;
foreach (QString t, status) {
if (count > 0) {
fullPath.append(queryDelimiter);
}
fullPath.append(::test_namespace::toStringValue(t));
count++;
}
}
}
@ -321,11 +441,19 @@ void PFXPetApi::findPetsByTags(const QList<QString> &tags) {
QString fullPath = QString(_serverConfigs["findPetsByTags"][_serverIndices.value("findPetsByTags")].URL()+"/pet/findByTags");
QString queryPrefix, querySuffix, queryDelimiter, queryStyle;
queryStyle = "form";
if(queryStyle == "")
queryStyle = "form";
queryPrefix = getParamStylePrefix(queryStyle);
querySuffix = getParamStyleSuffix(queryStyle);
queryDelimiter = getParamStyleDelimiter(queryStyle, "tags", false);
if (tags.size() > 0) {
if (QString("csv").indexOf("multi") == 0) {
foreach (QString t, tags) {
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
fullPath.append(queryPrefix);
else
fullPath.append("?");
fullPath.append("tags=").append(::test_namespace::toStringValue(t));
@ -334,27 +462,66 @@ void PFXPetApi::findPetsByTags(const QList<QString> &tags) {
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append("tags=");
fullPath.append("?").append(queryPrefix).append("tags").append(querySuffix);
qint32 count = 0;
foreach (QString t, tags) {
if (count > 0) {
fullPath.append(" ");
fullPath.append((false)? queryDelimiter : QUrl::toPercentEncoding(queryDelimiter));
}
fullPath.append(::test_namespace::toStringValue(t));
count++;
}
} else if (QString("csv").indexOf("tsv") == 0) {
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append("tags=");
fullPath.append("?").append(queryPrefix).append("tags").append(querySuffix);
qint32 count = 0;
foreach (QString t, tags) {
if (count > 0) {
fullPath.append("\t");
}
fullPath.append(::test_namespace::toStringValue(t));
count++;
}
} else if (QString("csv").indexOf("csv") == 0) {
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?").append(queryPrefix).append("tags").append(querySuffix);
qint32 count = 0;
foreach (QString t, tags) {
if (count > 0) {
fullPath.append(queryDelimiter);
}
fullPath.append(::test_namespace::toStringValue(t));
count++;
}
} else if (QString("csv").indexOf("pipes") == 0) {
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?").append(queryPrefix).append("tags").append(querySuffix);
qint32 count = 0;
foreach (QString t, tags) {
if (count > 0) {
fullPath.append(queryDelimiter);
}
fullPath.append(::test_namespace::toStringValue(t));
count++;
}
} else if (QString("csv").indexOf("deepObject") == 0) {
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?").append(queryPrefix).append("tags").append(querySuffix);
qint32 count = 0;
foreach (QString t, tags) {
if (count > 0) {
fullPath.append(queryDelimiter);
}
fullPath.append(::test_namespace::toStringValue(t));
count++;
}
}
}
@ -405,14 +572,23 @@ void PFXPetApi::findPetsByTagsCallback(PFXHttpRequestWorker *worker) {
void PFXPetApi::getPetById(const qint64 &pet_id) {
QString fullPath = QString(_serverConfigs["getPetById"][_serverIndices.value("getPetById")].URL()+"/pet/{petId}");
QString pet_idPathParam("{");
pet_idPathParam.append("petId").append("}");
fullPath.replace(pet_idPathParam, QUrl::toPercentEncoding(::test_namespace::toStringValue(pet_id)));
if(_apiKeys.contains("api_key")){
addHeaders("api_key",_apiKeys.find("api_key").value());
}
QString pet_idPathParam("{");
pet_idPathParam.append("petId").append("}");
QString pathPrefix, pathSuffix, pathDelimiter;
QString pathStyle = "";
if(pathStyle == "")
pathStyle = "simple";
pathPrefix = getParamStylePrefix(pathStyle);
pathSuffix = getParamStyleSuffix(pathStyle);
pathDelimiter = getParamStyleDelimiter(pathStyle, "petId", false);
QString paramString = (pathStyle == "matrix") ? pathPrefix+"petId"+pathSuffix : pathPrefix;
fullPath.replace(pet_idPathParam, paramString+QUrl::toPercentEncoding(::test_namespace::toStringValue(pet_id)));
PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager);
worker->setTimeOut(_timeOut);
@ -453,14 +629,15 @@ void PFXPetApi::updatePet(const PFXPet &body) {
QString fullPath = QString(_serverConfigs["updatePet"][_serverIndices.value("updatePet")].URL()+"/pet");
PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager);
worker->setTimeOut(_timeOut);
worker->setWorkingDirectory(_workingDirectory);
PFXHttpRequestInput input(fullPath, "PUT");
QByteArray output = body.asJson().toUtf8();
input.request_body.append(output);
foreach (QString key, this->defaultHeaders.keys()) { input.headers.insert(key, this->defaultHeaders.value(key)); }
connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::updatePetCallback);
@ -492,9 +669,18 @@ void PFXPetApi::updatePetCallback(PFXHttpRequestWorker *worker) {
void PFXPetApi::updatePetWithForm(const qint64 &pet_id, const QString &name, const QString &status) {
QString fullPath = QString(_serverConfigs["updatePetWithForm"][_serverIndices.value("updatePetWithForm")].URL()+"/pet/{petId}");
QString pet_idPathParam("{");
pet_idPathParam.append("petId").append("}");
fullPath.replace(pet_idPathParam, QUrl::toPercentEncoding(::test_namespace::toStringValue(pet_id)));
QString pathPrefix, pathSuffix, pathDelimiter;
QString pathStyle = "";
if(pathStyle == "")
pathStyle = "simple";
pathPrefix = getParamStylePrefix(pathStyle);
pathSuffix = getParamStyleSuffix(pathStyle);
pathDelimiter = getParamStyleDelimiter(pathStyle, "petId", false);
QString paramString = (pathStyle == "matrix") ? pathPrefix+"petId"+pathSuffix : pathPrefix;
fullPath.replace(pet_idPathParam, paramString+QUrl::toPercentEncoding(::test_namespace::toStringValue(pet_id)));
PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager);
@ -502,9 +688,7 @@ void PFXPetApi::updatePetWithForm(const qint64 &pet_id, const QString &name, con
worker->setWorkingDirectory(_workingDirectory);
PFXHttpRequestInput input(fullPath, "POST");
input.add_var("name", ::test_namespace::toStringValue(name));
input.add_var("status", ::test_namespace::toStringValue(status));
foreach (QString key, this->defaultHeaders.keys()) { input.headers.insert(key, this->defaultHeaders.value(key)); }
input.add_var("name", ::test_namespace::toStringValue(name)); input.add_var("status", ::test_namespace::toStringValue(status)); foreach (QString key, this->defaultHeaders.keys()) { input.headers.insert(key, this->defaultHeaders.value(key)); }
connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::updatePetWithFormCallback);
connect(this, &PFXPetApi::abortRequestsSignal, worker, &QObject::deleteLater);
@ -535,9 +719,18 @@ void PFXPetApi::updatePetWithFormCallback(PFXHttpRequestWorker *worker) {
void PFXPetApi::uploadFile(const qint64 &pet_id, const QString &additional_metadata, const PFXHttpFileElement &file) {
QString fullPath = QString(_serverConfigs["uploadFile"][_serverIndices.value("uploadFile")].URL()+"/pet/{petId}/uploadImage");
QString pet_idPathParam("{");
pet_idPathParam.append("petId").append("}");
fullPath.replace(pet_idPathParam, QUrl::toPercentEncoding(::test_namespace::toStringValue(pet_id)));
QString pathPrefix, pathSuffix, pathDelimiter;
QString pathStyle = "";
if(pathStyle == "")
pathStyle = "simple";
pathPrefix = getParamStylePrefix(pathStyle);
pathSuffix = getParamStyleSuffix(pathStyle);
pathDelimiter = getParamStyleDelimiter(pathStyle, "petId", false);
QString paramString = (pathStyle == "matrix") ? pathPrefix+"petId"+pathSuffix : pathPrefix;
fullPath.replace(pet_idPathParam, paramString+QUrl::toPercentEncoding(::test_namespace::toStringValue(pet_id)));
PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager);
@ -546,8 +739,7 @@ void PFXPetApi::uploadFile(const qint64 &pet_id, const QString &additional_metad
PFXHttpRequestInput input(fullPath, "POST");
input.add_var("additionalMetadata", ::test_namespace::toStringValue(additional_metadata));
input.add_file("file", file.local_filename, file.request_filename, file.mime_type);
foreach (QString key, this->defaultHeaders.keys()) { input.headers.insert(key, this->defaultHeaders.value(key)); }
input.add_file("file", file.local_filename, file.request_filename, file.mime_type); foreach (QString key, this->defaultHeaders.keys()) { input.headers.insert(key, this->defaultHeaders.value(key)); }
connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::uploadFileCallback);
connect(this, &PFXPetApi::abortRequestsSignal, worker, &QObject::deleteLater);

View File

@ -53,6 +53,9 @@ public:
void enableRequestCompression();
void enableResponseCompression();
void abortRequests();
QString getParamStylePrefix(QString style);
QString getParamStyleSuffix(QString style);
QString getParamStyleDelimiter(QString style, QString name, bool isExplode);
void addPet(const PFXPet &body);
void deletePet(const qint64 &pet_id, const QString &api_key);

View File

@ -133,11 +133,82 @@ void PFXStoreApi::abortRequests(){
emit abortRequestsSignal();
}
QString PFXStoreApi::getParamStylePrefix(QString style){
if(style == "matrix"){
return ";";
}else if(style == "label"){
return ".";
}else if(style == "form"){
return "&";
}else if(style == "simple"){
return "";
}else if(style == "spaceDelimited"){
return "&";
}else if(style == "pipeDelimited"){
return "&";
}else
return "none";
}
QString PFXStoreApi::getParamStyleSuffix(QString style){
if(style == "matrix"){
return "=";
}else if(style == "label"){
return "";
}else if(style == "form"){
return "=";
}else if(style == "simple"){
return "";
}else if(style == "spaceDelimited"){
return "=";
}else if(style == "pipeDelimited"){
return "=";
}else
return "none";
}
QString PFXStoreApi::getParamStyleDelimiter(QString style, QString name, bool isExplode){
if(style == "matrix"){
return (isExplode) ? ";" + name + "=" : ",";
}else if(style == "label"){
return (isExplode) ? "." : ",";
}else if(style == "form"){
return (isExplode) ? "&" + name + "=" : ",";
}else if(style == "simple"){
return ",";
}else if(style == "spaceDelimited"){
return (isExplode) ? "&" + name + "=" : " ";
}else if(style == "pipeDelimited"){
return (isExplode) ? "&" + name + "=" : "|";
}else if(style == "deepObject"){
return (isExplode) ? "&" : "none";
}else
return "none";
}
void PFXStoreApi::deleteOrder(const QString &order_id) {
QString fullPath = QString(_serverConfigs["deleteOrder"][_serverIndices.value("deleteOrder")].URL()+"/store/order/{orderId}");
QString order_idPathParam("{");
order_idPathParam.append("orderId").append("}");
fullPath.replace(order_idPathParam, QUrl::toPercentEncoding(::test_namespace::toStringValue(order_id)));
QString pathPrefix, pathSuffix, pathDelimiter;
QString pathStyle = "";
if(pathStyle == "")
pathStyle = "simple";
pathPrefix = getParamStylePrefix(pathStyle);
pathSuffix = getParamStyleSuffix(pathStyle);
pathDelimiter = getParamStyleDelimiter(pathStyle, "orderId", false);
QString paramString = (pathStyle == "matrix") ? pathPrefix+"orderId"+pathSuffix : pathPrefix;
fullPath.replace(order_idPathParam, paramString+QUrl::toPercentEncoding(::test_namespace::toStringValue(order_id)));
PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager);
@ -182,6 +253,7 @@ void PFXStoreApi::getInventory() {
}
PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager);
worker->setTimeOut(_timeOut);
worker->setWorkingDirectory(_workingDirectory);
@ -228,9 +300,18 @@ void PFXStoreApi::getInventoryCallback(PFXHttpRequestWorker *worker) {
void PFXStoreApi::getOrderById(const qint64 &order_id) {
QString fullPath = QString(_serverConfigs["getOrderById"][_serverIndices.value("getOrderById")].URL()+"/store/order/{orderId}");
QString order_idPathParam("{");
order_idPathParam.append("orderId").append("}");
fullPath.replace(order_idPathParam, QUrl::toPercentEncoding(::test_namespace::toStringValue(order_id)));
QString pathPrefix, pathSuffix, pathDelimiter;
QString pathStyle = "";
if(pathStyle == "")
pathStyle = "simple";
pathPrefix = getParamStylePrefix(pathStyle);
pathSuffix = getParamStyleSuffix(pathStyle);
pathDelimiter = getParamStyleDelimiter(pathStyle, "orderId", false);
QString paramString = (pathStyle == "matrix") ? pathPrefix+"orderId"+pathSuffix : pathPrefix;
fullPath.replace(order_idPathParam, paramString+QUrl::toPercentEncoding(::test_namespace::toStringValue(order_id)));
PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager);
@ -272,14 +353,15 @@ void PFXStoreApi::placeOrder(const PFXOrder &body) {
QString fullPath = QString(_serverConfigs["placeOrder"][_serverIndices.value("placeOrder")].URL()+"/store/order");
PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager);
worker->setTimeOut(_timeOut);
worker->setWorkingDirectory(_workingDirectory);
PFXHttpRequestInput input(fullPath, "POST");
QByteArray output = body.asJson().toUtf8();
input.request_body.append(output);
foreach (QString key, this->defaultHeaders.keys()) { input.headers.insert(key, this->defaultHeaders.value(key)); }
connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXStoreApi::placeOrderCallback);

View File

@ -52,6 +52,9 @@ public:
void enableRequestCompression();
void enableResponseCompression();
void abortRequests();
QString getParamStylePrefix(QString style);
QString getParamStyleSuffix(QString style);
QString getParamStyleDelimiter(QString style, QString name, bool isExplode);
void deleteOrder(const QString &order_id);
void getInventory();

View File

@ -145,18 +145,81 @@ void PFXUserApi::abortRequests(){
emit abortRequestsSignal();
}
QString PFXUserApi::getParamStylePrefix(QString style){
if(style == "matrix"){
return ";";
}else if(style == "label"){
return ".";
}else if(style == "form"){
return "&";
}else if(style == "simple"){
return "";
}else if(style == "spaceDelimited"){
return "&";
}else if(style == "pipeDelimited"){
return "&";
}else
return "none";
}
QString PFXUserApi::getParamStyleSuffix(QString style){
if(style == "matrix"){
return "=";
}else if(style == "label"){
return "";
}else if(style == "form"){
return "=";
}else if(style == "simple"){
return "";
}else if(style == "spaceDelimited"){
return "=";
}else if(style == "pipeDelimited"){
return "=";
}else
return "none";
}
QString PFXUserApi::getParamStyleDelimiter(QString style, QString name, bool isExplode){
if(style == "matrix"){
return (isExplode) ? ";" + name + "=" : ",";
}else if(style == "label"){
return (isExplode) ? "." : ",";
}else if(style == "form"){
return (isExplode) ? "&" + name + "=" : ",";
}else if(style == "simple"){
return ",";
}else if(style == "spaceDelimited"){
return (isExplode) ? "&" + name + "=" : " ";
}else if(style == "pipeDelimited"){
return (isExplode) ? "&" + name + "=" : "|";
}else if(style == "deepObject"){
return (isExplode) ? "&" : "none";
}else
return "none";
}
void PFXUserApi::createUser(const PFXUser &body) {
QString fullPath = QString(_serverConfigs["createUser"][_serverIndices.value("createUser")].URL()+"/user");
PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager);
worker->setTimeOut(_timeOut);
worker->setWorkingDirectory(_workingDirectory);
PFXHttpRequestInput input(fullPath, "POST");
QByteArray output = body.asJson().toUtf8();
input.request_body.append(output);
foreach (QString key, this->defaultHeaders.keys()) { input.headers.insert(key, this->defaultHeaders.value(key)); }
connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXUserApi::createUserCallback);
@ -190,15 +253,16 @@ void PFXUserApi::createUsersWithArrayInput(const QList<PFXUser> &body) {
QString fullPath = QString(_serverConfigs["createUsersWithArrayInput"][_serverIndices.value("createUsersWithArrayInput")].URL()+"/user/createWithArray");
PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager);
worker->setTimeOut(_timeOut);
worker->setWorkingDirectory(_workingDirectory);
PFXHttpRequestInput input(fullPath, "POST");
QJsonDocument doc(::test_namespace::toJsonValue(body).toArray());
QByteArray bytes = doc.toJson();
input.request_body.append(bytes);
foreach (QString key, this->defaultHeaders.keys()) { input.headers.insert(key, this->defaultHeaders.value(key)); }
connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXUserApi::createUsersWithArrayInputCallback);
@ -232,15 +296,16 @@ void PFXUserApi::createUsersWithListInput(const QList<PFXUser> &body) {
QString fullPath = QString(_serverConfigs["createUsersWithListInput"][_serverIndices.value("createUsersWithListInput")].URL()+"/user/createWithList");
PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager);
worker->setTimeOut(_timeOut);
worker->setWorkingDirectory(_workingDirectory);
PFXHttpRequestInput input(fullPath, "POST");
QJsonDocument doc(::test_namespace::toJsonValue(body).toArray());
QByteArray bytes = doc.toJson();
input.request_body.append(bytes);
foreach (QString key, this->defaultHeaders.keys()) { input.headers.insert(key, this->defaultHeaders.value(key)); }
connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXUserApi::createUsersWithListInputCallback);
@ -272,9 +337,18 @@ void PFXUserApi::createUsersWithListInputCallback(PFXHttpRequestWorker *worker)
void PFXUserApi::deleteUser(const QString &username) {
QString fullPath = QString(_serverConfigs["deleteUser"][_serverIndices.value("deleteUser")].URL()+"/user/{username}");
QString usernamePathParam("{");
usernamePathParam.append("username").append("}");
fullPath.replace(usernamePathParam, QUrl::toPercentEncoding(::test_namespace::toStringValue(username)));
QString pathPrefix, pathSuffix, pathDelimiter;
QString pathStyle = "";
if(pathStyle == "")
pathStyle = "simple";
pathPrefix = getParamStylePrefix(pathStyle);
pathSuffix = getParamStyleSuffix(pathStyle);
pathDelimiter = getParamStyleDelimiter(pathStyle, "username", false);
QString paramString = (pathStyle == "matrix") ? pathPrefix+"username"+pathSuffix : pathPrefix;
fullPath.replace(usernamePathParam, paramString+QUrl::toPercentEncoding(::test_namespace::toStringValue(username)));
PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager);
@ -313,9 +387,18 @@ void PFXUserApi::deleteUserCallback(PFXHttpRequestWorker *worker) {
void PFXUserApi::getUserByName(const QString &username) {
QString fullPath = QString(_serverConfigs["getUserByName"][_serverIndices.value("getUserByName")].URL()+"/user/{username}");
QString usernamePathParam("{");
usernamePathParam.append("username").append("}");
fullPath.replace(usernamePathParam, QUrl::toPercentEncoding(::test_namespace::toStringValue(username)));
QString pathPrefix, pathSuffix, pathDelimiter;
QString pathStyle = "";
if(pathStyle == "")
pathStyle = "simple";
pathPrefix = getParamStylePrefix(pathStyle);
pathSuffix = getParamStyleSuffix(pathStyle);
pathDelimiter = getParamStyleDelimiter(pathStyle, "username", false);
QString paramString = (pathStyle == "matrix") ? pathPrefix+"username"+pathSuffix : pathPrefix;
fullPath.replace(usernamePathParam, paramString+QUrl::toPercentEncoding(::test_namespace::toStringValue(username)));
PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager);
@ -357,17 +440,31 @@ void PFXUserApi::loginUser(const QString &username, const QString &password) {
QString fullPath = QString(_serverConfigs["loginUser"][_serverIndices.value("loginUser")].URL()+"/user/login");
QString queryPrefix, querySuffix, queryDelimiter, queryStyle;
queryStyle = "";
if(queryStyle == "")
queryStyle = "form";
queryPrefix = getParamStylePrefix(queryStyle);
querySuffix = getParamStyleSuffix(queryStyle);
queryDelimiter = getParamStyleDelimiter(queryStyle, "username", false);
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
fullPath.append(queryPrefix);
else
fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("username")).append("=").append(QUrl::toPercentEncoding(::test_namespace::toStringValue(username)));
fullPath.append(QUrl::toPercentEncoding("username")).append(querySuffix).append(QUrl::toPercentEncoding(::test_namespace::toStringValue(username)));
queryStyle = "";
if(queryStyle == "")
queryStyle = "form";
queryPrefix = getParamStylePrefix(queryStyle);
querySuffix = getParamStyleSuffix(queryStyle);
queryDelimiter = getParamStyleDelimiter(queryStyle, "password", false);
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
fullPath.append(queryPrefix);
else
fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("password")).append("=").append(QUrl::toPercentEncoding(::test_namespace::toStringValue(password)));
fullPath.append(QUrl::toPercentEncoding("password")).append(querySuffix).append(QUrl::toPercentEncoding(::test_namespace::toStringValue(password)));
PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager);
worker->setTimeOut(_timeOut);
@ -409,6 +506,7 @@ void PFXUserApi::logoutUser() {
QString fullPath = QString(_serverConfigs["logoutUser"][_serverIndices.value("logoutUser")].URL()+"/user/logout");
PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager);
worker->setTimeOut(_timeOut);
worker->setWorkingDirectory(_workingDirectory);
@ -445,9 +543,18 @@ void PFXUserApi::logoutUserCallback(PFXHttpRequestWorker *worker) {
void PFXUserApi::updateUser(const QString &username, const PFXUser &body) {
QString fullPath = QString(_serverConfigs["updateUser"][_serverIndices.value("updateUser")].URL()+"/user/{username}");
QString usernamePathParam("{");
usernamePathParam.append("username").append("}");
fullPath.replace(usernamePathParam, QUrl::toPercentEncoding(::test_namespace::toStringValue(username)));
QString pathPrefix, pathSuffix, pathDelimiter;
QString pathStyle = "";
if(pathStyle == "")
pathStyle = "simple";
pathPrefix = getParamStylePrefix(pathStyle);
pathSuffix = getParamStyleSuffix(pathStyle);
pathDelimiter = getParamStyleDelimiter(pathStyle, "username", false);
QString paramString = (pathStyle == "matrix") ? pathPrefix+"username"+pathSuffix : pathPrefix;
fullPath.replace(usernamePathParam, paramString+QUrl::toPercentEncoding(::test_namespace::toStringValue(username)));
PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager);
@ -455,9 +562,9 @@ void PFXUserApi::updateUser(const QString &username, const PFXUser &body) {
worker->setWorkingDirectory(_workingDirectory);
PFXHttpRequestInput input(fullPath, "PUT");
QByteArray output = body.asJson().toUtf8();
input.request_body.append(output);
foreach (QString key, this->defaultHeaders.keys()) { input.headers.insert(key, this->defaultHeaders.value(key)); }
connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXUserApi::updateUserCallback);

View File

@ -52,6 +52,9 @@ public:
void enableRequestCompression();
void enableResponseCompression();
void abortRequests();
QString getParamStylePrefix(QString style);
QString getParamStyleSuffix(QString style);
QString getParamStyleDelimiter(QString style, QString name, bool isExplode);
void createUser(const PFXUser &body);
void createUsersWithArrayInput(const QList<PFXUser> &body);

View File

@ -350,7 +350,7 @@ module Petstore
:verbose => @config.debugging
}
if [:post, :patch, :put, :delete].include?(http_method)
if [:post, :patch, :put, :delete].includes?(http_method)
req_body = build_request_body(header_params, form_params, opts[:body])
req_opts.update body: req_body
if @config.debugging

View File

@ -249,12 +249,12 @@ module Petstore
server = servers[index]
url = server[:url]
return url unless server.key? :variables
return url unless server.has_key? :variables
# go through variable and assign a value
server[:variables].each do |name, variable|
if variables.key?(name)
if (!server[:variables][name].key?(:enum_values) || server[:variables][name][:enum_values].include?(variables[name]))
if variables.has_key?(name)
if (!server[:variables][name].has_key?(:enum_values) || server[:variables][name][:enum_values].includes?(variables[name]))
url.gsub! "{" + name.to_s + "}", variables[name]
else
raise ArgumentError.new("The variable `#{name}` in the server URL has invalid value #{variables[name]}. Must be #{server[:variables][name][:enum_values]}.")

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