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

This commit is contained in:
William Cheng
2019-07-27 20:53:38 +08:00
2361 changed files with 50528 additions and 12787 deletions

9
CI/.drone.yml Normal file
View File

@@ -0,0 +1,9 @@
kind: pipeline
name: default
steps:
- name: test
image: hirokimatsumoto/alpine-openjdk-11
commands:
- ./mvnw clean install
- ./mvnw --quiet verify -Psamples.droneio

View File

@@ -0,0 +1,26 @@
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>org.openapitools</groupId>
<artifactId>TypeScriptAngularBuildPestoreClientTests</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<name>TS Fetch Multiple Parameters Petstore Client</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>
</plugins>
</build>
</project>

View File

@@ -6,11 +6,13 @@
[![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)
[![JDK11 Build](https://cloud.drone.io/api/badges/OpenAPITools/openapi-generator/status.svg?ref=refs/heads/master)](https://cloud.drone.io/OpenAPITools/openapi-generator)
[`5.0.x`](https://github.com/OpenAPITools/openapi-generator/tree/5.0.x) branch: [![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/5.0.x.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator)
[![Integration Test2](https://circleci.com/gh/OpenAPITools/openapi-generator/tree/5.0.x.svg?style=shield)](https://circleci.com/gh/OpenAPITools/openapi-generator)
[![Run Status](https://api.shippable.com/projects/5af6bf74e790f4070084a115/badge?branch=5.0.x)](https://app.shippable.com/github/OpenAPITools/openapi-generator)
[![Windows Test](https://ci.appveyor.com/api/projects/status/github/openapitools/openapi-generator?branch=5.0.x&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/openapi-generator-wh2wu)
[![JDK11 Build](https://cloud.drone.io/api/badges/OpenAPITools/openapi-generator/status.svg?ref=refs/heads/5.0.x)](https://cloud.drone.io/OpenAPITools/openapi-generator)
</div>
<div align="center">
@@ -46,12 +48,18 @@ If you find OpenAPI Generator useful for work, please consider asking your compa
[![NamSor](https://openapi-generator.tech/img/companies/namsor.png)](https://www.namsor.com/?utm_source=openapi_generator&utm_medium=github_webpage&utm_campaign=sponsor)
[![LightBow](https://openapi-generator.tech/img/companies/lightbow.png)](https://www.lightbow.net/?utm_source=openapi_generator&utm_medium=github_webpage&utm_campaign=sponsor)
#### Thank you GoDaddy for sponsoring the domain names and Linode for sponsoring the VPS
[<img src="https://openapi-generator.tech/img/companies/godaddy.png" width="150">](https://www.godaddy.com/?utm_source=openapi_generator&utm_medium=github_webpage&utm_campaign=sponsor)
[![Linode](https://www.linode.com/media/images/logos/standard/light/linode-logo_standard_light_small.png)](https://www.linode.com/?utm_source=openapi_generator&utm_medium=github_webpage&utm_campaign=sponsor)
## Overview
OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an [OpenAPI Spec](https://github.com/OAI/OpenAPI-Specification) (both 2.0 and 3.0 are supported). Currently, the following languages/frameworks are supported:
| | 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** (ES5, ES6, AngularJS with Google Closure Compiler annotations, Flow types) **Objective-C**, **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 - 7.x), Aurelia, Axios, Fetch, Inversify, jQuery, Node, Rxjs)
**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**, **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 - 7.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)
**API documentation generators** | **HTML**, **Confluence Wiki**
**Configuration files** | [**Apache2**](https://httpd.apache.org/)
@@ -217,9 +225,9 @@ openapi-generator-cli version # is always 3.0.2, unless any of the above overrid
To build from source, you need the following installed and available in your `$PATH:`
* [Java 8](http://java.oracle.com)
* [Java 8](https://www.oracle.com/technetwork/java/index.html)
* [Apache Maven 3.3.4 or greater](http://maven.apache.org/)
* [Apache Maven 3.3.4 or greater](https://maven.apache.org/)
After cloning the project, you can build it from source with this command:
```sh
@@ -242,6 +250,17 @@ openapi-generator generate -i https://raw.githubusercontent.com/openapitools/ope
To reinstall with the latest master, run `brew uninstall openapi-generator && brew install --HEAD openapi-generator`
To install OpenJDK (pre-requisites), please run
```sh
brew cask install adoptopenjdk12
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-12.0.2.jdk/Contents/Home/
```
To install Maven, please run
```sh
brew install maven
```
### [1.6 - Docker](#table-of-contents)
#### Public Pre-built Docker images
@@ -342,7 +361,7 @@ Right now: no solution for this one :|
#### Run Docker in Vagrant
Prerequisite: install [Vagrant](https://www.vagrantup.com/downloads.html) and [VirtualBox](https://www.virtualbox.org/wiki/Downloads).
```sh
git clone http://github.com/openapitools/openapi-generator.git
git clone https://github.com/openapitools/openapi-generator.git
cd openapi-generator
vagrant up
vagrant ssh
@@ -500,8 +519,8 @@ Please refer to [integration.md](docs/integration.md) on how to integrate OpenAP
Here are the public online services:
- latest stable version: http://api.openapi-generator.tech
- latest master: http://api-latest-master.openapi-generator.tech (updated with latest master every hour)
- latest stable version: https://api.openapi-generator.tech
- latest master: https://api-latest-master.openapi-generator.tech (updated with latest master every hour)
The server is sponsored by [Linode](https://www.linode.com/) [![Linode Logo](https://www.linode.com/media/images/logos/standard/light/linode-logo_standard_light_small.png)](https://www.linode.com/)
@@ -552,6 +571,7 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- [TUI InfoTec GmbH](http://www.tui-infotec.com/)
- [unblu inc.](https://www.unblu.com/)
- [Veamly](https://www.veamly.com/)
- [WSO2](https://wso2.com/)
- [Xero](https://www.xero.com/)
- [Yelp](https://www.yelp.com/)
- [Zalando](https://www.zalando.com)
@@ -591,7 +611,12 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- 2019-05-22 - [REST APIs代码生成指南(OpenAPI Generator)](https://gum.co/openapi_generator_ebook_gb) by [William Cheng](https://twitter.com/wing328), [Xin Meng](https://github.com/xmeng1)
- 2019-05-24 - [REST API 代碼生成指南 (OpenAPI Generator)](https://gum.co/openapi_generator_ebook_big5) by [William Cheng](https://twitter.com/wing328)
- 2019-06-24 - [Kubernetes Clients and OpenAPI Generator](https://speakerdeck.com/wing328/kubernetes-clients-and-openapi-generator) by [William Cheng](https://twitter.com/wing328) at [Kubernetes Contributor Summits Shanghai 2019](https://www.lfasiallc.com/events/contributors-summit-china-2019/)
- 2019-06-28 [Codewind OpenAPI Tools](https://marketplace.eclipse.org/content/codewind-openapi-tools) in [Eclipse Marketplace](https://marketplace.eclipse.org/) by IBM
- 2019-06-29 [Codewind OpenAPI Tools](https://marketplace.visualstudio.com/items?itemName=IBM.codewind-openapi-tools) in [Visual Studio Marketplace](https://marketplace.visualstudio.com/) by IBM
- 2019-07-04 - [REST API のためのコード生成入門 (OpenAPI Generator)](https://gum.co/openapi_generator_ebook_big5) by [William Cheng](https://twitter.com/wing328), [中野暁人](https://github.com/ackintosh), [和田拓朗](https://github.com/taxpon)
- 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/)
## [6 - About Us](#table-of-contents)
@@ -768,7 +793,7 @@ If you want to join the committee, please kindly apply by sending an email to te
| Elm | @eriktim (2018/09) |
| Erlang | @tsloughter (2017/11) @jfacorro (2018/10) @robertoaloi (2018/10) |
| F# | @nmfisher (2019/05) |
| Go | @antihax (2017/11) @bvwells (2017/12) @grokify (2018/07) @kemokemo (2018/09 |
| Go | @antihax (2017/11) @bvwells (2017/12) @grokify (2018/07) @kemokemo (2018/09) @bkabrda (2019/07) |
| GraphQL | @renepardon (2018/12) |
| Groovy | |
| Haskell | |
@@ -856,7 +881,7 @@ Copyright 2018 SmartBear Software
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at [apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)
You may obtain a copy of the License at [apache.org/licenses/LICENSE-2.0](https://www.apache.org/licenses/LICENSE-2.0)
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,

View File

@@ -34,6 +34,6 @@ rm -rf $STUB_DIR
# 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/$GENERATOR -i $SPEC -g $GENERATOR -o $STUB_DIR -DpackageName=petstore $@"
ags="generate -t modules/openapi-generator/src/main/resources/$GENERATOR -i $SPEC -g $GENERATOR -o $STUB_DIR --additional-properties packageName=petstore $@"
java $JAVA_OPTS -jar $executable $ags

View File

@@ -7,6 +7,7 @@
./bin/java-petstore-feign-10x.sh
./bin/java-petstore-okhttp-gson.sh
./bin/java-petstore-okhttp-gson-parcelable.sh
./bin/java-petstore-native.sh
./bin/java-petstore-retrofit.sh
./bin/java-petstore-retrofit2.sh
./bin/java-petstore-retrofit2rx.sh

View File

@@ -27,7 +27,7 @@ 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 --artifact-id petstore-java-client-jersey1 -t modules/openapi-generator/src/main/resources/Java -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g java -o samples/client/petstore/java/jersey1 --additional-properties hideGenerationTimestamp=true --library=jersey1 --additional-properties useNullForUnknownEnumValue=true $@"
ags="generate --artifact-id petstore-java-client-jersey1 -t modules/openapi-generator/src/main/resources/Java -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g java -o samples/client/petstore/java/jersey1 --additional-properties hideGenerationTimestamp=true --library=jersey1 $@"
echo "Removing files and folders under samples/client/petstore/java/jersey1/src/main"
rm -rf samples/client/petstore/java/jersey1/src/main

View File

@@ -1,7 +1,4 @@
{
"library": "jersey2",
"artifactId": "petstore-jersey2",
"additionalProperties" : {
"useNullForUnknownEnumValue" : true
}
"artifactId": "petstore-jersey2"
}

View File

@@ -0,0 +1,4 @@
{
"library": "native",
"artifactId": "petstore-native"
}

35
bin/java-petstore-native.sh Executable file
View File

@@ -0,0 +1,35 @@
#!/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 -t modules/openapi-generator/src/main/resources/Java/libraries/native -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g java -c bin/java-petstore-native.json -o samples/client/petstore/java/native --additional-properties hideGenerationTimestamp=true $@"
echo "Removing files and folders under samples/client/petstore/java/httpclient/src/main"
rm -rf samples/client/petstore/java/native/src/main
find samples/client/petstore/java/native -maxdepth 1 -type f ! -name "README.md" -exec rm {} +
java $JAVA_OPTS -jar $executable $ags

View File

@@ -30,3 +30,13 @@ export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/swift4 -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g swift4 -c ./bin/swift4-petstore-objcCompatible.json -o samples/client/petstore/swift4/objcCompatible $@"
java $JAVA_OPTS -jar $executable $ags
if type "xcodegen" > /dev/null 2>&1; then
cd samples/client/petstore/swift4/objcCompatible
xcodegen generate
fi
if type "swiftlint" > /dev/null 2>&1; then
cd samples/client/petstore/swift4/objcCompatible
swiftlint autocorrect
fi

View File

@@ -30,3 +30,13 @@ export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/swift4 -i modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml -g swift4 -c ./bin/swift4-petstore-promisekit.json -o samples/client/petstore/swift4/promisekit --generate-alias-as-model $@"
java $JAVA_OPTS -jar $executable $ags
if type "xcodegen" > /dev/null 2>&1; then
cd samples/client/petstore/swift4/promisekit
xcodegen generate
fi
if type "swiftlint" > /dev/null 2>&1; then
cd samples/client/petstore/swift4/promisekit
swiftlint autocorrect
fi

View File

@@ -30,3 +30,13 @@ export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/swift4 -i modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml -g swift4 -c ./bin/swift4-petstore-rxswift.json -o samples/client/petstore/swift4/rxswift --generate-alias-as-model $@"
java $JAVA_OPTS -jar $executable $ags
if type "xcodegen" > /dev/null 2>&1; then
cd samples/client/petstore/swift4/rxswift
xcodegen generate
fi
if type "swiftlint" > /dev/null 2>&1; then
cd samples/client/petstore/swift4/rxswift
swiftlint autocorrect
fi

View File

@@ -30,3 +30,13 @@ export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/swift4 -i modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml -g swift4 -c ./bin/swift4-petstore-unwrapRequired.json -o samples/client/petstore/swift4/unwrapRequired --generate-alias-as-model $@"
java $JAVA_OPTS -jar $executable $ags
if type "xcodegen" > /dev/null 2>&1; then
cd samples/client/petstore/swift4/unwrapRequired
xcodegen generate
fi
if type "swiftlint" > /dev/null 2>&1; then
cd samples/client/petstore/swift4/unwrapRequired
swiftlint autocorrect
fi

View File

@@ -30,3 +30,13 @@ export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/swift4 -i modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml -g swift4 -c ./bin/swift4-petstore.json -o samples/client/petstore/swift4/default --generate-alias-as-model $@"
java $JAVA_OPTS -jar $executable $ags
if type "xcodegen" > /dev/null 2>&1; then
cd samples/client/petstore/swift4/default
xcodegen generate
fi
if type "swiftlint" > /dev/null 2>&1; then
cd samples/client/petstore/swift4/default
swiftlint autocorrect
fi

View File

@@ -30,3 +30,13 @@ export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/swift4 -i modules/openapi-generator/src/test/resources/2_0/swift4Test.json -g swift4 -c ./bin/swift4-test.json -o samples/client/test/swift4/default $@"
java $JAVA_OPTS -jar $executable $ags
if type "xcodegen" > /dev/null 2>&1; then
cd samples/client/test/swift4/default
xcodegen generate
fi
if type "swiftlint" > /dev/null 2>&1; then
cd samples/client/test/swift4/default
swiftlint autocorrect
fi

View File

@@ -4,3 +4,4 @@
./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

View File

@@ -0,0 +1,4 @@
{
"snapshot" : false,
"useSingleRequestParameter": false
}

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-multiple-parameters.json -o samples/client/petstore/typescript-fetch/builds/multiple-parameters $@"
java $JAVA_OPTS -jar $executable $ags
cp CI/samples.ci/client/petstore/typescript-fetch/builds/multiple-parameters/pom.xml samples/client/petstore/typescript-fetch/builds/multiple-parameters/pom.xml
cp CI/samples.ci/client/petstore/typescript-fetch/tests/default/pom.xml samples/client/petstore/typescript-fetch/tests/default/pom.xml

View File

@@ -2,6 +2,7 @@ call .\bin\windows\java-petstore-jersey1.bat
call .\bin\windows\java-petstore-jersey2.bat
call .\bin\windows\java-petstore-feign.bat
call .\bin\windows\java-petstore-feign-10x.bat
call .\bin\windows\java-petstore-native.bat
call .\bin\windows\java-petstore-okhttp-gson.bat
call .\bin\windows\java-petstore-okhttp-gson-parcelable.bat
call .\bin\windows\java-petstore-retrofit.bat

View File

@@ -0,0 +1,10 @@
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 -t modules\openapi-generator\src\main\resources\Java\libraries\native -i modules\openapi-generator\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -g java -c bin\java-petstore-native.json -o samples\client\petstore\java\native --additional-properties hideGenerationTimestamp=true
java %JAVA_OPTS% -jar %executable% %ags%

View File

@@ -4,3 +4,4 @@ call bin\windows\typescript-fetch-petstore.bat
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

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 -c bin\typescript-fetch-petstore-multiple-parameters.json -o samples\client\petstore\typescript-fetch\builds\multiple-parameters
java %JAVA_OPTS% -jar %executable% %ags%

View File

@@ -19,7 +19,7 @@ if [[ -f "${codegen}" && -n "$(java ${JAVA_OPTS} -jar "${codegen}" completion |
command=$1
shift
exec java ${JAVA_OPTS} -jar "${codegen}" "${command}" "$@"
elif [[ -n "$(echo commands | tr ',' '\n' | grep "^$1\$" )" ]]; then
elif [[ -n "$(echo $commands | tr ',' '\n' | grep "^$1\$" )" ]]; then
# If CLI jar does not exist, and $1 is a known CLI command, build the CLI jar and run that command.
if [[ ! -f "${codegen}" ]]; then
(cd "${GEN_DIR}" && exec mvn -am -pl "modules/openapi-generator-cli" -Duser.home=$(dirname $MAVEN_CONFIG) package)

View File

@@ -62,3 +62,26 @@ The steps are shown here for a specific version of the generator, but apply the
Listening for transport dt_socket at address: 5005
```
* Set breakpoints in code, and then attach your remote debugger from your IDE (see above). The generator will automatically unblock once the remote debugger is attached. You can now step through the code.
## Logs
You can try to enable debugging log with `-Dlog.level=debug` option to the `JAVA_OPTS` environment variable to see more information:
```bash
export JAVA_OPTS="${JAVA_OPTS} -Dlog.level=debug"
```
Set the option then DEBUG logs are printed out:
```bash
openapi-generator generate -g go ...
...
...
[main] DEBUG o.o.codegen.DefaultCodegen - debugging fromProperty for files : class Schema {
type: null
format: null
$ref: #/components/schemas/File
...
...
```

View File

@@ -12,5 +12,5 @@ sidebar_label: cpp-qt5-client
|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|
|cppNamespace|C++ namespace (convention: name::space::for::api).| |OpenAPI|
|cppNamespace|C++ namespace (convention: name::space::for::api).| |OpenAPI|
|modelNamePrefix|Prefix that will be prepended to all model names.| |OAI|
|optionalProjectFile|Generate client.pri.| |true|

View File

@@ -12,4 +12,4 @@ sidebar_label: cpp-qt5-qhttpengine-server
|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|
|cppNamespace|C++ namespace (convention: name::space::for::api).| |OpenAPI|
|cppNamespace|C++ namespace (convention: name::space::for::api).| |OpenAPI|
|modelNamePrefix|Prefix that will be prepended to all model names.| |OAI|

View File

@@ -55,4 +55,4 @@ sidebar_label: java
|feignVersion|Version of OpenFeign: '10.x', '9.x' (default)| |false|
|useReflectionEqualsHashCode|Use org.apache.commons.lang3.builder for equals and hashCode in the models. WARNING: This will fail under a security manager, unless the appropriate permissions are set up correctly and also there's potential performance impact.| |false|
|caseInsensitiveResponseHeaders|Make API response's headers case-insensitive. Available on okhttp-gson, jersey2 libraries| |false|
|library|library template (sub-template) to use|<dl><dt>**jersey1**</dt><dd>HTTP client: Jersey client 1.19.x. JSON processing: Jackson 2.8.x. Enable Java6 support using '-DsupportJava6=true'. Enable gzip request encoding using '-DuseGzipFeature=true'. IMPORTANT NOTE: jersey 1.x is no longer actively maintained so please upgrade to 'jersey2' or other HTTP libaries instead.</dd><dt>**jersey2**</dt><dd>HTTP client: Jersey client 2.25.1. JSON processing: Jackson 2.8.x</dd><dt>**feign**</dt><dd>HTTP client: OpenFeign 9.x or 10.x. JSON processing: Jackson 2.8.x. To enable OpenFeign 10.x, set the 'feignVersion' option to '10.x'</dd><dt>**okhttp-gson**</dt><dd>[DEFAULT] HTTP client: OkHttp 3.x. JSON processing: Gson 2.8.x. Enable Parcelable models on Android using '-DparcelableModel=true'. Enable gzip request encoding using '-DuseGzipFeature=true'.</dd><dt>**retrofit**</dt><dd>HTTP client: OkHttp 2.x. JSON processing: Gson 2.x (Retrofit 1.9.0). IMPORTANT NOTE: retrofit1.x is no longer actively maintained so please upgrade to 'retrofit2' instead.</dd><dt>**retrofit2**</dt><dd>HTTP client: OkHttp 3.x. JSON processing: Gson 2.x (Retrofit 2.3.0). Enable the RxJava adapter using '-DuseRxJava[2]=true'. (RxJava 1.x or 2.x)</dd><dt>**resttemplate**</dt><dd>HTTP client: Spring RestTemplate 4.x. JSON processing: Jackson 2.8.x</dd><dt>**webclient**</dt><dd>HTTP client: Spring WebClient 5.x. JSON processing: Jackson 2.9.x</dd><dt>**resteasy**</dt><dd>HTTP client: Resteasy client 3.x. JSON processing: Jackson 2.8.x</dd><dt>**vertx**</dt><dd>HTTP client: VertX client 3.x. JSON processing: Jackson 2.8.x</dd><dt>**google-api-client**</dt><dd>HTTP client: Google API client 1.x. JSON processing: Jackson 2.8.x</dd><dt>**rest-assured**</dt><dd>HTTP client: rest-assured : 4.x. JSON processing: Gson 2.x. Only for Java8</dd><dl>|okhttp-gson|
|library|library template (sub-template) to use|<dl><dt>**jersey1**</dt><dd>HTTP client: Jersey client 1.19.x. JSON processing: Jackson 2.8.x. Enable Java6 support using '-DsupportJava6=true'. Enable gzip request encoding using '-DuseGzipFeature=true'. IMPORTANT NOTE: jersey 1.x is no longer actively maintained so please upgrade to 'jersey2' or other HTTP libaries instead.</dd><dt>**jersey2**</dt><dd>HTTP client: Jersey client 2.25.1. JSON processing: Jackson 2.8.x</dd><dt>**feign**</dt><dd>HTTP client: OpenFeign 9.x or 10.x. JSON processing: Jackson 2.8.x. To enable OpenFeign 10.x, set the 'feignVersion' option to '10.x'</dd><dt>**okhttp-gson**</dt><dd>[DEFAULT] HTTP client: OkHttp 3.x. JSON processing: Gson 2.8.x. Enable Parcelable models on Android using '-DparcelableModel=true'. Enable gzip request encoding using '-DuseGzipFeature=true'.</dd><dt>**retrofit**</dt><dd>HTTP client: OkHttp 2.x. JSON processing: Gson 2.x (Retrofit 1.9.0). IMPORTANT NOTE: retrofit1.x is no longer actively maintained so please upgrade to 'retrofit2' instead.</dd><dt>**retrofit2**</dt><dd>HTTP client: OkHttp 3.x. JSON processing: Gson 2.x (Retrofit 2.3.0). Enable the RxJava adapter using '-DuseRxJava[2]=true'. (RxJava 1.x or 2.x)</dd><dt>**resttemplate**</dt><dd>HTTP client: Spring RestTemplate 4.x. JSON processing: Jackson 2.8.x</dd><dt>**webclient**</dt><dd>HTTP client: Spring WebClient 5.x. JSON processing: Jackson 2.9.x</dd><dt>**resteasy**</dt><dd>HTTP client: Resteasy client 3.x. JSON processing: Jackson 2.8.x</dd><dt>**vertx**</dt><dd>HTTP client: VertX client 3.x. JSON processing: Jackson 2.8.x</dd><dt>**google-api-client**</dt><dd>HTTP client: Google API client 1.x. JSON processing: Jackson 2.8.x</dd><dt>**rest-assured**</dt><dd>HTTP client: rest-assured : 4.x. JSON processing: Gson 2.x. Only for Java8</dd><dt>**native**</dt><dd>HTTP client: Java native HttpClient. JSON processing: Jackson 2.9.x. Only for Java11+</dd><dl>|okhttp-gson|

View File

@@ -51,4 +51,5 @@ sidebar_label: jaxrs-cxf-cdi
|interfaceOnly|Whether to generate only API interface stubs without the server files.| |false|
|returnResponse|Whether generate API interface should return javax.ws.rs.core.Response instead of a deserialized entity. Only useful if interfaceOnly is true.| |false|
|useSwaggerAnnotations|Whether to generate Swagger annotations.| |true|
|openApiSpecFileLocation|Location where the file containing the spec will be generated in the output folder. No file generated when set to null or empty string.| |null|
|useBeanValidation|Use BeanValidation API annotations| |true|

View File

@@ -51,3 +51,4 @@ sidebar_label: jaxrs-spec
|interfaceOnly|Whether to generate only API interface stubs without the server files.| |false|
|returnResponse|Whether generate API interface should return javax.ws.rs.core.Response instead of a deserialized entity. Only useful if interfaceOnly is true.| |false|
|useSwaggerAnnotations|Whether to generate Swagger annotations.| |true|
|openApiSpecFileLocation|Location where the file containing the spec will be generated in the output folder. No file generated when set to null or empty string.| |null|

View File

@@ -15,7 +15,7 @@ sidebar_label: scala-play-server
|apiPackage|package for generated api classes| |null|
|sourceFolder|source folder for generated code| |null|
|routesFileName|Name of the routes file to generate.| |routes|
|routesFileName|Base package in which supporting classes are generated.| |org.openapitools|
|basePackage|Base package in which supporting classes are generated.| |org.openapitools|
|skipStubs|If set, skips generation of stub classes.| |false|
|supportAsync|If set, wraps API return types with Futures and generates async actions.| |false|
|generateCustomExceptions|If set, generates custom exception types.| |true|

View File

@@ -18,3 +18,4 @@ sidebar_label: typescript-fetch
|snapshot|When setting this property to true, the version will be suffixed with -SNAPSHOT.yyyyMMddHHmm| |false|
|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|

View File

@@ -19,6 +19,7 @@ package org.openapitools.codegen;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.parser.core.models.AuthorizationValue;
import org.openapitools.codegen.auth.AuthParser;
import java.util.List;
@@ -64,6 +65,10 @@ public class ClientOptInput {
return config;
}
/**
* @deprecated use {@link #config(CodegenConfig)} instead
* @param config codegen config
*/
@Deprecated
public void setConfig(CodegenConfig config) {
this.config = config;
@@ -74,6 +79,10 @@ public class ClientOptInput {
return openAPI;
}
/**
* @deprecated use {@link #openAPI(OpenAPI)} instead
* @param openAPI the specification
*/
@Deprecated
public void setOpenAPI(OpenAPI openAPI) {
this.openAPI = openAPI;

View File

@@ -203,10 +203,10 @@ public class CodegenConstants {
public static final String ENUM_PROPERTY_NAMING_DESC = "Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original'";
public static final String MODEL_NAME_PREFIX = "modelNamePrefix";
public static final String MODEL_NAME_PREFIX_DESC = "Prefix that will be prepended to all model names. Default is the empty string.";
public static final String MODEL_NAME_PREFIX_DESC = "Prefix that will be prepended to all model names.";
public static final String MODEL_NAME_SUFFIX = "modelNameSuffix";
public static final String MODEL_NAME_SUFFIX_DESC = "Suffix that will be appended to all model names. Default is the empty string.";
public static final String MODEL_NAME_SUFFIX_DESC = "Suffix that will be appended to all model names.";
public static final String GIT_USER_ID = "gitUserId";
public static final String GIT_USER_ID_DESC = "Git user ID, e.g. openapitools.";

View File

@@ -46,7 +46,7 @@ public class CodegenModel {
public String defaultValue;
public String arrayModelType;
public boolean isAlias; // Is this effectively an alias of another simple type
public boolean isString, isInteger;
public boolean isString, isInteger, isLong, isNumber, isNumeric, isFloat, isDouble;
public List<CodegenProperty> vars = new ArrayList<CodegenProperty>(); // all properties (without parent's properties)
public List<CodegenProperty> allVars = new ArrayList<CodegenProperty>(); // all properties (with parent's properties)
public List<CodegenProperty> requiredVars = new ArrayList<CodegenProperty>(); // a list of required properties
@@ -61,7 +61,7 @@ public class CodegenModel {
public Set<String> allMandatory = new TreeSet<String>(); // with parent's required properties
public Set<String> imports = new TreeSet<String>();
public boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum, hasRequired, hasOptional, isArrayModel, hasChildren, isMapModel;
public boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum, isNullable, hasRequired, hasOptional, isArrayModel, hasChildren, isMapModel;
public boolean hasOnlyReadOnly = true; // true if all properties are read-only
public ExternalDocumentation externalDocumentation;
@@ -96,7 +96,12 @@ public class CodegenModel {
.append("arrayModelType", arrayModelType)
.append("isAlias", isAlias)
.append("isString", isString)
.append("isNumeric", isNumeric)
.append("isInteger", isInteger)
.append("isLong", isLong)
.append("isNumber", isNumber)
.append("isFloat", isFloat)
.append("isDouble", isDouble)
.append("vars", vars)
.append("requiredVars", requiredVars)
.append("optionalVars", optionalVars)
@@ -113,6 +118,7 @@ public class CodegenModel {
.append("hasMoreModels", hasMoreModels)
.append("hasEnums", hasEnums)
.append("isEnum", isEnum)
.append("isNullable", isEnum)
.append("hasRequired", hasRequired)
.append("hasOptional", hasOptional)
.append("isArrayModel", isArrayModel)
@@ -133,86 +139,86 @@ public class CodegenModel {
CodegenModel that = (CodegenModel) o;
return Objects.equals(parent, that.parent) &&
Objects.equals(parentSchema, that.parentSchema) &&
Objects.equals(interfaces, that.interfaces) &&
Objects.equals(allParents, that.allParents) &&
Objects.equals(parentModel, that.parentModel) &&
Objects.equals(interfaceModels, that.interfaceModels) &&
Objects.equals(name, that.name) &&
Objects.equals(classname, that.classname) &&
Objects.equals(title, that.title) &&
Objects.equals(description, that.description) &&
Objects.equals(classVarName, that.classVarName) &&
Objects.equals(modelJson, that.modelJson) &&
Objects.equals(dataType, that.dataType) &&
Objects.equals(xmlPrefix, that.xmlPrefix) &&
Objects.equals(xmlNamespace, that.xmlNamespace) &&
Objects.equals(xmlName, that.xmlName) &&
Objects.equals(classFilename, that.classFilename) &&
Objects.equals(unescapedDescription, that.unescapedDescription) &&
Objects.equals(discriminator, that.discriminator) &&
Objects.equals(defaultValue, that.defaultValue) &&
Objects.equals(vars, that.vars) &&
Objects.equals(requiredVars, that.requiredVars) &&
Objects.equals(optionalVars, that.optionalVars) &&
Objects.equals(allVars, that.allVars) &&
Objects.equals(allowableValues, that.allowableValues) &&
Objects.equals(mandatory, that.mandatory) &&
Objects.equals(allMandatory, that.allMandatory) &&
Objects.equals(imports, that.imports) &&
Objects.equals(hasVars, that.hasVars) &&
Objects.equals(emptyVars, that.emptyVars) &&
Objects.equals(hasMoreModels, that.hasMoreModels) &&
Objects.equals(hasEnums, that.hasEnums) &&
Objects.equals(isEnum, that.isEnum) &&
Objects.equals(externalDocumentation, that.externalDocumentation) &&
Objects.equals(hasOnlyReadOnly, that.hasOnlyReadOnly) &&
Objects.equals(hasChildren, that.hasChildren) &&
Objects.equals(parentVars, that.parentVars) &&
Objects.equals(vendorExtensions, that.vendorExtensions);
Objects.equals(parentSchema, that.parentSchema) &&
Objects.equals(interfaces, that.interfaces) &&
Objects.equals(allParents, that.allParents) &&
Objects.equals(parentModel, that.parentModel) &&
Objects.equals(interfaceModels, that.interfaceModels) &&
Objects.equals(name, that.name) &&
Objects.equals(classname, that.classname) &&
Objects.equals(title, that.title) &&
Objects.equals(description, that.description) &&
Objects.equals(classVarName, that.classVarName) &&
Objects.equals(modelJson, that.modelJson) &&
Objects.equals(dataType, that.dataType) &&
Objects.equals(xmlPrefix, that.xmlPrefix) &&
Objects.equals(xmlNamespace, that.xmlNamespace) &&
Objects.equals(xmlName, that.xmlName) &&
Objects.equals(classFilename, that.classFilename) &&
Objects.equals(unescapedDescription, that.unescapedDescription) &&
Objects.equals(discriminator, that.discriminator) &&
Objects.equals(defaultValue, that.defaultValue) &&
Objects.equals(vars, that.vars) &&
Objects.equals(requiredVars, that.requiredVars) &&
Objects.equals(optionalVars, that.optionalVars) &&
Objects.equals(allVars, that.allVars) &&
Objects.equals(allowableValues, that.allowableValues) &&
Objects.equals(mandatory, that.mandatory) &&
Objects.equals(allMandatory, that.allMandatory) &&
Objects.equals(imports, that.imports) &&
Objects.equals(hasVars, that.hasVars) &&
Objects.equals(emptyVars, that.emptyVars) &&
Objects.equals(hasMoreModels, that.hasMoreModels) &&
Objects.equals(hasEnums, that.hasEnums) &&
Objects.equals(isEnum, that.isEnum) &&
Objects.equals(externalDocumentation, that.externalDocumentation) &&
Objects.equals(hasOnlyReadOnly, that.hasOnlyReadOnly) &&
Objects.equals(hasChildren, that.hasChildren) &&
Objects.equals(parentVars, that.parentVars) &&
Objects.equals(vendorExtensions, that.vendorExtensions);
}
@Override
public int hashCode() {
return Objects.hash(
parent,
parentSchema,
interfaces,
allParents,
parentModel,
interfaceModels,
name,
classname,
title,
description,
classVarName,
modelJson,
dataType,
xmlPrefix,
xmlNamespace,
xmlName,
classFilename,
unescapedDescription,
discriminator,
defaultValue,
vars,
requiredVars,
optionalVars,
allVars,
allowableValues,
mandatory,
allMandatory,
imports,
hasVars,
emptyVars,
hasMoreModels,
hasEnums,
isEnum,
externalDocumentation,
vendorExtensions,
hasOnlyReadOnly,
hasChildren,
parentVars);
parent,
parentSchema,
interfaces,
allParents,
parentModel,
interfaceModels,
name,
classname,
title,
description,
classVarName,
modelJson,
dataType,
xmlPrefix,
xmlNamespace,
xmlName,
classFilename,
unescapedDescription,
discriminator,
defaultValue,
vars,
requiredVars,
optionalVars,
allVars,
allowableValues,
mandatory,
allMandatory,
imports,
hasVars,
emptyVars,
hasMoreModels,
hasEnums,
isEnum,
externalDocumentation,
vendorExtensions,
hasOnlyReadOnly,
hasChildren,
parentVars);
}
public String getParent() {

View File

@@ -19,7 +19,11 @@ package org.openapitools.codegen;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.CaseFormat;
import com.google.common.collect.ImmutableMap;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Mustache.Compiler;
import com.samskivert.mustache.Mustache.Lambda;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
@@ -48,6 +52,11 @@ import org.openapitools.codegen.meta.GeneratorMetadata;
import org.openapitools.codegen.meta.Stability;
import org.openapitools.codegen.serializer.SerializerUtils;
import org.openapitools.codegen.templating.MustacheEngineAdapter;
import org.openapitools.codegen.templating.mustache.CamelCaseLambda;
import org.openapitools.codegen.templating.mustache.IndentedLambda;
import org.openapitools.codegen.templating.mustache.LowercaseLambda;
import org.openapitools.codegen.templating.mustache.TitlecaseLambda;
import org.openapitools.codegen.templating.mustache.UppercaseLambda;
import org.openapitools.codegen.utils.ModelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -199,6 +208,47 @@ public class DefaultCodegen implements CodegenConfig {
}
}
/***
* Preset map builder with commonly used Mustache lambdas.
*
* To extend the map, override addMustacheLambdas(), call parent method
* first and then add additional lambdas to the returned builder.
*
* If common lambdas are not desired, override addMustacheLambdas() method
* and return empty builder.
*
* @return preinitialized map builder with common lambdas
*/
protected ImmutableMap.Builder<String, Lambda> addMustacheLambdas() {
return new ImmutableMap.Builder<String, Mustache.Lambda>()
.put("lowercase", new LowercaseLambda().generator(this))
.put("uppercase", new UppercaseLambda())
.put("titlecase", new TitlecaseLambda())
.put("camelcase", new CamelCaseLambda().generator(this))
.put("indented", new IndentedLambda())
.put("indented_8", new IndentedLambda(8, " "))
.put("indented_12", new IndentedLambda(12, " "))
.put("indented_16", new IndentedLambda(16, " "));
}
private void registerMustacheLambdas() {
ImmutableMap<String, Lambda> lambdas = addMustacheLambdas().build();
if (lambdas.size() == 0) {
return;
}
if (additionalProperties.containsKey("lambda")) {
LOGGER.warn("A property named 'lambda' already exists. Mustache lambdas renamed from 'lambda' to '_lambda'. " +
"You'll likely need to use a custom template, " +
"see https://github.com/OpenAPITools/openapi-generator/blob/master/docs/templating.md. ");
additionalProperties.put("_lambda", lambdas);
} else {
additionalProperties.put("lambda", lambdas);
}
}
// override with any special post-processing for all models
@SuppressWarnings({"static-method", "unchecked"})
public Map<String, Object> postProcessAllModels(Map<String, Object> objs) {
@@ -1060,6 +1110,9 @@ public class DefaultCodegen implements CodegenConfig {
// initialize special character mapping
initalizeSpecialCharacterMapping();
// Register common Mustache lambdas.
registerMustacheLambdas();
}
/**
@@ -1519,11 +1572,11 @@ public class DefaultCodegen implements CodegenConfig {
} else if (ModelUtils.isURISchema(schema)) {
return "URI";
} else if (ModelUtils.isStringSchema(schema)) {
if(typeMapping.containsKey(schema.getFormat())) {
if (typeMapping.containsKey(schema.getFormat())) {
// If the format matches a typeMapping (supplied with the --typeMappings flag)
// then treat the format as a primitive type.
// This allows the typeMapping flag to add a new custom type which can then
// be used in the format field.
// be used in the format field.
return schema.getFormat();
}
return "string";
@@ -1831,14 +1884,28 @@ public class DefaultCodegen implements CodegenConfig {
if (ModelUtils.isMapSchema(schema)) {
addAdditionPropertiesToCodeGenModel(m, schema);
m.isMapModel = true;
}
if (ModelUtils.isIntegerSchema(schema)) { // integer type
if (!ModelUtils.isLongSchema(schema)) { // long type is not integer
} else if (ModelUtils.isIntegerSchema(schema)) { // integer type
m.isNumeric = Boolean.TRUE;
if (ModelUtils.isLongSchema(schema)) { // int64/long format
m.isLong = Boolean.TRUE;
} else { // int32 format
m.isInteger = Boolean.TRUE;
}
}
if (ModelUtils.isStringSchema(schema)) {
} else if (ModelUtils.isStringSchema(schema)) {
m.isString = Boolean.TRUE;
} else if (ModelUtils.isNumberSchema(schema)) {
m.isNumeric = Boolean.TRUE;
if (ModelUtils.isFloatSchema(schema)) { // float
m.isFloat = Boolean.TRUE;
} else if (ModelUtils.isDoubleSchema(schema)) { // double
m.isDouble = Boolean.TRUE;
} else { // type is number and without format
m.isNumber = Boolean.TRUE;
}
}
if (Boolean.TRUE.equals(schema.getNullable())) {
m.isNullable = Boolean.TRUE;
}
// passing null to allProperties and allRequired as there's no parent
@@ -2006,7 +2073,7 @@ public class DefaultCodegen implements CodegenConfig {
String type = getSchemaType(p);
if (ModelUtils.isIntegerSchema(p)) { // integer type
property.isNumeric = Boolean.TRUE;
if (SchemaTypeUtil.INTEGER64_FORMAT.equals(p.getFormat())) { // int64/long format
if (ModelUtils.isLongSchema(p)) { // int64/long format
property.isLong = Boolean.TRUE;
} else { // int32 format
property.isInteger = Boolean.TRUE;
@@ -2584,7 +2651,7 @@ public class DefaultCodegen implements CodegenConfig {
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"))) {
getContentType(requestBody).toLowerCase(Locale.ROOT).startsWith("multipart/form-data"))) {
// process form parameters
formParams = fromRequestBodyToFormParameters(requestBody, imports);
for (CodegenParameter cp : formParams) {
@@ -2952,7 +3019,7 @@ public class DefaultCodegen implements CodegenConfig {
}
Schema s;
if(parameter.getSchema() != null) {
if (parameter.getSchema() != null) {
s = parameter.getSchema();
} else if (parameter.getContent() != null) {
Content content = parameter.getContent();
@@ -4876,7 +4943,7 @@ public class DefaultCodegen implements CodegenConfig {
}
protected void removeOption(String key) {
for(int i = 0; i < cliOptions.size(); i++) {
for (int i = 0; i < cliOptions.size(); i++) {
if (key.equals(cliOptions.get(i).getOpt())) {
cliOptions.remove(i);
break;

View File

@@ -223,6 +223,7 @@ public class CodegenConfigurator {
}
public CodegenConfigurator setImportMappings(Map<String, String> importMappings) {
this.importMappings = importMappings;
generatorSettingsBuilder.withImportMappings(importMappings);
return this;
}
@@ -234,6 +235,7 @@ public class CodegenConfigurator {
}
public CodegenConfigurator setInstantiationTypes(Map<String, String> instantiationTypes) {
this.instantiationTypes = instantiationTypes;
generatorSettingsBuilder.withInstantiationTypes(instantiationTypes);
return this;
}
@@ -295,6 +297,7 @@ public class CodegenConfigurator {
}
public CodegenConfigurator setReservedWordsMappings(Map<String, String> reservedWordMappings) {
this.reservedWordMappings = reservedWordMappings;
generatorSettingsBuilder.withReservedWordMappings(reservedWordMappings);
return this;
}
@@ -310,6 +313,7 @@ public class CodegenConfigurator {
}
public CodegenConfigurator setSystemProperties(Map<String, String> systemProperties) {
this.systemProperties = systemProperties;
workflowSettingsBuilder.withSystemProperties(systemProperties);
return this;
}
@@ -326,6 +330,7 @@ public class CodegenConfigurator {
}
public CodegenConfigurator setTypeMappings(Map<String, String> typeMappings) {
this.typeMappings = typeMappings;
generatorSettingsBuilder.withTypeMappings(typeMappings);
return this;
}
@@ -454,6 +459,12 @@ public class CodegenConfigurator {
config.reservedWordsMappings().putAll(generatorSettings.getReservedWordMappings());
config.additionalProperties().putAll(generatorSettings.getAdditionalProperties());
// any other additional properties?
String templateDir = workflowSettings.getTemplateDir();
if (templateDir != null) {
config.additionalProperties().put(CodegenConstants.TEMPLATE_DIR, workflowSettings.getTemplateDir());
}
ClientOptInput input = new ClientOptInput()
.config(config);

View File

@@ -17,8 +17,9 @@
package org.openapitools.codegen.languages;
import com.google.common.collect.ImmutableMap;
import com.samskivert.mustache.Mustache;
import com.google.common.collect.ImmutableMap.Builder;
import com.samskivert.mustache.Mustache.Lambda;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.Schema;
@@ -359,32 +360,12 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
// This either updates additionalProperties with the above fixes, or sets the default if the option was not specified.
additionalProperties.put(CodegenConstants.INTERFACE_PREFIX, interfacePrefix);
addMustacheLambdas(additionalProperties);
}
private void addMustacheLambdas(Map<String, Object> objs) {
Map<String, Mustache.Lambda> lambdas = new ImmutableMap.Builder<String, Mustache.Lambda>()
.put("lowercase", new LowercaseLambda().generator(this))
.put("uppercase", new UppercaseLambda())
.put("titlecase", new TitlecaseLambda())
.put("camelcase", new CamelCaseLambda().generator(this))
.put("camelcase_param", new CamelCaseLambda().generator(this).escapeAsParamName(true))
.put("indented", new IndentedLambda())
.put("indented_8", new IndentedLambda(8, " "))
.put("indented_12", new IndentedLambda(12, " "))
.put("indented_16", new IndentedLambda(16, " "))
.build();
if (objs.containsKey("lambda")) {
LOGGER.warn("A property named 'lambda' already exists. Mustache lambdas renamed from 'lambda' to '_lambda'. " +
"You'll likely need to use a custom template, " +
"see https://github.com/swagger-api/swagger-codegen#modifying-the-client-library-format. ");
objs.put("_lambda", lambdas);
} else {
objs.put("lambda", lambdas);
}
@Override
protected Builder<String, Lambda> addMustacheLambdas() {
return super.addMustacheLambdas()
.put("camelcase_param", new CamelCaseLambda().generator(this).escapeAsParamName(true));
}
@Override

View File

@@ -17,8 +17,8 @@
package org.openapitools.codegen.languages;
import com.google.common.collect.ImmutableMap;
import com.samskivert.mustache.Mustache;
import com.google.common.collect.ImmutableMap.Builder;
import com.samskivert.mustache.Mustache.Lambda;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.Schema;
@@ -35,7 +35,6 @@ import org.slf4j.LoggerFactory;
import java.io.File;
import java.net.URL;
import java.util.Arrays;
import java.util.Map;
abstract public class AbstractCppCodegen extends DefaultCodegen implements CodegenConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractCppCodegen.class);
@@ -260,22 +259,12 @@ abstract public class AbstractCppCodegen extends DefaultCodegen implements Codeg
LOGGER.info("Environment variable CPP_POST_PROCESS_FILE not defined so the C++ code may not be properly formatted. To define it, try 'export CPP_POST_PROCESS_FILE=\"/usr/local/bin/clang-format -i\"' (Linux/Mac)");
LOGGER.info("NOTE: To enable file post-processing, 'enablePostProcessFile' must be set to `true` (--enable-post-process-file for CLI).");
}
addMustacheLambdas(additionalProperties);
}
private void addMustacheLambdas(Map<String, Object> objs) {
Map<String, Mustache.Lambda> lambdas = new ImmutableMap.Builder<String, Mustache.Lambda>()
.put("multiline_comment_4", new IndentedLambda(4, " ", "///"))
.build();
if (objs.containsKey("lambda")) {
LOGGER.warn("A property named 'lambda' already exists. Mustache lambdas renamed from 'lambda' to '_lambda'.");
objs.put("_lambda", lambdas);
} else {
objs.put("lambda", lambdas);
}
@Override
protected Builder<String, Lambda> addMustacheLambdas() {
return super.addMustacheLambdas()
.put("multiline_comment_4", new IndentedLambda(4, " ", "///"));
}
@Override
@@ -304,17 +293,17 @@ abstract public class AbstractCppCodegen extends DefaultCodegen implements Codeg
}
}
}
@Override
public void preprocessOpenAPI(OpenAPI openAPI) {
URL url = URLPathUtils.getServerURL(openAPI);
String port = URLPathUtils.getPort(url, "");
String host = url.getHost();
if(!port.isEmpty()) {
this.additionalProperties.put("serverPort", port);
this.additionalProperties.put("serverPort", port);
}
if(!host.isEmpty()) {
this.additionalProperties.put("serverHost", host);
}
this.additionalProperties.put("serverHost", host);
}
}
}

View File

@@ -16,8 +16,9 @@
package org.openapitools.codegen.languages;
import com.google.common.collect.ImmutableMap;
import com.samskivert.mustache.Mustache;
import com.google.common.collect.ImmutableMap.Builder;
import com.samskivert.mustache.Mustache.Lambda;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.Schema;
@@ -67,7 +68,7 @@ public abstract class AbstractFSharpCodegen extends DefaultCodegen implements Co
protected Set<String> collectionTypes;
protected Set<String> mapTypes;
// true if nullable types will be supported (as option)
// true if nullable types will be supported (as option)
protected boolean supportNullable = Boolean.TRUE;
protected Set<String> nullableType = new HashSet<String>();
@@ -329,32 +330,12 @@ public abstract class AbstractFSharpCodegen extends DefaultCodegen implements Co
// This either updates additionalProperties with the above fixes, or sets the default if the option was not specified.
additionalProperties.put(CodegenConstants.INTERFACE_PREFIX, interfacePrefix);
addMustacheLambdas(additionalProperties);
}
private void addMustacheLambdas(Map<String, Object> objs) {
Map<String, Mustache.Lambda> lambdas = new ImmutableMap.Builder<String, Mustache.Lambda>()
.put("lowercase", new LowercaseLambda().generator(this))
.put("uppercase", new UppercaseLambda())
.put("titlecase", new TitlecaseLambda())
.put("camelcase", new CamelCaseLambda().generator(this))
.put("camelcase_param", new CamelCaseLambda().generator(this).escapeAsParamName(true))
.put("indented", new IndentedLambda())
.put("indented_8", new IndentedLambda(8, " "))
.put("indented_12", new IndentedLambda(12, " "))
.put("indented_16", new IndentedLambda(16, " "))
.build();
if (objs.containsKey("lambda")) {
LOGGER.warn("A property named 'lambda' already exists. Mustache lambdas renamed from 'lambda' to '_lambda'. " +
"You'll likely need to use a custom template, " +
"see https://github.com/swagger-api/swagger-codegen#modifying-the-client-library-format. ");
objs.put("_lambda", lambdas);
} else {
objs.put("lambda", lambdas);
}
@Override
protected Builder<String, Lambda> addMustacheLambdas() {
return super.addMustacheLambdas()
.put("camelcase_param", new CamelCaseLambda().generator(this).escapeAsParamName(true));
}
@Override

View File

@@ -52,7 +52,6 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
public static final String SUPPORT_JAVA6 = "supportJava6";
public static final String DISABLE_HTML_ESCAPING = "disableHtmlEscaping";
public static final String BOOLEAN_GETTER_PREFIX = "booleanGetterPrefix";
public static final String USE_NULL_FOR_UNKNOWN_ENUM_VALUE = "useNullForUnknownEnumValue";
protected String dateLibrary = "threetenbp";
protected boolean supportAsync = false;
@@ -86,7 +85,6 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
protected boolean supportJava6 = false;
protected boolean disableHtmlEscaping = false;
protected String booleanGetterPrefix = "get";
protected boolean useNullForUnknownEnumValue = false;
protected String parentGroupId = "";
protected String parentArtifactId = "";
protected String parentVersion = "";
@@ -220,10 +218,6 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
this.setBooleanGetterPrefix(additionalProperties.get(BOOLEAN_GETTER_PREFIX).toString());
}
additionalProperties.put(BOOLEAN_GETTER_PREFIX, booleanGetterPrefix);
if (additionalProperties.containsKey(USE_NULL_FOR_UNKNOWN_ENUM_VALUE)) {
this.setUseNullForUnknownEnumValue(Boolean.valueOf(additionalProperties.get(USE_NULL_FOR_UNKNOWN_ENUM_VALUE).toString()));
}
additionalProperties.put(USE_NULL_FOR_UNKNOWN_ENUM_VALUE, useNullForUnknownEnumValue);
if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) {
this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE));
@@ -417,6 +411,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
// imports for pojos
importMapping.put("ApiModelProperty", "io.swagger.annotations.ApiModelProperty");
importMapping.put("ApiModel", "io.swagger.annotations.ApiModel");
importMapping.put("BigDecimal", "java.math.BigDecimal");
importMapping.put("JsonProperty", "com.fasterxml.jackson.annotation.JsonProperty");
importMapping.put("JsonSubTypes", "com.fasterxml.jackson.annotation.JsonSubTypes");
importMapping.put("JsonTypeInfo", "com.fasterxml.jackson.annotation.JsonTypeInfo");
@@ -585,6 +580,11 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
name = "_u";
}
// numbers are not allowed at the beginning
if (name.matches("^\\d.*")) {
name = "_" + name;
}
// if it's all uppper case, do nothing
if (name.matches("^[A-Z0-9_]*$")) {
return name;
@@ -944,6 +944,9 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel);
codegenModel = AbstractJavaCodegen.reconcileInlineEnums(codegenModel, parentCodegenModel);
}
if ("BigDecimal".equals(codegenModel.dataType)) {
codegenModel.imports.add("BigDecimal");
}
return codegenModel;
}
@@ -1107,7 +1110,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
// number
if ("Integer".equals(datatype) || "Long".equals(datatype) ||
"Float".equals(datatype) || "Double".equals(datatype)) {
"Float".equals(datatype) || "Double".equals(datatype) || "BigDecimal".equals(datatype)) {
String varName = "NUMBER_" + value;
varName = varName.replaceAll("-", "MINUS_");
varName = varName.replaceAll("\\+", "PLUS_");
@@ -1134,6 +1137,9 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
} else if ("Float".equals(datatype)) {
// add f to number, e.g. 3.14 => 3.14f
return value + "f";
} else if ("BigDecimal".equals(datatype)) {
// use BigDecimal String constructor
return "new BigDecimal(\"" + value + "\")";
} else {
return "\"" + escapeText(value) + "\"";
}
@@ -1393,10 +1399,6 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
this.booleanGetterPrefix = booleanGetterPrefix;
}
public void setUseNullForUnknownEnumValue(boolean useNullForUnknownEnumValue) {
this.useNullForUnknownEnumValue = useNullForUnknownEnumValue;
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection

View File

@@ -5,6 +5,7 @@ import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.parser.util.SchemaTypeUtil;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.CodegenConstants;
import org.openapitools.codegen.CodegenModel;
import org.openapitools.codegen.CodegenOperation;
import org.openapitools.codegen.CodegenParameter;
@@ -34,6 +35,7 @@ public class CppQt5AbstractCodegen extends AbstractCppCodegen implements Codegen
}
// CLI options
addOption(CPP_NAMESPACE, CPP_NAMESPACE_DESC, this.cppNamespace);
addOption(CodegenConstants.MODEL_NAME_PREFIX, CodegenConstants.MODEL_NAME_PREFIX_DESC, this.modelNamePrefix);
/*
* Additional Properties. These values can be passed to the templates and
@@ -45,9 +47,7 @@ public class CppQt5AbstractCodegen extends AbstractCppCodegen implements Codegen
// Write defaults namespace in properties so that it can be accessible in templates.
// At this point command line has not been parsed so if value is given
// in command line it will supersede this content
additionalProperties.put("cppNamespace", cppNamespace);
// CLI options
addOption(CPP_NAMESPACE, CPP_NAMESPACE_DESC, this.cppNamespace);
additionalProperties.put("cppNamespace", cppNamespace);
/*
* Language Specific Primitives. These types will not trigger imports by
* the client generator
@@ -112,7 +112,9 @@ public class CppQt5AbstractCodegen extends AbstractCppCodegen implements Codegen
}
additionalProperties.put("cppNamespaceDeclarations", cppNamespace.split("\\::"));
if (additionalProperties.containsKey("modelNamePrefix")) {
modelNamePrefix = (String) additionalProperties.get("modelNamePrefix");
typeMapping.put("object", modelNamePrefix + "Object");
additionalProperties().put("prefix", modelNamePrefix);
}

View File

@@ -16,15 +16,12 @@
package org.openapitools.codegen.languages;
import org.apache.commons.io.FilenameUtils;
import org.openapitools.codegen.*;
import org.openapitools.codegen.utils.ModelUtils;
import io.swagger.v3.oas.models.media.*;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.*;
import org.openapitools.codegen.utils.ModelUtils;
import org.openapitools.codegen.utils.ProcessUtils;
import java.io.File;
@@ -37,6 +34,8 @@ public class DartJaguarClientCodegen extends DartClientCodegen {
private static final String SERIALIZATION_FORMAT = "serialization";
private static final String IS_FORMAT_JSON = "jsonFormat";
private static final String IS_FORMAT_PROTO = "protoFormat";
private static final String CLIENT_NAME = "clientName";
private static Set<String> modelToIgnore = new HashSet<>();
private HashMap<String, String> protoTypeMapping = new HashMap<>();
@@ -141,6 +140,7 @@ public class DartJaguarClientCodegen extends DartClientCodegen {
//not set, use to be passed to template
additionalProperties.put(PUB_NAME, pubName);
}
additionalProperties.put(CLIENT_NAME, org.openapitools.codegen.utils.StringUtils.camelize(pubName));
if (additionalProperties.containsKey(PUB_VERSION)) {
this.setPubVersion((String) additionalProperties.get(PUB_VERSION));

View File

@@ -16,15 +16,23 @@
package org.openapitools.codegen.languages;
import org.openapitools.codegen.CodegenModel;
import org.openapitools.codegen.CodegenProperty;
import org.openapitools.codegen.SupportingFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
public class GoClientExperimentalCodegen extends GoClientCodegen {
private static final Logger LOGGER = LoggerFactory.getLogger(GoClientExperimentalCodegen.class);
public GoClientExperimentalCodegen() {
super();
outputFolder = "generated-code/go-experimental";
embeddedTemplateDir = templateDir = "go-experimental";
}
/**
@@ -49,4 +57,35 @@ public class GoClientExperimentalCodegen extends GoClientCodegen {
return "Generates a Go client library (experimental and may subject to breaking changes without further notice).";
}
@Override
public void processOpts() {
super.processOpts();
supportingFiles.add(new SupportingFile("utils.mustache", "", "utils.go"));
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
objs = super.postProcessModels(objs);
List<Map<String, String>> imports = (List<Map<String, String>>) objs.get("imports");
boolean addedErrorsImport = false;
List<Map<String, Object>> models = (List<Map<String, Object>>) objs.get("models");
for (Map<String, Object> m : models) {
Object v = m.get("model");
if (v instanceof CodegenModel) {
CodegenModel model = (CodegenModel) v;
if (!model.isEnum) {
imports.add(createMapping("import", "encoding/json"));
}
for (CodegenProperty param : model.vars) {
if (!addedErrorsImport && param.required) {
imports.add(createMapping("import", "errors"));
addedErrorsImport = true;
}
}
}
}
return objs;
}
}

View File

@@ -67,6 +67,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
public static final String GOOGLE_API_CLIENT = "google-api-client";
public static final String JERSEY1 = "jersey1";
public static final String JERSEY2 = "jersey2";
public static final String NATIVE = "native";
public static final String OKHTTP_GSON = "okhttp-gson";
public static final String RESTEASY = "resteasy";
public static final String RESTTEMPLATE = "resttemplate";
@@ -139,6 +140,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
supportedLibraries.put(VERTX, "HTTP client: VertX client 3.x. JSON processing: Jackson 2.8.x");
supportedLibraries.put(GOOGLE_API_CLIENT, "HTTP client: Google API client 1.x. JSON processing: Jackson 2.8.x");
supportedLibraries.put(REST_ASSURED, "HTTP client: rest-assured : 4.x. JSON processing: Gson 2.x. Only for Java8");
supportedLibraries.put(NATIVE, "HTTP client: Java native HttpClient. JSON processing: Jackson 2.9.x. Only for Java11+");
CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use");
libraryOption.setEnum(supportedLibraries);
@@ -166,7 +168,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
@Override
public void processOpts() {
if (WEBCLIENT.equals(getLibrary()) && "threetenbp".equals(dateLibrary)) {
if ((WEBCLIENT.equals(getLibrary()) && "threetenbp".equals(dateLibrary)) || NATIVE.equals(getLibrary())) {
dateLibrary = "java8";
}
@@ -254,12 +256,12 @@ public class JavaClientCodegen extends AbstractJavaCodegen
writeOptional(outputFolder, new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml"));
supportingFiles.add(new SupportingFile("travis.mustache", "", ".travis.yml"));
supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java"));
if (!(RESTTEMPLATE.equals(getLibrary()) || REST_ASSURED.equals(getLibrary()))) {
if (!(RESTTEMPLATE.equals(getLibrary()) || REST_ASSURED.equals(getLibrary()) || NATIVE.equals(getLibrary()))) {
supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java"));
}
// google-api-client doesn't use the OpenAPI auth, because it uses Google Credential directly (HttpRequestInitializer)
if (!(GOOGLE_API_CLIENT.equals(getLibrary()) || REST_ASSURED.equals(getLibrary()))) {
if (!(GOOGLE_API_CLIENT.equals(getLibrary()) || REST_ASSURED.equals(getLibrary()) || NATIVE.equals(getLibrary()))) {
supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java"));
supportingFiles.add(new SupportingFile("auth/HttpBearerAuth.mustache", authFolder, "HttpBearerAuth.java"));
supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java"));
@@ -293,7 +295,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
supportingFiles.add(new SupportingFile("Pair.mustache", invokerFolder, "Pair.java"));
}
if (!(FEIGN.equals(getLibrary()) || RESTTEMPLATE.equals(getLibrary()) || usesAnyRetrofitLibrary() || GOOGLE_API_CLIENT.equals(getLibrary()) || REST_ASSURED.equals(getLibrary()))) {
if (!(FEIGN.equals(getLibrary()) || RESTTEMPLATE.equals(getLibrary()) || usesAnyRetrofitLibrary() || GOOGLE_API_CLIENT.equals(getLibrary()) || REST_ASSURED.equals(getLibrary()) || NATIVE.equals(getLibrary()))) {
supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java"));
}
@@ -325,6 +327,10 @@ public class JavaClientCodegen extends AbstractJavaCodegen
supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java"));
supportingFiles.add(new SupportingFile("ApiResponse.mustache", invokerFolder, "ApiResponse.java"));
additionalProperties.put("jackson", "true");
} else if (NATIVE.equals(getLibrary())) {
setJava8Mode(true);
additionalProperties.put("java8", "true");
additionalProperties.put("jackson", "true");
} else if (RESTEASY.equals(getLibrary())) {
supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java"));
additionalProperties.put("jackson", "true");
@@ -412,7 +418,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
additionalProperties.remove("gson");
}
if (additionalProperties.containsKey("jackson")) {
if (additionalProperties.containsKey("jackson") && !NATIVE.equals(getLibrary())) {
supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", invokerFolder, "RFC3339DateFormat.java"));
if ("threetenbp".equals(dateLibrary) && !usePlayWS) {
supportingFiles.add(new SupportingFile("CustomInstantDeserializer.mustache", invokerFolder, "CustomInstantDeserializer.java"));
@@ -500,7 +506,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
}
// google-api-client doesn't use the OpenAPI auth, because it uses Google Credential directly (HttpRequestInitializer)
if ((!(GOOGLE_API_CLIENT.equals(getLibrary()) || REST_ASSURED.equals(getLibrary()) || usePlayWS)) && ProcessUtils.hasOAuthMethods(objs)) {
if ((!(GOOGLE_API_CLIENT.equals(getLibrary()) || REST_ASSURED.equals(getLibrary()) || usePlayWS || NATIVE.equals(getLibrary()))) && ProcessUtils.hasOAuthMethods(objs)) {
supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java"));
supportingFiles.add(new SupportingFile("auth/OAuthFlow.mustache", authFolder, "OAuthFlow.java"));
}

View File

@@ -37,12 +37,14 @@ public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen {
public static final String GENERATE_POM = "generatePom";
public static final String USE_SWAGGER_ANNOTATIONS = "useSwaggerAnnotations";
public static final String JACKSON = "jackson";
public static final String OPEN_API_SPEC_FILE_LOCATION = "openApiSpecFileLocation";
private boolean interfaceOnly = false;
private boolean returnResponse = false;
private boolean generatePom = true;
private boolean useSwaggerAnnotations = true;
private boolean useJackson = false;
private String openApiSpecFileLocation = "src/main/openapi/openapi.yaml";
private String primaryResourceName;
@@ -91,6 +93,7 @@ public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen {
cliOptions.add(CliOption.newBoolean(INTERFACE_ONLY, "Whether to generate only API interface stubs without the server files.").defaultValue(String.valueOf(interfaceOnly)));
cliOptions.add(CliOption.newBoolean(RETURN_RESPONSE, "Whether generate API interface should return javax.ws.rs.core.Response instead of a deserialized entity. Only useful if interfaceOnly is true.").defaultValue(String.valueOf(returnResponse)));
cliOptions.add(CliOption.newBoolean(USE_SWAGGER_ANNOTATIONS, "Whether to generate Swagger annotations.", useSwaggerAnnotations));
cliOptions.add(CliOption.newString(OPEN_API_SPEC_FILE_LOCATION, "Location where the file containing the spec will be generated in the output folder. No file generated when set to null or empty string."));
}
@Override
@@ -114,6 +117,10 @@ public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen {
useSwaggerAnnotations = Boolean.valueOf(additionalProperties.get(USE_SWAGGER_ANNOTATIONS).toString());
}
writePropertyBack(USE_SWAGGER_ANNOTATIONS, useSwaggerAnnotations);
if (additionalProperties.containsKey(OPEN_API_SPEC_FILE_LOCATION)) {
openApiSpecFileLocation = additionalProperties.get(OPEN_API_SPEC_FILE_LOCATION).toString();
}
additionalProperties.put(OPEN_API_SPEC_FILE_LOCATION, openApiSpecFileLocation);
useJackson = convertPropertyToBoolean(JACKSON);
@@ -134,18 +141,38 @@ public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen {
(sourceFolder + '/' + invokerPackage).replace(".", "/"), "RestApplication.java"));
}
supportingFiles.add(new SupportingFile("openapi.mustache",
"src/main/openapi",
"openapi.yaml")
);
if(StringUtils.isNotEmpty(openApiSpecFileLocation)) {
int index = openApiSpecFileLocation.lastIndexOf('/');
String fileFolder;
String fileName;
if(index >= 0) {
fileFolder = openApiSpecFileLocation.substring(0, index);
fileName = openApiSpecFileLocation.substring(index + 1);
} else {
fileFolder = "";
fileName = openApiSpecFileLocation;
}
supportingFiles.add(new SupportingFile("openapi.mustache", fileFolder, fileName));
}
}
@Override
public String getName() {
return "jaxrs-spec";
}
public String getOpenApiSpecFileLocation() {
return openApiSpecFileLocation;
}
/**
* Location where the file containing the spec will be generated in the output folder.
* @param location location inside the output folder. No file generated when set to null or empty string.
*/
public void setOpenApiSpecFileLocation(String location) {
this.openApiSpecFileLocation = location;
}
@Override
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
String basePath = resourcePath;

View File

@@ -18,13 +18,11 @@
package org.openapitools.codegen.languages;
import com.google.common.collect.ImmutableMap;
import com.samskivert.mustache.Mustache;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.CliOption;
import org.openapitools.codegen.CodegenConstants;
import org.openapitools.codegen.CodegenType;
import org.openapitools.codegen.SupportingFile;
import org.openapitools.codegen.templating.mustache.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -211,31 +209,6 @@ public class KotlinServerCodegen extends AbstractKotlinCodegen {
final String infrastructureFolder = (sourceFolder + File.separator + packageName + File.separator + "infrastructure").replace(".", File.separator);
supportingFiles.add(new SupportingFile("ApiKeyAuth.kt.mustache", infrastructureFolder, "ApiKeyAuth.kt"));
addMustacheLambdas(additionalProperties);
}
private void addMustacheLambdas(Map<String, Object> objs) {
Map<String, Mustache.Lambda> lambdas = new ImmutableMap.Builder<String, Mustache.Lambda>()
.put("lowercase", new LowercaseLambda().generator(this))
.put("uppercase", new UppercaseLambda())
.put("titlecase", new TitlecaseLambda())
.put("camelcase", new CamelCaseLambda().generator(this))
.put("indented", new IndentedLambda())
.put("indented_8", new IndentedLambda(8, " "))
.put("indented_12", new IndentedLambda(12, " "))
.put("indented_16", new IndentedLambda(16, " "))
.build();
if (objs.containsKey("lambda")) {
LOGGER.warn("A property named 'lambda' already exists. Mustache lambdas renamed from 'lambda' to '_lambda'. " +
"You'll likely need to use a custom template, " +
"see https://github.com/OpenAPITools/openapi-generator/blob/master/docs/templating.md. ");
objs.put("_lambda", lambdas);
} else {
objs.put("lambda", lambdas);
}
}
public static class Constants {

View File

@@ -16,9 +16,11 @@
package org.openapitools.codegen.languages;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;
import com.samskivert.mustache.Mustache.Lambda;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.Schema;
import org.openapitools.codegen.*;
@@ -51,7 +53,6 @@ public class KotlinSpringServerCodegen extends AbstractKotlinCodegen
));
public static final String TITLE = "title";
public static final String LAMBDA = "lambda";
public static final String SERVER_PORT = "serverPort";
public static final String BASE_PACKAGE = "basePackage";
public static final String SPRING_BOOT = "spring-boot";
@@ -370,22 +371,14 @@ public class KotlinSpringServerCodegen extends AbstractKotlinCodegen
sanitizeDirectory(sourceFolder + File.separator + basePackage), "Application.kt"));
}
addMustacheLambdas(additionalProperties);
// spring uses the jackson lib, and we disallow configuration.
additionalProperties.put("jackson", "true");
}
private void addMustacheLambdas(final Map<String, Object> objs) {
Map<String, Mustache.Lambda> lambdas =
new ImmutableMap.Builder<String, Mustache.Lambda>()
.put("escapeDoubleQuote", new EscapeLambda("\"", "\\\""))
.build();
if (objs.containsKey(LAMBDA)) {
LOGGER.warn("The lambda property is a reserved word, and will be overwritten!");
}
objs.put(LAMBDA, lambdas);
@Override
protected Builder<String, Lambda> addMustacheLambdas() {
return super.addMustacheLambdas()
.put("escapeDoubleQuote", new EscapeLambda("\"", "\\\""));
}
@Override

View File

@@ -18,9 +18,17 @@
package org.openapitools.codegen.languages;
import org.openapitools.codegen.*;
import org.openapitools.codegen.templating.mustache.OnChangeLambda;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableMap.Builder;
import com.samskivert.mustache.Mustache.Lambda;
import io.swagger.v3.oas.models.Operation;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class OpenAPIYamlGenerator extends DefaultCodegen implements CodegenConfig {
@@ -63,6 +71,24 @@ public class OpenAPIYamlGenerator extends DefaultCodegen implements CodegenConfi
supportingFiles.add(new SupportingFile("openapi.mustache", outputFile));
}
@Override
protected Builder<String, Lambda> addMustacheLambdas() {
return super.addMustacheLambdas()
.put("onchange", new OnChangeLambda());
}
/**
* Group operations by resourcePath so that operations with same path and
* different http method can be rendered one after the other.
*/
@Override
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation
co, Map<String, List<CodegenOperation>> operations) {
List<CodegenOperation> opList = operations.computeIfAbsent(resourcePath,
k -> new ArrayList<>());
opList.add(co);
}
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
generateYAMLSpecFile(objs);

View File

@@ -124,9 +124,9 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {
// I tried to map as "std::io::File", but Reqwest multipart file requires a "AsRef<Path>" param.
// Getting a file from a Path is simple, but the opposite is difficult. So I map as "std::path::Path".
typeMapping.put("file", "std::path::PathBuf");
typeMapping.put("binary", "::models::File");
typeMapping.put("binary", "crate::models::File");
typeMapping.put("ByteArray", "String");
typeMapping.put("object", "Value");
typeMapping.put("object", "serde_json::Value");
// no need for rust
//importMapping = new HashMap<String, String>();
@@ -352,8 +352,8 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {
}
// return fully-qualified model name
// ::models::{{classnameFile}}::{{classname}}
return "::models::" + toModelName(schemaType);
// crate::models::{{classnameFile}}::{{classname}}
return "crate::models::" + toModelName(schemaType);
}
@Override

View File

@@ -16,8 +16,9 @@
package org.openapitools.codegen.languages;
import com.google.common.collect.ImmutableMap;
import com.samskivert.mustache.Mustache;
import com.google.common.collect.ImmutableMap.Builder;
import com.samskivert.mustache.Mustache.Lambda;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.Schema;
import org.openapitools.codegen.*;
@@ -84,7 +85,7 @@ public class ScalaPlayFrameworkServerCodegen extends AbstractScalaCodegen implem
importMapping.put("TemporaryFile", "play.api.libs.Files.TemporaryFile");
cliOptions.add(new CliOption(ROUTES_FILE_NAME, "Name of the routes file to generate.").defaultValue(routesFileName));
cliOptions.add(new CliOption(ROUTES_FILE_NAME, "Base package in which supporting classes are generated.").defaultValue(basePackage));
cliOptions.add(new CliOption(BASE_PACKAGE, "Base package in which supporting classes are generated.").defaultValue(basePackage));
addCliOptionWithDefault(SKIP_STUBS, "If set, skips generation of stub classes.", skipStubs);
addCliOptionWithDefault(SUPPORT_ASYNC, "If set, wraps API return types with Futures and generates async actions.", supportAsync);
@@ -192,15 +193,12 @@ public class ScalaPlayFrameworkServerCodegen extends AbstractScalaCodegen implem
supportingFiles.add(new SupportingFile("public/openapi.json.mustache", "public", "openapi.json"));
supportingFiles.add(new SupportingFile("app/apiDocController.scala.mustache", String.format(Locale.ROOT, "app/%s", apiPackage.replace(".", File.separator)), "ApiDocController.scala"));
}
addMustacheLambdas(additionalProperties);
}
private void addMustacheLambdas(Map<String, Object> objs) {
Map<String, Mustache.Lambda> lambdas = new ImmutableMap.Builder<String, Mustache.Lambda>()
.put("indented_4", new IndentedLambda(4, " "))
.put("indented_8", new IndentedLambda(8, " "))
.build();
objs.put("lambda", lambdas);
@Override
protected Builder<String, Lambda> addMustacheLambdas() {
return super.addMustacheLambdas()
.put("indented_4", new IndentedLambda(4, " "));
}
@SuppressWarnings("unchecked")

View File

@@ -421,6 +421,9 @@ public class Swift4Codegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("README.mustache",
"",
"README.md"));
supportingFiles.add(new SupportingFile("XcodeGen.mustache",
"",
"project.yml"));
}

View File

@@ -24,19 +24,21 @@ import org.openapitools.codegen.*;
import org.openapitools.codegen.utils.ModelUtils;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.TreeSet;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodegen {
public static final String NPM_REPOSITORY = "npmRepository";
public static final String WITH_INTERFACES = "withInterfaces";
public static final String USE_SINGLE_REQUEST_PARAMETER = "useSingleRequestParameter";
protected String npmRepository = null;
private boolean useSingleRequestParameter = true;
protected boolean addedApiIndex = false;
protected boolean addedModelIndex = false;
public TypeScriptFetchClientCodegen() {
super();
@@ -56,6 +58,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()));
}
@Override
@@ -83,10 +86,14 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege
additionalProperties.put("modelPropertyNaming", getModelPropertyNaming());
supportingFiles.add(new SupportingFile("index.mustache", "", "index.ts"));
supportingFiles.add(new SupportingFile("runtime.mustache", "", "runtime.ts"));
supportingFiles.add(new SupportingFile("apis.index.mustache", apiPackage().replace('.', File.separatorChar), "index.ts"));
supportingFiles.add(new SupportingFile("models.index.mustache", modelPackage().replace('.', File.separatorChar), "index.ts"));
supportingFiles.add(new SupportingFile("tsconfig.mustache", "", "tsconfig.json"));
supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore"));
if (additionalProperties.containsKey(USE_SINGLE_REQUEST_PARAMETER)) {
this.setUseSingleRequestParameter(convertPropertyToBoolean(USE_SINGLE_REQUEST_PARAMETER));
}
writePropertyBack(USE_SINGLE_REQUEST_PARAMETER, getUseSingleRequestParameter());
if (additionalProperties.containsKey(NPM_NAME)) {
addNpmPackageGeneration();
}
@@ -121,8 +128,9 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
// process enum in models
List<Object> models = (List<Object>) postProcessModelsEnum(objs).get("models");
// process enum in models
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
@@ -184,8 +192,21 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege
@Override
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> operations, List<Object> allModels) {
// Add supporting file only if we plan to generate files in /apis
if (operations.size() > 0 && !addedApiIndex) {
addedApiIndex = true;
supportingFiles.add(new SupportingFile("apis.index.mustache", apiPackage().replace('.', File.separatorChar), "index.ts"));
}
// Add supporting file only if we plan to generate files in /models
if (allModels.size() > 0 && !addedModelIndex) {
addedModelIndex = true;
supportingFiles.add(new SupportingFile("models.index.mustache", modelPackage().replace('.', File.separatorChar), "index.ts"));
}
this.addOperationModelImportInfomation(operations);
this.updateOperationParameterEnumInformation(operations);
this.addOperationObjectResponseInformation(operations);
return operations;
}
@@ -218,6 +239,20 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege
operations.put("hasEnums", hasEnum);
}
private void addOperationObjectResponseInformation(Map<String, Object> operations) {
// This method will modify the infomation on the operations' return type.
// The api template uses this infomation to know when to return a text
// response for a given simple response operation.
Map<String, Object> _operations = (Map<String, Object>) operations.get("operations");
List<CodegenOperation> operationList = (List<CodegenOperation>) _operations.get("operation");
for (CodegenOperation op : operationList) {
if(op.returnType == "object") {
op.isMapContainer = true;
op.returnSimpleType = false;
}
}
}
private void addExtraReservedWords() {
this.reservedWords.add("BASE_PATH");
this.reservedWords.add("BaseAPI");
@@ -245,4 +280,12 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege
this.reservedWords.add("BlobApiResponse");
this.reservedWords.add("TextApiResponse");
}
private boolean getUseSingleRequestParameter() {
return useSingleRequestParameter;
}
private void setUseSingleRequestParameter(boolean useSingleRequestParameter) {
this.useSingleRequestParameter = useSingleRequestParameter;
}
}

View File

@@ -28,6 +28,7 @@ import java.text.SimpleDateFormat;
import java.util.TreeSet;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Map;
@@ -41,10 +42,6 @@ public class TypeScriptRxjsClientCodegen extends AbstractTypeScriptClientCodegen
public TypeScriptRxjsClientCodegen() {
super();
// clear import mapping (from default generator) as TS does not use it
// at the moment
importMapping.clear();
outputFolder = "generated-code/typescript-rxjs";
embeddedTemplateDir = templateDir = "typescript-rxjs";
@@ -54,6 +51,9 @@ public class TypeScriptRxjsClientCodegen extends AbstractTypeScriptClientCodegen
this.modelTemplateFiles.put("models.mustache", ".ts");
this.addExtraReservedWords();
languageSpecificPrimitives.add("Blob");
typeMapping.put("file", "Blob");
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()));
}
@@ -92,6 +92,11 @@ public class TypeScriptRxjsClientCodegen extends AbstractTypeScriptClientCodegen
}
}
@Override
public boolean isDataTypeFile(final String dataType) {
return dataType != null && dataType.equals("Blob");
}
@Override
public String getTypeDeclaration(Schema p) {
Schema inner;
@@ -161,27 +166,64 @@ public class TypeScriptRxjsClientCodegen extends AbstractTypeScriptClientCodegen
return result;
}
private void addNpmPackageGeneration() {
@Override
public void postProcessParameter(CodegenParameter parameter) {
super.postProcessParameter(parameter);
parameter.dataType = applyLocalTypeMapping(parameter.dataType);
}
@Override
public String getSchemaType(Schema p) {
String openAPIType = super.getSchemaType(p);
if (isLanguagePrimitive(openAPIType)) {
return openAPIType;
}
applyLocalTypeMapping(openAPIType);
return openAPIType;
}
private String applyLocalTypeMapping(String type) {
if (typeMapping.containsKey(type)) {
type = typeMapping.get(type);
}
return type;
}
private boolean isLanguagePrimitive(String type) {
return languageSpecificPrimitives.contains(type);
}
private void addNpmPackageGeneration() {
if (additionalProperties.containsKey(NPM_REPOSITORY)) {
this.setNpmRepository(additionalProperties.get(NPM_REPOSITORY).toString());
}
//Files for building our lib
// Files for building our lib
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("package.mustache", "", "package.json"));
}
@Override
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> operations, List<Object> allModels) {
this.addOperationModelImportInfomation(operations);
// Convert List of CodegenOperation to List of ExtendedCodegenOperation
Map<String, Object> _operations = (Map<String, Object>) operations.get("operations");
List<CodegenOperation> os = (List<CodegenOperation>) _operations.get("operation");
List<ExtendedCodegenOperation> newOs = new ArrayList<ExtendedCodegenOperation>();
for (CodegenOperation o : os) {
newOs.add(new ExtendedCodegenOperation(o));
}
_operations.put("operation", newOs);
this.addOperationModelImportInformation(operations);
this.updateOperationParameterEnumInformation(operations);
this.addConditionalImportInformation(operations);
return operations;
}
private void addOperationModelImportInfomation(Map<String, Object> operations) {
// This method will add extra infomation to the operations.imports array.
// The api template uses this infomation to import all the required
private void addOperationModelImportInformation(Map<String, Object> operations) {
// This method will add extra information to the operations.imports array.
// The api template uses this information to import all the required
// models for a given operation.
List<Map<String, Object>> imports = (List<Map<String, Object>>) operations.get("imports");
for (Map<String, Object> im : imports) {
@@ -190,22 +232,79 @@ public class TypeScriptRxjsClientCodegen extends AbstractTypeScriptClientCodegen
}
private void updateOperationParameterEnumInformation(Map<String, Object> operations) {
// This method will add extra infomation as to whether or not we have enums and
// This method will add extra information as to whether or not we have enums and
// update their names with the operation.id prefixed.
Map<String, Object> _operations = (Map<String, Object>) operations.get("operations");
List<CodegenOperation> operationList = (List<CodegenOperation>) _operations.get("operation");
boolean hasEnum = false;
for (CodegenOperation op : operationList) {
List<ExtendedCodegenOperation> operationList = (List<ExtendedCodegenOperation>) _operations.get("operation");
boolean hasEnums = false;
for (ExtendedCodegenOperation op : operationList) {
for (CodegenParameter param : op.allParams) {
if (Boolean.TRUE.equals(param.isEnum)) {
hasEnum = true;
hasEnums = true;
param.datatypeWithEnum = param.datatypeWithEnum
.replace(param.enumName, op.operationIdCamelCase + param.enumName);
}
}
}
operations.put("hasEnums", hasEnum);
operations.put("hasEnums", hasEnums);
}
private void addConditionalImportInformation(Map<String, Object> operations) {
// This method will determine if there are required parameters and if there are list containers
Map<String, Object> _operations = (Map<String, Object>) operations.get("operations");
List<ExtendedCodegenOperation> operationList = (List<ExtendedCodegenOperation>) _operations.get("operation");
boolean hasRequiredParameters = false;
boolean hasListContainers = false;
boolean hasHttpHeaders = false;
boolean hasQueryParams = false;
boolean hasPathParams = false;
for (ExtendedCodegenOperation op : operationList) {
if (op.getHasRequiredParams()) {
hasRequiredParameters = true;
}
for (CodegenParameter param : op.headerParams) {
if (param.isListContainer) {
hasListContainers = true;
break;
}
}
for (CodegenParameter param : op.queryParams) {
if (param.isListContainer && !param.isCollectionFormatMulti) {
hasListContainers = true;
break;
}
}
for (CodegenParameter param : op.formParams) {
if (param.isListContainer && !param.isCollectionFormatMulti) {
hasListContainers = true;
break;
}
}
if (op.hasHttpHeaders) {
hasHttpHeaders = true;
}
if (op.getHasQueryParams()) {
hasQueryParams = true;
}
if (op.getHasPathParams()) {
hasPathParams = true;
}
if(hasRequiredParameters && hasListContainers && hasHttpHeaders && hasQueryParams && hasPathParams){
break;
}
}
operations.put("hasRequiredParameters", hasRequiredParameters);
operations.put("hasListContainers", hasListContainers);
operations.put("hasHttpHeaders", hasHttpHeaders);
operations.put("hasQueryParams", hasQueryParams);
operations.put("hasPathParams", hasPathParams);
}
private void addExtraReservedWords() {
@@ -222,10 +321,88 @@ public class TypeScriptRxjsClientCodegen extends AbstractTypeScriptClientCodegen
this.reservedWords.add("ModelPropertyNaming");
this.reservedWords.add("RequestArgs");
this.reservedWords.add("RequestOpts");
this.reservedWords.add("ResponseArgs");
this.reservedWords.add("exists");
this.reservedWords.add("RequestContext");
this.reservedWords.add("ResponseContext");
this.reservedWords.add("Middleware");
this.reservedWords.add("AjaxRequest");
this.reservedWords.add("AjaxResponse");
}
class ExtendedCodegenOperation extends CodegenOperation {
public boolean hasHttpHeaders;
public ExtendedCodegenOperation(CodegenOperation o) {
super();
// Copy all fields of CodegenOperation
this.responseHeaders.addAll(o.responseHeaders);
this.hasAuthMethods = o.hasAuthMethods;
this.hasConsumes = o.hasConsumes;
this.hasProduces = o.hasProduces;
this.hasParams = o.hasParams;
this.hasOptionalParams = o.hasOptionalParams;
this.hasRequiredParams = o.hasRequiredParams;
this.returnTypeIsPrimitive = o.returnTypeIsPrimitive;
this.returnSimpleType = o.returnSimpleType;
this.subresourceOperation = o.subresourceOperation;
this.isMapContainer = o.isMapContainer;
this.isListContainer = o.isListContainer;
this.isMultipart = o.isMultipart;
this.hasMore = o.hasMore;
this.isResponseBinary = o.isResponseBinary;
this.isResponseFile = o.isResponseFile;
this.hasReference = o.hasReference;
this.isRestfulIndex = o.isRestfulIndex;
this.isRestfulShow = o.isRestfulShow;
this.isRestfulCreate = o.isRestfulCreate;
this.isRestfulUpdate = o.isRestfulUpdate;
this.isRestfulDestroy = o.isRestfulDestroy;
this.isRestful = o.isRestful;
this.isDeprecated = o.isDeprecated;
this.isCallbackRequest = o.isCallbackRequest;
this.path = o.path;
this.operationId = o.operationId;
this.returnType = o.returnType;
this.httpMethod = o.httpMethod;
this.returnBaseType = o.returnBaseType;
this.returnContainer = o.returnContainer;
this.summary = o.summary;
this.unescapedNotes = o.unescapedNotes;
this.notes = o.notes;
this.baseName = o.baseName;
this.defaultResponse = o.defaultResponse;
this.discriminator = o.discriminator;
this.consumes = o.consumes;
this.produces = o.produces;
this.prioritizedContentTypes = o.prioritizedContentTypes;
this.servers = o.servers;
this.bodyParam = o.bodyParam;
this.allParams = o.allParams;
this.bodyParams = o.bodyParams;
this.pathParams = o.pathParams;
this.queryParams = o.queryParams;
this.headerParams = o.headerParams;
this.formParams = o.formParams;
this.cookieParams = o.cookieParams;
this.requiredParams = o.requiredParams;
this.optionalParams = o.optionalParams;
this.authMethods = o.authMethods;
this.tags = o.tags;
this.responses = o.responses;
this.callbacks = o.callbacks;
this.imports = o.imports;
this.examples = o.examples;
this.requestBodyExamples = o.requestBodyExamples;
this.externalDocs = o.externalDocs;
this.vendorExtensions = o.vendorExtensions;
this.nickname = o.nickname;
this.operationIdOriginal = o.operationIdOriginal;
this.operationIdLowerCase = o.operationIdLowerCase;
this.operationIdCamelCase = o.operationIdCamelCase;
this.operationIdSnakeCase = o.operationIdSnakeCase;
// new fields
this.hasHttpHeaders = o.getHasHeaderParams() || o.getHasBodyParam() || o.hasAuthMethods;
}
}
}

View File

@@ -0,0 +1,40 @@
package org.openapitools.codegen.templating.mustache;
import java.io.IOException;
import java.io.Writer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;
/**
* Lambda writes current fragment to the output when it is different than
* the previous fragment.
*
* Register:
* <pre>
* additionalProperties.put("onchange", new OnChangeLambda());
* </pre>
*
* Use:
* <pre>
* {{#onchange}}{{name}}{{/onchange}}
* </pre>
*/
public class OnChangeLambda implements Mustache.Lambda {
private static final Logger LOGGER = LoggerFactory.getLogger(OnChangeLambda.class);
private String lastVal = null;
@Override
public void execute(Template.Fragment frag, Writer out) throws IOException {
String curVal = frag.execute();
LOGGER.debug("[lastVal={}, curVal={}]", lastVal, curVal);
if (curVal != null && !curVal.equals(lastVal)) {
out.write(curVal);
lastVal = curVal;
}
}
}

View File

@@ -145,6 +145,7 @@ ext {
dependencies {
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "com.google.code.findbugs:jsr305:3.0.2"
compile "com.sun.jersey:jersey-client:$jersey_version"
compile "com.sun.jersey.contribs:jersey-multipart:$jersey_version"
compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"

View File

@@ -133,6 +133,7 @@ ext {
dependencies {
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "com.google.code.findbugs:jsr305:3.0.2"
compile "io.github.openfeign:feign-core:$feign_version"
compile "io.github.openfeign:feign-jackson:$feign_version"
compile "io.github.openfeign:feign-slf4j:$feign_version"

View File

@@ -199,6 +199,13 @@
<version>${swagger-annotations-version}</version>
</dependency>
<!-- @Nullable annotation -->
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.2</version>
</dependency>
<!-- HTTP client: Netflix Feign -->
<dependency>
<groupId>io.github.openfeign</groupId>

View File

@@ -133,6 +133,7 @@ ext {
dependencies {
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "com.google.code.findbugs:jsr305:3.0.2"
compile "com.google.api-client:google-api-client:${google_api_client_version}"
compile "org.glassfish.jersey.core:jersey-common:${jersey_common_version}"
compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"

View File

@@ -219,6 +219,12 @@
<artifactId>swagger-annotations</artifactId>
<version>${swagger-annotations-version}</version>
</dependency>
<!-- @Nullable annotation -->
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.2</version>
</dependency>
<!-- HTTP client: google-api-client -->
<dependency>
<groupId>com.google.api-client</groupId>

View File

@@ -137,6 +137,7 @@ ext {
dependencies {
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "com.google.code.findbugs:jsr305:3.0.2"
compile "org.glassfish.jersey.core:jersey-client:$jersey_version"
compile "org.glassfish.jersey.media:jersey-media-multipart:$jersey_version"
compile "org.glassfish.jersey.media:jersey-media-json-jackson:$jersey_version"

View File

@@ -229,6 +229,13 @@
<version>${swagger-annotations-version}</version>
</dependency>
<!-- @Nullable annotation -->
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.2</version>
</dependency>
<!-- HTTP client: jersey-client -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>

View File

@@ -0,0 +1,306 @@
{{>licenseInfo}}
package {{invokerPackage}};
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.nio.charset.Charset;
import java.time.Duration;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.StringJoiner;
import java.util.function.Consumer;
import java.util.stream.Collectors;
/**
* Configuration and utility class for API clients.
*
* <p>This class can be constructed and modified, then used to instantiate the
* various API classes. The API classes use the settings in this class to
* configure themselves, but otherwise do not store a link to this class.</p>
*
* <p>This class is mutable and not synchronized, so it is not thread-safe.
* The API classes generated from this are immutable and thread-safe.</p>
*
* <p>The setter methods of this class return the current object to facilitate
* a fluent style of configuration.</p>
*/
{{>generatedAnnotation}}
public class ApiClient {
private static final Charset UTF_8 = Charset.forName("UTF-8");
private HttpClient.Builder builder;
private ObjectMapper mapper;
private String scheme;
private String host;
private int port;
private String basePath;
private Consumer<HttpRequest.Builder> interceptor;
private Duration readTimeout;
private static String valueToString(Object value) {
if (value == null) {
return "";
}
return value.toString();
}
/**
* URL encode a string in the UTF-8 encoding.
*
* @param s String to encode.
* @return URL-encoded representation of the input string.
*/
public static String urlEncode(String s) {
return URLEncoder.encode(s, UTF_8);
}
/**
* Convert a URL query name/value parameter to a list of encoded {@link Pair}
* objects.
*
* <p>The value can be null, in which case an empty list is returned.</p>
*
* @param name The query name parameter.
* @param value The query value, which may not be a collection but may be
* null.
* @return A singleton list of the {@link Pair} objects representing the input
* parameters, which is encoded for use in a URL. If the value is null, an
* empty list is returned.
*/
public static List<Pair> parameterToPairs(String name, Object value) {
if (name == null || name.isEmpty() || value == null) {
return Collections.emptyList();
}
return Collections.singletonList(new Pair(urlEncode(name), urlEncode(value.toString())));
}
/**
* Convert a URL query name/collection parameter to a list of encoded
* {@link Pair} objects.
*
* @param collectionFormat The swagger collectionFormat string (csv, tsv, etc).
* @param name The query name parameter.
* @param values A collection of values for the given query name, which may be
* null.
* @return A list of {@link Pair} objects representing the input parameters,
* which is encoded for use in a URL. If the values collection is null, an
* empty list is returned.
*/
public static List<Pair> parameterToPairs(
String collectionFormat, String name, Collection<?> values) {
if (name == null || name.isEmpty() || values == null || values.isEmpty()) {
return Collections.emptyList();
}
// get the collection format (default: csv)
String format = collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat;
// create the params based on the collection format
if ("multi".equals(format)) {
return values.stream()
.map(value -> new Pair(urlEncode(name), urlEncode(valueToString(value))))
.collect(Collectors.toList());
}
String delimiter;
switch(format) {
case "csv":
delimiter = urlEncode(",");
break;
case "ssv":
delimiter = urlEncode(" ");
break;
case "tsv":
delimiter = urlEncode("\t");
break;
case "pipes":
delimiter = urlEncode("|");
break;
default:
throw new IllegalArgumentException("Illegal collection format: " + collectionFormat);
}
StringJoiner joiner = new StringJoiner(delimiter);
for (Object value : values) {
joiner.add(urlEncode(valueToString(value)));
}
return Collections.singletonList(new Pair(urlEncode(name), joiner.toString()));
}
/**
* Ctor.
*/
public ApiClient() {
builder = HttpClient.newBuilder();
mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
mapper.registerModule(new JavaTimeModule());
URI baseURI = URI.create("{{{basePath}}}");
scheme = baseURI.getScheme();
host = baseURI.getHost();
port = baseURI.getPort();
basePath = baseURI.getRawPath();
interceptor = null;
readTimeout = null;
}
/**
* Set a custom {@link HttpClient.Builder} object to use when creating the
* {@link HttpClient} that is used by the API client.
*
* @param builder Custom client builder.
* @return This object.
*/
public ApiClient setHttpClientBuilder(HttpClient.Builder builder) {
this.builder = builder;
return this;
}
/**
* Get an {@link HttpClient} based on the current {@link HttpClient.Builder}.
*
* <p>The returned object is immutable and thread-safe.</p>
*
* @return The HTTP client.
*/
public HttpClient getHttpClient() {
return builder.build();
}
/**
* Set a custom {@link ObjectMapper} to serialize and deserialize the request
* and response bodies.
*
* @param mapper Custom object mapper.
* @return This object.
*/
public ApiClient setObjectMapper(ObjectMapper mapper) {
this.mapper = mapper;
return this;
}
/**
* Get a copy of the current {@link ObjectMapper}.
*
* @return A copy of the current object mapper.
*/
public ObjectMapper getObjectMapper() {
return mapper.copy();
}
/**
* Set a custom host name for the target service.
*
* @param host The host name of the target service.
* @return This object.
*/
public ApiClient setHost(String host) {
this.host = host;
return this;
}
/**
* Set a custom port number for the target service.
*
* @param port The port of the target service. Set this to -1 to reset the
* value to the default for the scheme.
* @return This object.
*/
public ApiClient setPort(int port) {
this.port = port;
return this;
}
/**
* Set a custom base path for the target service, for example '/v2'.
*
* @param basePath The base path against which the rest of the path is
* resolved.
* @return This object.
*/
public ApiClient setBasePath(String basePath) {
this.basePath = basePath;
return this;
}
/**
* Get the base URI to resolve the endpoint paths against.
*
* @return The complete base URI that the rest of the API parameters are
* resolved against.
*/
public String getBaseUri() {
return scheme + "://" + host + (port == -1 ? "" : ":" + port) + basePath;
}
/**
* Set a custom request interceptor.
*
* <p>A request interceptor is a mechanism for altering each request before it
* is sent. After the request has been fully configured but not yet built, the
* request builder is passed into this function for further modification,
* after which it is sent out.</p>
*
* <p>This is useful for altering the requests in a custom manner, such as
* adding headers. It could also be used for logging and monitoring.</p>
*
* @param interceptor A function invoked before creating each request. A value
* of null resets the interceptor to a no-op.
* @return This object.
*/
public ApiClient setRequestInterceptor(Consumer<HttpRequest.Builder> interceptor) {
this.interceptor = interceptor;
return this;
}
/**
* Get the custom interceptor.
*
* @return The custom interceptor that was set, or null if there isn't any.
*/
public Consumer<HttpRequest.Builder> getRequestInterceptor() {
return interceptor;
}
/**
* Set the read timeout for the http client.
*
* <p>This is the value used by default for each request, though it can be
* overridden on a per-request basis with a request interceptor.</p>
*
* @param readTimeout The read timeout used by default by the http client.
* Setting this value to null resets the timeout to an
* effectively infinite value.
* @return This object.
*/
public ApiClient setReadTimeout(Duration readTimeout) {
this.readTimeout = readTimeout;
return this;
}
/**
* Get the read timeout that was set.
*
* @return The read timeout, or null if no timeout was set. Null represents
* an infinite wait time.
*/
public Duration getReadTimeout() {
return readTimeout;
}
}

View File

@@ -0,0 +1,161 @@
# {{artifactId}}
{{appName}}
- API version: {{appVersion}}
{{^hideGenerationTimestamp}}
- Build date: {{generatedDate}}
{{/hideGenerationTimestamp}}
{{#appDescription}}{{{appDescription}}}{{/appDescription}}
{{#infoUrl}}
For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}})
{{/infoUrl}}
*Automatically generated by the [OpenAPI Generator](https://openapi-generator.tech)*
## Requirements
Building the API client library requires:
1. Java 11+
2. Maven/Gradle
## Installation
To install the API client library to your local Maven repository, simply execute:
```shell
mvn clean install
```
To deploy it to a remote Maven repository instead, configure the settings of the repository and execute:
```shell
mvn clean deploy
```
Refer to the [OSSRH Guide](http://central.sonatype.org/pages/ossrh-guide.html) for more information.
### Maven users
Add this dependency to your project's POM:
```xml
<dependency>
<groupId>{{{groupId}}}</groupId>
<artifactId>{{{artifactId}}}</artifactId>
<version>{{{artifactVersion}}}</version>
<scope>compile</scope>
</dependency>
```
### Gradle users
Add this dependency to your project's build file:
```groovy
compile "{{{groupId}}}:{{{artifactId}}}:{{{artifactVersion}}}"
```
### Others
At first generate the JAR by executing:
```shell
mvn clean package
```
Then manually install the following JARs:
- `target/{{{artifactId}}}-{{{artifactVersion}}}.jar`
- `target/lib/*.jar`
## Getting Started
Please follow the [installation](#installation) instruction and execute the following Java code:
```java
{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}
import {{{invokerPackage}}}.*;
import {{{modelPackage}}}.*;
import {{{package}}}.{{{classname}}};
public class {{{classname}}}Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
// Configure clients using the `defaultClient` object, such as
// overriding the host and port, timeout, etc.
{{{classname}}} apiInstance = new {{{classname}}}(defaultClient);
{{#allParams}}
{{{dataType}}} {{{paramName}}} = {{{example}}}; // {{{dataType}}} | {{{description}}}
{{/allParams}}
try {
{{#returnType}}{{{returnType}}} result = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{{paramName}}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}}
System.out.println(result);{{/returnType}}
} catch (ApiException e) {
System.err.println("Exception when calling {{{classname}}}#{{{operationId}}}");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}}
```
## Documentation for API Endpoints
All URIs are relative to *{{basePath}}*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}}
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
## Documentation for Models
{{#models}}{{#model}} - [{{classname}}]({{modelDocPath}}{{classname}}.md)
{{/model}}{{/models}}
## Documentation for Authorization
{{^authMethods}}All endpoints do not require authorization.
{{/authMethods}}Authentication schemes defined for the API:
{{#authMethods}}### {{name}}
{{#isApiKey}}
- **Type**: API key
- **API key parameter name**: {{keyParamName}}
- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}}
{{/isApiKey}}
{{#isBasic}}
- **Type**: HTTP basic authentication
{{/isBasic}}
{{#isOAuth}}
- **Type**: OAuth
- **Flow**: {{flow}}
- **Authorization URL**: {{authorizationUrl}}
- **Scopes**: {{^scopes}}N/A{{/scopes}}
{{#scopes}} - {{scope}}: {{description}}
{{/scopes}}
{{/isOAuth}}
{{/authMethods}}
## Recommendation
It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues.
However, the instances of the api clients created from the `ApiClient` are thread-safe and can be re-used.
## Author
{{#apiInfo}}{{#apis}}{{^hasMore}}{{infoEmail}}
{{/hasMore}}{{/apis}}{{/apiInfo}}

View File

@@ -0,0 +1,157 @@
{{>licenseInfo}}
package {{package}};
import {{invokerPackage}}.ApiClient;
import {{invokerPackage}}.ApiException;
import {{invokerPackage}}.Pair;
{{#imports}}
import {{import}};
{{/imports}}
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.function.Consumer;
{{^fullJavaUtil}}
import java.util.ArrayList;
import java.util.StringJoiner;
import java.util.List;
import java.util.Map;
{{/fullJavaUtil}}
{{>generatedAnnotation}}
{{#operations}}
public class {{classname}} {
private final HttpClient memberVarHttpClient;
private final ObjectMapper memberVarObjectMapper;
private final String memberVarBaseUri;
private final Consumer<HttpRequest.Builder> memberVarInterceptor;
private final Duration memberVarReadTimeout;
public {{classname}}() {
this(new ApiClient());
}
public {{classname}}(ApiClient apiClient) {
memberVarHttpClient = apiClient.getHttpClient();
memberVarObjectMapper = apiClient.getObjectMapper();
memberVarBaseUri = apiClient.getBaseUri();
memberVarInterceptor = apiClient.getRequestInterceptor();
memberVarReadTimeout = apiClient.getReadTimeout();
}
{{#operation}}
/**
* {{summary}}
* {{notes}}
{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{^isContainer}}{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/isContainer}}{{/required}}
{{/allParams}}
{{#returnType}}
* @return {{returnType}}
{{/returnType}}
* @throws ApiException if fails to make API call
{{#isDeprecated}}
* @deprecated
{{/isDeprecated}}
{{#externalDocs}}
* {{description}}
* @see <a href="{{url}}">{{summary}} Documentation</a>
{{/externalDocs}}
*/
{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
{{#allParams}}
{{#required}}
// verify the required parameter '{{paramName}}' is set
if ({{paramName}} == null) {
throw new ApiException(400, "Missing the required parameter '{{paramName}}' when calling {{operationId}}");
}
{{/required}}
{{/allParams}}
HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder();
{{! Switch delimiters for baseName so we can write constants like "{query}" }}
String localVarPath = "{{{path}}}"{{#pathParams}}
.replace({{=<% %>=}}"{<%baseName%>}"<%={{ }}=%>, ApiClient.urlEncode({{{paramName}}}.toString())){{/pathParams}};
{{#hasQueryParams}}
{{javaUtilPrefix}}List<Pair> localVarQueryParams = new {{javaUtilPrefix}}ArrayList<>();
{{#queryParams}}
{{#collectionFormat}}
localVarQueryParams.addAll(ApiClient.parameterToPairs("{{{collectionFormat}}}", "{{baseName}}", {{paramName}}));
{{/collectionFormat}}
{{^collectionFormat}}
localVarQueryParams.addAll(ApiClient.parameterToPairs("{{baseName}}", {{paramName}}));
{{/collectionFormat}}
{{/queryParams}}
if (!localVarQueryParams.isEmpty()) {
{{javaUtilPrefix}}StringJoiner queryJoiner = new StringJoiner("&");
localVarQueryParams.forEach(p -> queryJoiner.add(p.getName() + '=' + p.getValue()));
localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath + '?' + queryJoiner.toString()));
} else {
localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath));
}
{{/hasQueryParams}}
{{^hasQueryParams}}
localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath));
{{/hasQueryParams}}
{{#headerParams}}
if ({{paramName}} != null) {
localVarRequestBuilder.header("{{baseName}}", {{paramName}}.toString());
}
{{/headerParams}}
{{#bodyParam}}
localVarRequestBuilder.header("Content-Type", "application/json");
{{/bodyParam}}
localVarRequestBuilder.header("Accept", "application/json");
try {
{{#bodyParam}}
byte[] localVarPostBody = memberVarObjectMapper.writeValueAsBytes({{paramName}});
localVarRequestBuilder.method("{{httpMethod}}", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody));
{{/bodyParam}}
{{^bodyParam}}
localVarRequestBuilder.method("{{httpMethod}}", HttpRequest.BodyPublishers.noBody());
{{/bodyParam}}
if (memberVarReadTimeout != null) {
localVarRequestBuilder.timeout(memberVarReadTimeout);
}
if (memberVarInterceptor != null) {
memberVarInterceptor.accept(localVarRequestBuilder);
}
HttpResponse<InputStream> localVarResponse = memberVarHttpClient.send(
localVarRequestBuilder.build(),
HttpResponse.BodyHandlers.ofInputStream());
if (localVarResponse.statusCode()/ 100 != 2) {
throw new ApiException(localVarResponse.statusCode(),
"{{operationId}} call received non-success response",
localVarResponse.headers(),
localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes()));
}
{{#returnType}}
return memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference<{{{returnType}}}>() {});
{{/returnType}}
} catch (IOException | InterruptedException e) {
throw new ApiException(e);
}
}
{{/operation}}
}
{{/operations}}

View File

@@ -0,0 +1,79 @@
{{>licenseInfo}}
package {{invokerPackage}};
import java.net.http.HttpHeaders;
{{>generatedAnnotation}}
public class ApiException extends{{#useRuntimeException}} RuntimeException {{/useRuntimeException}}{{^useRuntimeException}} Exception {{/useRuntimeException}}{
private int code = 0;
private HttpHeaders responseHeaders = null;
private String responseBody = null;
public ApiException() {}
public ApiException(Throwable throwable) {
super(throwable);
}
public ApiException(String message) {
super(message);
}
public ApiException(String message, Throwable throwable, int code, HttpHeaders responseHeaders, String responseBody) {
super(message, throwable);
this.code = code;
this.responseHeaders = responseHeaders;
this.responseBody = responseBody;
}
public ApiException(String message, int code, HttpHeaders responseHeaders, String responseBody) {
this(message, (Throwable) null, code, responseHeaders, responseBody);
}
public ApiException(String message, Throwable throwable, int code, HttpHeaders responseHeaders) {
this(message, throwable, code, responseHeaders, null);
}
public ApiException(int code, HttpHeaders responseHeaders, String responseBody) {
this((String) null, (Throwable) null, code, responseHeaders, responseBody);
}
public ApiException(int code, String message) {
super(message);
this.code = code;
}
public ApiException(int code, String message, HttpHeaders responseHeaders, String responseBody) {
this(code, message);
this.responseHeaders = responseHeaders;
this.responseBody = responseBody;
}
/**
* Get the HTTP status code.
*
* @return HTTP status code
*/
public int getCode() {
return code;
}
/**
* Get the HTTP response headers.
*
* @return Headers as an HttpHeaders object
*/
public HttpHeaders getResponseHeaders() {
return responseHeaders;
}
/**
* Get the HTTP response body.
*
* @return Response body in the form of string
*/
public String getResponseBody() {
return responseBody;
}
}

View File

@@ -0,0 +1,66 @@
apply plugin: 'idea'
apply plugin: 'eclipse'
group = '{{groupId}}'
version = '{{artifactVersion}}'
buildscript {
repositories {
mavenCentral()
jcenter()
}
}
repositories {
mavenCentral()
jcenter()
}
apply plugin: 'java'
apply plugin: 'maven'
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
install {
repositories.mavenInstaller {
pom.artifactId = '{{artifactId}}'
}
}
task execute(type:JavaExec) {
main = System.getProperty('mainClass')
classpath = sourceSets.main.runtimeClasspath
}
task sourcesJar(type: Jar, dependsOn: classes) {
classifier = 'sources'
from sourceSets.main.allSource
}
task javadocJar(type: Jar, dependsOn: javadoc) {
classifier = 'javadoc'
from javadoc.destinationDir
}
artifacts {
archives sourcesJar
archives javadocJar
}
ext {
swagger_annotations_version = "1.5.22"
jackson_version = "2.9.9"
junit_version = "4.12"
}
dependencies {
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "com.google.code.findbugs:jsr305:3.0.2"
compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version"
compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version"
testCompile "junit:junit:$junit_version"
}

View File

@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.5-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@@ -0,0 +1,100 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -0,0 +1,188 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

View File

@@ -0,0 +1,215 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>{{groupId}}</groupId>
<artifactId>{{artifactId}}</artifactId>
<packaging>jar</packaging>
<name>{{artifactId}}</name>
<version>{{artifactVersion}}</version>
<url>{{artifactUrl}}</url>
<description>{{artifactDescription}}</description>
<scm>
<connection>{{scmConnection}}</connection>
<developerConnection>{{scmDeveloperConnection}}</developerConnection>
<url>{{scmUrl}}</url>
</scm>
{{#parentOverridden}}
<parent>
<groupId>{{{parentGroupId}}}</groupId>
<artifactId>{{{parentArtifactId}}}</artifactId>
<version>{{{parentVersion}}}</version>
</parent>
{{/parentOverridden}}
<licenses>
<license>
<name>{{licenseName}}</name>
<url>{{licenseUrl}}</url>
<distribution>repo</distribution>
</license>
</licenses>
<developers>
<developer>
<name>{{developerName}}</name>
<email>{{developerEmail}}</email>
<organization>{{developerOrganization}}</organization>
<organizationUrl>{{developerOrganizationUrl}}</organizationUrl>
</developer>
</developers>
<build>
<plugins>
<plugin>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.0.0-M1</version>
<executions>
<execution>
<id>enforce-maven</id>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<requireMavenVersion>
<version>3</version>
</requireMavenVersion>
<requireJavaVersion>
<version>11</version>
</requireJavaVersion>
</rules>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M3</version>
<configuration>
<systemPropertyVariables>
<loggerPath>conf/log4j.properties</loggerPath>
</systemPropertyVariables>
<argLine>-Xms512m -Xmx1500m</argLine>
<parallel>methods</parallel>
<threadCount>10</threadCount>
</configuration>
</plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.1.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<!-- attach test jar -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.1.2</version>
<executions>
<execution>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
<configuration>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-source-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>sign-artifacts</id>
<build>
<plugins>
<plugin>
<artifactId>maven-gpg-plugin</artifactId>
<version>1.6</version>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<dependencies>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>${swagger-annotations-version}</version>
</dependency>
<!-- JSON processing: jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>${jackson-version}</version>
</dependency>
<!-- @Nullable annotation -->
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.2</version>
</dependency>
<!-- test dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<swagger-annotations-version>1.5.22</swagger-annotations-version>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<jackson-version>2.9.9</jackson-version>
<junit-version>4.12</junit-version>
</properties>
</project>

View File

@@ -0,0 +1,16 @@
#
# Generated by: https://openapi-generator.tech
#
language: java
jdk:
- oraclejdk11
before_install:
# ensure gradlew has proper permission
- chmod a+x ./gradlew
script:
# test using maven
- mvn test
# uncomment below to test using gradle
# - gradle test
# uncomment below to test using sbt
# - sbt test

View File

@@ -52,6 +52,7 @@ import java.util.regex.Pattern;
import {{invokerPackage}}.auth.Authentication;
import {{invokerPackage}}.auth.HttpBasicAuth;
import {{invokerPackage}}.auth.HttpBearerAuth;
import {{invokerPackage}}.auth.ApiKeyAuth;
{{#hasOAuthMethods}}
import {{invokerPackage}}.auth.OAuth;

View File

@@ -127,6 +127,7 @@ if(hasProperty('target') && target == 'android') {
dependencies {
compile 'io.swagger:swagger-annotations:1.5.22'
compile "com.google.code.findbugs:jsr305:3.0.2"
compile 'com.squareup.okhttp3:okhttp:3.14.2'
compile 'com.squareup.okhttp3:logging-interceptor:3.14.2'
compile 'com.google.code.gson:gson:2.8.5'

View File

@@ -207,6 +207,12 @@
<artifactId>swagger-annotations</artifactId>
<version>${swagger-core-version}</version>
</dependency>
<!-- @Nullable annotation -->
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>

View File

@@ -34,13 +34,13 @@ public class ApiClient {
{{#apiInfo}}
{{#apis}}
public {{classname}} {{classVarName}}() {
return {{classname}}.{{classVarName}}(config.baseReqSpec.get());
return {{classname}}.{{classVarName}}(config.reqSpecSupplier);
}
{{/apis}}
{{/apiInfo}}
public static class Config {
private Supplier<RequestSpecBuilder> baseReqSpec = () -> new RequestSpecBuilder()
private Supplier<RequestSpecBuilder> reqSpecSupplier = () -> new RequestSpecBuilder()
{{#basePath}}.setBaseUri(BASE_URI){{/basePath}}
.setConfig(config().objectMapperConfig(objectMapperConfig().defaultObjectMapper(gson())));
@@ -50,7 +50,7 @@ public class ApiClient {
* @return configuration
*/
public Config reqSpecSupplier(Supplier<RequestSpecBuilder> supplier) {
this.baseReqSpec = supplier;
this.reqSpecSupplier = supplier;
return this;
}

View File

@@ -31,14 +31,23 @@ import static io.restassured.http.Method.*;
@Api(value = "{{{baseName}}}")
public class {{classname}} {
private RequestSpecBuilder reqSpec;
private Supplier<RequestSpecBuilder> reqSpecSupplier;
private Consumer<RequestSpecBuilder> reqSpecCustomizer;
private {{classname}}(RequestSpecBuilder reqSpec) {
this.reqSpec = reqSpec;
private {{classname}}(Supplier<RequestSpecBuilder> reqSpecSupplier) {
this.reqSpecSupplier = reqSpecSupplier;
}
public static {{classname}} {{classVarName}}(RequestSpecBuilder reqSpec) {
return new {{classname}}(reqSpec);
public static {{classname}} {{classVarName}}(Supplier<RequestSpecBuilder> reqSpecSupplier) {
return new {{classname}}(reqSpecSupplier);
}
private RequestSpecBuilder createReqSpec() {
RequestSpecBuilder reqSpec = reqSpecSupplier.get();
if(reqSpecCustomizer != null) {
reqSpecCustomizer.accept(reqSpec);
}
return reqSpec;
}
{{#operations}}
@@ -54,18 +63,18 @@ public class {{classname}} {
@Deprecated
{{/isDeprecated}}
public {{operationIdCamelCase}}Oper {{operationId}}() {
return new {{operationIdCamelCase}}Oper(reqSpec);
return new {{operationIdCamelCase}}Oper(createReqSpec());
}
{{/operation}}
{{/operations}}
/**
* Customise request specification
* @param consumer consumer
* Customize request specification
* @param reqSpecCustomizer consumer to modify the RequestSpecBuilder
* @return api
*/
public {{classname}} reqSpec(Consumer<RequestSpecBuilder> consumer) {
consumer.accept(reqSpec);
public {{classname}} reqSpec(Consumer<RequestSpecBuilder> reqSpecCustomizer) {
this.reqSpecCustomizer = reqSpecCustomizer;
return this;
}
@@ -216,22 +225,22 @@ public class {{classname}} {
{{/formParams}}
/**
* Customise request specification
* @param consumer consumer
* Customize request specification
* @param reqSpecCustomizer consumer to modify the RequestSpecBuilder
* @return operation
*/
public {{operationIdCamelCase}}Oper reqSpec(Consumer<RequestSpecBuilder> consumer) {
consumer.accept(reqSpec);
public {{operationIdCamelCase}}Oper reqSpec(Consumer<RequestSpecBuilder> reqSpecCustomizer) {
reqSpecCustomizer.accept(reqSpec);
return this;
}
/**
* Customise response specification
* @param consumer consumer
* Customize response specification
* @param respSpecCustomizer consumer to modify the ResponseSpecBuilder
* @return operation
*/
public {{operationIdCamelCase}}Oper respSpec(Consumer<ResponseSpecBuilder> consumer) {
consumer.accept(respSpec);
public {{operationIdCamelCase}}Oper respSpec(Consumer<ResponseSpecBuilder> respSpecCustomizer) {
respSpecCustomizer.accept(respSpec);
return this;
}
}

View File

@@ -111,6 +111,7 @@ ext {
dependencies {
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "com.google.code.findbugs:jsr305:3.0.2"
compile "io.rest-assured:scala-support:$rest_assured_version"
compile "io.gsonfire:gson-fire:$gson_fire_version"
{{#joda}}

View File

@@ -206,6 +206,12 @@
<artifactId>swagger-annotations</artifactId>
<version>${swagger-annotations-version}</version>
</dependency>
<!-- @Nullable annotation -->
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>

View File

@@ -135,6 +135,7 @@ ext {
dependencies {
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "com.google.code.findbugs:jsr305:3.0.2"
compile "org.jboss.resteasy:resteasy-client:$resteasy_version"
compile "org.jboss.resteasy:resteasy-multipart-provider:$resteasy_version"
compile "org.jboss.resteasy:resteasy-jackson2-provider:$resteasy_version"

View File

@@ -179,6 +179,12 @@
<artifactId>swagger-annotations</artifactId>
<version>${swagger-annotations-version}</version>
</dependency>
<!-- @Nullable annotation -->
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.2</version>
</dependency>
<!-- HTTP client: jersey-client -->
<dependency>
<groupId>org.jboss.resteasy</groupId>

View File

@@ -132,6 +132,7 @@ ext {
dependencies {
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "com.google.code.findbugs:jsr305:3.0.2"
compile "org.springframework:spring-web:$spring_web_version"
compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"

View File

@@ -219,6 +219,13 @@
<artifactId>swagger-annotations</artifactId>
<version>${swagger-annotations-version}</version>
</dependency>
<!-- @Nullable annotation -->
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.2</version>
</dependency>
<!-- HTTP client: Spring RestTemplate -->
<dependency>

View File

@@ -120,6 +120,7 @@ ext {
dependencies {
compile "com.squareup.okhttp:okhttp:$okhttp_version"
compile "com.google.code.findbugs:jsr305:3.0.2"
compile "com.squareup.retrofit:retrofit:$retrofit_version"
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version"

View File

@@ -219,6 +219,12 @@
<artifactId>swagger-annotations</artifactId>
<version>${swagger-annotations-version}</version>
</dependency>
<!-- @Nullable annotation -->
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>com.squareup.retrofit</groupId>
<artifactId>retrofit</artifactId>

View File

@@ -166,6 +166,7 @@ dependencies {
compile "io.reactivex.rxjava2:rxjava:$rx_java_version"
{{/useRxJava2}}
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "com.google.code.findbugs:jsr305:3.0.2"
compile ("org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version"){
exclude group:'org.apache.oltu.oauth2' , module: 'org.apache.oltu.oauth2.common'
}

View File

@@ -198,6 +198,12 @@
<artifactId>swagger-annotations</artifactId>
<version>${swagger-annotations-version}</version>
</dependency>
<!-- @Nullable annotation -->
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-gson</artifactId>

View File

@@ -36,6 +36,7 @@ ext {
dependencies {
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "com.google.code.findbugs:jsr305:3.0.2"
compile "io.vertx:vertx-web-client:$vertx_version"
compile "io.vertx:vertx-rx-java:$vertx_version"
compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"

View File

@@ -208,6 +208,13 @@
<version>${swagger-annotations-version}</version>
</dependency>
<!-- @Nullable annotation -->
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.2</version>
</dependency>
<!-- Vertx -->
<dependency>
<groupId>io.vertx</groupId>

View File

@@ -72,6 +72,13 @@
<artifactId>swagger-annotations</artifactId>
<version>${swagger-annotations-version}</version>
</dependency>
<!-- @Nullable annotation -->
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>

View File

@@ -53,7 +53,7 @@ public enum {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum
return b;
}
}
{{#useNullForUnknownEnumValue}}return null;{{/useNullForUnknownEnumValue}}{{^useNullForUnknownEnumValue}}throw new IllegalArgumentException("Unexpected value '" + value + "'");{{/useNullForUnknownEnumValue}}
{{#isNullable}}return null;{{/isNullable}}{{^isNullable}}throw new IllegalArgumentException("Unexpected value '" + value + "'");{{/isNullable}}
}
{{#gson}}
@@ -65,8 +65,8 @@ public enum {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum
@Override
public {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} read(final JsonReader jsonReader) throws IOException {
{{{dataType}}} value = jsonReader.{{#isInteger}}nextInt(){{/isInteger}}{{^isInteger}}next{{{dataType}}}(){{/isInteger}};
return {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.fromValue(value);
{{^isNumber}}{{{dataType}}}{{/isNumber}}{{#isNumber}}String{{/isNumber}} value = jsonReader.{{#isNumber}}nextString(){{/isNumber}}{{#isInteger}}nextInt(){{/isInteger}}{{^isNumber}}{{^isInteger}}next{{{dataType}}}(){{/isInteger}}{{/isNumber}};
return {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.fromValue({{#isNumber}}new BigDecimal({{/isNumber}}value{{#isNumber}}){{/isNumber}});
}
}
{{/gson}}

View File

@@ -44,7 +44,7 @@
return b;
}
}
{{#useNullForUnknownEnumValue}}return null;{{/useNullForUnknownEnumValue}}{{^useNullForUnknownEnumValue}}throw new IllegalArgumentException("Unexpected value '" + value + "'");{{/useNullForUnknownEnumValue}}
{{#isNullable}}return null;{{/isNullable}}{{^isNullable}}throw new IllegalArgumentException("Unexpected value '" + value + "'");{{/isNullable}}
}
{{#gson}}
@@ -56,8 +56,8 @@
@Override
public {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} read(final JsonReader jsonReader) throws IOException {
{{{dataType}}} value = jsonReader.{{#isInteger}}nextInt(){{/isInteger}}{{^isInteger}}next{{{dataType}}}(){{/isInteger}};
return {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}.fromValue(value);
{{^isNumber}}{{{dataType}}}{{/isNumber}}{{#isNumber}}String{{/isNumber}} value = jsonReader.{{#isNumber}}nextString(){{/isNumber}}{{#isInteger}}nextInt(){{/isInteger}}{{^isNumber}}{{^isInteger}}next{{{dataType}}}(){{/isInteger}}{{/isNumber}};
return {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}.fromValue({{#isNumber}}new BigDecimal({{/isNumber}}value{{#isNumber}}){{/isNumber}});
}
}
{{/gson}}

View File

@@ -129,6 +129,14 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#parcela
{{/maximum}}
* @return {{name}}
**/
{{#required}}
{{#isNullable}}
@javax.annotation.Nullable
{{/isNullable}}
{{/required}}
{{^required}}
@javax.annotation.Nullable
{{/required}}
{{#useBeanValidation}}{{>beanValidation}}{{/useBeanValidation}} @ApiModelProperty({{#example}}example = "{{{example}}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}")
{{#vendorExtensions.extraAnnotation}}
{{{vendorExtensions.extraAnnotation}}}

View File

@@ -220,6 +220,14 @@
<version>${swagger-annotations-version}</version>
</dependency>
<!-- @Nullable annotation -->
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.2</version>
</dependency>
<!-- HTTP client: jersey-client -->
<dependency>
<groupId>com.sun.jersey</groupId>

View File

@@ -39,6 +39,6 @@
return b;
}
}
{{#useNullForUnknownEnumValue}}return null;{{/useNullForUnknownEnumValue}}{{^useNullForUnknownEnumValue}}throw new IllegalArgumentException("Unexpected value '" + text + "'");{{/useNullForUnknownEnumValue}}
{{#isNullable}}return null;{{/isNullable}}{{^isNullable}}throw new IllegalArgumentException("Unexpected value '" + text + "'");{{/isNullable}}
}
}

View File

@@ -37,6 +37,6 @@ public enum {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum
return b;
}
}
{{#useNullForUnknownEnumValue}}return null;{{/useNullForUnknownEnumValue}}{{^useNullForUnknownEnumValue}}throw new IllegalArgumentException("Unexpected value '" + text + "'");{{/useNullForUnknownEnumValue}}
{{#isNullable}}return null;{{/isNullable}}{{^isNullable}}throw new IllegalArgumentException("Unexpected value '" + text + "'");{{/isNullable}}
}
}

View File

@@ -28,6 +28,6 @@ public enum {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum
return b;
}
}
{{#useNullForUnknownEnumValue}}return null;{{/useNullForUnknownEnumValue}}{{^useNullForUnknownEnumValue}}throw new IllegalArgumentException("Unexpected value '" + value + "'");{{/useNullForUnknownEnumValue}}
{{#isNullable}}return null;{{/isNullable}}{{^isNullable}}throw new IllegalArgumentException("Unexpected value '" + value + "'");{{/isNullable}}
}
}

View File

@@ -77,6 +77,13 @@
<version>[1.5.3,1.5.16]</version>
</dependency>
<!-- @Nullable annotation -->
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.2</version>
</dependency>
{{#useBeanValidation}}
<!-- Bean Validation API support -->
<dependency>

View File

@@ -28,6 +28,6 @@ public enum {{datatypeWithEnum}} {
return b;
}
}
{{#useNullForUnknownEnumValue}}return null;{{/useNullForUnknownEnumValue}}{{^useNullForUnknownEnumValue}}throw new IllegalArgumentException("Unexpected value '" + value + "'");{{/useNullForUnknownEnumValue}}
{{#isNullable}}return null;{{/isNullable}}{{^isNullable}}throw new IllegalArgumentException("Unexpected value '" + value + "'");{{/isNullable}}
}
}

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