Compare commits

...

52 Commits

Author SHA1 Message Date
William Cheng
197294a167 Prepare 4.1.1 release (#3756)
* 4.1.1 release

* update doc
2019-08-26 15:59:33 +08:00
William Cheng
7afd350616 [WIP] Escape import with underscore in go-experimental client (#3659)
* escape import with underscore in go client

* update ioutil

* Fix collectionFormat=multi request bug in go experimental
2019-08-26 10:38:24 +08:00
William Cheng
7e772e1b71 comment out qt5 cpp tests 2019-08-26 09:30:30 +08:00
Jim Schubert
ee7c8a82e8 [BUG][CLI][GENERATOR] NullPointer when not setting outputDir (updated) (#3752)
* Fixes NPE when no outputDir is set

* Fix behaviors of default values for values not provided by user

* Easier handling of default behavior in settings.

* Fixes for dynamic config deserialization (specifically, ruby client sample fix)

* Tests for WorkflowSettings (defaults, modified defaults, nulls)

* Test modification of WorkflowSettings defaults for both class constructor and builder
2019-08-25 19:19:52 -04:00
William Cheng
136c1407ac Move tests to Drone.io CI (#3754)
* move tests to drone.io

* ls dir

* debug

* use bash

* use jdk 11 image

* move tests to drone.io

* use maven wrapper

* comment out scripts in circleci

* update dart samples

* remove commented tests

* update dart samples
2019-08-26 00:35:51 +08:00
William Cheng
5289262aec Add a link to bitmovin blog post (#3753) 2019-08-25 23:19:04 +08:00
William Cheng
cba2d3b8cf Merge branch 'master' of https://github.com/OpenAPITools/openapi-generator 2019-08-25 18:05:50 +08:00
William Cheng
cd6b844d75 update python samples 2019-08-25 18:05:37 +08:00
FlorianBruckner
16ac05dcdf Two tiny fixes for Java Vertx client (#3683)
* two tiny fixes:

1.) ApiClient already defines and configures an objectMapper to not fail on unknown properties, but it is not used when parsing the response. The fix uses the pre-configured object mapper instead of the vertx default one

2.) When an operation has no response (or just ones without content), the accept array passed to ApiClient is emtpy. This makes the null check in ApiClient useless, as it still tries to set a null Accept header, which is refused with an NPE. Amend the check with .length > 0 to catch this case.

* update generated client as required by contributor guidelines
2019-08-25 18:02:36 +08:00
Andreas Kägi
859df23428 Exclude "test" from packages so that it is not installed as top-level package when "pip installing" the generated sdk (#3731) 2019-08-25 17:59:38 +08:00
sullis
e12459f3bd [java-client] add unit test for JDK 11 HttpClient (#3735) 2019-08-25 17:15:46 +08:00
Ramanth Addala
8cd5a4187b [R] feat(r): handling error response for 3xx cases (#3571)
* feat(r): handling error response for 3xx cases

* fix(r) : changed the message for 3XX case

* fix(r) : fixing the status code 3xx
2019-08-25 01:21:03 +08:00
Nick Meinhold
a05f68431a [Dart] Avoid redundant null checking in fromJson (#3632)
* Move dart null checks inside mustache type checks

- removed surrounding null check
- added a conditional expression to each case except the redundant one

* Run shell scripts so CIs can verify the change
2019-08-25 01:16:32 +08:00
Jim Schubert
15f680e1eb [core] Set isMultipart=true for multipart operations, fix possible NPE (#3750) 2019-08-25 01:02:12 +08:00
William Cheng
0beb8caa85 reenable kotlin client tests in shippable ci (#3751) 2019-08-25 00:53:11 +08:00
Armand Mégrot
1f5aa22f5c Fix null assignation to header/query param map (#3749)
Also regenerates the clients
2019-08-24 23:09:57 +08:00
sullis
dfb4c133d8 Mockito 3.0.0 (#3732) 2019-08-24 21:40:24 +08:00
Jérémie Bresson
286ddf38f7 Update to swagger-parser to 2.0.14-OpenAPITools.org-1 (#3737) 2019-08-24 10:40:05 +02:00
William Cheng
761e435248 Add a link to a Qiita blog post (#3747)
Add a link to a Qiita blog post
2019-08-24 11:59:47 +08:00
William Cheng
1188d0f141 update csharp samples 2019-08-24 11:55:16 +08:00
Jake Moening
a390676cc6 Simple spelling error in dotnet core comments (#3746)
* Simple spelling error in dotnet core comments

Dictioary -> Dictionary

* Updated the sample files as well.
2019-08-24 11:35:11 +08:00
William Cheng
b8f9e995ce better support for multipart (#3736) 2019-08-24 11:24:51 +08:00
Josh Giles
158cdfeb3c [typescript-fetch] fix #1998: prefix req ifaces. (#3740)
Prefix generated request interface names with API classname rather than
using namespaces, because namespaces are not well-supported by some
tooling (in particular, Babel).
2019-08-23 16:58:51 +02:00
Martin Delille
1fc03c88b2 cpp-qt5-client: add valgrind memory test (#3663) 2019-08-23 14:23:47 +02:00
Daniel Schreiber
d64ec14ab4 [typescript-angular] Encode objects for multipart/form-data with json - fixes #2733 (#3738) 2019-08-23 13:54:14 +02:00
thecrazzymouse
73eae09738 [BUG] Https protocol schema is not handled correctly in java 11 native code #3729 (#3730)
* added getter for schema
2019-08-23 13:52:48 +02:00
William Cheng
96dd31a462 comment out kotlin client tests 2019-08-23 17:45:47 +08:00
William Cheng
14a39349d5 update kotlin client sample 2019-08-22 21:43:06 +08:00
Armand Mégrot
4898ffa4e9 [Kotlin-client] Authentication support (#3722)
* Handle and document authorization for kotlin client

* Regenerate clients and tests

* Remove testing files
2019-08-22 21:32:07 +08:00
James Russo
62ca0c78ff [csharp] Update UserAgent in the async version of ClientAPI execute method. (#3723)
* move UserAgent up to the constructor

* userAgent on both constructors.

* update location of UserAgent

* re-ran the petstore generation
2019-08-22 20:24:32 +08:00
Shogoki
a748e1ff9a [BUG][Python-Flask] Primitive type bytearray deserialization missing in util.py. #2724 (#3642)
* added bytearray to list of types

* adding regenerated sample files for python-flask
2019-08-22 17:15:10 +08:00
William Cheng
8741a8ca35 Minor enhancements to the Avro schema generator (#3728)
* minor enhancements to the avro generator

* add option to customize package name

* update doc
2019-08-22 16:06:04 +08:00
Jérémie Bresson
870bb1c858 [java-client][resteasy][jersey2][google-api-client][okhttp-json] several fixes to make sent requests more accurate (#3703) 2019-08-22 09:50:47 +02:00
sullis
f6ead7b877 [java][JAX-RS] enhance JavaJAXRSSpecServerCodegenTest (#3727) 2019-08-22 09:45:31 +02:00
sgadouar
abfef86c8b feature/add-avro-generator (#3662)
* feature/add-avro-generator

* feature/add-avro-generator

* review/test/change output folder generation for avro

* doc/update copyright for avro generator
2019-08-22 14:39:35 +08:00
Josh Giles
b323b0a0af [typescript-fetch] Fix #1998: namespace reqs. (#3695)
* [typescript-fetch] Fix #1998: namespace reqs.

Fix #1998 by namespacing the generated request object types used in the
typescript-fetch client codegen.

* Update petstore samples.

* Add default-false namespacing config option.

* Re-run code sample generation.

* Add maven build configurations.

* Fix sample VERSION files.

* Update typescript-fetch docs.

* Emulate with-npm-version, adding package.json.

* Add Paxos to companies using.

* Prefix namespace with basename to avoid collisions.
2019-08-22 07:59:34 +02:00
sullis
1a808dd644 [java] use javaparser library to detect syntax errors in the tests (#3715) 2019-08-22 07:34:28 +02:00
William Cheng
d09e097e4e update qna with more info on nullable (#3726) 2019-08-22 11:39:57 +08:00
William Cheng
9de908a386 comment out ts axios test due to ci build failure 2019-08-21 22:02:45 +08:00
Jérémie Bresson
57236bc846 [java-client][resteasy] support bearer authentication (#3706) 2019-08-21 21:38:27 +08:00
Sai Giridhar P
6924b3c710 [csharp-netcore] Making HTTP response headers dictionary case-insensitive (#3707)
* fix(csharp-netcore): Making response headers case-insensitive

* fix(r): Adding response headers on docs
2019-08-21 21:20:05 +08:00
William Cheng
bb5cd4c42d [Dart] test Dart petstore clients in drone.io (#3717)
* test dart 1x in drone

* update dart image

* trigger build failure

* Revert "trigger build failure"

This reverts commit d565f348ba.

* add dart 2 test

* update build runner version

* test dart2

* only test dart jaguar

* remove pubspec.lock

* better wording

* use pub run test

* revert changes in build_runner

* update test in pom.xml

* update samples

* add dart scripts to ensure up-to-date
2019-08-21 18:19:38 +08:00
Sai Giridhar P
94eb6860aa [csharp-netcore]: Fixing the build issues (#3681)
* fix(csharp-netcore): Fixing the build issues

* fix(csharp-netcore): Fixing the build issues

* fix(csharp-netcore): Fixing the Pet project

* fix(csharp-netcore): help fixes
2019-08-21 18:18:58 +08:00
Sai Giridhar P
10a310ef69 [r] Updating api docs to include HTTP response codes and their corresponding headers (#3699)
* fix(r): Adding response headers on docs

* fix(r): Adding response headers on docs
2019-08-21 10:21:56 +08:00
sullis
50253f2b15 Swagger 2.0.8 (#3710) 2019-08-21 10:16:41 +08:00
sullis
99d7b4e70b maven-compiler-plugin 3.8.1 (#3711) 2019-08-21 10:15:21 +08:00
sullis
2ee0c34347 fix typo in [TestUtils] (#3713) 2019-08-21 10:14:32 +08:00
William Cheng
4575b3074a [Go] add option to use class as enum prefix (#3675)
* add option to use class as enum prefix

* update doc

* fix go test

* update go xml petstore

* fix format
2019-08-20 00:33:08 +08:00
benjaminr-ps
7abd2e141a mention Java Jersey server-side code-generator (#3685) 2019-08-20 00:19:02 +08:00
Martin Delille
1adb0ba588 cpp-qt5-client: Improve tests (#3667) 2019-08-19 17:58:03 +02:00
Akihito Nakano
6addd76e11 Add a test case for inline models within Callback Object (#3665) 2019-08-19 22:52:06 +08:00
Jérémie Bresson
8c498fb08a [java-client][jersey2][resteasy] add support for OPTIONS method (#3677)
* [java-client][jersey2][resteasy] add support for OPTIONS method

* Update samples
2019-08-19 22:51:18 +08:00
491 changed files with 7466 additions and 3521 deletions

View File

@@ -94,6 +94,8 @@ before_install:
# - Rely on `kerl` for [pre-compiled versions available](https://docs.travis-ci.com/user/languages/erlang#Choosing-OTP-releases-to-test-against). Rely on installation path chosen by [`travis-erlang-builder`](https://github.com/travis-ci/travis-erlang-builder/blob/e6d016b1a91ca7ecac5a5a46395bde917ea13d36/bin/compile#L18).
# - . ~/otp/18.2.1/activate && erl -version
#- curl -f -L -o ./rebar3 https://s3.amazonaws.com/rebar3/rebar3 && chmod +x ./rebar3 && ./rebar3 version && export PATH="${TRAVIS_BUILD_DIR}:$PATH"
# install valgrind for C++ memory test
- sudo apt-get install valgrind
# install Qt 5.10
- sudo add-apt-repository --yes ppa:beineri/opt-qt-5.10.1-trusty
- sudo apt-get update -qq

View File

@@ -2,12 +2,27 @@ kind: pipeline
name: default
steps:
# test Dart 2.x petstore client
- name: dart2x-test
image: google/dart
commands:
- (cd samples/client/petstore/dart-jaguar/openapi && pub get && pub run build_runner build --delete-conflicting-outputs)
- (cd samples/client/petstore/dart-jaguar/flutter_petstore/openapi && pub get && pub run build_runner build --delete-conflicting-outputs)
- (cd samples/client/petstore/dart2/openapi && pub get && pub run test)
# test Java 11 HTTP client
- name: java11-test
image: hirokimatsumoto/alpine-openjdk-11
image: openjdk:11.0
commands:
- ./mvnw clean install
- ./mvnw --quiet verify -Psamples.droneio
# test all generators with fake petstore spec (2.0, 3.0)
- /bin/bash bin/utils/test-fake-petstore-for-all.sh
# generate test scripts
- /bin/bash bin/tests/run-all-test
# generate all petstore samples (client, servers, doc)
- /bin/bash bin/run-all-petstore
# generate all petstore samples (openapi3)
- /bin/bash bin/openapi3/run-all-petstore
# test ocaml petstore client
- name: ocaml-test
image: ocaml/opam2:4.07

View File

@@ -14,14 +14,6 @@ if [ "$NODE_INDEX" = "1" ]; then
mvn --quiet verify -Psamples.circleci
mvn --quiet javadoc:javadoc -Psamples.circleci
# generate all petstore samples (client, servers, doc)
./bin/run-all-petstore
# generate all petstore samples (openapi3)
./bin/openapi3/run-all-petstore
# generate test scripts
./bin/tests/run-all-test
# test all generators with fake petstore spec (2.0, 3.0)
./bin/utils/test-fake-petstore-for-all.sh
elif [ "$NODE_INDEX" = "2" ]; then
# run ensure-up-to-date sample script on SNAPSHOT version only
project_version=`mvn org.apache.maven.plugins:maven-help-plugin:3.1.0:evaluate -Dexpression=project.version -q -DforceStdout`
@@ -29,12 +21,6 @@ elif [ "$NODE_INDEX" = "2" ]; then
echo "Running node $NODE_INDEX to test ensure-up-to-date"
java -version
# install elm-format for formatting elm code
npm install -g elm-format
# symlink elm-format
sudo ln -s /opt/circleci/.nvm/versions/node/v12.1.0/bin/elm-format /usr/local/bin/elm-format
./bin/utils/ensure-up-to-date
fi
#elif [ "$NODE_INDEX" = "3" ]; then

View File

@@ -0,0 +1,73 @@
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>org.openapitools</groupId>
<artifactId>TypeScriptFetchBuildPrefixParameterInterfacesPestoreClientTests</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<name>TS Fetch Petstore Client (with namespacing for parameter interfaces)</name>
<build>
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<id>npm-install</id>
<phase>integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>npm</executable>
<arguments>
<argument>install</argument>
</arguments>
</configuration>
</execution>
<execution>
<id>npm-build</id>
<phase>integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>npm</executable>
<arguments>
<argument>run</argument>
<argument>build</argument>
</arguments>
</configuration>
</execution>
<execution>
<id>npm-test</id>
<phase>integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>npm</executable>
<arguments>
<argument>test</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@@ -2,7 +2,7 @@
<div align="center">
[Master](https://github.com/OpenAPITools/openapi-generator/tree/master) (`4.1.0`): [![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/master.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator)
[Master](https://github.com/OpenAPITools/openapi-generator/tree/master) (`4.1.1`): [![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)
[![Windows Test](https://ci.appveyor.com/api/projects/status/github/openapitools/openapi-generator?branch=master&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/openapi-generator-wh2wu)
@@ -66,7 +66,7 @@ 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), **C++** (cpp-restsdk, Qt5, Tizen), **Clojure**, **Dart (1.x, 2.x)**, **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), **Kotlin**, **Lua**, **Node.js/JavaScript** (ES5, ES6, AngularJS with Google Closure Compiler annotations, Flow types), **Objective-C**, **OCaml**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (rust, rust-server), **Scala** (akka, http4s, scalaz, swagger-async-httpclient), **Swift** (2.x, 3.x, 4.x), **Typescript** (AngularJS, Angular (2.x - 8.x), Aurelia, Axios, Fetch, Inversify, jQuery, Node, 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, RestEasy, Play Framework, [PKMST](https://github.com/ProKarma-Inc/pkmst-getting-started-examples)), **Kotlin** (Spring Boot, Ktor), **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** ([Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), [Play](https://www.playframework.com/), Scalatra)
**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)), **Kotlin** (Spring Boot, Ktor), **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** ([Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), [Play](https://www.playframework.com/), Scalatra)
**API documentation generators** | **HTML**, **Confluence Wiki**
**Configuration files** | [**Apache2**](https://httpd.apache.org/)
**Others** | **GraphQL**, **JMeter**, **MySQL Schema**
@@ -108,8 +108,8 @@ OpenAPI Generator Version | Release Date | Notes
---------------------------- | ------------ | -----
5.0.0 (upcoming major release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/5.0.0-SNAPSHOT/)| 13.05.2020 | Major release with breaking changes (no fallback)
4.2.0 (upcoming minor release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/4.2.0-SNAPSHOT/)| 09.10.2019 | Minor release (breaking changes with fallbacks)
4.1.1 (upcoming minor release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/4.1.1-SNAPSHOT/)| 23.08.2019 | Patch release (bug fixes, enhancements)
[4.1.0](https://github.com/OpenAPITools/openapi-generator/releases/tag/v4.1.0) (latest stable release) | 09.08.2019 | Minor release (breaking changes with fallbacks)
4.1.1 (upcoming minor release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/4.1.1/)| 23.08.2019 | Patch release (bug fixes, enhancements)
[4.1.1](https://github.com/OpenAPITools/openapi-generator/releases/tag/v4.1.1) (latest stable release) | 09.08.2019 | Minor release (breaking changes with fallbacks)
OpenAPI Spec compatibility: 1.0, 1.1, 1.2, 2.0, 3.0
@@ -165,16 +165,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: `http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/4.1.0/openapi-generator-cli-4.1.0.jar`
JAR location: `http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/4.1.1/openapi-generator-cli-4.1.1.jar`
For **Mac/Linux** users:
```sh
wget http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/4.1.0/openapi-generator-cli-4.1.0.jar -O openapi-generator-cli.jar
wget http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/4.1.1/openapi-generator-cli-4.1.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 http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/4.1.0/openapi-generator-cli-4.1.0.jar
Invoke-WebRequest -OutFile openapi-generator-cli.jar http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/4.1.1/openapi-generator-cli-4.1.1.jar
```
After downloading the JAR, run `java -jar openapi-generator-cli.jar help` to show the usage.
@@ -389,10 +389,10 @@ openapi-generator version
```
<!-- RELEASE_VERSION -->
Or install a particular OpenAPI Generator version (e.g. v4.1.0):
Or install a particular OpenAPI Generator version (e.g. v4.1.1):
```sh
npm install @openapitools/openapi-generator-cli@cli-4.1.0 -g
npm install @openapitools/openapi-generator-cli@cli-4.1.1 -g
```
Or install it as dev-dependency:
@@ -416,7 +416,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/2_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](http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/4.1.0/openapi-generator-cli-4.1.0.jar)
You can also download the JAR (latest release) directly from [maven.org](http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/4.1.1/openapi-generator-cli-4.1.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`
@@ -569,6 +569,7 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- [Klarna](https://www.klarna.com/)
- [Metaswitch](https://www.metaswitch.com/)
- [Myworkout](https://myworkout.com)
- [Paxos](https://www.paxos.com)
- [Prometheus/Alertmanager](https://github.com/prometheus/alertmanager)
- [Raiffeisen Schweiz Genossenschaft](https://www.raiffeisen.ch)
- [RepreZen API Studio](https://www.reprezen.com/swagger-openapi-code-generation-api-first-microservices-enterprise-development)
@@ -626,6 +627,8 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- 2019-07-08 - [OpenAPI Generator にコントリビュートしたら社名が載った話。(CAM) - CAM TECH BLOG](https://tech.cam-inc.co.jp/entry/2019/07/08/140000) by [CAM, Inc.](https://www.cam-inc.co.jp/)
- 2019-07-14 - [OpenAPI GeneratorでPythonのクライアントライブラリを作成した](https://qiita.com/yuji38kwmt/items/dfb929316a1335a161c0) by [yuji38kwmt](https://qiita.com/yuji38kwmt)
- 2019-07-19 - [Developer Experience (DX) for Open-Source Projects: How to Engage Developers and Build a Growing Developer Community](https://speakerdeck.com/wing328/developer-experience-dx-for-open-source-projects-english-japanese) by [William Cheng](https://twitter.com/wing328), [中野暁人](https://github.com/ackintosh) at [Open Source Summit Japan 2019](https://events.linuxfoundation.org/events/open-source-summit-japan-2019/)
- 2019-08-14 - [Our OpenAPI journey with Standardizing SDKs](https://bitmovin.com/our-openapi-journey-with-standardizing-sdks/) by [Sebastian Burgstaller](https://bitmovin.com/author/sburgstaller/) at [Bitmovin](https://www.bitmovin.com)
- 2019-08-24 - [SwaggerドキュメントからOpenAPI Generatorを使ってモックサーバー作成](https://qiita.com/masayoshi0222/items/4845e4c715d04587c104) by [坂本正義](https://qiita.com/masayoshi0222)
## [6 - About Us](#table-of-contents)
@@ -755,6 +758,7 @@ Here is a list of template creators:
* Configuration
* Apache2: @stkrwork
* Schema
* Avro: @sgadouar
* GraphQL: @wing328 [:heart:](https://www.patreon.com/wing328)
* MySQL: @ybelenko

View File

@@ -22,7 +22,7 @@ executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar"
if [ ! -f "$executable" ]
then
mvn -B clean package
./mvnw -B clean package
fi
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
@@ -30,7 +30,7 @@ ags="meta -n myClientCodegen -t DOCUMENTATION -p com.my.company.codegen -o sampl
java $JAVA_OPTS -jar $executable $ags
mvn clean package -f samples/meta-codegen/pom.xml
./mvnw clean package -f samples/meta-codegen/pom.xml
ags2="generate -g myClientCodegen -i modules/openapi-generator/src/test/resources/2_0/petstore.json -o samples/meta-codegen/usage $@"

32
bin/openapi3/avro-petstore.sh Executable file
View File

@@ -0,0 +1,32 @@
#!/bin/sh
SCRIPT="$0"
echo "# START SCRIPT: $SCRIPT"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar"
if [ ! -f "$executable" ]
then
mvn clean package
fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/avro-schema -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g avro-schema -o samples/openapi3/schema/petstore/avro-schema $@"
java $JAVA_OPTS -jar $executable $ags

View File

@@ -4,3 +4,4 @@
./bin/openapi3/typescript-fetch-petstore-with-npm-version.sh
./bin/openapi3/typescript-fetch-petstore-interfaces.sh
./bin/openapi3/typescript-fetch-petstore.sh
./bin/openapi3/typescript-fetch-petstore-prefix-parameter-interfaces.sh

View File

@@ -0,0 +1,32 @@
#!/bin/sh
SCRIPT="$0"
echo "# START SCRIPT: $SCRIPT"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar"
if [ ! -f "$executable" ]
then
mvn clean package
fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g typescript-fetch -o samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces --additional-properties prefixParameterInterfaces=true $@"
java $JAVA_OPTS -jar $executable $ags

View File

@@ -2,5 +2,6 @@
"gemName": "petstore",
"moduleName": "Petstore",
"library": "faraday",
"gemVersion": "1.0.0"
"gemVersion": "1.0.0",
"strictSpecBehavior": false
}

View File

@@ -2,5 +2,6 @@
"gemName": "petstore",
"library": "typhoeus",
"moduleName": "Petstore",
"gemVersion": "1.0.0"
"gemVersion": "1.0.0",
"strictSpecBehavior": false
}

View File

@@ -4,4 +4,5 @@
./bin/typescript-fetch-petstore-with-npm-version.sh
./bin/typescript-fetch-petstore-interfaces.sh
./bin/typescript-fetch-petstore.sh
./bin/typescript-fetch-petstore-multiple-parameters.sh
./bin/typescript-fetch-petstore-multiple-parameters.sh
./bin/typescript-fetch-petstore-prefix-parameter-interfaces.sh

View File

@@ -0,0 +1,7 @@
{
"npmName": "@openapitools/typescript-fetch-petstore",
"npmVersion": "1.0.0",
"npmRepository" : "https://skimdb.npmjs.com/registry",
"snapshot" : false,
"prefixParameterInterfaces": true
}

View File

@@ -0,0 +1,34 @@
#!/bin/sh
SCRIPT="$0"
echo "# START SCRIPT: $SCRIPT"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar"
if [ ! -f "$executable" ]
then
mvn -B clean package
fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g typescript-fetch -c bin/typescript-fetch-petstore-prefix-parameter-interfaces.json -o samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces $@"
java $JAVA_OPTS -jar $executable $ags
cp CI/samples.ci/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/pom.xml samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/pom.xml

View File

@@ -59,6 +59,9 @@ declare -a scripts=(
"./bin/apex-petstore.sh"
"./bin/perl-petstore-all.sh"
"./bin/dart-jaguar-petstore.sh"
"./bin/dart-flutter-petstore.sh"
"./bin/dart-petstore.sh"
"./bin/dart2-petstore.sh"
#"./bin/elm-petstore-all.sh"
"./bin/meta-codegen.sh"
# OTHERS

View File

@@ -5,3 +5,4 @@ call bin\windows\typescript-fetch-petstore-target-es6.bat
call bin\windows\typescript-fetch-petstore-with-npm-version.bat
call bin\windows\typescript-fetch-petstore-interfaces.bat
call bin\windows\typescript-fetch-petstore-multiple-parameters.bat
call bin\windows\typescript-fetch-petstore-prefix-parameter-interfaces.bat

View File

@@ -0,0 +1,12 @@
@ECHO OFF
set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar
If Not Exist %executable% (
mvn clean package
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g typescript-fetch -o samples\client\petstore\typescript-fetch\builds\prefix-parameter-interfaces --additional-properties prefixParameterInterfaces=true
java %JAVA_OPTS% -jar %executable% %ags%

View File

@@ -125,6 +125,7 @@ The following generators are available:
## SCHEMA generators
* [avro-schema (beta)](generators/avro-schema)
* [mysql-schema](generators/mysql-schema)

View File

@@ -0,0 +1,14 @@
---
id: generator-opts-schema-avro-schema
title: Config Options for avro-schema
sidebar_label: avro-schema
---
| Option | Description | Values | Default |
| ------ | ----------- | ------ | ------- |
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false|
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
|packageName|package for generated classes (where supported)| |null|

View File

@@ -12,7 +12,7 @@ sidebar_label: csharp-netcore
|sourceFolder|source folder for generated code| |src|
|packageGuid|The GUID that will be associated with the C# project| |null|
|interfacePrefix|Prefix interfaces with a community standard or widely accepted prefix.| |I|
|targetFramework|The target .NET framework version.|<dl><dt>**netstandard1.3**</dt><dd>.NET Standard 1.3 compatible</dd><dt>**netstandard1.4**</dt><dd>.NET Standard 1.4 compatible</dd><dt>**netstandard1.5**</dt><dd>.NET Standard 1.5 compatible</dd><dt>**netstandard1.6**</dt><dd>.NET Standard 1.6 compatible</dd><dt>**netstandard2.0**</dt><dd>.NET Standard 2.0 compatible</dd><dt>**netcoreapp2.0**</dt><dd>.NET Core 2.0 compatible</dd><dl>|v4.6.1|
|targetFramework|The target .NET framework version.|<dl><dt>**netstandard1.3**</dt><dd>.NET Standard 1.3 compatible</dd><dt>**netstandard1.4**</dt><dd>.NET Standard 1.4 compatible</dd><dt>**netstandard1.5**</dt><dd>.NET Standard 1.5 compatible</dd><dt>**netstandard1.6**</dt><dd>.NET Standard 1.6 compatible</dd><dt>**netstandard2.0**</dt><dd>.NET Standard 2.0 compatible</dd><dt>**netcoreapp2.0**</dt><dd>.NET Core 2.0 compatible</dd><dl>|netstandard2.0|
|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |PascalCase|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true|
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
@@ -26,3 +26,4 @@ sidebar_label: csharp-netcore
|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false|
|netCoreProjectFile|Use the new format (.NET Core) for .NET project files (.csproj).| |false|
|validatable|Generates self-validatable models.| |true|
|caseInsensitiveResponseHeaders|Make API response's headers case-insensitive| |false|

View File

@@ -13,4 +13,5 @@ sidebar_label: go-experimental
|isGoSubmodule|whether the generated Go module is a submodule| |false|
|withGoCodegenComment|whether to include Go codegen comment to disable Go Lint and collapse by default GitHub in PRs and diffs| |false|
|withXml|whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)| |false|
|enumClassPrefix|Prefix enum with class name| |false|
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|

View File

@@ -13,4 +13,5 @@ sidebar_label: go
|isGoSubmodule|whether the generated Go module is a submodule| |false|
|withGoCodegenComment|whether to include Go codegen comment to disable Go Lint and collapse by default GitHub in PRs and diffs| |false|
|withXml|whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)| |false|
|enumClassPrefix|Prefix enum with class name| |false|
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|

View File

@@ -19,3 +19,4 @@ sidebar_label: typescript-fetch
|npmRepository|Use this property to set an url your private npmRepo in the package.json| |null|
|withInterfaces|Setting this property to true will generate interfaces next to the default class implementations.| |false|
|useSingleRequestParameter|Setting this property to true will generate functions with a single argument containing all API endpoint parameters instead of one argument per parameter.| |true|
|prefixParameterInterfaces|Setting this property to true will generate parameter interface declarations prefixed with API class name to avoid name conflicts.| |false|

View File

@@ -3,7 +3,7 @@ id: swagger-codegen-migration
title: Migrating from Swagger Codegen
---
OpenAPI Generator is a fork of `swagger-codegen` between version `2.3.1` and `2.4.0`.
OpenAPI Generator is a fork of `swagger-codegen` between version `2.3.1` and `2.4.0`. For the reasons behind the fork, please refer to the [Q&A](https://github.com/OpenAPITools/openapi-generator/blob/master/docs/qna.md).
This community-driven version called "OpenAPI Generator" provides similar functionalities and can be used as drop-in replacement.
This guide explains the major differences in order to help you with the migration.
@@ -22,6 +22,7 @@ This guide explains the major differences in order to help you with the migratio
- [New fully qualified name for the classes](#new-fully-qualified-name-for-the-classes)
- [Body parameter name](#body-parameter-name)
- [Default basePath](#default-basepath)
- [Nullable](#nullable)
## New docker images
@@ -250,3 +251,7 @@ If your API client is using named parameters in the function call (e.g. Perl req
## Default basePath
The default `basePath` has been changed from `https://localhost` to `http://localhost` (http without s)
## Nullable
OpenAPI spec v3 has better support for `nullable`. If you're still using OpenAPI/Swagger spec v2, please use `x-nullable: true` instead.

View File

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

View File

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

View File

@@ -421,13 +421,27 @@ public final class GeneratorSettings implements Serializable {
builder.artifactId = copy.getArtifactId();
builder.artifactVersion = copy.getArtifactVersion();
builder.library = copy.getLibrary();
builder.instantiationTypes = new HashMap<>(copy.getInstantiationTypes());
builder.typeMappings = new HashMap<>(copy.getTypeMappings());
builder.additionalProperties = new HashMap<>(copy.getAdditionalProperties());
builder.importMappings = new HashMap<>(copy.getImportMappings());
builder.languageSpecificPrimitives = new HashSet<>(copy.getLanguageSpecificPrimitives());
builder.reservedWordMappings = new HashMap<>(copy.getReservedWordMappings());
builder.serverVariables = new HashMap<>(copy.getServerVariables());
if (copy.getInstantiationTypes() != null) {
builder.instantiationTypes.putAll(copy.getInstantiationTypes());
}
if (copy.getTypeMappings() != null) {
builder.typeMappings.putAll(copy.getTypeMappings());
}
if (copy.getAdditionalProperties() != null) {
builder.additionalProperties.putAll(copy.getAdditionalProperties());
}
if (copy.getImportMappings() != null) {
builder.importMappings.putAll(copy.getImportMappings());
}
if (copy.getLanguageSpecificPrimitives() != null) {
builder.languageSpecificPrimitives.addAll(copy.getLanguageSpecificPrimitives());
}
if (copy.getReservedWordMappings() != null) {
builder.reservedWordMappings.putAll(copy.getReservedWordMappings());
}
if (copy.getServerVariables() != null) {
builder.serverVariables.putAll(copy.getServerVariables());
}
builder.gitUserId = copy.getGitUserId();
builder.gitRepoId = copy.getGitRepoId();
builder.releaseNote = copy.getReleaseNote();

View File

@@ -33,38 +33,48 @@ import java.util.Objects;
public class WorkflowSettings {
private static final Logger LOGGER = LoggerFactory.getLogger(WorkflowSettings.class);
public static final String DEFAULT_OUTPUT_DIR = ".";
public static final boolean DEFAULT_VERBOSE = false;
public static final boolean DEFAULT_SKIP_OVERWRITE = false;
public static final boolean DEFAULT_REMOVE_OPERATION_ID_PREFIX = false;
public static final boolean DEFAULT_LOG_TO_STDERR = false;
public static final boolean DEFAULT_VALIDATE_SPEC = true;
public static final boolean DEFAULT_ENABLE_POST_PROCESS_FILE = false;
public static final boolean DEFAULT_ENABLE_MINIMAL_UPDATE = false;
public static final boolean DEFAULT_STRICT_SPEC_BEHAVIOR = true;
public static final String DEFAULT_TEMPLATING_ENGINE_NAME = "mustache";
public static final ImmutableMap<String, String> DEFAULT_SYSTEM_PROPERTIES = ImmutableMap.of();
private String inputSpec;
private String outputDir;
private boolean verbose;
private boolean skipOverwrite;
private boolean removeOperationIdPrefix;
private boolean logToStderr;
private boolean validateSpec;
private boolean enablePostProcessFile;
private boolean enableMinimalUpdate;
private boolean strictSpecBehavior;
private String outputDir = DEFAULT_OUTPUT_DIR;
private boolean verbose = DEFAULT_VERBOSE;
private boolean skipOverwrite = DEFAULT_SKIP_OVERWRITE;
private boolean removeOperationIdPrefix = DEFAULT_REMOVE_OPERATION_ID_PREFIX;
private boolean logToStderr = DEFAULT_LOG_TO_STDERR;
private boolean validateSpec = DEFAULT_VALIDATE_SPEC;
private boolean enablePostProcessFile = DEFAULT_ENABLE_POST_PROCESS_FILE;
private boolean enableMinimalUpdate = DEFAULT_ENABLE_MINIMAL_UPDATE;
private boolean strictSpecBehavior = DEFAULT_STRICT_SPEC_BEHAVIOR;
private String templateDir;
private String templatingEngineName;
private String templatingEngineName = DEFAULT_TEMPLATING_ENGINE_NAME;
private String ignoreFileOverride;
private ImmutableMap<String, String> systemProperties;
private ImmutableMap<String, String> systemProperties = DEFAULT_SYSTEM_PROPERTIES;
private WorkflowSettings(Builder builder) {
setDefaults();
inputSpec = builder.inputSpec;
outputDir = builder.outputDir;
verbose = builder.verbose;
skipOverwrite = builder.skipOverwrite;
removeOperationIdPrefix = builder.removeOperationIdPrefix;
logToStderr = builder.logToStderr;
validateSpec = builder.validateSpec;
enablePostProcessFile = builder.enablePostProcessFile;
enableMinimalUpdate = builder.enableMinimalUpdate;
strictSpecBehavior = builder.strictSpecBehavior;
templateDir = builder.templateDir;
templatingEngineName = builder.templatingEngineName;
ignoreFileOverride = builder.ignoreFileOverride;
systemProperties = ImmutableMap.copyOf(builder.systemProperties);
this.inputSpec = builder.inputSpec;
this.outputDir = builder.outputDir;
this.verbose = builder.verbose;
this.skipOverwrite = builder.skipOverwrite;
this.removeOperationIdPrefix = builder.removeOperationIdPrefix;
this.logToStderr = builder.logToStderr;
this.validateSpec = builder.validateSpec;
this.enablePostProcessFile = builder.enablePostProcessFile;
this.enableMinimalUpdate = builder.enableMinimalUpdate;
this.strictSpecBehavior = builder.strictSpecBehavior;
this.templateDir = builder.templateDir;
this.templatingEngineName = builder.templatingEngineName;
this.ignoreFileOverride = builder.ignoreFileOverride;
this.systemProperties = ImmutableMap.copyOf(builder.systemProperties);
}
/**
@@ -72,14 +82,7 @@ public class WorkflowSettings {
*/
@SuppressWarnings("unused")
public WorkflowSettings() {
setDefaults();
systemProperties = ImmutableMap.of();
}
private void setDefaults(){
validateSpec = true;
strictSpecBehavior = true;
outputDir = ".";
}
public static Builder newBuilder() {
@@ -87,7 +90,7 @@ public class WorkflowSettings {
}
public static Builder newBuilder(WorkflowSettings copy) {
Builder builder = new Builder();
Builder builder = newBuilder();
builder.inputSpec = copy.getInputSpec();
builder.outputDir = copy.getOutputDir();
builder.verbose = copy.isVerbose();
@@ -257,24 +260,24 @@ public class WorkflowSettings {
@SuppressWarnings("unused")
public static final class Builder {
private String inputSpec;
private String outputDir;
private boolean verbose;
private boolean skipOverwrite;
private boolean removeOperationIdPrefix;
private boolean logToStderr;
private boolean validateSpec;
private boolean enablePostProcessFile;
private boolean enableMinimalUpdate;
private boolean strictSpecBehavior;
private String outputDir = DEFAULT_OUTPUT_DIR;
private Boolean verbose = DEFAULT_VERBOSE;
private Boolean skipOverwrite = DEFAULT_SKIP_OVERWRITE;
private Boolean removeOperationIdPrefix = DEFAULT_REMOVE_OPERATION_ID_PREFIX;
private Boolean logToStderr = DEFAULT_LOG_TO_STDERR;
private Boolean validateSpec = DEFAULT_VALIDATE_SPEC;
private Boolean enablePostProcessFile = DEFAULT_ENABLE_POST_PROCESS_FILE;
private Boolean enableMinimalUpdate = DEFAULT_ENABLE_MINIMAL_UPDATE;
private Boolean strictSpecBehavior = DEFAULT_STRICT_SPEC_BEHAVIOR;
private String templateDir;
private String templatingEngineName;
private String templatingEngineName = DEFAULT_TEMPLATING_ENGINE_NAME;
private String ignoreFileOverride;
private Map<String, String> systemProperties;
private Map<String, String> systemProperties = new HashMap<>();;
private Builder() {
systemProperties = new HashMap<>();
}
/**
* Sets the {@code inputSpec} and returns a reference to this Builder so that the methods can be chained together.
*
@@ -282,7 +285,9 @@ public class WorkflowSettings {
* @return a reference to this Builder
*/
public Builder withInputSpec(String inputSpec) {
this.inputSpec = inputSpec;
if (inputSpec != null) {
this.inputSpec = inputSpec;
}
return this;
}
@@ -293,7 +298,11 @@ public class WorkflowSettings {
* @return a reference to this Builder
*/
public Builder withOutputDir(String outputDir) {
this.outputDir = Paths.get(outputDir).toAbsolutePath().toString();;
if (outputDir != null ) {
this.outputDir = Paths.get(outputDir).toAbsolutePath().toString();
} else {
this.outputDir = DEFAULT_OUTPUT_DIR;
}
return this;
}
@@ -303,8 +312,8 @@ public class WorkflowSettings {
* @param verbose the {@code verbose} to set
* @return a reference to this Builder
*/
public Builder withVerbose(boolean verbose) {
this.verbose = verbose;
public Builder withVerbose(Boolean verbose) {
this.verbose = verbose != null ? verbose : Boolean.valueOf(DEFAULT_VERBOSE);
return this;
}
@@ -314,8 +323,8 @@ public class WorkflowSettings {
* @param skipOverwrite the {@code skipOverwrite} to set
* @return a reference to this Builder
*/
public Builder withSkipOverwrite(boolean skipOverwrite) {
this.skipOverwrite = skipOverwrite;
public Builder withSkipOverwrite(Boolean skipOverwrite) {
this.skipOverwrite = skipOverwrite != null ? skipOverwrite : Boolean.valueOf(DEFAULT_SKIP_OVERWRITE);
return this;
}
@@ -325,8 +334,8 @@ public class WorkflowSettings {
* @param removeOperationIdPrefix the {@code removeOperationIdPrefix} to set
* @return a reference to this Builder
*/
public Builder withRemoveOperationIdPrefix(boolean removeOperationIdPrefix) {
this.removeOperationIdPrefix = removeOperationIdPrefix;
public Builder withRemoveOperationIdPrefix(Boolean removeOperationIdPrefix) {
this.removeOperationIdPrefix = removeOperationIdPrefix != null ? removeOperationIdPrefix : Boolean.valueOf(DEFAULT_REMOVE_OPERATION_ID_PREFIX);
return this;
}
@@ -336,8 +345,8 @@ public class WorkflowSettings {
* @param logToStderr the {@code logToStderr} to set
* @return a reference to this Builder
*/
public Builder withLogToStderr(boolean logToStderr) {
this.logToStderr = logToStderr;
public Builder withLogToStderr(Boolean logToStderr) {
this.logToStderr = logToStderr != null ? logToStderr : Boolean.valueOf(DEFAULT_LOG_TO_STDERR);
return this;
}
@@ -347,8 +356,8 @@ public class WorkflowSettings {
* @param validateSpec the {@code validateSpec} to set
* @return a reference to this Builder
*/
public Builder withValidateSpec(boolean validateSpec) {
this.validateSpec = validateSpec;
public Builder withValidateSpec(Boolean validateSpec) {
this.validateSpec = validateSpec != null ? validateSpec : Boolean.valueOf(DEFAULT_VALIDATE_SPEC);
return this;
}
@@ -358,8 +367,8 @@ public class WorkflowSettings {
* @param enablePostProcessFile the {@code enablePostProcessFile} to set
* @return a reference to this Builder
*/
public Builder withEnablePostProcessFile(boolean enablePostProcessFile) {
this.enablePostProcessFile = enablePostProcessFile;
public Builder withEnablePostProcessFile(Boolean enablePostProcessFile) {
this.enablePostProcessFile = enablePostProcessFile != null ? enablePostProcessFile : Boolean.valueOf(DEFAULT_ENABLE_POST_PROCESS_FILE);
return this;
}
@@ -369,8 +378,8 @@ public class WorkflowSettings {
* @param enableMinimalUpdate the {@code enableMinimalUpdate} to set
* @return a reference to this Builder
*/
public Builder withEnableMinimalUpdate(boolean enableMinimalUpdate) {
this.enableMinimalUpdate = enableMinimalUpdate;
public Builder withEnableMinimalUpdate(Boolean enableMinimalUpdate) {
this.enableMinimalUpdate = enableMinimalUpdate != null ? enableMinimalUpdate : Boolean.valueOf(DEFAULT_ENABLE_MINIMAL_UPDATE);
return this;
}
@@ -380,8 +389,8 @@ public class WorkflowSettings {
* @param strictSpecBehavior the {@code strictSpecBehavior} to set
* @return a reference to this Builder
*/
public Builder withStrictSpecBehavior(boolean strictSpecBehavior) {
this.strictSpecBehavior = strictSpecBehavior;
public Builder withStrictSpecBehavior(Boolean strictSpecBehavior) {
this.strictSpecBehavior = strictSpecBehavior != null ? strictSpecBehavior : Boolean.valueOf(DEFAULT_STRICT_SPEC_BEHAVIOR);
return this;
}
@@ -392,9 +401,7 @@ public class WorkflowSettings {
* @return a reference to this Builder
*/
public Builder withTemplateDir(String templateDir) {
if (templateDir == null) {
this.templateDir = null;
} else {
if (templateDir != null) {
File f = new File(templateDir);
// check to see if the folder exists
@@ -416,7 +423,7 @@ public class WorkflowSettings {
* @return a reference to this Builder
*/
public Builder withTemplatingEngineName(String templatingEngineName) {
this.templatingEngineName = templatingEngineName;
this.templatingEngineName = templatingEngineName != null ? templatingEngineName : DEFAULT_TEMPLATING_ENGINE_NAME;
return this;
}
@@ -438,7 +445,9 @@ public class WorkflowSettings {
* @return a reference to this Builder
*/
public Builder withSystemProperties(Map<String, String> systemProperties) {
this.systemProperties = systemProperties;
if (systemProperties != null) {
this.systemProperties = systemProperties;
}
return this;
}

View File

@@ -0,0 +1,103 @@
/*
* Copyright 2019 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.config;
import org.testng.annotations.Test;
import java.nio.file.Paths;
import static org.testng.Assert.*;
public class WorkflowSettingsTest {
@Test
public void defaultValuesNotOverriddenByNulls(){
WorkflowSettings settings = WorkflowSettings.newBuilder()
.withOutputDir(null)
.withVerbose(null)
.withSkipOverwrite(null)
.withRemoveOperationIdPrefix(null)
.withLogToStderr(null)
.withValidateSpec(null)
.withEnablePostProcessFile(null)
.withEnableMinimalUpdate(null)
.withStrictSpecBehavior(null)
.build();
assertEquals(settings.getOutputDir(), ".");
assertFalse(settings.isVerbose());
assertFalse(settings.isSkipOverwrite());
assertFalse(settings.isRemoveOperationIdPrefix());
assertFalse(settings.isLogToStderr());
assertTrue(settings.isValidateSpec());
assertFalse(settings.isEnablePostProcessFile());
assertFalse(settings.isEnableMinimalUpdate());
assertTrue(settings.isStrictSpecBehavior());
}
private void assertOnChangesToDefaults(WorkflowSettings defaults) {
WorkflowSettings settings = WorkflowSettings.newBuilder()
.withOutputDir("output")
.withVerbose(true)
.withSkipOverwrite(true)
.withRemoveOperationIdPrefix(true)
.withLogToStderr(true)
.withValidateSpec(false)
.withEnablePostProcessFile(true)
.withEnableMinimalUpdate(true)
.withStrictSpecBehavior(false)
.build();
assertNotEquals(defaults.getOutputDir(), settings.getOutputDir());
assertEquals(settings.getOutputDir(), Paths.get("output").toAbsolutePath().toString());
assertNotEquals(defaults.isVerbose(), settings.isVerbose());
assertTrue(settings.isVerbose());
assertNotEquals(defaults.isSkipOverwrite(), settings.isSkipOverwrite());
assertTrue(settings.isSkipOverwrite());
assertNotEquals(defaults.isRemoveOperationIdPrefix(), settings.isRemoveOperationIdPrefix());
assertTrue(settings.isRemoveOperationIdPrefix());
assertNotEquals(defaults.isLogToStderr(), settings.isLogToStderr());
assertTrue(settings.isLogToStderr());
assertNotEquals(defaults.isValidateSpec(), settings.isValidateSpec());
assertFalse(settings.isValidateSpec());
assertNotEquals(defaults.isEnablePostProcessFile(), settings.isEnablePostProcessFile());
assertTrue(settings.isEnablePostProcessFile());
assertNotEquals(defaults.isEnableMinimalUpdate(), settings.isEnableMinimalUpdate());
assertTrue(settings.isEnableMinimalUpdate());
assertNotEquals(defaults.isStrictSpecBehavior(), settings.isStrictSpecBehavior());
assertFalse(settings.isStrictSpecBehavior());
}
@Test
public void defaultValuesCanBeChangedClassConstructor(){
WorkflowSettings defaults = new WorkflowSettings();
assertOnChangesToDefaults(defaults);
}
@Test
public void defaultValuesCanBeChangedBuilder(){
WorkflowSettings defaults = WorkflowSettings.newBuilder().build();
assertOnChangesToDefaults(defaults);
}
}

View File

@@ -45,7 +45,7 @@ compileJava.dependsOn tasks.openApiGenerate
[source,group]
----
plugins {
id "org.openapi.generator" version "4.1.0"
id "org.openapi.generator" version "4.1.1"
}
----
@@ -61,7 +61,7 @@ buildscript {
// url "https://plugins.gradle.org/m2/"
}
dependencies {
classpath "org.openapitools:openapi-generator-gradle-plugin:4.1.0"
classpath "org.openapitools:openapi-generator-gradle-plugin:4.1.1"
}
}
@@ -621,7 +621,7 @@ buildscript {
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
classpath('org.openapitools:openapi-generator-gradle-plugin:4.1.0') {
classpath('org.openapitools:openapi-generator-gradle-plugin:4.1.1') {
exclude group: 'com.google.guava'
}
}

View File

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

View File

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

View File

@@ -17,5 +17,5 @@ gradle generateGoWithInvalidSpec
The samples can be tested against other versions of the plugin using the `openApiGeneratorVersion` property. For example:
```bash
gradle -PopenApiGeneratorVersion=4.1.0 openApiValidate
gradle -PopenApiGeneratorVersion=4.1.1 openApiValidate
```

View File

@@ -1,3 +1,3 @@
# RELEASE_VERSION
openApiGeneratorVersion=4.1.0
openApiGeneratorVersion=4.1.1
# /RELEASE_VERSION

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -4,7 +4,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>4.1.1-SNAPSHOT</version>
<version>4.1.1</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath>
</parent>
@@ -268,6 +268,12 @@
<!-- <version>${testng-version}</version> -->
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.javaparser</groupId>
<artifactId>javaparser-core</artifactId>
<version>3.14.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
@@ -294,7 +300,7 @@
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.23.0</version>
<version>3.0.0</version>
<scope>test</scope>
</dependency>
<dependency>

View File

@@ -308,4 +308,7 @@ public class CodegenConstants {
public static final String EXCEPTION_ON_FAILURE = "returnExceptionOnFailure";
public static final String EXCEPTION_ON_FAILURE_DESC = "Throw an exception on non success response codes";
public static final String ENUM_CLASS_PREFIX = "enumClassPrefix";
public static final String ENUM_CLASS_PREFIX_DESC = "Prefix enum with class name";
}

View File

@@ -2659,11 +2659,13 @@ public class DefaultCodegen implements CodegenConfig {
CodegenParameter bodyParam = null;
RequestBody requestBody = operation.getRequestBody();
if (requestBody != null) {
if (getContentType(requestBody) != null &&
(getContentType(requestBody).toLowerCase(Locale.ROOT).startsWith("application/x-www-form-urlencoded") ||
getContentType(requestBody).toLowerCase(Locale.ROOT).startsWith("multipart/form-data"))) {
String contentType = getContentType(requestBody);
if (contentType != null &&
(contentType.toLowerCase(Locale.ROOT).startsWith("application/x-www-form-urlencoded") ||
contentType.toLowerCase(Locale.ROOT).startsWith("multipart"))) {
// process form parameters
formParams = fromRequestBodyToFormParameters(requestBody, imports);
op.isMultipart = contentType.toLowerCase(Locale.ROOT).startsWith("multipart");
for (CodegenParameter cp : formParams) {
postProcessParameter(cp);
}
@@ -4463,8 +4465,8 @@ public class DefaultCodegen implements CodegenConfig {
for (String consume : consumesInfo) {
if (consume != null &&
consume.toLowerCase(Locale.ROOT).startsWith("application/x-www-form-urlencoded") ||
consume.toLowerCase(Locale.ROOT).startsWith("multipart/form-data")) {
(consume.toLowerCase(Locale.ROOT).startsWith("application/x-www-form-urlencoded") ||
consume.toLowerCase(Locale.ROOT).startsWith("multipart"))) {
return true;
}
}
@@ -4907,7 +4909,7 @@ public class DefaultCodegen implements CodegenConfig {
LOGGER.warn("The following schema has undefined (null) baseType. " +
"It could be due to form parameter defined in OpenAPI v2 spec with incorrect consumes. " +
"A correct 'consumes' for form parameters should be " +
"'application/x-www-form-urlencoded' or 'multipart/form-data'");
"'application/x-www-form-urlencoded' or 'multipart/?'");
LOGGER.warn("schema: " + schema);
LOGGER.warn("codegenModel is null. Default to UNKNOWN_BASE_TYPE");
codegenModelName = "UNKNOWN_BASE_TYPE";

View File

@@ -91,6 +91,7 @@ public class CodegenConfigurator {
DynamicSettings settings = mapper.readValue(new File(configFile), DynamicSettings.class);
CodegenConfigurator configurator = new CodegenConfigurator();
configurator.generatorSettingsBuilder = GeneratorSettings.newBuilder(settings.getGeneratorSettings());
configurator.workflowSettingsBuilder = WorkflowSettings.newBuilder(settings.getWorkflowSettings());
return configurator;
} catch (IOException ex) {
LOGGER.error("Unable to deserialize config file: " + configFile, ex);

View File

@@ -38,6 +38,7 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
protected boolean withGoCodegenComment = false;
protected boolean withXml = false;
protected boolean enumClassPrefix = false;
protected String packageName = "openapi";
@@ -618,6 +619,10 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
this.withXml = withXml;
}
public void setEnumClassPrefix(boolean enumClassPrefix) {
this.enumClassPrefix = enumClassPrefix;
}
@Override
public String toDefaultValue(Schema schema) {
if (schema.getDefault() != null) {

View File

@@ -0,0 +1,135 @@
/*
* Copyright 2019 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.languages;
import org.openapitools.codegen.*;
import org.openapitools.codegen.meta.GeneratorMetadata;
import org.openapitools.codegen.meta.Stability;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import static org.openapitools.codegen.utils.StringUtils.camelize;
public class AvroSchemaCodegen extends DefaultCodegen implements CodegenConfig {
private static final String AVRO = "avro-schema";
protected String packageName = "model";
public AvroSchemaCodegen() {
super();
generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata)
.stability(Stability.BETA)
.build();
outputFolder = "generated-code/avro-schema";
modelTemplateFiles.put("model.mustache", ".avsc");
apiPackage = "api";
modelPackage = "model";
importMapping.clear();
embeddedTemplateDir = templateDir = AVRO;
// default HIDE_GENERATION_TIMESTAMP to true
hideGenerationTimestamp = Boolean.TRUE;
languageSpecificPrimitives = new HashSet<>(
Arrays.asList("null", "boolean", "int", "integer", "long", "float", "double", "bytes", "string",
"BigDecimal", "UUID", "number", "date", "DateTime")
);
defaultIncludes = new HashSet<>(languageSpecificPrimitives);
instantiationTypes.put("array", "Array");
instantiationTypes.put("list", "Array");
instantiationTypes.put("map", "Object");
typeMapping.clear();
typeMapping.put("number", "double");
typeMapping.put("DateTime", "string");
typeMapping.put("date", "string");
typeMapping.put("short", "int");
typeMapping.put("char", "string");
typeMapping.put("integer", "int");
typeMapping.put("ByteArray", "bytes");
typeMapping.put("binary", "File");
typeMapping.put("file", "File");
typeMapping.put("UUID", "string");
typeMapping.put("BigDecimal", "string");
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, CodegenConstants.PACKAGE_NAME_DESC));
}
@Override
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) {
packageName = (String) additionalProperties.get(CodegenConstants.PACKAGE_NAME);
}
additionalProperties.put("packageName", packageName);
}
@Override
public CodegenType getTag() {
return CodegenType.SCHEMA;
}
@Override
public String getName() {
return "avro-schema";
}
@Override
public String getHelp() {
return "Generates a Avro model (beta).";
}
@Override
public String modelFileFolder() {
return outputFolder + File.separator;
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
return postProcessModelsEnum(objs);
}
@Override
protected void setNonArrayMapProperty(CodegenProperty property, String type) {
super.setNonArrayMapProperty(property, type);
if (property.isModel) {
property.dataType = camelize(modelNamePrefix + property.dataType + modelNameSuffix);
}
}
@Override
public String escapeUnsafeCharacters(String input) {
// do nothing as it's a schema conversion
return input;
}
@Override
public String escapeQuotationMark(String input) {
// do nothing as it's a schema conversion
return input;
}
}

View File

@@ -65,7 +65,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
protected String modelDocPath = "docs/";
// Defines TargetFrameworkVersion in csproj files
protected String targetFramework = defaultFramework.dotNetFrameworkVersion;
protected String targetFramework = defaultFramework.name;
// Defines nuget identifiers for target framework
protected String targetFrameworkNuget = targetFramework;
@@ -78,6 +78,8 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
// By default, generated code is considered public
protected boolean nonPublicApi = Boolean.FALSE;
protected boolean caseInsensitiveResponseHeaders = Boolean.FALSE;
public CSharpNetCoreClientCodegen() {
super();
@@ -206,6 +208,10 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
CodegenConstants.VALIDATABLE_DESC,
this.validatable);
addSwitch(CodegenConstants.CASE_INSENSITIVE_RESPONSE_HEADERS,
CodegenConstants.CASE_INSENSITIVE_RESPONSE_HEADERS_DESC,
this.caseInsensitiveResponseHeaders);
regexModifiers = new HashMap<>();
regexModifiers.put('i', "IgnoreCase");
regexModifiers.put('m', "Multiline");
@@ -470,7 +476,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
}
clientPackage = "Client";
String framework = (String) additionalProperties.getOrDefault(CodegenConstants.DOTNET_FRAMEWORK, defaultFramework.dotNetFrameworkVersion);
String framework = (String) additionalProperties.getOrDefault(CodegenConstants.DOTNET_FRAMEWORK, defaultFramework.name);
FrameworkStrategy strategy = defaultFramework;
for (FrameworkStrategy frameworkStrategy : frameworkStrategies) {
if (framework.equals(frameworkStrategy.name)) {
@@ -481,7 +487,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
strategy.configureAdditionalProperties(additionalProperties);
setTargetFrameworkNuget(strategy.getNugetFrameworkIdentifier());
setTargetFramework(strategy.dotNetFrameworkVersion);
setTargetFramework(strategy.name);
if (strategy != FrameworkStrategy.NETSTANDARD_2_0) {
LOGGER.warn("If using built-in templates-RestSharp only supports netstandard 2.0 or later.");
@@ -640,6 +646,10 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
this.validatable = validatable;
}
public void setCaseInsensitiveResponseHeaders(final Boolean caseInsensitiveResponseHeaders) {
this.caseInsensitiveResponseHeaders = caseInsensitiveResponseHeaders;
}
@Override
public String toEnumVarName(String value, String datatype) {
if (value.length() == 0) {
@@ -800,7 +810,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
}
protected void configureAdditionalProperties(final Map<String, Object> properties) {
properties.putIfAbsent(CodegenConstants.DOTNET_FRAMEWORK, this.dotNetFrameworkVersion);
properties.putIfAbsent(CodegenConstants.DOTNET_FRAMEWORK, this.name);
// not intended to be user-settable
properties.put(TARGET_FRAMEWORK_IDENTIFIER, this.getTargetFrameworkIdentifier());

View File

@@ -55,7 +55,7 @@ public class GoClientCodegen extends AbstractGoCodegen {
cliOptions.add(CliOption.newBoolean(CodegenConstants.IS_GO_SUBMODULE, CodegenConstants.IS_GO_SUBMODULE_DESC));
cliOptions.add(CliOption.newBoolean(WITH_GO_CODEGEN_COMMENT, "whether to include Go codegen comment to disable Go Lint and collapse by default GitHub in PRs and diffs"));
cliOptions.add(CliOption.newBoolean(WITH_XML, "whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)"));
cliOptions.add(CliOption.newBoolean(CodegenConstants.ENUM_CLASS_PREFIX, CodegenConstants.ENUM_CLASS_PREFIX_DESC));
// option to change the order of form/body parameter
cliOptions.add(CliOption.newBoolean(
@@ -114,6 +114,13 @@ public class GoClientCodegen extends AbstractGoCodegen {
}
}
if (additionalProperties.containsKey(CodegenConstants.ENUM_CLASS_PREFIX)) {
setEnumClassPrefix(Boolean.parseBoolean(additionalProperties.get(CodegenConstants.ENUM_CLASS_PREFIX).toString()));
if (enumClassPrefix) {
additionalProperties.put(CodegenConstants.ENUM_CLASS_PREFIX, "true");
}
}
if (additionalProperties.containsKey(CodegenConstants.IS_GO_SUBMODULE)) {
setIsGoSubmodule(Boolean.parseBoolean(additionalProperties.get(CodegenConstants.IS_GO_SUBMODULE).toString()));
if (isGoSubmodule) {

View File

@@ -33,9 +33,11 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege
public static final String NPM_REPOSITORY = "npmRepository";
public static final String WITH_INTERFACES = "withInterfaces";
public static final String USE_SINGLE_REQUEST_PARAMETER = "useSingleRequestParameter";
public static final String PREFIX_PARAMETER_INTERFACES = "prefixParameterInterfaces";
protected String npmRepository = null;
private boolean useSingleRequestParameter = true;
private boolean prefixParameterInterfaces = false;
protected boolean addedApiIndex = false;
protected boolean addedModelIndex = false;
@@ -59,6 +61,7 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege
this.cliOptions.add(new CliOption(NPM_REPOSITORY, "Use this property to set an url your private npmRepo in the package.json"));
this.cliOptions.add(new CliOption(WITH_INTERFACES, "Setting this property to true will generate interfaces next to the default class implementations.", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString()));
this.cliOptions.add(new CliOption(USE_SINGLE_REQUEST_PARAMETER, "Setting this property to true will generate functions with a single argument containing all API endpoint parameters instead of one argument per parameter.", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.TRUE.toString()));
this.cliOptions.add(new CliOption(PREFIX_PARAMETER_INTERFACES, "Setting this property to true will generate parameter interface declarations prefixed with API class name to avoid name conflicts.", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString()));
}
@Override
@@ -94,6 +97,11 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege
}
writePropertyBack(USE_SINGLE_REQUEST_PARAMETER, getUseSingleRequestParameter());
if (additionalProperties.containsKey(PREFIX_PARAMETER_INTERFACES)) {
this.setPrefixParameterInterfaces(convertPropertyToBoolean(PREFIX_PARAMETER_INTERFACES));
}
writePropertyBack(PREFIX_PARAMETER_INTERFACES, getPrefixParameterInterfaces());
if (additionalProperties.containsKey(NPM_NAME)) {
addNpmPackageGeneration();
}
@@ -208,6 +216,7 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege
this.addOperationModelImportInfomation(operations);
this.updateOperationParameterEnumInformation(operations);
this.addOperationObjectResponseInformation(operations);
this.addOperationPrefixParameterInterfacesInformation(operations);
return operations;
}
@@ -254,6 +263,11 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege
}
}
private void addOperationPrefixParameterInterfacesInformation(Map<String, Object> operations) {
Map<String, Object> _operations = (Map<String, Object>) operations.get("operations");
operations.put("prefixParameterInterfaces", getPrefixParameterInterfaces());
}
private void addExtraReservedWords() {
this.reservedWords.add("BASE_PATH");
this.reservedWords.add("BaseAPI");
@@ -289,4 +303,12 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege
private void setUseSingleRequestParameter(boolean useSingleRequestParameter) {
this.useSingleRequestParameter = useSingleRequestParameter;
}
private boolean getPrefixParameterInterfaces() {
return prefixParameterInterfaces;
}
private void setPrefixParameterInterfaces(boolean prefixParameterInterfaces) {
this.prefixParameterInterfaces = prefixParameterInterfaces;
}
}

View File

@@ -6,6 +6,7 @@ import {{invokerPackage}}.ApiClient;
{{/imports}}
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.api.client.http.EmptyContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpContent;
import com.google.api.client.http.InputStreamContent;
@@ -107,7 +108,7 @@ public class {{classname}} {
String localVarUrl = uriBuilder{{#hasPathParams}}.buildFromMap(uriVariables).toString();{{/hasPathParams}}{{^hasPathParams}}.build().toString();{{/hasPathParams}}
GenericUrl genericUrl = new GenericUrl(localVarUrl);
HttpContent content = {{#isBodyAllowed}}apiClient.new JacksonJsonHttpContent({{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}){{/isBodyAllowed}}{{^isBodyAllowed}}null{{/isBodyAllowed}};
HttpContent content = {{#isBodyAllowed}}{{#bodyParam}}apiClient.new JacksonJsonHttpContent({{paramName}}){{/bodyParam}}{{^bodyParam}}new EmptyContent(){{/bodyParam}}{{/isBodyAllowed}}{{^isBodyAllowed}}null{{/isBodyAllowed}};
return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.{{httpMethod}}, genericUrl, content).execute();
}{{#bodyParam}}
@@ -179,7 +180,7 @@ public class {{classname}} {
String localVarUrl = uriBuilder{{#hasPathParams}}.buildFromMap(uriVariables).toString();{{/hasPathParams}}{{^hasPathParams}}.build().toString();{{/hasPathParams}}
GenericUrl genericUrl = new GenericUrl(localVarUrl);
HttpContent content = {{#isBodyAllowed}}apiClient.new JacksonJsonHttpContent({{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}){{/isBodyAllowed}}{{^isBodyAllowed}}null{{/isBodyAllowed}};
HttpContent content = {{#isBodyAllowed}}{{#bodyParam}}apiClient.new JacksonJsonHttpContent({{paramName}}){{/bodyParam}}{{^bodyParam}}new EmptyContent(){{/bodyParam}}{{/isBodyAllowed}}{{^isBodyAllowed}}null{{/isBodyAllowed}};
return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.{{httpMethod}}, genericUrl, content).execute();
}

View File

@@ -704,7 +704,7 @@ public class ApiClient {
}
}
Entity<?> entity = serialize(body, formParams, contentType);
Entity<?> entity = (body == null) ? Entity.json("") : serialize(body, formParams, contentType);
Response response = null;
@@ -716,11 +716,13 @@ public class ApiClient {
} else if ("PUT".equals(method)) {
response = invocationBuilder.put(entity);
} else if ("DELETE".equals(method)) {
response = invocationBuilder.delete();
response = invocationBuilder.method("DELETE", entity);
} else if ("PATCH".equals(method)) {
response = invocationBuilder.method("PATCH", entity);
} else if ("HEAD".equals(method)) {
response = invocationBuilder.head();
} else if ("OPTIONS".equals(method)) {
response = invocationBuilder.options();
} else if ("TRACE".equals(method)) {
response = invocationBuilder.trace();
} else {
@@ -774,6 +776,8 @@ public class ApiClient {
clientConfig.register(json);
clientConfig.register(JacksonFeature.class);
clientConfig.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
// turn off compliance validation to be able to send payloads with DELETE calls
clientConfig.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
if (debugging) {
{{^supportJava6}}
clientConfig.register(new LoggingFeature(java.util.logging.Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME), java.util.logging.Level.INFO, LoggingFeature.Verbosity.PAYLOAD_ANY, 1024*50 /* Log payloads up to 50K */));
@@ -784,6 +788,9 @@ public class ApiClient {
{{#supportJava6}}
clientConfig.register(new LoggingFilter(java.util.logging.Logger.getLogger(LoggingFilter.class.getName()), true));
{{/supportJava6}}
} else {
// suppress warnings for payloads with DELETE calls:
java.util.logging.Logger.getLogger("org.glassfish.jersey.client").setLevel(java.util.logging.Level.SEVERE);
}
performAdditionalClientConfiguration(clientConfig);
return ClientBuilder.newClient(clientConfig);

View File

@@ -107,7 +107,7 @@ public class {{classname}} {
@Deprecated
{{/isDeprecated}}
public ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
Object localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}new Object(){{/bodyParam}};
Object localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
{{#allParams}}{{#required}}
// verify the required parameter '{{paramName}}' is set
if ({{paramName}} == null) {

View File

@@ -252,6 +252,17 @@ public class ApiClient {
return scheme + "://" + host + (port == -1 ? "" : ":" + port) + basePath;
}
/**
* Set a custom scheme for the target service, for example 'https'.
*
* @param scheme The scheme of the target service
* @return This object.
*/
public ApiClient setScheme(String scheme){
this.scheme = scheme;
return this;
}
/**
* Set a custom request interceptor.
*

View File

@@ -90,7 +90,7 @@ public class {{classname}} {
@Deprecated
{{/isDeprecated}}
public{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}private{{/vendorExtensions.x-group-parameters}} okhttp3.Call {{operationId}}Call({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback _callback) throws ApiException {
Object localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}new Object(){{/bodyParam}};
Object localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
// create path and map variables
String localVarPath = "{{{path}}}"{{#pathParams}}

View File

@@ -41,6 +41,7 @@ import org.jboss.resteasy.spi.ResteasyProviderFactory;
import {{invokerPackage}}.auth.Authentication;
import {{invokerPackage}}.auth.HttpBasicAuth;
import {{invokerPackage}}.auth.HttpBearerAuth;
import {{invokerPackage}}.auth.ApiKeyAuth;
{{#hasOAuthMethods}}
import {{invokerPackage}}.auth.OAuth;
@@ -78,8 +79,9 @@ public class ApiClient {
setUserAgent("{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{{artifactVersion}}}/java{{/httpUserAgent}}");
// Setup authentications (key: authentication name, value: authentication).
authentications = new HashMap<String, Authentication>();{{#authMethods}}{{#isBasic}}
authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}}
authentications = new HashMap<String, Authentication>();{{#authMethods}}{{#isBasic}}{{#isBasicBasic}}
authentications.put("{{name}}", new HttpBasicAuth());{{/isBasicBasic}}{{^isBasicBasic}}
authentications.put("{{name}}", new HttpBearerAuth("{{scheme}}"));{{/isBasicBasic}}{{/isBasic}}{{#isApiKey}}
authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}}
authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}}
// Prevent the authentications from being modified.
@@ -661,11 +663,13 @@ public class ApiClient {
} else if ("PUT".equals(method)) {
response = invocationBuilder.put(entity);
} else if ("DELETE".equals(method)) {
response = invocationBuilder.delete();
response = invocationBuilder.method("DELETE", entity);
} else if ("PATCH".equals(method)) {
response = invocationBuilder.header("X-HTTP-Method-Override", "PATCH").post(entity);
response = invocationBuilder.method("PATCH", entity);
} else if ("HEAD".equals(method)) {
response = invocationBuilder.head();
} else if ("OPTIONS".equals(method)) {
response = invocationBuilder.options();
} else if ("TRACE".equals(method)) {
response = invocationBuilder.trace();
} else {

View File

@@ -57,7 +57,7 @@ public class {{classname}} {
@Deprecated
{{/isDeprecated}}
public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
Object localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}new Object(){{/bodyParam}};
Object localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
{{#allParams}}{{#required}}
// verify the required parameter '{{paramName}}' is set
if ({{paramName}} == null) {

View File

@@ -444,7 +444,7 @@ public class ApiClient {
updateParamsForAuth(authNames, queryParams, headerParams);
if (accepts != null) {
if (accepts != null && accepts.length > 0) {
headerParams.add(HttpHeaders.ACCEPT, selectHeaderAccept(accepts));
}
@@ -579,7 +579,7 @@ public class ApiClient {
return;
} else {
try {
resultContent = Json.mapper.readValue(httpResponse.bodyAsString(), returnType);
resultContent = this.objectMapper.readValue(httpResponse.bodyAsString(), returnType);
result = Future.succeededFuture(resultContent);
} catch (Exception e) {
result = ApiException.fail(new DecodeException("Failed to decode:" + e.getMessage(), e));

View File

@@ -4,6 +4,7 @@ org.openapitools.codegen.languages.AndroidClientCodegen
org.openapitools.codegen.languages.Apache2ConfigCodegen
org.openapitools.codegen.languages.ApexClientCodegen
org.openapitools.codegen.languages.AspNetCoreServerCodegen
org.openapitools.codegen.languages.AvroSchemaCodegen
org.openapitools.codegen.languages.BashClientCodegen
org.openapitools.codegen.languages.CLibcurlClientCodegen
org.openapitools.codegen.languages.ClojureClientCodegen

View File

@@ -0,0 +1,11 @@
{{#models}}
{{#model}}
{
"namespace": "{{packageName}}",
"type": "{{#isEnum}}enum{{/isEnum}}{{^isEnum}}record{{/isEnum}}",
"doc": "{{{description}}}",
"name": "{{{classname}}}",
{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{>pojo}}{{/isEnum}}
}
{{/model}}
{{/models}}

View File

@@ -0,0 +1,3 @@
"symbols": [{{#allowableValues}}{{#enumVars}}
{{{value}}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}}
]

View File

@@ -0,0 +1,9 @@
"fields": [
{{#vars}}
{
"name": "{{baseName}}",
"type": {{^required}}["null", {{/required}}{{>typeProperty}}{{^required}}]{{/required}},
"doc": "{{{description}}}"
}{{^-last}},{{/-last}}
{{/vars}}
]

View File

@@ -0,0 +1,4 @@
{
"type": "{{dataType}}",
{{#items}}"items": "{{#isModel}}{{package}}.{{/isModel}}{{dataType}}"{{/items}}
}

View File

@@ -0,0 +1,7 @@
{
"type": "enum",
"name": "{{classname}}_{{name}}",
"symbols": [{{#allowableValues}}{{#enumVars}}
{{{value}}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}}
]
}

View File

@@ -0,0 +1 @@
{{^isEnum}}{{^isContainer}}{{#isPrimitiveType}}"{{dataType}}"{{/isPrimitiveType}}{{#isModel}}"{{package}}.{{dataType}}"{{/isModel}}{{/isContainer}}{{#isContainer}}{{>typeArray}}{{/isContainer}}{{/isEnum}}{{#isEnum}}{{>typeEnum}}{{/isEnum}}

View File

@@ -347,7 +347,7 @@ namespace {{packageName}}.Client
private ApiResponse<T> toApiResponse<T>({{#supportsAsync}}IRestResponse<T> response{{/supportsAsync}}{{^supportsAsync}}IRestResponse response, CustomJsonCodec des{{/supportsAsync}})
{
T result = {{#supportsAsync}}response.Data{{/supportsAsync}}{{^supportsAsync}}(T)des.Deserialize(response, typeof(T)){{/supportsAsync}};
var transformed = new ApiResponse<T>(response.StatusCode, new Multimap<string, string>(), result)
var transformed = new ApiResponse<T>(response.StatusCode, new Multimap<string, string>({{#caseInsensitiveResponseHeaders}}StringComparer.OrdinalIgnoreCase{{/caseInsensitiveResponseHeaders}}), result)
{
ErrorText = response.ErrorMessage,
Cookies = new List<Cookie>()

View File

@@ -21,6 +21,26 @@ namespace {{packageName}}.Client
#endregion Private Fields
#region Constructors
/// <summary>
/// Empty Constructor.
/// </summary>
public Multimap()
{
_dictionary = new {{^net35}}Concurrent{{/net35}}Dictionary<T, IList<TValue>>();
}
/// <summary>
/// Constructor with comparer.
/// </summary>
/// <param name="comparer"></param>
public Multimap(IEqualityComparer<T> comparer) {
_dictionary = new {{^net35}}Concurrent{{/net35}}Dictionary<T, IList<TValue>>(comparer);
}
#endregion Constructors
#region Enumerators
/// <summary>
@@ -257,7 +277,7 @@ namespace {{packageName}}.Client
#region Private Members
/**
* Helper method to encapsulate generator differences between dictioary types.
* Helper method to encapsulate generator differences between dictionary types.
*/
private bool TryRemove(T key, out IList<TValue> value)
{
@@ -279,7 +299,7 @@ namespace {{packageName}}.Client
}
/**
* Helper method to encapsulate generator differences between dictioary types.
* Helper method to encapsulate generator differences between dictionary types.
*/
private bool TryAdd(T key, IList<TValue> value)
{

View File

@@ -23,9 +23,7 @@
<RootNamespace>{{packageName}}</RootNamespace>
<AssemblyName>{{packageName}}</AssemblyName>
<ProjectTypeGuids>{786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<!--<TargetFrameworkVersion>{{targetFramework}}</TargetFrameworkVersion>-->
<TargetFrameworkVersion>{{targetFrameworkVersion}}</TargetFrameworkVersion>
<TargetFrameworkIdentifier>{{targetFrameworkIdentifier}}</TargetFrameworkIdentifier>
<TargetFramework>{{targetFramework}}</TargetFramework>
<FileAlignment>512</FileAlignment>
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\{{packageName}}.xml</DocumentationFile>
</PropertyGroup>
@@ -40,6 +38,4 @@
<PackageReference Include="RestSharp" Version="106.6.7" />
<PackageReference Include="System.ComponentModel.Annotations" Version="4.5.0" />
</ItemGroup>
<Import Project="..\..\packages\NETStandard.Library.2.0.3\build\netstandard2.0\NETStandard.Library.targets" Condition="Exists('..\..\packages\NETStandard.Library.2.0.3\build\netstandard2.0\NETStandard.Library.targets')" />
</Project>

View File

@@ -32,18 +32,11 @@
<PackageReference Include="RestSharp" Version="106.6.7" />
<PackageReference Include="System.ComponentModel.Annotations" Version="4.5.0" />
</ItemGroup>
<Import Project="..\..\packages\NETStandard.Library.2.0.3\build\netstandard2.0\NETStandard.Library.targets" Condition="Exists('..\..\packages\NETStandard.Library.2.0.3\build\netstandard2.0\NETStandard.Library.targets')" />
<ItemGroup>
<ProjectReference Include="..\{{packageName}}\{{packageName}}.csproj">
<Project>{{packageGuid}}</Project>
<Name>{{packageName}}</Name>
</ProjectReference>
</ItemGroup>
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105.The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\..\packages\NETStandard.Library.2.0.3\build\netstandard2.0\NETStandard.Library.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\NETStandard.Library.2.0.3\build\netstandard2.0\NETStandard.Library.targets'))" />
</Target>
</Project>

View File

@@ -3,8 +3,6 @@
<PropertyGroup>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<TargetFramework>{{targetFramework}}</TargetFramework>
<TargetFrameworkVersion>{{targetFrameworkVersion}}</TargetFrameworkVersion>
<TargetFrameworkIdentifier>{{targetFrameworkIdentifier}}</TargetFrameworkIdentifier>
<AssemblyName>{{packageName}}</AssemblyName>
<PackageId>{{packageName}}</PackageId>
<OutputType>Library</OutputType>

View File

@@ -23,6 +23,8 @@
<PackageReference Include="Newtonsoft.Json" Version="12.0.1" />
<PackageReference Include="RestSharp" Version="106.6.7" />
<PackageReference Include="System.ComponentModel.Annotations" Version="4.5.0" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.1" />
</ItemGroup>
{{^netStandard}}

View File

@@ -245,6 +245,7 @@ namespace {{packageName}}.Client
var request = PrepareRequest(
path, method, queryParams, postBody, headerParams, formParams, fileParams,
pathParams, contentType);
RestClient.UserAgent = Configuration.UserAgent;
InterceptRequest(request);
var response = await RestClient.Execute{{^netStandard}}TaskAsync{{/netStandard}}(request);
InterceptResponse(request, response);

View File

@@ -16,51 +16,63 @@ class {{classname}} {
{{classname}}.fromJson(Map<String, dynamic> json) {
if (json == null) return;
{{#vars}}
if (json['{{baseName}}'] == null) {
{{name}} = null;
} else {
{{#isDateTime}}
{{name}} = DateTime.parse(json['{{baseName}}']);
{{name}} = (json['{{baseName}}'] == null) ?
null :
DateTime.parse(json['{{baseName}}']);
{{/isDateTime}}
{{#isDate}}
{{name}} = DateTime.parse(json['{{baseName}}']);
{{name}} = (json['{{baseName}}'] == null) ?
null :
DateTime.parse(json['{{baseName}}']);
{{/isDate}}
{{^isDateTime}}
{{^isDate}}
{{#complexType}}
{{#isListContainer}}
{{name}} = {{complexType}}.listFromJson(json['{{baseName}}']);
{{name}} = (json['{{baseName}}'] == null) ?
null :
{{complexType}}.listFromJson(json['{{baseName}}']);
{{/isListContainer}}
{{^isListContainer}}
{{#isMapContainer}}
{{name}} = {{complexType}}.mapFromJson(json['{{baseName}}']);
{{name}} = (json['{{baseName}}'] == null) ?
null :
{{complexType}}.mapFromJson(json['{{baseName}}']);
{{/isMapContainer}}
{{^isMapContainer}}
{{name}} = {{complexType}}.fromJson(json['{{baseName}}']);
{{name}} = (json['{{baseName}}'] == null) ?
null :
{{complexType}}.fromJson(json['{{baseName}}']);
{{/isMapContainer}}
{{/isListContainer}}
{{/complexType}}
{{^complexType}}
{{#isListContainer}}
{{name}} = (json['{{baseName}}'] as List).cast<{{items.datatype}}>();
{{name}} = (json['{{baseName}}'] == null) ?
null :
(json['{{baseName}}'] as List).cast<{{items.datatype}}>();
{{/isListContainer}}
{{^isListContainer}}
{{#isMapContainer}}
{{name}} = (json['{{baseName}}'] as Map).cast<String, {{items.datatype}}>();
{{name}} = (json['{{baseName}}'] == null) ?
null :
(json['{{baseName}}'] as Map).cast<String, {{items.datatype}}>();
{{/isMapContainer}}
{{^isMapContainer}}
{{#isDouble}}
{{name}} = json['{{baseName}}'].toDouble();
{{/isDouble}}
{{^isDouble}}
{{name}} = json['{{baseName}}'];
{{/isDouble}}
{{#isDouble}}
{{name}} = (json['{{baseName}}'] == null) ?
null :
json['{{baseName}}'].toDouble();
{{/isDouble}}
{{^isDouble}}
{{name}} = json['{{baseName}}'];
{{/isDouble}}
{{/isMapContainer}}
{{/isListContainer}}
{{/complexType}}
{{/isDate}}
{{/isDateTime}}
}
{{/vars}}
}

View File

@@ -3,17 +3,17 @@ package {{packageName}}
{{#operations}}
import (
"context"
"io/ioutil"
"net/http"
"net/url"
_context "context"
_ioutil "io/ioutil"
_nethttp "net/http"
_neturl "net/url"
{{#imports}} "{{import}}"
{{/imports}}
)
// Linger please
var (
_ context.Context
_ _context.Context
)
type {{classname}}Service service
@@ -24,7 +24,7 @@ type {{classname}}Service service
{{#notes}}
{{notes}}
{{/notes}}
* @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
{{#allParams}}
{{#required}}
* @param {{paramName}}{{#description}} {{{.}}}{{/description}}
@@ -63,9 +63,9 @@ type {{{nickname}}}Opts struct {
}
{{/hasOptionalParams}}
func (a *{{{classname}}}Service) {{{nickname}}}(ctx context.Context{{#hasParams}}, {{/hasParams}}{{#allParams}}{{#required}}{{paramName}} {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}}{{#hasOptionalParams}}localVarOptionals *{{{nickname}}}Opts{{/hasOptionalParams}}) ({{#returnType}}{{{returnType}}}, {{/returnType}}*http.Response, error) {
func (a *{{{classname}}}Service) {{{nickname}}}(ctx _context.Context{{#hasParams}}, {{/hasParams}}{{#allParams}}{{#required}}{{paramName}} {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}}{{#hasOptionalParams}}localVarOptionals *{{{nickname}}}Opts{{/hasOptionalParams}}) ({{#returnType}}{{{returnType}}}, {{/returnType}}*_nethttp.Response, error) {
var (
localVarHttpMethod = http.Method{{httpMethod}}
localVarHttpMethod = _nethttp.Method{{httpMethod}}
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
@@ -77,11 +77,11 @@ func (a *{{{classname}}}Service) {{{nickname}}}(ctx context.Context{{#hasParams}
// create path and map variables
localVarPath := a.client.cfg.BasePath + "{{{path}}}"{{#pathParams}}
localVarPath = strings.Replace(localVarPath, "{"+"{{baseName}}"+"}", url.QueryEscape(fmt.Sprintf("%v", {{paramName}})), -1){{/pathParams}}
localVarPath = strings.Replace(localVarPath, "{"+"{{baseName}}"+"}", _neturl.QueryEscape(fmt.Sprintf("%v", {{paramName}})), -1){{/pathParams}}
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := url.Values{}
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
{{#allParams}}
{{#required}}
{{#minItems}}
@@ -132,11 +132,37 @@ func (a *{{{classname}}}Service) {{{nickname}}}(ctx context.Context{{#hasParams}
{{#hasQueryParams}}
{{#queryParams}}
{{#required}}
{{#isCollectionFormatMulti}}
t:={{paramName}}
if reflect.TypeOf(t).Kind() == reflect.Slice {
s := reflect.ValueOf(t)
for i := 0; i < s.Len(); i++ {
localVarQueryParams.Add("{{baseName}}", parameterToString(s.Index(i), "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
}
} else {
localVarQueryParams.Add("{{baseName}}", parameterToString(t, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
}
{{/isCollectionFormatMulti}}
{{^isCollectionFormatMulti}}
localVarQueryParams.Add("{{baseName}}", parameterToString({{paramName}}, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
{{/isCollectionFormatMulti}}
{{/required}}
{{^required}}
if localVarOptionals != nil && localVarOptionals.{{vendorExtensions.x-exportParamName}}.IsSet() {
{{#isCollectionFormatMulti}}
t:=localVarOptionals.{{vendorExtensions.x-exportParamName}}.Value()
if reflect.TypeOf(t).Kind() == reflect.Slice {
s := reflect.ValueOf(t)
for i := 0; i < s.Len(); i++ {
localVarQueryParams.Add("{{baseName}}", parameterToString(s.Index(i), "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
}
} else {
localVarQueryParams.Add("{{baseName}}", parameterToString(t, "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
}
{{/isCollectionFormatMulti}}
{{^isCollectionFormatMulti}}
localVarQueryParams.Add("{{baseName}}", parameterToString(localVarOptionals.{{vendorExtensions.x-exportParamName}}.Value(), "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"))
{{/isCollectionFormatMulti}}
}
{{/required}}
{{/queryParams}}
@@ -192,7 +218,7 @@ func (a *{{{classname}}}Service) {{{nickname}}}(ctx context.Context{{#hasParams}
}
{{/required}}
if localVarFile != nil {
fbs, _ := ioutil.ReadAll(localVarFile)
fbs, _ := _ioutil.ReadAll(localVarFile)
localVarFileBytes = fbs
localVarFileName = localVarFile.Name()
localVarFile.Close()
@@ -277,7 +303,7 @@ func (a *{{{classname}}}Service) {{{nickname}}}(ctx context.Context{{#hasParams}
return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHttpResponse, err
}
localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)
localVarBody, err := _ioutil.ReadAll(localVarHttpResponse.Body)
localVarHttpResponse.Body.Close()
if err != nil {
return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHttpResponse, err

View File

@@ -23,7 +23,7 @@ const (
{{#enumVars}}
{{^-first}}
{{/-first}}
{{{classname.toUpperCase}}}_{{name}} {{{classname}}} = "{{{value}}}"
{{#enumClassPrefix}}{{{classname.toUpperCase}}}_{{/enumClassPrefix}}{{name}} {{{classname}}} = "{{{value}}}"
{{/enumVars}}
{{/allowableValues}}
){{/isEnum}}{{^isEnum}}{{#description}}
@@ -36,7 +36,7 @@ type {{classname}} struct {
// {{{description}}}
{{/description}}
{{name}} *{{{dataType}}} `json:"{{baseName}},omitempty"{{#withXml}} xml:"{{baseName}}{{#isXmlAttribute}},attr{{/isXmlAttribute}}"{{/withXml}}{{#vendorExtensions.x-go-custom-tag}} {{{.}}}{{/vendorExtensions.x-go-custom-tag}}`
{{#isNullable}} isExplicitNull{{name}} bool `json:"-"{{#withXml}} xml:"-"{{/withXml}}`{{/isNullable}}
{{#isNullable}} isExplicitNull{{name}} bool `json:"-"{{#withXml}} xml:"-"{{/withXml}}`{{/isNullable}}
{{/vars}}
}
{{/isEnum}}

View File

@@ -23,7 +23,7 @@ const (
{{#enumVars}}
{{^-first}}
{{/-first}}
{{{classname.toUpperCase}}}_{{name}} {{{classname}}} = "{{{value}}}"
{{#enumClassPrefix}}{{{classname.toUpperCase}}}_{{/enumClassPrefix}}{{name}} {{{classname}}} = "{{{value}}}"
{{/enumVars}}
{{/allowableValues}}
){{/isEnum}}{{^isEnum}}{{#description}}

View File

@@ -54,7 +54,29 @@ Name | Type | Description | Notes
### Authorization
{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{name}}](../README.md#{{name}}){{^-last}}, {{/-last}}{{/authMethods}}
{{^authMethods}}No authorization required{{/authMethods}}
{{#authMethods}}
{{#isApiKey}}
Configure {{name}}:
ApiClient.apiKey["{{keyParamName}}"] = ""
ApiClient.apiKeyPrefix["{{keyParamName}}"] = ""
{{/isApiKey}}
{{#isBasic}}
{{^isBasicBearer}}
Configure {{name}}:
ApiClient.username = ""
ApiClient.password = ""
{{/isBasicBearer}}
{{#isBasicBearer}}
Configure {{name}}:
ApiClient.accessToken = ""
{{/isBasicBearer}}
{{/isBasic}}
{{#isOAuth}}
Configure {{name}}:
ApiClient.accessToken = ""
{{/isOAuth}}
{{/authMethods}}
### HTTP request headers

View File

@@ -15,11 +15,18 @@ open class ApiClient(val baseUrl: String) {
companion object {
protected const val ContentType = "Content-Type"
protected const val Accept = "Accept"
protected const val Authorization = "Authorization"
protected const val JsonMediaType = "application/json"
protected const val FormDataMediaType = "multipart/form-data"
protected const val FormUrlEncMediaType = "application/x-www-form-urlencoded"
protected const val XmlMediaType = "application/xml"
val apiKey: MutableMap<String, String> = mutableMapOf()
val apiKeyPrefix: MutableMap<String, String> = mutableMapOf()
var username: String? = null
var password: String? = null
var accessToken: String? = null
@JvmStatic
val client: OkHttpClient by lazy {
builder.build()
@@ -65,8 +72,63 @@ open class ApiClient(val baseUrl: String) {
}
}
{{#hasAuthMethods}}
protected fun updateAuthParams(requestConfig: RequestConfig) {
{{#authMethods}}
{{#isApiKey}}
{{#isKeyInHeader}}
if (requestConfig.headers["{{keyParamName}}"].isNullOrEmpty()) {
{{/isKeyInHeader}}
{{#isKeyInQuery}}
if (requestConfig.query["{{keyParamName}}"].isNullOrEmpty()) {
{{/isKeyInQuery}}
if (apiKey["{{keyParamName}}"] != null) {
if (apiKeyPrefix["{{keyParamName}}"] != null) {
{{#isKeyInHeader}}
requestConfig.headers["{{keyParamName}}"] = apiKeyPrefix["{{keyParamName}}"]!! + " " + apiKey["{{keyParamName}}"]!!
{{/isKeyInHeader}}
{{#isKeyInQuery}}
requestConfig.query["{{keyParamName}}"] = apiKeyPrefix["{{keyParamName}}"]!! + " " + apiKey["{{keyParamName}}"]!!
{{/isKeyInQuery}}
} else {
{{#isKeyInHeader}}
requestConfig.headers["{{keyParamName}}"] = apiKey["{{keyParamName}}"]!!
{{/isKeyInHeader}}
{{#isKeyInQuery}}
requestConfig.query["{{keyParamName}}"] = apiKey["{{keyParamName}}"]!!
{{/isKeyInQuery}}
}
}
}
{{/isApiKey}}
{{#isBasic}}
{{^isBasicBearer}}
if (requestConfig.headers[Authorization].isNullOrEmpty()) {
requestConfig.headers[Authorization] = Credentials.basic(username, password)
}
{{/isBasicBearer}}
{{#isBasicBearer}}
if (requestConfig.headers[Authorization].isNullOrEmpty()) {
requestConfig.headers[Authorization] = "Bearer " + accessToken
}
{{/isBasicBearer}}
{{/isBasic}}
{{#isOAuth}}
if (requestConfig.headers[Authorization].isNullOrEmpty()) {
requestConfig.headers[Authorization] = "Bearer " + accessToken
}
{{/isOAuth}}
{{/authMethods}}
}
{{/hasAuthMethods}}
protected inline fun <reified T: Any?> request(requestConfig: RequestConfig, body : Any? = null): ApiInfrastructureResponse<T?> {
val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.")
{{#hasAuthMethods}}
// take authMethod from operation
updateAuthParams(requestConfig)
{{/hasAuthMethods}}
val url = httpUrl.newBuilder()
.addPathSegments(requestConfig.path.trimStart('/'))

View File

@@ -16,7 +16,7 @@ def _deserialize(data, klass):
if data is None:
return None
if klass in six.integer_types or klass in (float, str, bool):
if klass in six.integer_types or klass in (float, str, bool, bytearray):
return _deserialize_primitive(data, klass)
elif klass == object:
return _deserialize_object(data)

View File

@@ -32,7 +32,7 @@ setup(
url="{{packageUrl}}",
keywords=["OpenAPI", "OpenAPI-Generator", "{{{appName}}}"],
install_requires=REQUIRES,
packages=find_packages(),
packages=find_packages(exclude=["test", "tests"]),
include_package_data=True,
long_description="""\
{{appDescription}} # noqa: E501

View File

@@ -291,6 +291,22 @@
{{! Returning the ApiResponse object with NULL object when the endpoint doesn't return anything}}
ApiResponse$new(NULL, resp)
{{/returnType}}
} else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) {
{{#returnExceptionOnFailure}}
errorMsg <- toString(content(resp))
if(errorMsg == ""){
errorMsg <- paste("Server returned " , httr::status_code(resp) , " response status code.")
}
{{#useDefaultExceptionHandling}}
stop(errorMsg)
{{/useDefaultExceptionHandling}}
{{#useRlangExceptionHandling}}
rlang::abort(message = errorMsg, .subclass = "ApiException", ApiException = ApiException$new(http_response = resp))
{{/useRlangExceptionHandling}}
{{/returnExceptionOnFailure}}
{{^returnExceptionOnFailure}}
ApiResponse$new(paste("Server returned " , httr::status_code(resp) , " response status code."), resp)
{{/returnExceptionOnFailure}}
} else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) {
{{#returnExceptionOnFailure}}
errorMsg <- toString(content(resp))

View File

@@ -95,7 +95,14 @@ Name | Type | Description | Notes
- **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}}
- **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}}
{{#responses.0}}
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
{{#responses}}
| **{{code}}** | {{message}} | {{#headers}} * {{baseName}} - {{description}} <br> {{/headers}}{{^headers.0}} - {{/headers.0}} |
{{/responses}}
{{/responses.0}}
{{/operation}}
{{/operations}}

View File

@@ -342,7 +342,7 @@ export class {{classname}} {
{{/isListContainer}}
{{^isListContainer}}
if ({{paramName}} !== undefined) {
{{#useHttpClient}}formParams = {{/useHttpClient}}formParams.append('{{baseName}}', <any>{{paramName}}){{#useHttpClient}} as any || formParams{{/useHttpClient}};
{{#useHttpClient}}formParams = {{/useHttpClient}}formParams.append('{{baseName}}', {{^isModel}}<any>{{paramName}}{{/isModel}}{{#isModel}}useForm ? JSON.stringify({{paramName}}) : <any>{{paramName}}{{/isModel}}){{#useHttpClient}} as any || formParams{{/useHttpClient}};
}
{{/isListContainer}}
{{/formParams}}

View File

@@ -15,10 +15,10 @@ import {
{{#operations}}
{{#operation}}
{{#allParams.0}}
export interface {{operationIdCamelCase}}Request {
{{#allParams}}
export interface {{#prefixParameterInterfaces}}{{classname}}{{/prefixParameterInterfaces}}{{operationIdCamelCase}}Request {
{{#allParams}}
{{paramName}}{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{#isNullable}} | null{{/isNullable}}{{/isEnum}};
{{/allParams}}
{{/allParams}}
}
{{/allParams.0}}
@@ -39,7 +39,7 @@ export class {{classname}} extends runtime.BaseAPI {
* {{&summary}}
{{/summary}}
*/
async {{nickname}}Raw({{#allParams.0}}requestParameters: {{operationIdCamelCase}}Request{{/allParams.0}}): Promise<runtime.ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}>> {
async {{nickname}}Raw({{#allParams.0}}requestParameters: {{#prefixParameterInterfaces}}{{classname}}{{/prefixParameterInterfaces}}{{operationIdCamelCase}}Request{{/allParams.0}}): Promise<runtime.ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}>> {
{{#allParams}}
{{#required}}
if (requestParameters.{{paramName}} === null || requestParameters.{{paramName}} === undefined) {
@@ -249,7 +249,7 @@ export class {{classname}} extends runtime.BaseAPI {
}
{{/useSingleRequestParameter}}
{{#useSingleRequestParameter}}
async {{nickname}}({{#allParams.0}}requestParameters: {{operationIdCamelCase}}Request{{/allParams.0}}): Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}> {
async {{nickname}}({{#allParams.0}}requestParameters: {{#prefixParameterInterfaces}}{{classname}}{{/prefixParameterInterfaces}}{{operationIdCamelCase}}Request{{/allParams.0}}): Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}> {
{{#returnType}}
const response = await this.{{nickname}}Raw({{#allParams.0}}requestParameters{{/allParams.0}});
return await response.value();

View File

@@ -804,4 +804,42 @@ public class InlineModelResolverTest {
Schema nullableRequestBodySchema = ModelUtils.getReferencedSchema(openAPI, nullableRequestBodyReference);
assertTrue(nullableRequestBodySchema.getNullable());
}
@Test
public void callbacks() {
OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/3_0/inline_model_resolver.yaml");
new InlineModelResolver().flatten(openAPI);
RequestBody callbackRequestBodyReference = openAPI
.getPaths()
.get("/callback")
.getPost()
.getCallbacks()
.get("webhook")
.get("{$request.body#/callbackUri}")
.getPost()
.getRequestBody();
assertNotNull(callbackRequestBodyReference.get$ref());
RequestBody resolvedCallbackRequestBody = openAPI
.getComponents()
.getRequestBodies()
.get(ModelUtils.getSimpleRef(callbackRequestBodyReference.get$ref()));
Schema callbackRequestSchemaReference = resolvedCallbackRequestBody
.getContent()
.get("application/json")
.getSchema();
assertNotNull(callbackRequestSchemaReference.get$ref());
Schema resolvedCallbackSchema = openAPI
.getComponents()
.getSchemas()
.get(ModelUtils.getSimpleRef(callbackRequestSchemaReference.get$ref()));
Map properties = resolvedCallbackSchema.getProperties();
assertTrue(properties.get("notificationId") instanceof StringSchema);
assertTrue(properties.get("action") instanceof StringSchema);
assertTrue(properties.get("data") instanceof StringSchema);
}
}

View File

@@ -1,8 +1,12 @@
package org.openapitools.codegen;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.fail;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.assertFalse;
import com.github.javaparser.ParseProblemException;
import com.github.javaparser.StaticJavaParser;
import com.github.javaparser.ast.CompilationUnit;
import io.swagger.parser.OpenAPIParser;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
@@ -66,19 +70,38 @@ public class TestUtils {
File file = new File(root, filename);
String absoluteFilename = file.getAbsolutePath().replace("\\", "/");
if (!generatedFiles.containsKey(absoluteFilename)) {
Assert.fail("Could not find '" + absoluteFilename + "' file in list:\n" +
fail("Could not find '" + absoluteFilename + "' file in list:\n" +
generatedFiles.keySet().stream().sorted().collect(Collectors.joining(",\n")));
}
assertTrue(generatedFiles.containsKey(absoluteFilename), "File '" + absoluteFilename + "' was not fould in the list of generated files");
assertTrue(generatedFiles.containsKey(absoluteFilename), "File '" + absoluteFilename + "' was not found in the list of generated files");
}
public static void ensureDoesNotContainsFile(Map<String, String> generatedFiles, File root, String filename) {
File file = new File(root, filename);
String absoluteFilename = file.getAbsolutePath().replace("\\", "/");
if (generatedFiles.containsKey(absoluteFilename)) {
Assert.fail("File '" + absoluteFilename + "' exists in file in list:\n" +
fail("File '" + absoluteFilename + "' exists in file in list:\n" +
generatedFiles.keySet().stream().sorted().collect(Collectors.joining(",\n")));
}
assertFalse(generatedFiles.containsKey(absoluteFilename), "File '" + absoluteFilename + "' was fould in the list of generated files");
assertFalse(generatedFiles.containsKey(absoluteFilename), "File '" + absoluteFilename + "' was found in the list of generated files");
}
public static void validateJavaSourceFiles(Map<String, String> fileMap) {
fileMap.forEach( (fileName, fileContents) -> {
if (fileName.endsWith(".java")) {
assertValidJavaSourceCode(fileContents, fileName);
}
}
);
}
public static void assertValidJavaSourceCode(String javaSourceCode, String filename) {
try {
CompilationUnit compilation = StaticJavaParser.parse(javaSourceCode);
assertTrue(compilation.getTypes().size() > 0, "File: " + filename);
}
catch (ParseProblemException ex) {
fail("Java parse problem: " + filename, ex);
}
}
}

View File

@@ -50,6 +50,8 @@ public class GoClientOptionsTest extends AbstractOptionsTest {
times = 1;
clientCodegen.setWithXml(GoClientOptionsProvider.WITH_XML_VALUE);
times = 1;
clientCodegen.setWithXml(GoClientOptionsProvider.ENUM_CLASS_PREFIX_VALUE);
times = 1;
clientCodegen.setPrependFormOrBodyParameters(Boolean.valueOf(GoClientOptionsProvider.PREPEND_FORM_OR_BODY_PARAMETERS_VALUE));
times = 1;
clientCodegen.setIsGoSubmodule(Boolean.valueOf(GoClientOptionsProvider.IS_GO_SUBMODULE_VALUE));

View File

@@ -17,6 +17,7 @@
package org.openapitools.codegen.java;
import static org.openapitools.codegen.TestUtils.*;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
@@ -318,6 +319,8 @@ public class JavaClientCodegenTest {
TestUtils.ensureContainsFile(generatedFiles, output, "src/main/java/xyz/abcdef/StringUtil.java");
TestUtils.ensureContainsFile(generatedFiles, output, "src/test/java/xyz/abcdef/api/DefaultApiTest.java");
validateJavaSourceFiles(generatedFiles);
String defaultApiFilename = new File(output, "src/main/java/xyz/abcdef/api/DefaultApi.java").getAbsolutePath().replace("\\", "/");
String defaultApiConent = generatedFiles.get(defaultApiFilename);
assertTrue(defaultApiConent.contains("public class DefaultApi"));
@@ -328,6 +331,44 @@ public class JavaClientCodegenTest {
output.deleteOnExit();
}
@Test
public void testJdkHttpClient() throws Exception {
Map<String, Object> properties = new HashMap<>();
properties.put(JavaClientCodegen.JAVA8_MODE, true);
properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api");
File output = Files.createTempDirectory("test").toFile();
output.deleteOnExit();
final CodegenConfigurator configurator = new CodegenConfigurator()
.setGeneratorName("java")
.setLibrary(JavaClientCodegen.NATIVE)
.setAdditionalProperties(properties)
.setInputSpec("src/test/resources/3_0/ping.yaml")
.setOutputDir(output.getAbsolutePath().replace("\\", "/"));
final ClientOptInput clientOptInput = configurator.toClientOptInput();
MockDefaultGenerator generator = new MockDefaultGenerator();
generator.opts(clientOptInput).generate();
Map<String, String> generatedFiles = generator.getFiles();
Assert.assertEquals(generatedFiles.size(), 23);
validateJavaSourceFiles(generatedFiles);
String defaultApiFilename = new File(output, "src/main/java/xyz/abcdef/api/DefaultApi.java").getAbsolutePath().replace("\\", "/");
String defaultApiContent = generatedFiles.get(defaultApiFilename);
assertTrue(defaultApiContent.contains("public class DefaultApi"));
assertTrue(defaultApiContent.contains("import java.net.http.HttpClient;"));
assertTrue(defaultApiContent.contains("import java.net.http.HttpRequest;"));
assertTrue(defaultApiContent.contains("import java.net.http.HttpResponse;"));
String apiClientFilename = new File(output, "src/main/java/xyz/abcdef/ApiClient.java").getAbsolutePath().replace("\\", "/");
String apiClientContent = generatedFiles.get(apiClientFilename);
assertTrue(apiClientContent.contains("public class ApiClient"));
assertTrue(apiClientContent.contains("import java.net.http.HttpClient;"));
assertTrue(apiClientContent.contains("import java.net.http.HttpRequest;"));
}
@Test
public void testReferencedHeader() {
final OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/3_0/issue855.yaml");

View File

@@ -23,6 +23,8 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.openapitools.codegen.TestUtils.validateJavaSourceFiles;
/**
* Unit-Test for {@link org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen}.
*
@@ -204,6 +206,7 @@ public class JavaJAXRSSpecServerCodegenTest extends JavaJaxrsBaseTest {
generator.opts(clientOptInput).generate();
Map<String, String> generatedFiles = generator.getFiles();
validateJavaSourceFiles(generatedFiles);
TestUtils.ensureContainsFile(generatedFiles, output, "src/main/openapi/openapi.yaml");
output.deleteOnExit();
@@ -228,6 +231,7 @@ public class JavaJAXRSSpecServerCodegenTest extends JavaJaxrsBaseTest {
generator.opts(clientOptInput).generate();
Map<String, String> generatedFiles = generator.getFiles();
validateJavaSourceFiles(generatedFiles);
TestUtils.ensureDoesNotContainsFile(generatedFiles, output, "src/main/openapi/openapi.yaml");
output.deleteOnExit();
@@ -252,6 +256,7 @@ public class JavaJAXRSSpecServerCodegenTest extends JavaJaxrsBaseTest {
generator.opts(clientOptInput).generate();
Map<String, String> generatedFiles = generator.getFiles();
validateJavaSourceFiles(generatedFiles);
TestUtils.ensureContainsFile(generatedFiles, output, "src/main/resources/META-INF/openapi.yaml");
output.deleteOnExit();
@@ -276,6 +281,7 @@ public class JavaJAXRSSpecServerCodegenTest extends JavaJaxrsBaseTest {
generator.opts(clientOptInput).generate();
Map<String, String> generatedFiles = generator.getFiles();
validateJavaSourceFiles(generatedFiles);
TestUtils.ensureContainsFile(generatedFiles, output, "openapi.yml");
output.deleteOnExit();

View File

@@ -28,6 +28,7 @@ public class GoClientOptionsProvider implements OptionsProvider {
public static final String PACKAGE_NAME_VALUE = "Go";
public static final boolean WITH_GO_CODEGEN_COMMENT_VALUE = true;
public static final boolean WITH_XML_VALUE = true;
public static final boolean ENUM_CLASS_PREFIX_VALUE = true;
public static final Boolean PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = true;
public static final boolean IS_GO_SUBMODULE_VALUE = true;
@@ -45,6 +46,7 @@ public class GoClientOptionsProvider implements OptionsProvider {
.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true")
.put(CodegenConstants.WITH_GO_CODEGEN_COMMENT, "true")
.put(CodegenConstants.WITH_XML, "true")
.put(CodegenConstants.ENUM_CLASS_PREFIX, "true")
.put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, "true")
.put(CodegenConstants.IS_GO_SUBMODULE, "true")
.build();

View File

@@ -52,6 +52,7 @@ public class TypeScriptFetchClientOptionsProvider implements OptionsProvider {
.put(TypeScriptFetchClientCodegen.SNAPSHOT, Boolean.FALSE.toString())
.put(TypeScriptFetchClientCodegen.WITH_INTERFACES, Boolean.FALSE.toString())
.put(TypeScriptFetchClientCodegen.USE_SINGLE_REQUEST_PARAMETER, Boolean.FALSE.toString())
.put(TypeScriptFetchClientCodegen.PREFIX_PARAMETER_INTERFACES, Boolean.FALSE.toString())
.put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE)
.put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, PREPEND_FORM_OR_BODY_PARAMETERS_VALUE)
.build();

View File

@@ -293,6 +293,40 @@ paths:
responses:
'200':
description: OK
/callback:
post:
requestBody:
content:
application/json:
schema:
type: object
properties:
callbackUri:
type: string
responses:
201:
headers:
Location:
description: Contains the URI of the newly created resource
schema:
type: string
callbacks:
webhook:
'{$request.body#/callbackUri}':
post:
operationId: webhookNotify
requestBody:
content:
application/json:
schema:
type: object
properties:
notificationId:
type: string
action:
type: string
data:
type: string
components:
schemas:
Users:

28
pom.xml
View File

@@ -10,7 +10,7 @@
<packaging>pom</packaging>
<name>openapi-generator-project</name>
<!-- RELEASE_VERSION -->
<version>4.1.1-SNAPSHOT</version>
<version>4.1.1</version>
<!-- /RELEASE_VERSION -->
<url>https://github.com/openapitools/openapi-generator</url>
<scm>
@@ -188,7 +188,7 @@
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
@@ -843,6 +843,18 @@
<module>samples/client/petstore/typescript-fetch/builds/with-npm-version</module>
</modules>
</profile>
<profile>
<id>typescript-fetch-client-builds-prefix-parameter-interfaces</id>
<activation>
<property>
<name>env</name>
<value>java</value>
</property>
</activation>
<modules>
<module>samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces</module>
</modules>
</profile>
<profile>
<id>typescript-angularjs-client</id>
<activation>
@@ -1024,10 +1036,7 @@
<modules>
<!-- clients -->
<module>samples/client/petstore/c</module>
<module>samples/client/petstore/cpp-qt5</module>
<!--<module>samples/client/petstore/dart-jaguar/openapi</module>
<module>samples/client/petstore/dart-jaguar/flutter_petstore/openapi</module>-->
<!--<module>samples/client/petstore/dart2/petstore</module>-->
<!-- <module>samples/client/petstore/cpp-qt5</module> -->
<module>samples/client/petstore/elm-0.18</module>
<module>samples/client/petstore/rust</module>
<module>samples/client/petstore/rust-reqwest</module>
@@ -1050,7 +1059,8 @@
<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>
<!-- comment out due to CI failure, e.g. https://travis-ci.org/OpenAPITools/openapi-generator/builds/574865730
<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>
<!-- comment out due to github rate limit error
@@ -1385,8 +1395,8 @@
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<swagger-parser-groupid>org.openapitools.swagger.parser</swagger-parser-groupid>
<swagger-parser-version>2.0.13-OpenAPITools.org-2</swagger-parser-version>
<swagger-core-version>2.0.7</swagger-core-version>
<swagger-core-version>2.0.9</swagger-core-version>
<swagger-parser-version>2.0.14-OpenAPITools.org-1</swagger-parser-version>
<scala-version>2.11.1</scala-version>
<felix-version>3.3.1</felix-version>
<commons-io-version>2.4</commons-io-version>

View File

@@ -371,6 +371,8 @@ PetApi <- R6::R6Class(
if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) {
ApiResponse$new(NULL, resp)
} else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) {
ApiResponse$new(paste("Server returned " , httr::status_code(resp) , " response status code."), resp)
} else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) {
ApiResponse$new("API client error", resp)
} else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) {
@@ -417,6 +419,8 @@ PetApi <- R6::R6Class(
if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) {
ApiResponse$new(NULL, resp)
} else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) {
ApiResponse$new(paste("Server returned " , httr::status_code(resp) , " response status code."), resp)
} else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) {
ApiResponse$new("API client error", resp)
} else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) {
@@ -465,6 +469,8 @@ PetApi <- R6::R6Class(
}
)
ApiResponse$new(deserializedRespObj, resp)
} else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) {
ApiResponse$new(paste("Server returned " , httr::status_code(resp) , " response status code."), resp)
} else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) {
ApiResponse$new("API client error", resp)
} else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) {
@@ -513,6 +519,8 @@ PetApi <- R6::R6Class(
}
)
ApiResponse$new(deserializedRespObj, resp)
} else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) {
ApiResponse$new(paste("Server returned " , httr::status_code(resp) , " response status code."), resp)
} else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) {
ApiResponse$new("API client error", resp)
} else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) {
@@ -565,6 +573,8 @@ PetApi <- R6::R6Class(
}
)
ApiResponse$new(deserializedRespObj, resp)
} else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) {
ApiResponse$new(paste("Server returned " , httr::status_code(resp) , " response status code."), resp)
} else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) {
ApiResponse$new("API client error", resp)
} else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) {
@@ -611,6 +621,8 @@ PetApi <- R6::R6Class(
if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) {
ApiResponse$new(NULL, resp)
} else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) {
ApiResponse$new(paste("Server returned " , httr::status_code(resp) , " response status code."), resp)
} else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) {
ApiResponse$new("API client error", resp)
} else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) {
@@ -660,6 +672,8 @@ PetApi <- R6::R6Class(
if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) {
ApiResponse$new(NULL, resp)
} else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) {
ApiResponse$new(paste("Server returned " , httr::status_code(resp) , " response status code."), resp)
} else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) {
ApiResponse$new("API client error", resp)
} else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) {
@@ -715,6 +729,8 @@ PetApi <- R6::R6Class(
}
)
ApiResponse$new(deserializedRespObj, resp)
} else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) {
ApiResponse$new(paste("Server returned " , httr::status_code(resp) , " response status code."), resp)
} else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) {
ApiResponse$new("API client error", resp)
} else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) {

View File

@@ -210,6 +210,8 @@ StoreApi <- R6::R6Class(
if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) {
ApiResponse$new(NULL, resp)
} else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) {
ApiResponse$new(paste("Server returned " , httr::status_code(resp) , " response status code."), resp)
} else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) {
ApiResponse$new("API client error", resp)
} else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) {
@@ -254,6 +256,8 @@ StoreApi <- R6::R6Class(
}
)
ApiResponse$new(deserializedRespObj, resp)
} else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) {
ApiResponse$new(paste("Server returned " , httr::status_code(resp) , " response status code."), resp)
} else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) {
ApiResponse$new("API client error", resp)
} else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) {
@@ -302,6 +306,8 @@ StoreApi <- R6::R6Class(
}
)
ApiResponse$new(deserializedRespObj, resp)
} else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) {
ApiResponse$new(paste("Server returned " , httr::status_code(resp) , " response status code."), resp)
} else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) {
ApiResponse$new("API client error", resp)
} else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) {
@@ -352,6 +358,8 @@ StoreApi <- R6::R6Class(
}
)
ApiResponse$new(deserializedRespObj, resp)
} else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) {
ApiResponse$new(paste("Server returned " , httr::status_code(resp) , " response status code."), resp)
} else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) {
ApiResponse$new("API client error", resp)
} else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) {

View File

@@ -329,6 +329,8 @@ UserApi <- R6::R6Class(
if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) {
ApiResponse$new(NULL, resp)
} else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) {
ApiResponse$new(paste("Server returned " , httr::status_code(resp) , " response status code."), resp)
} else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) {
ApiResponse$new("API client error", resp)
} else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) {
@@ -374,6 +376,8 @@ UserApi <- R6::R6Class(
if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) {
ApiResponse$new(NULL, resp)
} else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) {
ApiResponse$new(paste("Server returned " , httr::status_code(resp) , " response status code."), resp)
} else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) {
ApiResponse$new("API client error", resp)
} else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) {
@@ -419,6 +423,8 @@ UserApi <- R6::R6Class(
if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) {
ApiResponse$new(NULL, resp)
} else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) {
ApiResponse$new(paste("Server returned " , httr::status_code(resp) , " response status code."), resp)
} else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) {
ApiResponse$new("API client error", resp)
} else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) {
@@ -461,6 +467,8 @@ UserApi <- R6::R6Class(
if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) {
ApiResponse$new(NULL, resp)
} else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) {
ApiResponse$new(paste("Server returned " , httr::status_code(resp) , " response status code."), resp)
} else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) {
ApiResponse$new("API client error", resp)
} else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) {
@@ -509,6 +517,8 @@ UserApi <- R6::R6Class(
}
)
ApiResponse$new(deserializedRespObj, resp)
} else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) {
ApiResponse$new(paste("Server returned " , httr::status_code(resp) , " response status code."), resp)
} else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) {
ApiResponse$new("API client error", resp)
} else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) {
@@ -561,6 +571,8 @@ UserApi <- R6::R6Class(
}
)
ApiResponse$new(deserializedRespObj, resp)
} else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) {
ApiResponse$new(paste("Server returned " , httr::status_code(resp) , " response status code."), resp)
} else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) {
ApiResponse$new("API client error", resp)
} else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) {
@@ -595,6 +607,8 @@ UserApi <- R6::R6Class(
if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) {
ApiResponse$new(NULL, resp)
} else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) {
ApiResponse$new(paste("Server returned " , httr::status_code(resp) , " response status code."), resp)
} else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) {
ApiResponse$new("API client error", resp)
} else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) {
@@ -647,6 +661,8 @@ UserApi <- R6::R6Class(
if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) {
ApiResponse$new(NULL, resp)
} else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) {
ApiResponse$new(paste("Server returned " , httr::status_code(resp) , " response status code."), resp)
} else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) {
ApiResponse$new("API client error", resp)
} else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) {

View File

@@ -51,7 +51,10 @@ void (empty response body)
- **Content-Type**: application/json, application/xml
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **405** | Invalid input | - |
# **DeletePet**
> DeletePet(pet.id, api.key=var.api.key)
@@ -92,7 +95,10 @@ void (empty response body)
- **Content-Type**: Not defined
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **400** | Invalid pet value | - |
# **FindPetsByStatus**
> array[Pet] FindPetsByStatus(status)
@@ -134,7 +140,11 @@ Name | Type | Description | Notes
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid status value | - |
# **FindPetsByTags**
> array[Pet] FindPetsByTags(tags)
@@ -176,7 +186,11 @@ Name | Type | Description | Notes
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid tag value | - |
# **GetPetById**
> Pet GetPetById(pet.id)
@@ -218,7 +232,12 @@ Name | Type | Description | Notes
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid ID supplied | - |
| **404** | Pet not found | - |
# **UpdatePet**
> UpdatePet(body)
@@ -257,7 +276,12 @@ void (empty response body)
- **Content-Type**: application/json, application/xml
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **400** | Invalid ID supplied | - |
| **404** | Pet not found | - |
| **405** | Validation exception | - |
# **UpdatePetWithForm**
> UpdatePetWithForm(pet.id, name=var.name, status=var.status)
@@ -300,7 +324,10 @@ void (empty response body)
- **Content-Type**: application/x-www-form-urlencoded
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **405** | Invalid input | - |
# **UploadFile**
> ModelApiResponse UploadFile(pet.id, additional.metadata=var.additional.metadata, file=var.file)
@@ -344,5 +371,8 @@ Name | Type | Description | Notes
- **Content-Type**: multipart/form-data
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |

View File

@@ -47,7 +47,11 @@ No authorization required
- **Content-Type**: Not defined
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **400** | Invalid ID supplied | - |
| **404** | Order not found | - |
# **GetInventory**
> map(integer) GetInventory()
@@ -85,7 +89,10 @@ This endpoint does not need any parameter.
- **Content-Type**: Not defined
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
# **GetOrderById**
> Order GetOrderById(order.id)
@@ -125,7 +132,12 @@ No authorization required
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid ID supplied | - |
| **404** | Order not found | - |
# **PlaceOrder**
> Order PlaceOrder(body)
@@ -163,5 +175,9 @@ No authorization required
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid Order | - |

View File

@@ -51,7 +51,10 @@ No authorization required
- **Content-Type**: Not defined
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **0** | successful operation | - |
# **CreateUsersWithArrayInput**
> CreateUsersWithArrayInput(body)
@@ -88,7 +91,10 @@ No authorization required
- **Content-Type**: Not defined
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **0** | successful operation | - |
# **CreateUsersWithListInput**
> CreateUsersWithListInput(body)
@@ -125,7 +131,10 @@ No authorization required
- **Content-Type**: Not defined
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **0** | successful operation | - |
# **DeleteUser**
> DeleteUser(username)
@@ -164,7 +173,11 @@ No authorization required
- **Content-Type**: Not defined
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **400** | Invalid username supplied | - |
| **404** | User not found | - |
# **GetUserByName**
> User GetUserByName(username)
@@ -202,7 +215,12 @@ No authorization required
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid username supplied | - |
| **404** | User not found | - |
# **LoginUser**
> character LoginUser(username, password)
@@ -242,7 +260,11 @@ No authorization required
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | * X-Rate-Limit - calls per hour allowed by the user <br> * X-Expires-After - date in UTC when toekn expires <br> |
| **400** | Invalid username/password supplied | - |
# **LogoutUser**
> LogoutUser()
@@ -275,7 +297,10 @@ No authorization required
- **Content-Type**: Not defined
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **0** | successful operation | - |
# **UpdateUser**
> UpdateUser(username, body)
@@ -316,5 +341,9 @@ No authorization required
- **Content-Type**: Not defined
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **400** | Invalid user supplied | - |
| **404** | User not found | - |

View File

@@ -1,15 +1,7 @@
#include "PetApiTests.h"
#include <QJsonDocument>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QDebug>
PetApiTests::PetApiTests () {}
PetApiTests::~PetApiTests () {
}
#include <QTest>
#include <QTimer>
OAIPetApi* PetApiTests::getApi() {
auto api = new OAIPetApi();
@@ -20,96 +12,65 @@ OAIPetApi* PetApiTests::getApi() {
OAIPet PetApiTests::createRandomPet() {
OAIPet pet;
qint64 id = QDateTime::currentMSecsSinceEpoch();
pet.setName(QString("monster"));
pet.setName("monster");
pet.setId(id);
pet.setStatus(QString("freaky"));
pet.setStatus("freaky");
return pet;
}
void PetApiTests::runTests() {
PetApiTests* tests = new PetApiTests();
QTest::qExec(tests);
delete tests;
}
void PetApiTests::findPetsByStatusTest() {
OAIPetApi* api = getApi();
QEventLoop loop;
QTimer timer;
timer.setInterval(14000);
timer.setSingleShot(true);
bool petFound = false;
auto validator = [this](QList<OAIPet> pets) {
connect(api, &OAIPetApi::findPetsByStatusSignal, [&](QList<OAIPet> pets) {
petFound = true;
foreach(OAIPet pet, pets) {
QVERIFY(pet.getStatus().startsWith("available") || pet.getStatus().startsWith("sold"));
}
emit quit();
};
auto finalizer = [&]() {
loop.quit();
};
connect(this, &PetApiTests::quit, finalizer);
connect(api, &OAIPetApi::findPetsByStatusSignal, this, validator);
connect(&timer, &QTimer::timeout, &loop, finalizer);
});
QList<QString> status;
QString available("available");
QString sold("sold");
status.append(available);
status.append(sold);
api->findPetsByStatus(status);
timer.start();
api->findPetsByStatus({"available", "sold"});
QTimer::singleShot(5000, &loop, &QEventLoop::quit);
loop.exec();
QVERIFY2(timer.isActive(), "didn't finish within timeout");
disconnect(this, nullptr, nullptr, nullptr);
QVERIFY2(petFound, "didn't finish within timeout");
delete api;
}
void PetApiTests::createAndGetPetTest() {
OAIPetApi* api = getApi();
QEventLoop loop;
QTimer timer;
timer.setInterval(14000);
timer.setSingleShot(true);
bool petCreated = false;
auto validator = [this]() {
connect(api, &OAIPetApi::addPetSignal, [&]() {
// pet created
emit quit();
};
auto finalizer = [&]() {
petCreated = true;
loop.quit();
};
connect(this, &PetApiTests::quit, finalizer);
connect(api, &OAIPetApi::addPetSignal, this, validator);
connect(&timer, &QTimer::timeout, &loop, finalizer);
});
OAIPet pet = createRandomPet();
qint64 id = pet.getId();
api->addPet(pet);
timer.start();
QTimer::singleShot(14000, &loop, &QEventLoop::quit);
loop.exec();
QVERIFY2(timer.isActive(), "didn't finish within timeout");
QVERIFY2(petCreated, "didn't finish within timeout");
timer.setInterval(1000);
timer.setSingleShot(true);
bool petFetched = false;
auto getPetValidator = [this](OAIPet pet) {
connect(api, &OAIPetApi::getPetByIdSignal, [&](OAIPet pet) {
QVERIFY(pet.getId() > 0);
QVERIFY(pet.getStatus().compare("freaky") == 0);
emit quit();
};
connect(api, &OAIPetApi::getPetByIdSignal, this, getPetValidator);
connect(&timer, &QTimer::timeout, &loop, finalizer);
loop.quit();
petFetched = true;
});
api->getPetById(id);
timer.start();
QTimer::singleShot(14000, &loop, &QEventLoop::quit);
loop.exec();
QVERIFY2(timer.isActive(), "didn't finish within timeout");
disconnect(this, nullptr, nullptr, nullptr);
QVERIFY2(petFetched, "didn't finish within timeout");
delete api;
}
@@ -120,76 +81,61 @@ void PetApiTests::updatePetTest() {
OAIPet petToCheck;
qint64 id = pet.getId();
QEventLoop loop;
QTimer timer;
timer.setInterval(100000);
timer.setSingleShot(true);
bool petAdded = false;
auto validator = [this]() {
emit quit();
};
auto finalizer = [&]() {
connect(api, &OAIPetApi::addPetSignal, [&](){
petAdded = true;
loop.quit();
};
connect(this, &PetApiTests::quit, finalizer);
connect(api, &OAIPetApi::addPetSignal, this, validator);
connect(&timer, &QTimer::timeout, &loop, finalizer);
});
// create pet
api->addPet(pet);
timer.start();
QTimer::singleShot(5000, &loop, &QEventLoop::quit);
loop.exec();
QVERIFY2(timer.isActive(), "didn't finish within timeout");
QVERIFY2(petAdded, "didn't finish within timeout");
// fetch it
timer.setInterval(1000);
timer.setSingleShot(true);
auto fetchPet = [&](OAIPet pet) {
petToCheck = pet;
emit quit();
};
connect(api, &OAIPetApi::getPetByIdSignal, this, fetchPet);
connect(&timer, &QTimer::timeout, &loop, finalizer);
bool petFetched = false;
connect(api, &OAIPetApi::getPetByIdSignal, this, [&](OAIPet pet) {
petFetched = true;
petToCheck = pet;
loop.quit();
});
// create pet
api->getPetById(id);
timer.start();
QTimer::singleShot(5000, &loop, &QEventLoop::quit);
loop.exec();
QVERIFY2(timer.isActive(), "didn't finish within timeout");
QVERIFY2(petFetched, "didn't finish within timeout");
// update it
timer.setInterval(1000);
timer.setSingleShot(true);
auto updatePetTest = [this]() {
emit quit();
};
connect(api, &OAIPetApi::updatePetSignal, this, updatePetTest);
connect(&timer, &QTimer::timeout, &loop, finalizer);
bool petUpdated = false;
connect(api, &OAIPetApi::updatePetSignal, [&]() {
petUpdated = true;
loop.quit();
});
// update pet
petToCheck.setStatus(QString("scary"));
api->updatePet(petToCheck);
timer.start();
QTimer::singleShot(5000, &loop, &QEventLoop::quit);
loop.exec();
QVERIFY2(timer.isActive(), "didn't finish within timeout");
QVERIFY2(petUpdated, "didn't finish within timeout");
// check it
timer.setInterval(1000);
timer.setSingleShot(true);
auto fetchPet2 = [&](OAIPet pet) {
bool petFetched2 = false;
connect(api, &OAIPetApi::getPetByIdSignal, [&](OAIPet pet) {
petFetched2 = true;
QVERIFY(pet.getId() == petToCheck.getId());
QVERIFY(pet.getStatus().compare(petToCheck.getStatus()) == 0);
emit quit();
};
connect(api, &OAIPetApi::getPetByIdSignal, this, fetchPet2);
connect(&timer, &QTimer::timeout, &loop, finalizer);
loop.quit();
});
api->getPetById(id);
timer.start();
QTimer::singleShot(5000, &loop, &QEventLoop::quit);
loop.exec();
QVERIFY2(timer.isActive(), "didn't finish within timeout");
disconnect(this, nullptr, nullptr, nullptr);
QVERIFY2(petFetched2, "didn't finish within timeout");
delete api;
}
@@ -200,70 +146,57 @@ void PetApiTests::updatePetWithFormTest() {
OAIPet petToCheck;
qint64 id = pet.getId();
QEventLoop loop;
QTimer timer;
// create pet
timer.setInterval(1000);
timer.setSingleShot(true);
auto validator = [this ]() {
emit quit();
};
auto finalizer = [&]() {
bool petAdded = false;
connect(api, &OAIPetApi::addPetSignal, [&](){
petAdded = true;
loop.quit();
};
connect(this, &PetApiTests::quit, finalizer);
connect(api, &OAIPetApi::addPetSignal, this, validator);
connect(&timer, &QTimer::timeout, &loop, finalizer);
});
api->addPet(pet);
timer.start();
QTimer::singleShot(5000, &loop, &QEventLoop::quit);
loop.exec();
QVERIFY2(timer.isActive(), "didn't finish within timeout");
QVERIFY2(petAdded, "didn't finish within timeout");
// fetch it
timer.setInterval(1000);
timer.setSingleShot(true);
auto fetchPet = [&](OAIPet pet) {
bool petFetched = false;
connect(api, &OAIPetApi::getPetByIdSignal, [&](OAIPet pet) {
petFetched = true;
petToCheck = pet;
emit quit();
};
connect(api, &OAIPetApi::getPetByIdSignal, this, fetchPet);
connect(&timer, &QTimer::timeout, &loop, finalizer);
loop.quit();
});
api->getPetById(id);
timer.start();
QTimer::singleShot(5000, &loop, &QEventLoop::quit);
loop.exec();
QVERIFY2(timer.isActive(), "didn't finish within timeout");
QVERIFY2(petFetched, "didn't finish within timeout");
// update it
timer.setInterval(1000);
timer.setSingleShot(true);
connect(api, &OAIPetApi::updatePetWithFormSignal, this, [this](){emit quit();});
connect(&timer, &QTimer::timeout, &loop, finalizer);
bool petUpdated = false;
connect(api, &OAIPetApi::updatePetWithFormSignal, [&](){
petUpdated = true;
loop.quit();
});
QString name("gorilla");
api->updatePetWithForm(id, name, nullptr);
timer.start();
QTimer::singleShot(5000, &loop, &QEventLoop::quit);
loop.exec();
QVERIFY2(timer.isActive(), "didn't finish within timeout");
QVERIFY2(petUpdated, "didn't finish within timeout");
// fetch it
timer.setInterval(1000);
timer.setSingleShot(true);
auto fetchUpdatedPet = [this](OAIPet pet) {
bool petUpdated2 = false;
connect(api, &OAIPetApi::getPetByIdSignal, [&](OAIPet pet) {
petUpdated2 = true;
QVERIFY(pet.getName().compare(QString("gorilla")) == 0);
emit quit();
};
connect(api, &OAIPetApi::getPetByIdSignal, this, fetchUpdatedPet);
connect(&timer, &QTimer::timeout, &loop, finalizer);
loop.quit();
});
api->getPetById(id);
timer.start();
QTimer::singleShot(5000, &loop, &QEventLoop::quit);
loop.exec();
QVERIFY2(timer.isActive(), "didn't finish within timeout");
disconnect(this, nullptr, nullptr, nullptr);
QVERIFY2(petUpdated2, "didn't finish within timeout");
delete api;
}

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