Merge pull request #4497 from swagger-api/2.3.0_sync_master

Merge the latest master into 2.3.0
This commit is contained in:
wing328 2017-01-06 01:00:08 +08:00 committed by GitHub
commit a541ecc2c5
2009 changed files with 48709 additions and 54067 deletions

View File

@ -0,0 +1,57 @@
sudo: required
language: objective-c
osx_image: xcode7.3
cache:
directories:
- $HOME/.m2
- $HOME/.gem
- $HOME/.rvm
- $HOME/.cocoapods
- swagger-api/swagger-codegen/samples/client/petstore/objc/default/SwaggerClientTests/Pods
- swagger-api/swagger-codegen/samples/client/petstore/objc/core-data/SwaggerClientTests/Pods
- swagger-api/swagger-codegen/samples/client/petstore/swift/default/SwaggerClientTests/Pods
- swagger-api/swagger-codegen/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods
services:
- docker
addons:
hosts:
- petstore.swagger.io
before_install:
- export SW=`pwd`
# show host table to confirm petstore.swagger.io is mapped to localhost
- cat /private/etc/hosts
#- rvm install 2.2.2 > /dev/null 2>&1
- rvm use 2.2.4
- gem environment
- gem install cocoapods -v 1.0.1 -N --no-ri --no-rdoc
- gem install xcpretty -N --no-ri --no-rdoc
- pod --version
- pod setup --silent > /dev/null
# xctool already pre-installed
#- brew install xctool
- git clone https://github.com/wing328/swagger-samples
- cd swagger-samples/java/java-jersey-jaxrs && sudo mvn -q jetty:run &
install:
script:
# test default objc client
- cd $SW/samples/client/petstore/objc/default/SwaggerClientTests && pod install && xctool -workspace "SwaggerClient.xcworkspace" -scheme "SwaggerClient-Example" -destination platform='iOS Simulator',OS=8.4,name='iPhone 6' test -test-sdk iphonesimulator CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO
# test objc client with coredata
- cd $SW/samples/client/petstore/objc/core-data/SwaggerClientTests && pod install && xctool -workspace "SwaggerClient.xcworkspace" -scheme "SwaggerClient-Example" -destination platform='iOS Simulator',OS=8.4,name='iPhone 6' test -test-sdk iphonesimulator CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO
- set -o pipefail
# test swift client with promisekit
- cd $SW/samples/client/petstore/swift/promisekit/SwaggerClientTests && pod install && xcodebuild clean test -workspace "SwaggerClient.xcworkspace" -scheme "SwaggerClient" -sdk iphonesimulator GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES GCC_GENERATE_TEST_COVERAGE_FILES=YES | xcpretty
# test default swift client
- cd $SW/samples/client/petstore/swift/default/SwaggerClientTests && pod install && xcodebuild clean test -workspace "SwaggerClient.xcworkspace" -scheme "SwaggerClient" -sdk iphonesimulator GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES GCC_GENERATE_TEST_COVERAGE_FILES=YES | xcpretty
# test swift3 client with promisekit
- cd $SW/samples/client/petstore/swift3/promisekit/SwaggerClientTests && pod install && xcodebuild clean test -workspace "SwaggerClient.xcworkspace" -scheme "SwaggerClient" -sdk iphonesimulator GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES GCC_GENERATE_TEST_COVERAGE_FILES=YES | xcpretty
# test default swift3 client
- cd $SW/samples/client/petstore/swift3/default/SwaggerClientTests && pod install && xcodebuild clean test -workspace "SwaggerClient.xcworkspace" -scheme "SwaggerClient" -sdk iphonesimulator GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES GCC_GENERATE_TEST_COVERAGE_FILES=YES | xcpretty
env:
- DOCKER_IMAGE_NAME=swaggerapi/swagger-generator

View File

@ -28,13 +28,14 @@ For a list of variables available in the template, please refer to this [page](h
### Style guide
Code change should conform to the programming style guide of the respective langauages:
Code change should conform to the programming style guide of the respective languages:
- Android: https://source.android.com/source/code-style.html
- C#: https://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx
- C++: https://google.github.io/styleguide/cppguide.html
- Clojure: https://github.com/bbatsov/clojure-style-guide
- Haskell: https://github.com/tibbe/haskell-style-guide/blob/master/haskell-style.md
- Java: https://google.github.io/styleguide/javaguide.html
- JavaScript: https://github.com/airbnb/javascript/tree/master/es5
- JavaScript: https://github.com/airbnb/javascript/
- Groovy: http://groovy-lang.org/style-guide.html
- Go: https://github.com/golang/go/wiki/CodeReviewComments
- ObjC: https://github.com/NYTimes/objective-c-style-guide
@ -52,8 +53,8 @@ You may find the current code base not 100% conform to the coding style and we w
For [Vendor Extensions](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#vendorExtensions), please follow the naming convention below:
- For general vendor extension, use lower case and hyphen. e.g. `x-is-unique`, `x-content-type`
- For language-specified vendor extension, put it in the form of `x-{lang}-{extension-name}`. e.g. `x-objc-operation-id`, `x-java-feign-retry-limit`
- For a list of existing vendor extensions in use, please refer to https://github.com/swagger-api/swagger-codegen/wiki/Vendor-Extensions. If you've addaed new vendor extensions as part of your PR, please update the wiki page.
- For language-specified vendor extension, put it in the form of `x-{lang}-{extension-name}`. e.g. `x-objc-operation-id`, `x-java-feign-retry-limit`
- For a list of existing vendor extensions in use, please refer to https://github.com/swagger-api/swagger-codegen/wiki/Vendor-Extensions. If you've added new vendor extensions as part of your PR, please update the wiki page.
### Testing

108
README.md
View File

@ -13,9 +13,14 @@
:warning: If the OpenAPI/Swagger spec is obtained from an untrusted source, please make sure you've reviewed the spec before using Swagger Codegen to generate the API client, server stub or documentation as [code injection](https://en.wikipedia.org/wiki/Code_injection) may occur :warning:
## Overview
This is the swagger codegen project, which allows generation of API client libraries, server stubs and documentation automatically given an [OpenAPI Spec](https://github.com/OAI/OpenAPI-Specification).
This is the swagger codegen project, which allows generation of API client libraries (SDK generation), server stubs and documentation automatically given an [OpenAPI Spec](https://github.com/OAI/OpenAPI-Specification). Currently, the following languages/frameworks are supported:
Check out [Swagger-Spec](https://github.com/OAI/OpenAPI-Specification) for additional information about the Swagger project, including additional libraries with support for other languages and more.
- **API clients**: **ActionScript**, **C#** (.net 2.0, 4.0 or later), **C++** (cpprest, Qt5, Tizen), **Clojure**, **Dart**, **Go**, **Groovy**, **Haskell**, **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign), **Node.js** (ES5, ES6, AngularJS with Google Closure Compiler annotations) **Objective-C**, **Perl**, **PHP**, **Python**, **Ruby**, **Scala**, **Swift** (2.x, 3.x), **Typescript** (Angular1.x, Angular2.x, Fetch, Node)
- **Server stubs**: **C#** (ASP.NET Core, NancyFx), **Erlang**, **Go**, **Haskell**, **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, RestEasy), **PHP** (Lumen, Slim, Silex), **Python** (Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Scala** (Scalatra)
- **API documentation generators**: **HTML**, **Confluence Wiki**
- **Others**: **JMeter**
Check out [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) for additional information about the OpenAPI project.
# Table of contents
@ -52,11 +57,12 @@ Check out [Swagger-Spec](https://github.com/OAI/OpenAPI-Specification) for addit
- [Guidelines for Contribution](https://github.com/swagger-api/swagger-codegen/wiki/Guidelines-for-Contribution)
- [Companies/Projects using Swagger Codegen](#companiesprojects-using-swagger-codegen)
- [Swagger Codegen Core Team](#swagger-codegen-core-team)
- [Swagger Codegen Evangelist](#swagger-codegen-evangelist)
- [License](#license)
## Compatibility
The OpenAPI Specification has undergone 3 revisions since initial creation in 2010. The swagger-codegen project has the following compatibilies with the OpenAPI Specification:
The OpenAPI Specification has undergone 3 revisions since initial creation in 2010. The swagger-codegen project has the following compatibilities with the OpenAPI Specification:
Swagger Codegen Version | Release Date | OpenAPI Spec compatibility | Notes
-------------------------- | ------------ | -------------------------- | -----
@ -128,7 +134,8 @@ cd /vagrant
#### Public Docker image
https://hub.docker.com/r/swaggerapi/swagger-generator/
- https://hub.docker.com/r/swaggerapi/swagger-generator/ (official)
- https://hub.docker.com/r/jimschubert/swagger-codegen-cli/ (unofficial)
### Homebrew
To install, run `brew install swagger-codegen`
@ -550,10 +557,10 @@ CONFIG OPTIONS
library
library template (sub-template) to use:
<default> - HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2
jersey1 - HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2
jersey2 - HTTP client: Jersey client 2.6
feign - HTTP client: Netflix Feign 8.1.1. JSON processing: Jackson 2.6.3
okhttp-gson - HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1
okhttp-gson (default) - HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1
retrofit - HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)
retrofit2 - HTTP client: OkHttp 2.5.0. JSON processing: Gson 2.4 (Retrofit 2.0.0-beta2)
```
@ -664,7 +671,7 @@ You can use the [swagger-codegen-maven-plugin](modules/swagger-codegen-maven-plu
To push the auto-generated SDK to GitHub, we provide `git_push.sh` to streamline the process. For example:
1) Create a new repository in GitHub (Ref: https://help.github.com/articles/creating-a-new-repository/)
2) Generate the SDK
```
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
@ -747,7 +754,10 @@ Here are some companies/projects using Swagger Codegen in production. To add you
- [Activehours](https://www.activehours.com/)
- [Acunetix](https://www.acunetix.com/)
- [Atlassian](https://www.atlassian.com/)
- [Autodesk](http://www.autodesk.com/)
- [Avenida Compras S.A.](https://www.avenida.com.ar)
- [AYLIEN](http://aylien.com/)
- [Balance Internet](https://www.balanceinternet.com.au/)
- [beemo](http://www.beemo.eu)
- [bitly](https://bitly.com)
- [Bufferfly Network](https://www.butterflynetinc.com/)
@ -765,6 +775,8 @@ Here are some companies/projects using Swagger Codegen in production. To add you
- [eureka](http://eure.jp/)
- [everystory.us](http://everystory.us)
- [Expected Behavior](http://www.expectedbehavior.com/)
- [Fastly](https://www.fastly.com/)
- [Flat](https://flat.io)
- [Finder](http://en.finder.pl/)
- [FH Münster - University of Applied Sciences](http://www.fh-muenster.de)
- [Gear Zero Network](https://www.gearzero.ca)
@ -773,15 +785,18 @@ Here are some companies/projects using Swagger Codegen in production. To add you
- [GraphHopper](https://graphhopper.com/)
- [Gravitate Solutions](http://gravitatesolutions.com/)
- [IMS Health](http://www.imshealth.com/en/solution-areas/technology-and-applications)
- [Intent HQ](http://www.intenthq.com)
- [Interactive Intelligence](http://developer.mypurecloud.com/)
- [LANDR Audio](https://www.landr.com/)
- [Lascaux](http://www.lascaux.it/)
- [LiveAgent](https://www.ladesk.com/)
- [Kabuku](http://www.kabuku.co.jp/en)
- [Kuroi](http://kuroiwebdesign.com/)
- [Kuary](https://kuary.com/)
- [LANDR Audio](https://www.landr.com/)
- [Lascaux](http://www.lascaux.it/)
- [Leica Geosystems AG](http://leica-geosystems.com)
- [LiveAgent](https://www.ladesk.com/)
- [LXL Tech](http://lxltech.com)
- [Mindera](http://mindera.com/)
- [Mporium](http://mporium.com/)
- [Mporium](http://mporium.com/)
- [nViso](http://www.nviso.ch/)
- [Okiok](https://www.okiok.com)
- [Onedata](http://onedata.org)
@ -792,20 +807,29 @@ Here are some companies/projects using Swagger Codegen in production. To add you
- [Plexxi](http://www.plexxi.com)
- [Pixoneye](http://www.pixoneye.com/)
- [PostAffiliatePro](https://www.postaffiliatepro.com/)
- [Prill Tecnologia](http://www.prill.com.br)
- [QAdept](http://qadept.com/)
- [QuantiModo](https://quantimo.do/)
- [Rapid7](https://rapid7.com/)
- [Reload! A/S](https://reload.dk/)
- [Reload! A/S](https://reload.dk/)
- [REstore](https://www.restore.eu)
- [Revault Sàrl](http://revault.ch)
- [Riffyn](https://riffyn.com)
- [Royal Bank of Canada (RBC)](http://www.rbc.com/canada.html)
- [Saritasa](https://www.saritasa.com/)
- [SCOOP Software GmbH](http://www.scoop-software.de)
- [Shine Solutions](https://shinesolutions.com/)
- [Skurt](http://www.skurt.com)
- [SmartRecruiters](https://www.smartrecruiters.com/)
- [snapCX](https://snapcx.io)
- [SRC](https://www.src.si/)
- [StyleRecipe](http://stylerecipe.co.jp)
- [Svenska Spel AB](https://www.svenskaspel.se/)
- [TaskData](http://www.taskdata.com/)
- [ThoughtWorks](https://www.thoughtworks.com)
- [Upwork](http://upwork.com/)
- [uShip](https://www.uship.com/)
- [VMware](https://vmware.com/)
- [W.UP](http://wup.hu/?siteLang=en)
- [Wealthfront](https://www.wealthfront.com/)
- [WEXO A/S](https://www.wexo.dk/)
@ -818,8 +842,8 @@ Here are some companies/projects using Swagger Codegen in production. To add you
Swagger Codegen core team members are contributors who have been making significant contributions (review issues, fix bugs, make enhancements, etc) to the project on a regular basis.
## API Clients
| Languages | Core Team (join date) |
|:-------------|:-------------|
| Languages | Core Team (join date) |
|:-------------|:-------------|
| ActionScript | |
| C++ | |
| C# | @jimschubert (2016/05/01) | |
@ -829,7 +853,7 @@ Swagger Codegen core team members are contributors who have been making signific
| Go | @guohuang (2016/05/01) @neilotoole (2016/05/01) |
| Java | @cbornet (2016/05/01) @xhh (2016/05/01) @epaul (2016/06/04) |
| Java (Spring Cloud) | @cbornet (2016/07/19) |
| NodeJS/Javascript | @xhh (2016/05/01) |
| NodeJS/Javascript | @xhh (2016/05/01) |
| ObjC | @mateuszmackowiak (2016/05/09) |
| Perl | @wing328 (2016/05/01) |
| PHP | @arnested (2016/05/01) |
@ -837,13 +861,13 @@ Swagger Codegen core team members are contributors who have been making signific
| Ruby | @wing328 (2016/05/01) @zlx (2016/05/22) |
| Scala | |
| Swift | @jaz-ah (2016/05/01) @Edubits (2016/05/01) |
| TypeScript (Node) | @Vrolijkx (2016/05/01) |
| TypeScript (Angular1) | @Vrolijkx (2016/05/01) |
| TypeScript (Node) | @Vrolijkx (2016/05/01) |
| TypeScript (Angular1) | @Vrolijkx (2016/05/01) |
| TypeScript (Angular2) | @Vrolijkx (2016/05/01) |
| TypeScript (Fetch) | |
## Server Stubs
| Languages | Core Team (date joined) |
|:------------- |:-------------|
| Languages | Core Team (date joined) |
|:------------- |:-------------|
| C# ASP.NET5 | @jimschubert (2016/05/01) |
| Go Server | @guohuang (2016/06/13) |
| Haskell Servant | |
@ -862,24 +886,26 @@ Swagger Codegen core team members are contributors who have been making signific
## Template Creator
Here is a list of template creators:
* API Clients:
* Akka-Scala: @cchafer
* Akka-Scala: @cchafer
* C++ REST: @Danielku15
* C# (.NET 2.0): @who
* Clojure: @xhh
* Dart: @yissachar
* Groovy: @victorgit
* Go: @wing328
* Dart: @yissachar
* Groovy: @victorgit
* Go: @wing328
* Java (Feign): @davidkiss
* Java (Retrofit): @0legg
* Java (Retrofi2): @emilianobonassi
* Java (Jersey2): @xhh
* Java (Jersey2): @xhh
* Java (okhttp-gson): @xhh
* Javascript/NodeJS: @jfiala
* Javascript/NodeJS: @jfiala
* Javascript (Closure-annotated Angular) @achew22
* JMeter @davidkiss
* Perl: @wing328
* Swift: @tkqubo
* Swift 3: @hexelon
* TypeScript (Node): @mhardorf
* TypeScript (Angular1): @mhardorf
* TypeScript (Node): @mhardorf
* TypeScript (Angular1): @mhardorf
* TypeScript (Fetch): @leonyu
* TypeScript (Angular2): @roni-frantchi
* Server Stubs
@ -896,7 +922,7 @@ Here is a list of template creators:
* JAX-RS CXF (CDI): @nickcmaynard
* PHP Lumen: @abcsum
* PHP Slim: @jfastnacht
* Ruby on Rails 5: @zlx
* Ruby on Rails 5: @zlx
* Documentation
* HTML Doc 2: @jhitchcock
* Confluence Wiki: @jhitchcock
@ -905,16 +931,36 @@ Here is a list of template creators:
Here are the requirements to become a core team member:
- rank within top 50 in https://github.com/swagger-api/swagger-codegen/graphs/contributors
- to contribute, here are some good [starting points](https://github.com/swagger-api/swagger-codegen/issues?q=is%3Aopen+is%3Aissue+label%3A%22Need+community+contribution%22)
- to contribute, here are some good [starting points](https://github.com/swagger-api/swagger-codegen/issues?q=is%3Aopen+is%3Aissue+label%3A%22Need+community+contribution%22)
- regular contributions to the project
- about 3 hours per week
- for contribution, it can be addressing issues, reviewing PRs submitted by others, submitting PR to fix bugs or make enhancements, etc
To join the core team, please reach out to wing328hk@gmail.com (@wing328) for more information.
To become a Template Creator, simply submit a PR for new API client (e.g. Rust, Elixir) or server stub (e.g. Ruby Grape) generator.
## License information on Generated Code
# Swagger Codegen Evangelist
Swagger Codegen Evangelist shoulders one or more of the following responsibilities:
- publishes articles on the benefit of Swagger Codegen
- organizes local Meetups
- presents the benefits of Swagger Codegen in local Meetups or conferences
- actively answers questions from others in [Github](https://github.com/swagger-api/swagger-codegen/issues), [StackOverflow](stackoverflow.com/search?q=%5Bswagger%5D)
- submits PRs to improve Swagger Codegen
- reviews PRs submitted by the others
- ranks within top 100 in the [contributor list](https://github.com/swagger-api/swagger-codegen/graphs/contributors)
If you want to be a Swagger Codegen Evangelist, please kindly apply by sending an email to wing328hk@gmail.com (@wing328)
### List of Swagger Codegen Evangelists
- Cliffano Subagio (@cliffano from Australia joined on Dec 9, 2016)
- [Building An AEM API Clients Ecosystem](http://www.slideshare.net/cliffano/building-an-aem-api-clients-ecosystem)
- [Adobe Marketing Cloud Community Expo](http://blog.cliffano.com/2016/11/10/adobe-marketing-cloud-community-expo/)
# License information on Generated Code
The Swagger Codegen project is intended as a benefit for users of the Swagger / Open API Specification. The project itself has the [License](#license) as specified. In addition, please understand the following points:

View File

@ -18,6 +18,8 @@ install:
- cmd: SET MAVEN_OPTS=-XX:MaxPermSize=2g -Xmx4g
- cmd: SET JAVA_OPTS=-XX:MaxPermSize=2g -Xmx4g
- cmd: SET M2_HOME=C:\maven\apache-maven-3.2.5
- cmd: dir/w
# - cmd: RMDIR "C:\projects\swagger-codegen\swagger-samples" /S /Q
- git clone https://github.com/wing328/swagger-samples
- ps: Start-Process -FilePath 'C:\maven\apache-maven-3.2.5\bin\mvn' -ArgumentList 'jetty:run' -WorkingDirectory "$env:appveyor_build_folder\swagger-samples\java\java-jersey-jaxrs"
build_script:
@ -37,6 +39,6 @@ test_script:
# generate all petstore clients
- .\bin\windows\run-all-petstore.cmd
cache:
#cache:
# - C:\maven\
# - C:\Users\appveyor\.m2

View File

@ -27,7 +27,7 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l dart -o samples/client/petstore/dart/swagger"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/dart -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l dart -o samples/client/petstore/dart/swagger"
# then options to generate the library for vm would be:
#ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l dart -o samples/client/petstore/dart/swagger_vm -DbrowserClient=false -DpubName=swagger_vm"

View File

@ -27,6 +27,7 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
#ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l python-flask -o samples/server/petstore/flaskConnexion-python2 -DsupportPython2=true"
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l python-flask -o samples/server/petstore/flaskConnexion-python2 -c bin/supportPython2.json"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/flaskConnexion -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l python-flask -o samples/server/petstore/flaskConnexion-python2 -c bin/supportPython2.json"
rm -rf samples/server/petstore/flaskConnexion-python2/*
java $JAVA_OPTS -Dservice -jar $executable $ags

View File

@ -26,6 +26,7 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l python-flask -o samples/server/petstore/flaskConnexion "
ags="$@ generate -t modules/swagger-codegen/src/main/resources/flaskConnexion -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l python-flask -o samples/server/petstore/flaskConnexion "
rm -rf samples/server/petstore/flaskConnexion/*
java $JAVA_OPTS -Dservice -jar $executable $ags

View File

@ -9,3 +9,4 @@
./bin/java-petstore-retrofit2.sh
./bin/java-petstore-retrofit2rx.sh
./bin/java8-petstore-jersey2.sh
./bin/java-petstore-retrofit2-play24.sh

View File

@ -0,0 +1 @@
{"useBeanValidation":"true","enableBuilderSupport":"true","library":"retrofit2", "usePlay24WS":"true"}

View File

@ -0,0 +1,34 @@
#!/bin/sh
SCRIPT="$0"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
if [ ! -f "$executable" ]
then
mvn clean package
fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-retrofit2-play24.json -o samples/client/petstore/java/retrofit2-play24 -DhideGenerationTimestamp=true"
echo "Removing files and folders under samples/client/petstore/java/retrofit2-play24/src/main"
rm -rf samples/client/petstore/java/retrofit2-play24/src/main
find samples/client/petstore/java/retrofit2-play24 -maxdepth 1 -type f ! -name "README.md" -exec rm {} +
java $JAVA_OPTS -jar $executable $ags

View File

@ -26,6 +26,6 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l jaxrs-cxf-cdi -o samples/server/petstore/jaxrs-cxf-cdi -DhideGenerationTimestamp=true"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l jaxrs-cxf-cdi -o samples/server/petstore/jaxrs-cxf-cdi -DhideGenerationTimestamp=true"
java $JAVA_OPTS -jar $executable $ags

View File

@ -0,0 +1,31 @@
#!/bin/sh
SCRIPT="$0"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
if [ ! -f "$executable" ]
then
mvn clean package
fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l nodejs-server --additional-properties=googleCloudFunctions=true -o samples/server/petstore/nodejs-google-cloud-functions"
java $JAVA_OPTS -Dservice -jar $executable $ags

44
circle.yml Normal file
View File

@ -0,0 +1,44 @@
# work in progress: the goal is to move all the existing tests
# handled by travis-ci to circle CI so that travis-ci can test
# objc/swift API client instead
machine:
environment:
_JAVA_OPTIONS: "-Xms512m -Xmx1024m"
java:
# TODO we also need to test oraclejdk8
version: oraclejdk7
node:
version: 5.0.0
services:
- docker
# Override /etc/hosts
hosts:
petstore.swagger.io: 127.0.0.1
dependencies:
cache_directories:
- ~/.jspm
- ~/.npm
- ~/builder
- ~/.m2
pre:
- export MAVEN_OPTS="-Xmx512m -XX:MaxPermSize=256m"
- gem install bundler
- npm install -g typescript
- sudo pip install virtualenv
# to run petstore server locally via docker
- docker pull swaggerapi/petstore
- docker run -d -e SWAGGER_HOST=http://petstore.swagger.io -e SWAGGER_BASE_PATH=/v2 -p 80:8080 swaggerapi/petstore
- docker ps -a
# show host table to confirm petstore.swagger.io is mapped to localhost
- cat /etc/hosts
override:
#- rvm --default use 2.1.0
#- ruby -v
test:
override:
- mvn verify -Psamples
#- mvn -q clean install
#- jdk_switcher use oraclejdk8
#- mvn -q clean install

341
eclipse-formatter.xml Normal file
View File

@ -0,0 +1,341 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Based on configuration from Google https://github.com/google/styleguide/blob/gh-pages/eclipse-java-google-style.xml
With adjustments for our project - see comments -->
<profiles version="13">
<profile kind="CodeFormatterProfile" name="GoogleStyle" version="13">
<setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.disabling_tag" value="@formatter:off"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_cascading_method_invocation_with_arguments.count_dependent" value="16|-1|16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_field" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.use_on_off_tags" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_prefer_two_fragments" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_ellipsis" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_comment_inline_tags" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_local_variable_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_multiple_fields" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_parameter" value="1040"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_type.count_dependent" value="1585|-1|1585"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_conditional_expression" value="80"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_multiple_fields.count_dependent" value="16|-1|16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_binary_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_array_initializer" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_after_package" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression.count_dependent" value="16|4|80"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration.count_dependent" value="16|4|48"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.continuation_indentation" value="2"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration.count_dependent" value="16|4|49"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_binary_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_package" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_cascading_method_invocation_with_arguments" value="16"/>
<setting id="org.eclipse.jdt.core.compiler.source" value="1.7"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration.count_dependent" value="16|4|48"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_line_comments" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.join_wrapped_lines" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_non_simple_local_variable_annotation" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.align_type_members_on_columns" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_member_type" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_enum_constants.count_dependent" value="16|5|48"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_unary_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.indent_parameter_description" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.lineSplit" value="100"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation.count_dependent" value="16|4|48"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.indentation.size" value="4"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.enabling_tag" value="@formatter:on"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_package" value="1585"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_assignment" value="16"/>
<setting id="org.eclipse.jdt.core.compiler.problem.assertIdentifier" value="error"/>
<setting id="org.eclipse.jdt.core.formatter.tabulation.char" value="space"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_body" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_method" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_non_simple_type_annotation" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_field_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_method_declaration" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_switch" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.compiler.problem.enumIdentifier" value="error"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_generic_type_arguments" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.comment_new_line_at_start_of_html_paragraph" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_ellipsis" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_block" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comment_prefix" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_method_declaration" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.compact_else_if" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_non_simple_parameter_annotation" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_method" value="1585"/>
<setting id="org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.indent_root_tags" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_constant" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression" value="do not insert"/>
<!-- We use 4 spaces to separate, not 2 -->
<setting id="org.eclipse.jdt.core.formatter.tabulation.size" value="4"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation.count_dependent" value="16|5|80"/>
<setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_parameter.count_dependent" value="1040|-1|1040"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_package.count_dependent" value="1585|-1|1585"/>
<setting id="org.eclipse.jdt.core.formatter.indent_empty_lines" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.force_if_else_statement_brace" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_block_in_case" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve" value="3"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_non_simple_package_annotation" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation.count_dependent" value="16|-1|16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_type" value="1585"/>
<setting id="org.eclipse.jdt.core.compiler.compliance" value="1.7"/>
<setting id="org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer" value="2"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_unary_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_new_anonymous_class" value="20"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_local_variable.count_dependent" value="1585|-1|1585"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_field.count_dependent" value="1585|-1|1585"/>
<setting id="org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration.count_dependent" value="16|5|80"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_binary_expression" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type" value="insert"/>
<setting id="org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode" value="enabled"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_label" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_javadoc_comments" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant.count_dependent" value="16|-1|16"/>
<setting id="org.eclipse.jdt.core.formatter.comment.line_length" value="100"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_between_import_groups" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_before_binary_operator" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations" value="2"/>
<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_block" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.join_lines_in_comments" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_compact_if" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_imports" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_field" value="1585"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_html" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer.count_dependent" value="16|5|80"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_source_code" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer" value="do not insert"/>
<setting id="org.eclipse.jdt.core.compiler.codegen.targetPlatform" value="1.7"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_resources_in_try" value="80"/>
<setting id="org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_header" value="true"/>
<!-- Leave block comments alone -->
<setting id="org.eclipse.jdt.core.formatter.comment.format_block_comments" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_enum_constants" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration.count_dependent" value="16|4|48"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_method.count_dependent" value="1585|-1|1585"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_type_declaration" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_binary_expression.count_dependent" value="16|-1|16"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_non_simple_member_annotation" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_local_variable" value="1585"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call.count_dependent" value="16|5|80"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_generic_type_arguments.count_dependent" value="16|-1|16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression.count_dependent" value="16|5|80"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration.count_dependent" value="16|5|80"/>
<setting id="org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_after_imports" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_for_statement" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line" value="false"/>
</profile>
</profiles>

View File

@ -61,6 +61,14 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>net.revelc.code</groupId>
<artifactId>formatter-maven-plugin</artifactId>
<configuration>
<!-- Point at the eclipse-formatter.xml in the swagger-codegen parent project directory -->
<configFile>${project.basedir}${file.separator}${project.parent.relativePath}${file.separator}eclipse-formatter.xml</configFile>
</configuration>
</plugin>
</plugins>
</build>

View File

@ -27,7 +27,7 @@
<!-- pass any necessary config options -->
<configOptions>
<dateLibrary>java8</dateLibrary>
<dateLibrary>joda</dateLibrary>
</configOptions>
<!-- override the default library to jersey2 -->
@ -39,17 +39,26 @@
</plugins>
</build>
<dependencies>
<!-- dependencies are needed for the client being generated -->
<!-- dependencies are needed for the client being generated -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>${swagger-annotations-version}</version>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>${swagger-annotations-version}</version>
</dependency>
<!-- You can find the dependencies for the library configuation you chose by looking in JavaClientCodegen.
Then find the corresponding dependency on Maven Central, and set the versions in the property section below -->
<!-- HTTP client: jersey-client -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
@ -57,58 +66,59 @@
<artifactId>jersey-media-multipart</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.22.1</version>
</dependency>
<!-- JSON processing: jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-base</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson-version}</version>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-version}</version>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>2.1.5</version>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${jodatime-version}</version>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>${jackson-version}</version>
</dependency>
<!-- Joda time: if you use it -->
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${jodatime-version}</version>
</dependency>
<!-- Base64 encoding that works in both JVM and Android -->
<dependency>
<groupId>com.brsanthu</groupId>
<artifactId>migbase64</artifactId>
<version>2.2</version>
</dependency>
<!-- test dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-version}</version>
<scope>test</scope>
</dependency>
</dependency>
</dependencies>
<properties>
<swagger-annotations-version>1.5.0</swagger-annotations-version>
<jersey-version>2.12</jersey-version>
<jackson-version>2.4.2</jackson-version>
<jodatime-version>2.3</jodatime-version>
<swagger-annotations-version>1.5.8</swagger-annotations-version>
<jersey-version>2.22.2</jersey-version>
<jackson-version>2.7.0</jackson-version>
<jodatime-version>2.7</jodatime-version>
<maven-plugin-version>1.0.0</maven-plugin-version>
<junit-version>4.8.1</junit-version>
</properties>

View File

@ -83,5 +83,15 @@
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>net.revelc.code</groupId>
<artifactId>formatter-maven-plugin</artifactId>
<configuration>
<!-- Point at the eclipse-formatter.xml in the swagger-codegen parent project directory -->
<configFile>${project.basedir}${file.separator}${project.parent.relativePath}${file.separator}eclipse-formatter.xml</configFile>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -110,6 +110,14 @@
<artifactId>maven-release-plugin</artifactId>
<version>2.5.3</version>
</plugin>
<plugin>
<groupId>net.revelc.code</groupId>
<artifactId>formatter-maven-plugin</artifactId>
<configuration>
<!-- Point at the eclipse-formatter.xml in the swagger-codegen parent project directory -->
<configFile>${project.basedir}${file.separator}${project.parent.relativePath}${file.separator}eclipse-formatter.xml</configFile>
</configuration>
</plugin>
</plugins>
</build>
<profiles>

View File

@ -16,6 +16,9 @@ public class CodegenConstants {
public static final String INVOKER_PACKAGE = "invokerPackage";
public static final String INVOKER_PACKAGE_DESC = "root package for generated code";
public static final String PHP_INVOKER_PACKAGE = "phpInvokerPackage";
public static final String PHP_INVOKER_PACKAGE_DESC = "root package for generated php code";
public static final String GROUP_ID = "groupId";
public static final String GROUP_ID_DESC = "groupId in generated pom.xml";
@ -25,12 +28,18 @@ public class CodegenConstants {
public static final String ARTIFACT_VERSION = "artifactVersion";
public static final String ARTIFACT_VERSION_DESC = "artifact version in generated pom.xml";
public static final String LICENSE_NAME = "licenseName";
public static final String LICENSE_NAME_DESC = "The name of the license";
public static final String LICENSE_URL = "licenseUrl";
public static final String LICENSE_URL_DESC = "The URL of the license";
public static final String SOURCE_FOLDER = "sourceFolder";
public static final String SOURCE_FOLDER_DESC = "source folder for generated code";
public static final String IMPL_FOLDER = "implFolder";
public static final String IMPL_FOLDER_DESC = "folder for generated implementation code";
public static final String LOCAL_VARIABLE_PREFIX = "localVariablePrefix";
public static final String LOCAL_VARIABLE_PREFIX_DESC = "prefix for generated code members and local variables";
@ -48,13 +57,13 @@ public class CodegenConstants {
public static final String USE_DATETIME_OFFSET = "useDateTimeOffset";
public static final String USE_DATETIME_OFFSET_DESC = "Use DateTimeOffset to model date-time properties";
public static final String ENSURE_UNIQUE_PARAMS = "ensureUniqueParams";
public static final String ENSURE_UNIQUE_PARAMS_DESC = "Whether to ensure parameter names are unique in an operation (rename parameters that are not).";
public static final String PACKAGE_NAME = "packageName";
public static final String PACKAGE_VERSION = "packageVersion";
public static final String PACKAGE_TITLE = "packageTitle";
public static final String PACKAGE_TITLE_DESC = "Specifies an AssemblyTitle for the .NET Framework global assembly attributes stored in the AssemblyInfo file.";
public static final String PACKAGE_PRODUCTNAME = "packageProductName";
@ -65,7 +74,7 @@ public class CodegenConstants {
public static final String PACKAGE_COMPANY_DESC = "Specifies an AssemblyCompany for the .NET Framework global assembly attributes stored in the AssemblyInfo file.";
public static final String PACKAGE_COPYRIGHT = "packageCopyright";
public static final String PACKAGE_COPYRIGHT_DESC = "Specifies an AssemblyCopyright for the .NET Framework global assembly attributes stored in the AssemblyInfo file.";
public static final String POD_VERSION = "podVersion";
public static final String OPTIONAL_METHOD_ARGUMENT = "optionalMethodArgument";
@ -79,13 +88,13 @@ public class CodegenConstants {
public static final String RETURN_ICOLLECTION = "returnICollection";
public static final String RETURN_ICOLLECTION_DESC = "Return ICollection<T> instead of the concrete type.";
public static final String OPTIONAL_PROJECT_FILE = "optionalProjectFile";
public static final String OPTIONAL_PROJECT_FILE_DESC = "Generate {PackageName}.csproj.";
public static final String OPTIONAL_PROJECT_GUID = "packageGuid";
public static final String OPTIONAL_PROJECT_GUID_DESC = "The GUID that will be associated with the C# project";
public static final String MODEL_PROPERTY_NAMING = "modelPropertyNaming";
public static final String MODEL_PROPERTY_NAMING_DESC = "Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name";
@ -132,5 +141,4 @@ public class CodegenConstants {
public static final String GENERATE_PROPERTY_CHANGED = "generatePropertyChanged";
public static final String GENERATE_PROPERTY_CHANGED_DESC = "Specifies that models support raising property changed events.";
}

View File

@ -17,6 +17,7 @@ public class CodegenModel {
// References to parent and interface CodegenModels. Only set when code generator supports inheritance.
public CodegenModel parentModel;
public List<CodegenModel> interfaceModels;
public List<CodegenModel> children;
public String name, classname, title, description, classVarName, modelJson, dataType;
public String classFilename; // store the class file name, mainly used for import
@ -38,8 +39,8 @@ public class CodegenModel {
public Set<String> allMandatory;
public Set<String> imports = new TreeSet<String>();
public Boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum, hasRequired, isArrayModel, hasChildren;
public Boolean hasOnlyReadOnly = true; // true if all properties are read-only
public boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum, hasRequired, isArrayModel, hasChildren;
public boolean hasOnlyReadOnly = true; // true if all properties are read-only
public ExternalDocs externalDocs;
public Map<String, Object> vendorExtensions;
@ -114,15 +115,15 @@ public class CodegenModel {
return false;
if (imports != null ? !imports.equals(that.imports) : that.imports != null)
return false;
if (hasVars != null ? !hasVars.equals(that.hasVars) : that.hasVars != null)
if (hasVars != that.hasVars)
return false;
if (emptyVars != null ? !emptyVars.equals(that.emptyVars) : that.emptyVars != null)
if (emptyVars != that.emptyVars)
return false;
if (hasMoreModels != null ? !hasMoreModels.equals(that.hasMoreModels) : that.hasMoreModels != null)
if (hasMoreModels != that.hasMoreModels)
return false;
if (hasEnums != null ? !hasEnums.equals(that.hasEnums) : that.hasEnums != null)
if (hasEnums != that.hasEnums)
return false;
if (isEnum != null ? !isEnum.equals(that.isEnum) : that.isEnum != null)
if (isEnum != that.isEnum)
return false;
if (externalDocs != null ? !externalDocs.equals(that.externalDocs) : that.externalDocs != null)
return false;
@ -162,11 +163,11 @@ public class CodegenModel {
result = 31 * result + (mandatory != null ? mandatory.hashCode() : 0);
result = 31 * result + (allMandatory != null ? allMandatory.hashCode() : 0);
result = 31 * result + (imports != null ? imports.hashCode() : 0);
result = 31 * result + (hasVars != null ? hasVars.hashCode() : 0);
result = 31 * result + (emptyVars != null ? emptyVars.hashCode() : 0);
result = 31 * result + (hasMoreModels != null ? hasMoreModels.hashCode() : 0);
result = 31 * result + (hasEnums != null ? hasEnums.hashCode() : 0);
result = 31 * result + (isEnum != null ? isEnum.hashCode() : 0);
result = 31 * result + (hasVars ? 13:31);
result = 31 * result + (emptyVars ? 13:31);
result = 31 * result + (hasMoreModels ? 13:31);
result = 31 * result + (hasEnums ? 13:31);
result = 31 * result + (isEnum ? 13:31);
result = 31 * result + (externalDocs != null ? externalDocs.hashCode() : 0);
result = 31 * result + (vendorExtensions != null ? vendorExtensions.hashCode() : 0);
result = 31 * result + Objects.hash(hasOnlyReadOnly);

View File

@ -11,10 +11,10 @@ import java.util.Arrays;
public class CodegenOperation {
public final List<CodegenProperty> responseHeaders = new ArrayList<CodegenProperty>();
public Boolean hasAuthMethods, hasConsumes, hasProduces, hasParams, hasOptionalParams,
public boolean hasAuthMethods, hasConsumes, hasProduces, hasParams, hasOptionalParams,
returnTypeIsPrimitive, returnSimpleType, subresourceOperation, isMapContainer,
isListContainer, isMultipart, hasMore = Boolean.TRUE,
isResponseBinary = Boolean.FALSE, hasReference = Boolean.FALSE,
isListContainer, isMultipart, hasMore = true,
isResponseBinary = false, isResponseFile = false, hasReference = false,
isRestfulIndex, isRestfulShow, isRestfulCreate, isRestfulUpdate, isRestfulDestroy,
isRestful;
public String path, operationId, returnType, httpMethod, returnBaseType,
@ -189,33 +189,35 @@ public class CodegenOperation {
if (responseHeaders != null ? !responseHeaders.equals(that.responseHeaders) : that.responseHeaders != null)
return false;
if (hasAuthMethods != null ? !hasAuthMethods.equals(that.hasAuthMethods) : that.hasAuthMethods != null)
if (hasAuthMethods != that.hasAuthMethods)
return false;
if (hasConsumes != null ? !hasConsumes.equals(that.hasConsumes) : that.hasConsumes != null)
if (hasConsumes != that.hasConsumes)
return false;
if (hasProduces != null ? !hasProduces.equals(that.hasProduces) : that.hasProduces != null)
if (hasProduces != that.hasProduces)
return false;
if (hasParams != null ? !hasParams.equals(that.hasParams) : that.hasParams != null)
if (hasParams != that.hasParams)
return false;
if (hasOptionalParams != null ? !hasOptionalParams.equals(that.hasOptionalParams) : that.hasOptionalParams != null)
if (hasOptionalParams != that.hasOptionalParams)
return false;
if (returnTypeIsPrimitive != null ? !returnTypeIsPrimitive.equals(that.returnTypeIsPrimitive) : that.returnTypeIsPrimitive != null)
if (returnTypeIsPrimitive != that.returnTypeIsPrimitive)
return false;
if (returnSimpleType != null ? !returnSimpleType.equals(that.returnSimpleType) : that.returnSimpleType != null)
if (returnSimpleType != that.returnSimpleType)
return false;
if (subresourceOperation != null ? !subresourceOperation.equals(that.subresourceOperation) : that.subresourceOperation != null)
if (subresourceOperation != that.subresourceOperation)
return false;
if (isMapContainer != null ? !isMapContainer.equals(that.isMapContainer) : that.isMapContainer != null)
if (isMapContainer != that.isMapContainer)
return false;
if (isListContainer != null ? !isListContainer.equals(that.isListContainer) : that.isListContainer != null)
if (isListContainer != that.isListContainer)
return false;
if (isMultipart != null ? !isMultipart.equals(that.isMultipart) : that.isMultipart != null)
if (isMultipart != that.isMultipart)
return false;
if (hasMore != null ? !hasMore.equals(that.hasMore) : that.hasMore != null)
if (hasMore != that.hasMore)
return false;
if (isResponseBinary != null ? !isResponseBinary.equals(that.isResponseBinary) : that.isResponseBinary != null)
if (isResponseBinary != that.isResponseBinary)
return false;
if (hasReference != null ? !hasReference.equals(that.hasReference) : that.hasReference != null)
if (hasReference != that.hasReference)
return false;
if (isResponseFile != that.isResponseFile)
return false;
if (path != null ? !path.equals(that.path) : that.path != null)
return false;
@ -284,20 +286,21 @@ public class CodegenOperation {
@Override
public int hashCode() {
int result = responseHeaders.hashCode();
result = 31 * result + (hasAuthMethods != null ? hasAuthMethods.hashCode() : 0);
result = 31 * result + (hasConsumes != null ? hasConsumes.hashCode() : 0);
result = 31 * result + (hasProduces != null ? hasProduces.hashCode() : 0);
result = 31 * result + (hasParams != null ? hasParams.hashCode() : 0);
result = 31 * result + (hasOptionalParams != null ? hasOptionalParams.hashCode() : 0);
result = 31 * result + (returnTypeIsPrimitive != null ? returnTypeIsPrimitive.hashCode() : 0);
result = 31 * result + (returnSimpleType != null ? returnSimpleType.hashCode() : 0);
result = 31 * result + (subresourceOperation != null ? subresourceOperation.hashCode() : 0);
result = 31 * result + (isMapContainer != null ? isMapContainer.hashCode() : 0);
result = 31 * result + (isListContainer != null ? isListContainer.hashCode() : 0);
result = 31 * result + (isMultipart != null ? isMultipart.hashCode() : 0);
result = 31 * result + (hasMore != null ? hasMore.hashCode() : 0);
result = 31 * result + (isResponseBinary != null ? isResponseBinary.hashCode() : 0);
result = 31 * result + (hasReference != null ? hasReference.hashCode() : 0);
result = 31 * result + (hasAuthMethods ? 13:31);
result = 31 * result + (hasConsumes ? 13:31);
result = 31 * result + (hasProduces ? 13:31);
result = 31 * result + (hasParams ? 13:31);
result = 31 * result + (hasOptionalParams ? 13:31);
result = 31 * result + (returnTypeIsPrimitive ? 13:31);
result = 31 * result + (returnSimpleType ? 13:31);
result = 31 * result + (subresourceOperation ? 13:31);
result = 31 * result + (isMapContainer ? 13:31);
result = 31 * result + (isListContainer ? 13:31);
result = 31 * result + (isMultipart ? 13:31);
result = 31 * result + (hasMore ? 13:31);
result = 31 * result + (isResponseBinary ? 13:31);
result = 31 * result + (isResponseFile ? 13:31);
result = 31 * result + (hasReference ? 13:31);
result = 31 * result + (path != null ? path.hashCode() : 0);
result = 31 * result + (operationId != null ? operationId.hashCode() : 0);
result = 31 * result + (returnType != null ? returnType.hashCode() : 0);

View File

@ -32,7 +32,7 @@ public class CodegenParameter {
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor17.
*/
public Number maximum;
public String maximum;
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor17
*/
@ -40,7 +40,7 @@ public class CodegenParameter {
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor21
*/
public Number minimum;
public String minimum;
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor21
*/
@ -122,7 +122,9 @@ public class CodegenParameter {
if (this.items != null) {
output.items = this.items;
}
output.vendorExtensions = this.vendorExtensions;
if(this.vendorExtensions != null){
output.vendorExtensions = new HashMap<String, Object>(this.vendorExtensions);
}
output.hasValidation = this.hasValidation;
output.isBinary = this.isBinary;
output.isByteArray = this.isByteArray;

View File

@ -1,5 +1,7 @@
package io.swagger.codegen;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@ -28,23 +30,23 @@ public class CodegenProperty implements Cloneable {
public String example;
public String jsonSchema;
public Double minimum;
public Double maximum;
public Boolean exclusiveMinimum;
public Boolean exclusiveMaximum;
public Boolean hasMore, required, secondaryParam;
public Boolean hasMoreNonReadOnly; // for model constructor, true if next properyt is not readonly
public Boolean isPrimitiveType, isContainer, isNotContainer;
public Boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, isBoolean, isDate, isDateTime;
public Boolean isListContainer, isMapContainer;
public String minimum;
public String maximum;
public boolean exclusiveMinimum;
public boolean exclusiveMaximum;
public boolean hasMore, required, secondaryParam;
public boolean hasMoreNonReadOnly; // for model constructor, true if next properyt is not readonly
public boolean isPrimitiveType, isContainer, isNotContainer;
public boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, isFile, isBoolean, isDate, isDateTime;
public boolean isListContainer, isMapContainer;
public boolean isEnum;
public Boolean isReadOnly = false;
public boolean isReadOnly = false;
public List<String> _enum;
public Map<String, Object> allowableValues;
public CodegenProperty items;
public Map<String, Object> vendorExtensions;
public Boolean hasValidation; // true if pattern, maximum, etc are set (only used in the mustache template)
public Boolean isInherited;
public boolean hasValidation; // true if pattern, maximum, etc are set (only used in the mustache template)
public boolean isInherited;
public String nameInCamelCase; // property name in camel case
// enum name based on the property name, usually use as a prefix (e.g. VAR_NAME) for enum name (e.g. VAR_NAME_VALUE1)
public String enumName;
@ -73,16 +75,16 @@ public class CodegenProperty implements Cloneable {
result = prime * result + ((defaultValueWithParam == null) ? 0 : defaultValueWithParam.hashCode());
result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result + ((example == null) ? 0 : example.hashCode());
result = prime * result + ((exclusiveMaximum == null) ? 0 : exclusiveMaximum.hashCode());
result = prime * result + ((exclusiveMinimum == null) ? 0 : exclusiveMinimum.hashCode());
result = prime * result + (exclusiveMaximum ? 13:31);
result = prime * result + (exclusiveMinimum ? 13:31);
result = prime * result + ((getter == null) ? 0 : getter.hashCode());
result = prime * result + ((hasMore == null) ? 0 : hasMore.hashCode());
result = prime * result + ((hasMoreNonReadOnly == null) ? 0 : hasMoreNonReadOnly.hashCode());
result = prime * result + ((isContainer == null) ? 0 : isContainer.hashCode());
result = prime * result + (hasMore ? 13:31);
result = prime * result + ((hasMoreNonReadOnly ? 13:31));
result = prime * result + ((isContainer ? 13:31));
result = prime * result + (isEnum ? 1231 : 1237);
result = prime * result + ((isNotContainer == null) ? 0 : isNotContainer.hashCode());
result = prime * result + ((isPrimitiveType == null) ? 0 : isPrimitiveType.hashCode());
result = prime * result + ((isReadOnly == null) ? 0 : isReadOnly.hashCode());
result = prime * result + ((isNotContainer ? 13:31));
result = prime * result + ((isPrimitiveType ? 13:31));
result = prime * result + ((isReadOnly ? 13:31));
result = prime * result + ((items == null) ? 0 : items.hashCode());
result = prime * result + ((jsonSchema == null) ? 0 : jsonSchema.hashCode());
result = prime * result + ((max == null) ? 0 : max.hashCode());
@ -93,24 +95,25 @@ public class CodegenProperty implements Cloneable {
result = prime * result + ((minimum == null) ? 0 : minimum.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((pattern == null) ? 0 : pattern.hashCode());
result = prime * result + ((required == null) ? 0 : required.hashCode());
result = prime * result + ((secondaryParam == null) ? 0 : secondaryParam.hashCode());
result = prime * result + ((required ? 13:31));
result = prime * result + ((secondaryParam ? 13:31));
result = prime * result + ((setter == null) ? 0 : setter.hashCode());
result = prime * result + ((unescapedDescription == null) ? 0 : unescapedDescription.hashCode());
result = prime * result + ((vendorExtensions == null) ? 0 : vendorExtensions.hashCode());
result = prime * result + ((hasValidation == null) ? 0 : hasValidation.hashCode());
result = prime * result + ((isString == null) ? 0 : isString.hashCode());
result = prime * result + ((isInteger == null) ? 0 : isInteger.hashCode());
result = prime * result + ((isLong == null) ? 0 : isLong.hashCode());
result = prime * result + ((isFloat == null) ? 0 : isFloat.hashCode());
result = prime * result + ((isDouble == null) ? 0 : isDouble.hashCode());
result = prime * result + ((isByteArray == null) ? 0 : isByteArray.hashCode());
result = prime * result + ((isBinary == null) ? 0 : isBinary.hashCode());
result = prime * result + ((isBoolean == null) ? 0 : isBoolean.hashCode());
result = prime * result + ((isDate == null) ? 0 : isDate.hashCode());
result = prime * result + ((isDateTime == null) ? 0 : isDateTime.hashCode());
result = prime * result + ((isMapContainer == null) ? 0 : isMapContainer.hashCode());
result = prime * result + ((isListContainer == null) ? 0 : isListContainer.hashCode());
result = prime * result + ((hasValidation ? 13:31));
result = prime * result + ((isString ? 13:31));
result = prime * result + ((isInteger ? 13:31));
result = prime * result + ((isLong ?13:31));
result = prime * result + ((isFloat ? 13:31));
result = prime * result + ((isDouble ? 13:31));
result = prime * result + ((isByteArray ? 13:31));
result = prime * result + ((isBinary ? 13:31));
result = prime * result + ((isFile ? 13:31));
result = prime * result + ((isBoolean ? 13:31));
result = prime * result + ((isDate ? 13:31));
result = prime * result + ((isDateTime ? 13:31));
result = prime * result + ((isMapContainer ? 13:31));
result = prime * result + ((isListContainer ? 13:31));
result = prime * result + Objects.hashCode(isInherited);
result = prime * result + Objects.hashCode(nameInCamelCase);
result = prime * result + Objects.hashCode(enumName);
@ -189,31 +192,31 @@ public class CodegenProperty implements Cloneable {
if (this.maximum != other.maximum && (this.maximum == null || !this.maximum.equals(other.maximum))) {
return false;
}
if (this.exclusiveMinimum != other.exclusiveMinimum && (this.exclusiveMinimum == null || !this.exclusiveMinimum.equals(other.exclusiveMinimum))) {
if (this.exclusiveMinimum != other.exclusiveMinimum) {
return false;
}
if (this.exclusiveMaximum != other.exclusiveMaximum && (this.exclusiveMaximum == null || !this.exclusiveMaximum.equals(other.exclusiveMaximum))) {
if (this.exclusiveMaximum != other.exclusiveMaximum) {
return false;
}
if (this.required != other.required && (this.required == null || !this.required.equals(other.required))) {
if (this.required != other.required) {
return false;
}
if (this.secondaryParam != other.secondaryParam && (this.secondaryParam == null || !this.secondaryParam.equals(other.secondaryParam))) {
if (this.secondaryParam != other.secondaryParam) {
return false;
}
if (this.isPrimitiveType != other.isPrimitiveType && (this.isPrimitiveType == null || !this.isPrimitiveType.equals(other.isPrimitiveType))) {
if (this.isPrimitiveType != other.isPrimitiveType) {
return false;
}
if (this.isContainer != other.isContainer && (this.isContainer == null || !this.isContainer.equals(other.isContainer))) {
if (this.isContainer != other.isContainer) {
return false;
}
if (this.isNotContainer != other.isNotContainer && (this.isNotContainer == null || !this.isNotContainer.equals(other.isNotContainer))) {
if (this.isNotContainer != other.isNotContainer) {
return false;
}
if (this.isEnum != other.isEnum) {
return false;
}
if (this.isReadOnly != other.isReadOnly && (this.isReadOnly == null || !this.isReadOnly.equals(other.isReadOnly))) {
if (this.isReadOnly != other.isReadOnly) {
return false;
}
if (this._enum != other._enum && (this._enum == null || !this._enum.equals(other._enum))) {
@ -227,45 +230,48 @@ public class CodegenProperty implements Cloneable {
return false;
}
if (this.hasValidation != other.hasValidation && (this.hasValidation == null || !this.hasValidation.equals(other.hasValidation))) {
if (this.hasValidation != other.hasValidation) {
return false;
}
if (this.isString != other.isString && (this.isString == null || !this.isString.equals(other.isString))) {
if (this.isString != other.isString) {
return false;
}
if (this.isInteger != other.isInteger && (this.isInteger == null || !this.isInteger.equals(other.isInteger))) {
if (this.isInteger != other.isInteger) {
return false;
}
if (this.isLong != other.isLong && (this.isLong == null || !this.isLong.equals(other.isLong))) {
if (this.isLong != other.isLong) {
return false;
}
if (this.isFloat != other.isFloat && (this.isFloat == null || !this.isFloat.equals(other.isFloat))) {
if (this.isFloat != other.isFloat) {
return false;
}
if (this.isDouble != other.isDouble && (this.isDouble == null || !this.isDouble.equals(other.isDouble))) {
if (this.isDouble != other.isDouble) {
return false;
}
if (this.isByteArray != other.isByteArray && (this.isByteArray == null || !this.isByteArray.equals(other.isByteArray))) {
if (this.isByteArray != other.isByteArray) {
return false;
}
if (this.isBoolean != other.isBoolean && (this.isBoolean == null || !this.isBoolean.equals(other.isBoolean))) {
if (this.isBoolean != other.isBoolean) {
return false;
}
if (this.isDate != other.isDate && (this.isDate == null || !this.isDate.equals(other.isDate))) {
if (this.isDate != other.isDate) {
return false;
}
if (this.isDateTime != other.isDateTime && (this.isDateTime == null || !this.isDateTime.equals(other.isDateTime))) {
if (this.isDateTime != other.isDateTime) {
return false;
}
if (this.isBinary != other.isBinary && (this.isBinary == null || !this.isBinary.equals(other.isBinary))) {
if (this.isBinary != other.isBinary) {
return false;
}
if (this.isListContainer != other.isListContainer && (this.isListContainer == null || !this.isListContainer.equals(other.isListContainer))) {
if (this.isFile != other.isFile) {
return false;
}
if (this.isMapContainer != other.isMapContainer && (this.isMapContainer == null || !this.isMapContainer.equals(other.isMapContainer))) {
if (this.isListContainer != other.isListContainer) {
return false;
}
if (this.isMapContainer != other.isMapContainer) {
return false;
}
if (!Objects.equals(this.isInherited, other.isInherited)) {
@ -283,9 +289,24 @@ public class CodegenProperty implements Cloneable {
@Override
public CodegenProperty clone() {
try {
return (CodegenProperty) super.clone();
CodegenProperty cp = (CodegenProperty) super.clone();
if (this._enum != null) {
cp._enum = new ArrayList<String>(this._enum);
}
if (this.allowableValues != null) {
cp.allowableValues = new HashMap<String, Object>(this.allowableValues);
}
if (this.items != null) {
cp.items = this.items;
}
if(this.vendorExtensions != null){
cp.vendorExtensions = new HashMap<String, Object>(this.vendorExtensions);
}
return cp;
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
}
}

View File

@ -16,6 +16,7 @@ public class CodegenResponse {
public Boolean isMapContainer;
public Boolean isListContainer;
public Boolean isBinary = Boolean.FALSE;
public Boolean isFile = Boolean.FALSE;
public Object schema;
public String jsonSchema;
@ -63,6 +64,8 @@ public class CodegenResponse {
return false;
if (isBinary != null ? !isBinary.equals(that.isBinary) : that.isBinary != null)
return false;
if (isFile != null ? !isFile.equals(that.isFile) : that.isFile != null)
return false;
if (schema != null ? !schema.equals(that.schema) : that.schema != null)
return false;
return jsonSchema != null ? jsonSchema.equals(that.jsonSchema) : that.jsonSchema == null;
@ -85,6 +88,7 @@ public class CodegenResponse {
result = 31 * result + (isMapContainer != null ? isMapContainer.hashCode() : 0);
result = 31 * result + (isListContainer != null ? isListContainer.hashCode() : 0);
result = 31 * result + (isBinary != null ? isBinary.hashCode() : 0);
result = 31 * result + (isFile != null ? isFile.hashCode() : 0);
result = 31 * result + (schema != null ? schema.hashCode() : 0);
result = 31 * result + (jsonSchema != null ? jsonSchema.hashCode() : 0);
return result;

View File

@ -36,6 +36,7 @@ import io.swagger.models.properties.DateProperty;
import io.swagger.models.properties.DateTimeProperty;
import io.swagger.models.properties.DecimalProperty;
import io.swagger.models.properties.DoubleProperty;
import io.swagger.models.properties.FileProperty;
import io.swagger.models.properties.FloatProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty;
@ -180,6 +181,18 @@ public class DefaultCodegen {
}
}
}
// Let parent know about all its children
for (String name : allModels.keySet()) {
CodegenModel cm = allModels.get(name);
CodegenModel parent = allModels.get(cm.parent);
while (parent != null) {
if (parent.children == null) {
parent.children = new ArrayList<CodegenModel>();
}
parent.children.add(cm);
parent = allModels.get(parent.parent);
}
}
}
return objs;
}
@ -205,7 +218,6 @@ public class DefaultCodegen {
// for enum model
if (Boolean.TRUE.equals(cm.isEnum) && cm.allowableValues != null) {
Map<String, Object> allowableValues = cm.allowableValues;
List<Object> values = (List<Object>) allowableValues.get("values");
List<Map<String, String>> enumVars = new ArrayList<Map<String, String>>();
String commonPrefix = findCommonPrefixOfVars(values);
@ -247,7 +259,6 @@ public class DefaultCodegen {
public String findCommonPrefixOfVars(List<Object> vars) {
try {
String[] listStr = vars.toArray(new String[vars.size()]);
String prefix = StringUtils.getCommonPrefix(listStr);
// exclude trailing characters that should be part of a valid variable
// e.g. ["status-on", "status-off"] => "status-" (not "status-o")
@ -350,7 +361,13 @@ public class DefaultCodegen {
// replace " with \"
// outter unescape to retain the original multi-byte characters
// finally escalate characters avoiding code injection
return escapeUnsafeCharacters(StringEscapeUtils.unescapeJava(StringEscapeUtils.escapeJava(input).replace("\\/", "/")).replaceAll("[\\t\\n\\r]"," ").replace("\\", "\\\\").replace("\"", "\\\""));
return escapeUnsafeCharacters(
StringEscapeUtils.unescapeJava(
StringEscapeUtils.escapeJava(input)
.replace("\\/", "/"))
.replaceAll("[\\t\\n\\r]"," ")
.replace("\\", "\\\\")
.replace("\"", "\\\""));
}
/**
@ -360,7 +377,8 @@ public class DefaultCodegen {
* @return string with unsafe characters removed or escaped
*/
public String escapeUnsafeCharacters(String input) {
LOGGER.warn("escapeUnsafeCharacters should be overridden in the code generator with proper logic to escape unsafe characters");
LOGGER.warn("escapeUnsafeCharacters should be overridden in the code generator with proper logic to escape " +
"unsafe characters");
// doing nothing by default and code generator should implement
// the logic to prevent code injection
// later we'll make this method abstract to make sure
@ -374,7 +392,8 @@ public class DefaultCodegen {
* @return string with quotation mark removed or escaped
*/
public String escapeQuotationMark(String input) {
LOGGER.warn("escapeQuotationMark should be overridden in the code generator with proper logic to escape single/double quote");
LOGGER.warn("escapeQuotationMark should be overridden in the code generator with proper logic to escape " +
"single/double quote");
return input.replace("\"", "\\\"");
}
@ -765,6 +784,7 @@ public class DefaultCodegen {
typeMapping.put("integer", "Integer");
typeMapping.put("ByteArray", "byte[]");
typeMapping.put("binary", "byte[]");
typeMapping.put("file", "File");
instantiationTypes = new HashMap<String, String>();
@ -1069,6 +1089,8 @@ public class DefaultCodegen {
datatype = "ByteArray";
} else if (p instanceof BinaryProperty) {
datatype = "binary";
} else if (p instanceof FileProperty) {
datatype = "file";
} else if (p instanceof BooleanProperty) {
datatype = "boolean";
} else if (p instanceof DateProperty) {
@ -1171,7 +1193,8 @@ public class DefaultCodegen {
}
/**
* Output the proper model name (capitalized)
* Output the proper model name (capitalized).
* In case the name belongs to the TypeSystem it won't be renamed.
*
* @param name the name of the model
* @return capitalized model name
@ -1220,11 +1243,9 @@ public class DefaultCodegen {
m.discriminator = ((ModelImpl) model).getDiscriminator();
}
if (model instanceof ArrayModel) {
ArrayModel am = (ArrayModel) model;
ArrayProperty arrayProperty = new ArrayProperty(am.getItems());
m.hasEnums = false; // Otherwise there will be a NullPointerException in JavaClientCodegen.fromModel
m.isArrayModel = true;
m.arrayModelType = fromProperty(name, arrayProperty).complexType;
addParentContainer(m, name, arrayProperty);
@ -1307,7 +1328,7 @@ public class DefaultCodegen {
addVars(m, properties, required, allProperties, allRequired);
} else {
ModelImpl impl = (ModelImpl) model;
if (m != null && impl.getType() != null) {
if (impl.getType() != null) {
Property p = PropertyBuilder.build(impl.getType(), impl.getFormat(), null);
m.dataType = getSwaggerType(p);
}
@ -1338,7 +1359,7 @@ public class DefaultCodegen {
if (model == null || allDefinitions == null)
return false;
Model child = ((ComposedModel) model).getChild();
Model child = model.getChild();
if (child instanceof ModelImpl && ((ModelImpl) child).getDiscriminator() != null) {
return true;
}
@ -1360,7 +1381,9 @@ public class DefaultCodegen {
addParentContainer(codegenModel, codegenModel.name, mapProperty);
}
protected void addProperties(Map<String, Property> properties, List<String> required, Model model, Map<String, Model> allDefinitions) {
protected void addProperties(Map<String, Property> properties,
List<String> required, Model model,
Map<String, Model> allDefinitions) {
if (model instanceof ModelImpl) {
ModelImpl mi = (ModelImpl) model;
@ -1391,9 +1414,7 @@ public class DefaultCodegen {
if (name == null || name.length() == 0) {
return name;
}
return camelize(toVarName(name));
}
/**
@ -1410,7 +1431,6 @@ public class DefaultCodegen {
}
CodegenProperty property = CodegenModelFactory.newInstance(CodegenModelType.PROPERTY);
property.name = toVarName(name);
property.baseName = name;
property.nameInCamelCase = camelize(property.name, false);
@ -1422,16 +1442,35 @@ public class DefaultCodegen {
property.defaultValue = toDefaultValue(p);
property.defaultValueWithParam = toDefaultValueWithParam(name, p);
property.jsonSchema = Json.pretty(p);
property.isReadOnly = p.getReadOnly();
if (p.getReadOnly() != null) {
property.isReadOnly = p.getReadOnly();
}
property.vendorExtensions = p.getVendorExtensions();
String type = getSwaggerType(p);
if (p instanceof AbstractNumericProperty) {
AbstractNumericProperty np = (AbstractNumericProperty) p;
property.minimum = np.getMinimum();
property.maximum = np.getMaximum();
property.exclusiveMinimum = np.getExclusiveMinimum();
property.exclusiveMaximum = np.getExclusiveMaximum();
if (np.getMinimum() != null) {
if (p instanceof BaseIntegerProperty) { // int, long
property.minimum = String.valueOf(np.getMinimum().longValue());
} else { // double, decimal
property.minimum = String.valueOf(np.getMinimum());
}
}
if (np.getMaximum() != null) {
if (p instanceof BaseIntegerProperty) { // int, long
property.maximum = String.valueOf(np.getMaximum().longValue());
} else { // double, decimal
property.maximum = String.valueOf(np.getMaximum());
}
}
if (np.getExclusiveMinimum() != null) {
property.exclusiveMinimum = np.getExclusiveMinimum();
}
if (np.getExclusiveMaximum() != null) {
property.exclusiveMaximum = np.getExclusiveMaximum();
}
// check if any validation rule defined
// exclusive* are noop without corresponding min/max
@ -1492,7 +1531,6 @@ public class DefaultCodegen {
property.allowableValues = allowableValues;
}*/
}
if (p instanceof IntegerProperty) {
IntegerProperty sp = (IntegerProperty) p;
property.isInteger = true;
@ -1510,7 +1548,6 @@ public class DefaultCodegen {
property.allowableValues = allowableValues;
}
}
if (p instanceof LongProperty) {
LongProperty sp = (LongProperty) p;
property.isLong = true;
@ -1528,21 +1565,21 @@ public class DefaultCodegen {
property.allowableValues = allowableValues;
}
}
if (p instanceof BooleanProperty) {
property.isBoolean = true;
}
if (p instanceof BinaryProperty) {
property.isBinary = true;
}
if (p instanceof FileProperty) {
property.isFile = true;
}
if (p instanceof UUIDProperty) {
property.isString = true;
}
if (p instanceof ByteArrayProperty) {
property.isByteArray = true;
}
// type is number and without format
if (p instanceof DecimalProperty && !(p instanceof DoubleProperty) && !(p instanceof FloatProperty)) {
DecimalProperty sp = (DecimalProperty) p;
@ -1561,7 +1598,6 @@ public class DefaultCodegen {
property.allowableValues = allowableValues;
}*/
}
if (p instanceof DoubleProperty) {
DoubleProperty sp = (DoubleProperty) p;
property.isDouble = true;
@ -1579,7 +1615,6 @@ public class DefaultCodegen {
property.allowableValues = allowableValues;
}
}
if (p instanceof FloatProperty) {
FloatProperty sp = (FloatProperty) p;
property.isFloat = true;
@ -1615,7 +1650,6 @@ public class DefaultCodegen {
property.allowableValues = allowableValues;
}
}
if (p instanceof DateTimeProperty) {
DateTimeProperty sp = (DateTimeProperty) p;
property.isDateTime = true;
@ -1678,25 +1712,26 @@ public class DefaultCodegen {
protected void updatePropertyForArray(CodegenProperty property, CodegenProperty innerProperty) {
if (innerProperty == null) {
LOGGER.warn("skipping invalid array property " + Json.pretty(property));
} else {
if (!languageSpecificPrimitives.contains(innerProperty.baseType)) {
property.complexType = innerProperty.baseType;
} else {
property.isPrimitiveType = true;
}
property.items = innerProperty;
// inner item is Enum
if (isPropertyInnerMostEnum(property)) {
// isEnum is set to true when the type is an enum
// or the inner type of an array/map is an enum
property.isEnum = true;
// update datatypeWithEnum and default value for array
// e.g. List<string> => List<StatusEnum>
updateDataTypeWithEnumForArray(property);
// set allowable values to enum values (including array/map of enum)
property.allowableValues = getInnerEnumAllowableValues(property);
}
return;
}
if (!languageSpecificPrimitives.contains(innerProperty.baseType)) {
property.complexType = innerProperty.baseType;
} else {
property.isPrimitiveType = true;
}
property.items = innerProperty;
// inner item is Enum
if (isPropertyInnerMostEnum(property)) {
// isEnum is set to true when the type is an enum
// or the inner type of an array/map is an enum
property.isEnum = true;
// update datatypeWithEnum and default value for array
// e.g. List<string> => List<StatusEnum>
updateDataTypeWithEnumForArray(property);
// set allowable values to enum values (including array/map of enum)
property.allowableValues = getInnerEnumAllowableValues(property);
}
}
/**
@ -1708,24 +1743,23 @@ public class DefaultCodegen {
if (innerProperty == null) {
LOGGER.warn("skipping invalid map property " + Json.pretty(property));
return;
}
if (!languageSpecificPrimitives.contains(innerProperty.baseType)) {
property.complexType = innerProperty.baseType;
} else {
if (!languageSpecificPrimitives.contains(innerProperty.baseType)) {
property.complexType = innerProperty.baseType;
} else {
property.isPrimitiveType = true;
}
property.items = innerProperty;
// inner item is Enum
if (isPropertyInnerMostEnum(property)) {
// isEnum is set to true when the type is an enum
// or the inner type of an array/map is an enum
property.isEnum = true;
// update datatypeWithEnum and default value for map
// e.g. Dictionary<string, string> => Dictionary<string, StatusEnum>
updateDataTypeWithEnumForMap(property);
// set allowable values to enum values (including array/map of enum)
property.allowableValues = getInnerEnumAllowableValues(property);
}
property.isPrimitiveType = true;
}
property.items = innerProperty;
// inner item is Enum
if (isPropertyInnerMostEnum(property)) {
// isEnum is set to true when the type is an enum
// or the inner type of an array/map is an enum
property.isEnum = true;
// update datatypeWithEnum and default value for map
// e.g. Dictionary<string, string> => Dictionary<string, StatusEnum>
updateDataTypeWithEnumForMap(property);
// set allowable values to enum values (including array/map of enum)
property.allowableValues = getInnerEnumAllowableValues(property);
}
}
@ -1855,7 +1889,11 @@ public class DefaultCodegen {
* @param swagger a Swagger object representing the spec
* @return Codegen Operation object
*/
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Model> definitions, Swagger swagger) {
public CodegenOperation fromOperation(String path,
String httpMethod,
Operation operation,
Map<String, Model> definitions,
Swagger swagger) {
CodegenOperation op = CodegenModelFactory.newInstance(CodegenModelType.OPERATION);
Set<String> imports = new HashSet<String>();
op.vendorExtensions = operation.getVendorExtensions();
@ -1924,7 +1962,7 @@ public class DefaultCodegen {
}
// if "produces" is defined (per operation or using global definition)
if (produces != null && produces.size() > 0) {
if (produces != null && !produces.isEmpty()) {
List<Map<String, String>> c = new ArrayList<Map<String, String>>();
int count = 0;
for (String key : produces) {
@ -1964,6 +2002,9 @@ public class DefaultCodegen {
if (r.isBinary && r.isDefault){
op.isResponseBinary = Boolean.TRUE;
}
if (r.isFile && r.isDefault){
op.isResponseFile = Boolean.TRUE;
}
}
op.responses.get(op.responses.size() - 1).hasMore = false;
@ -1998,14 +2039,14 @@ public class DefaultCodegen {
}
}
if (cm.isContainer != null) {
if (cm.isContainer) {
op.returnContainer = cm.containerType;
if ("map".equals(cm.containerType)) {
op.isMapContainer = Boolean.TRUE;
op.isMapContainer = true;
} else if ("list".equalsIgnoreCase(cm.containerType)) {
op.isListContainer = Boolean.TRUE;
op.isListContainer = true;
} else if ("array".equalsIgnoreCase(cm.containerType)) {
op.isListContainer = Boolean.TRUE;
op.isListContainer = true;
}
} else {
op.returnSimpleType = true;
@ -2163,11 +2204,12 @@ public class DefaultCodegen {
}
r.dataType = cm.datatype;
r.isBinary = isDataTypeBinary(cm.datatype);
if (cm.isContainer != null) {
r.isFile = isDataTypeFile(cm.datatype);
if (cm.isContainer) {
r.simpleType = false;
r.containerType = cm.containerType;
r.isMapContainer = "map".equals(cm.containerType);
r.isListContainer = "list".equals(cm.containerType);
r.isListContainer = "list".equalsIgnoreCase(cm.containerType) || "array".equalsIgnoreCase(cm.containerType);
} else {
r.simpleType = true;
}
@ -2200,27 +2242,36 @@ public class DefaultCodegen {
p.jsonSchema = Json.pretty(param);
if (System.getProperty("debugParser") != null) {
LOGGER.info("working on Parameter " + param);
LOGGER.info("working on Parameter " + param.getName());
}
// move the defaultValue for headers, forms and params
if (param instanceof QueryParameter) {
p.defaultValue = ((QueryParameter) param).getDefaultValue();
QueryParameter qp = (QueryParameter) param;
if(qp.getDefaultValue() != null) {
p.defaultValue = qp.getDefaultValue().toString();
}
} else if (param instanceof HeaderParameter) {
p.defaultValue = ((HeaderParameter) param).getDefaultValue();
HeaderParameter hp = (HeaderParameter) param;
if(hp.getDefaultValue() != null) {
p.defaultValue = hp.getDefaultValue().toString();
}
} else if (param instanceof FormParameter) {
p.defaultValue = ((FormParameter) param).getDefaultValue();
FormParameter fp = (FormParameter) param;
if(fp.getDefaultValue() != null) {
p.defaultValue = fp.getDefaultValue().toString();
}
}
p.vendorExtensions = param.getVendorExtensions();
if (param instanceof SerializableParameter) {
SerializableParameter qp = (SerializableParameter) param;
Property property = null;
Property property;
String collectionFormat = null;
String type = qp.getType();
if (null == type) {
LOGGER.warn("Type is NULL for Serializable Parameter: " + param);
LOGGER.warn("Type is NULL for Serializable Parameter: " + param.getName());
}
if ("array".equals(type)) { // for array parameter
Property inner = qp.getItems();
@ -2234,6 +2285,7 @@ public class DefaultCodegen {
collectionFormat = "csv";
}
CodegenProperty pr = fromProperty("inner", inner);
p.items = pr;
p.baseType = pr.datatype;
p.isContainer = true;
p.isListContainer = true;
@ -2247,6 +2299,7 @@ public class DefaultCodegen {
property = new MapProperty(inner);
collectionFormat = qp.getCollectionFormat();
CodegenProperty pr = fromProperty("inner", inner);
p.items = pr;
p.baseType = pr.datatype;
p.isContainer = true;
p.isMapContainer = true;
@ -2300,9 +2353,16 @@ public class DefaultCodegen {
}
// validation
p.maximum = qp.getMaximum();
// handle maximum, minimum properly for int/long by removing the trailing ".0"
if ("integer".equals(type)) {
p.maximum = qp.getMaximum() == null ? null : String.valueOf(qp.getMaximum().longValue());
p.minimum = qp.getMinimum() == null ? null : String.valueOf(qp.getMinimum().longValue());
} else {
p.maximum = qp.getMaximum() == null ? null : String.valueOf(qp.getMaximum());
p.minimum = qp.getMinimum() == null ? null : String.valueOf(qp.getMinimum());
}
p.exclusiveMaximum = qp.isExclusiveMaximum();
p.minimum = qp.getMinimum();
p.exclusiveMinimum = qp.isExclusiveMinimum();
p.maxLength = qp.getMaxLength();
p.minLength = qp.getMinLength();
@ -2331,7 +2391,7 @@ public class DefaultCodegen {
if (model instanceof ModelImpl) {
ModelImpl impl = (ModelImpl) model;
CodegenModel cm = fromModel(bp.getName(), impl);
if (cm.emptyVars != null && cm.emptyVars == false) {
if (!cm.emptyVars) {
p.dataType = getTypeDeclaration(cm.classname);
imports.add(p.dataType);
} else {
@ -2343,6 +2403,7 @@ public class DefaultCodegen {
p.dataType = cp.datatype;
p.isPrimitiveType = cp.isPrimitiveType;
p.isBinary = isDataTypeBinary(cp.datatype);
p.isFile = isDataTypeFile(cp.datatype);
}
// set boolean flag (e.g. isString)
@ -2360,6 +2421,7 @@ public class DefaultCodegen {
imports.add(cp.complexType);
}
imports.add(cp.baseType);
p.items = cp;
p.dataType = cp.datatype;
p.baseType = cp.complexType;
p.isPrimitiveType = cp.isPrimitiveType;
@ -2389,6 +2451,31 @@ public class DefaultCodegen {
p.paramName = toParamName(bp.getName());
}
// Issue #2561 (neilotoole) : Set the is<TYPE>Param flags.
// This code has been moved to here from #fromOperation
// because these values should be set before calling #postProcessParameter.
// See: https://github.com/swagger-api/swagger-codegen/issues/2561
if (param instanceof QueryParameter) {
p.isQueryParam = true;
} else if (param instanceof PathParameter) {
p.required = true;
p.isPathParam = true;
} else if (param instanceof HeaderParameter) {
p.isHeaderParam = true;
} else if (param instanceof CookieParameter) {
p.isCookieParam = true;
} else if (param instanceof BodyParameter) {
p.isBodyParam = true;
p.isBinary = isDataTypeBinary(p.dataType);
} else if (param instanceof FormParameter) {
if ("file".equalsIgnoreCase(((FormParameter) param).getType()) || "file".equals(p.baseType)) {
p.isFile = true;
} else {
p.notFile = true;
}
p.isFormParam = true;
}
// set the example value
// if not specified in x-example, generate a default value
if (p.vendorExtensions.containsKey("x-example")) {
@ -2409,14 +2496,13 @@ public class DefaultCodegen {
p.example = "BINARY_DATA_HERE";
} else if (Boolean.TRUE.equals(p.isByteArray)) {
p.example = "B";
} else if (Boolean.TRUE.equals(p.isFile)) {
p.example = "/path/to/file.txt";
} else if (Boolean.TRUE.equals(p.isDate)) {
p.example = "2013-10-20";
} else if (Boolean.TRUE.equals(p.isDateTime)) {
p.example = "2013-10-20T19:20:30+01:00";
} else if (param instanceof FormParameter &&
("file".equalsIgnoreCase(((FormParameter) param).getType()) ||
"file".equals(p.baseType))) {
p.isFile = true;
} else if (Boolean.TRUE.equals(p.isFile)) {
p.example = "/path/to/file.txt";
}
@ -2424,33 +2510,6 @@ public class DefaultCodegen {
// should be overridden by lang codegen
setParameterExampleValue(p);
// Issue #2561 (neilotoole) : Set the is<TYPE>Param flags.
// This code has been moved to here from #fromOperation
// because these values should be set before calling #postProcessParameter.
// See: https://github.com/swagger-api/swagger-codegen/issues/2561
if (param instanceof QueryParameter) {
p.isQueryParam = true;
} else if (param instanceof PathParameter) {
p.required = true;
p.isPathParam = true;
} else if (param instanceof HeaderParameter) {
p.isHeaderParam = true;
} else if (param instanceof CookieParameter) {
p.isCookieParam = true;
} else if (param instanceof BodyParameter) {
p.isBodyParam = true;
p.isBinary = isDataTypeBinary(p.dataType);
} else if (param instanceof FormParameter) {
if ("file".equalsIgnoreCase(((FormParameter) param).getType())) {
p.isFile = true;
} else if("file".equals(p.baseType)){
p.isFile = true;
} else {
p.notFile = true;
}
p.isFormParam = true;
}
postProcessParameter(p);
return p;
}
@ -2459,6 +2518,10 @@ public class DefaultCodegen {
return dataType.toLowerCase().startsWith("byte");
}
public boolean isDataTypeFile(String dataType) {
return dataType.toLowerCase().equals("file");
}
/**
* Convert map of Swagger SecuritySchemeDefinition objects to a list of Codegen Security objects
*
@ -2812,8 +2875,8 @@ public class DefaultCodegen {
LOGGER.warn("null property for " + key);
} else {
final CodegenProperty cp = fromProperty(key, prop);
cp.required = mandatory.contains(key) ? true : null;
m.hasRequired = Boolean.TRUE.equals(m.hasRequired) || Boolean.TRUE.equals(cp.required);
cp.required = mandatory.contains(key) ? true : false;
m.hasRequired = m.hasRequired || cp.required;
if (cp.isEnum) {
// FIXME: if supporting inheritance, when called a second time for allProperties it is possible for
// m.hasEnums to be set incorrectly if allProperties has enumerations but properties does not.
@ -2833,7 +2896,7 @@ public class DefaultCodegen {
}
}
if (cp.isContainer != null) {
if (cp.isContainer) {
addImport(m, typeMapping.get("array"));
}
@ -3254,6 +3317,10 @@ public class DefaultCodegen {
} else if (Boolean.TRUE.equals(property.isBinary)) {
parameter.isByteArray = true;
parameter.isPrimitiveType = true;
} else if (Boolean.TRUE.equals(property.isFile)) {
parameter.isFile = true;
// file is *not* a primitive type
//parameter.isPrimitiveType = true;
} else if (Boolean.TRUE.equals(property.isDate)) {
parameter.isDate = true;
parameter.isPrimitiveType = true;
@ -3335,7 +3402,6 @@ public class DefaultCodegen {
if (pattern != null && !pattern.matches("^/.*")) {
return "/" + pattern + "/";
}
return pattern;
}

View File

@ -57,7 +57,7 @@ public class CodegenConfigurator {
private Map<String, String> systemProperties = new HashMap<String, String>();
private Map<String, String> instantiationTypes = new HashMap<String, String>();
private Map<String, String> typeMappings = new HashMap<String, String>();
private Map<String, String> additionalProperties = new HashMap<String, String>();
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
private Map<String, String> importMappings = new HashMap<String, String>();
private Set<String> languageSpecificPrimitives = new HashSet<String>();
private String gitUserId="GIT_USER_ID";
@ -65,7 +65,7 @@ public class CodegenConfigurator {
private String releaseNote="Minor update";
private String httpUserAgent;
private final Map<String, String> dynamicProperties = new HashMap<String, String>(); //the map that holds the JsonAnySetter/JsonAnyGetter values
private final Map<String, Object> dynamicProperties = new HashMap<String, Object>(); //the map that holds the JsonAnySetter/JsonAnyGetter values
public CodegenConfigurator() {
this.setOutputDir(".");
@ -255,16 +255,16 @@ public class CodegenConfigurator {
return this;
}
public Map<String, String> getAdditionalProperties() {
public Map<String, Object> getAdditionalProperties() {
return additionalProperties;
}
public CodegenConfigurator setAdditionalProperties(Map<String, String> additionalProperties) {
public CodegenConfigurator setAdditionalProperties(Map<String, Object> additionalProperties) {
this.additionalProperties = additionalProperties;
return this;
}
public CodegenConfigurator addAdditionalProperty(String key, String value) {
public CodegenConfigurator addAdditionalProperty(String key, Object value) {
this.additionalProperties.put(key, value);
return this;
}
@ -398,12 +398,12 @@ public class CodegenConfigurator {
@JsonAnySetter
public CodegenConfigurator addDynamicProperty(String name, Object value) {
dynamicProperties.put(name, value.toString());
dynamicProperties.put(name, value);
return this;
}
@JsonAnyGetter
public Map<String, String> getDynamicProperties() {
public Map<String, Object> getDynamicProperties() {
return dynamicProperties;
}

View File

@ -3,6 +3,7 @@ package io.swagger.codegen.examples;
import io.swagger.models.Model;
import io.swagger.models.ModelImpl;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BaseIntegerProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.DateProperty;
import io.swagger.models.properties.DateTimeProperty;
@ -93,10 +94,10 @@ public class ExampleGenerator {
};
}
} else if (property instanceof DateProperty) {
return "2000-01-23T04:56:07.000+00:00";
return "2000-01-23";
} else if (property instanceof DateTimeProperty) {
return "2000-01-23T04:56:07.000+00:00";
} else if (property instanceof DecimalProperty) {
} else if (property instanceof DecimalProperty) {
return new BigDecimal(1.3579);
} else if (property instanceof DoubleProperty) {
return 3.149;
@ -108,6 +109,9 @@ public class ExampleGenerator {
return 123;
} else if (property instanceof LongProperty) {
return 123456789L;
// Properties that are not Integer or Long may still be BaseInteger
} else if (property instanceof BaseIntegerProperty) {
return 123;
} else if (property instanceof MapProperty) {
Map<String, Object> mp = new HashMap<String, Object>();
if (property.getName() != null) {

View File

@ -180,7 +180,7 @@ public class XmlExampleGenerator {
if (property.getExample() != null) {
return property.getExample().toString();
} else {
return "2000-01-23T04:56:07.000Z";
return "2000-01-23";
}
} else if (property instanceof IntegerProperty) {
if (property.getExample() != null) {

View File

@ -60,10 +60,10 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
setReservedWordsLowerCase(
Arrays.asList(
// set client as a reserved word to avoid conflicts with IO.Swagger.Client
// set "client" as a reserved word to avoid conflicts with IO.Swagger.Client
// this is a workaround and can be removed if c# api client is updated to use
// fully qualified name
"client",
"client", "parameter",
// local variable names in API methods (endpoints)
"localVarPath", "localVarPathParams", "localVarQueryParams", "localVarHeaderParams",
"localVarFormParams", "localVarFileParams", "localVarStatusCode", "localVarResponse",

View File

@ -52,6 +52,8 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
protected String groupId = "io.swagger";
protected String artifactId = "swagger-java";
protected String artifactVersion = "1.0.0";
protected String licenseName = "Unlicense";
protected String licenseUrl = "http://unlicense.org";
protected String projectFolder = "src" + File.separator + "main";
protected String projectTestFolder = "src" + File.separator + "test";
protected String sourceFolder = projectFolder + File.separator + "java";
@ -116,6 +118,8 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
cliOptions.add(new CliOption(CodegenConstants.GROUP_ID, CodegenConstants.GROUP_ID_DESC));
cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_ID, CodegenConstants.ARTIFACT_ID_DESC));
cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, CodegenConstants.ARTIFACT_VERSION_DESC));
cliOptions.add(new CliOption(CodegenConstants.LICENSE_NAME, CodegenConstants.LICENSE_NAME_DESC));
cliOptions.add(new CliOption(CodegenConstants.LICENSE_URL, CodegenConstants.LICENSE_URL_DESC));
cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC));
cliOptions.add(new CliOption(CodegenConstants.LOCAL_VARIABLE_PREFIX, CodegenConstants.LOCAL_VARIABLE_PREFIX_DESC));
cliOptions.add(CliOption.newBoolean(CodegenConstants.SERIALIZABLE_MODEL, CodegenConstants.SERIALIZABLE_MODEL_DESC));
@ -187,6 +191,18 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);
}
if (additionalProperties.containsKey(CodegenConstants.LICENSE_NAME)) {
this.setLicenseName((String) additionalProperties.get(CodegenConstants.LICENSE_NAME));
} else {
additionalProperties.put(CodegenConstants.LICENSE_NAME, licenseName);
}
if (additionalProperties.containsKey(CodegenConstants.LICENSE_URL)) {
this.setLicenseUrl((String) additionalProperties.get(CodegenConstants.LICENSE_URL));
} else {
additionalProperties.put(CodegenConstants.LICENSE_URL, licenseUrl);
}
if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) {
this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER));
}
@ -253,6 +269,8 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
importMapping.put("ApiModelProperty", "io.swagger.annotations.ApiModelProperty");
importMapping.put("ApiModel", "io.swagger.annotations.ApiModel");
importMapping.put("JsonProperty", "com.fasterxml.jackson.annotation.JsonProperty");
importMapping.put("JsonSubTypes", "com.fasterxml.jackson.annotation.JsonSubTypes");
importMapping.put("JsonTypeInfo", "com.fasterxml.jackson.annotation.JsonTypeInfo");
importMapping.put("JsonCreator", "com.fasterxml.jackson.annotation.JsonCreator");
importMapping.put("JsonValue", "com.fasterxml.jackson.annotation.JsonValue");
importMapping.put("SerializedName", "com.google.gson.annotations.SerializedName");
@ -366,7 +384,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
// sanitize name
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
if ("class".equals(name.toLowerCase())) {
if (name.toLowerCase().matches("^_*class$")) {
return "propertyClass";
}
@ -450,11 +468,20 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
if (inner == null) {
LOGGER.warn(ap.getName() + "(array property) does not have a proper inner type defined");
// TODO maybe better defaulting to StringProperty than returning null
return null;
}
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
if (inner == null) {
LOGGER.warn(mp.getName() + "(map property) does not have a proper inner type defined");
// TODO maybe better defaulting to StringProperty than returning null
return null;
}
return getSwaggerType(p) + "<String, " + getTypeDeclaration(inner) + ">";
}
return super.getTypeDeclaration(p);
@ -470,6 +497,9 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
} else {
pattern = "new ArrayList<%s>()";
}
if (ap.getItems() == null) {
return null;
}
return String.format(pattern, getTypeDeclaration(ap.getItems()));
} else if (p instanceof MapProperty) {
final MapProperty ap = (MapProperty) p;
@ -479,6 +509,9 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
} else {
pattern = "new HashMap<String, %s>()";
}
if (ap.getAdditionalProperties() == null) {
return null;
}
return String.format(pattern, getTypeDeclaration(ap.getAdditionalProperties()));
} else if (p instanceof IntegerProperty) {
IntegerProperty dp = (IntegerProperty) p;
@ -593,21 +626,16 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type;
// don't apply renaming on types from the typeMapping
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type) || type.indexOf(".") >= 0 ||
type.equals("Map") || type.equals("List") ||
type.equals("File") || type.equals("Date")) {
return type;
}
} else {
type = swaggerType;
return typeMapping.get(swaggerType);
}
if (null == type) {
if (null == swaggerType) {
LOGGER.error("No Type defined for Property " + p);
}
return toModelName(type);
return toModelName(swaggerType);
}
@Override
@ -635,12 +663,15 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
if(codegenModel.description != null) {
codegenModel.imports.add("ApiModel");
}
if (codegenModel.discriminator != null && additionalProperties.containsKey("jackson")) {
codegenModel.imports.add("JsonSubTypes");
codegenModel.imports.add("JsonTypeInfo");
}
if (allDefinitions != null && codegenModel.parentSchema != null && codegenModel.hasEnums) {
final Model parentModel = allDefinitions.get(codegenModel.parentSchema);
final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel);
codegenModel = AbstractJavaCodegen.reconcileInlineEnums(codegenModel, parentCodegenModel);
}
return codegenModel;
}
@ -668,7 +699,6 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
model.imports.add("ApiModelProperty");
model.imports.add("ApiModel");
}
return;
}
@Override
@ -713,26 +743,27 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
@Override
public void preprocessSwagger(Swagger swagger) {
if (swagger != null && swagger.getPaths() != null) {
for (String pathname : swagger.getPaths().keySet()) {
Path path = swagger.getPath(pathname);
if (path.getOperations() != null) {
for (Operation operation : path.getOperations()) {
boolean hasFormParameters = false;
for (Parameter parameter : operation.getParameters()) {
if (parameter instanceof FormParameter) {
hasFormParameters = true;
}
}
String defaultContentType = hasFormParameters ? "application/x-www-form-urlencoded" : "application/json";
String contentType = operation.getConsumes() == null || operation.getConsumes().isEmpty()
? defaultContentType : operation.getConsumes().get(0);
String accepts = getAccept(operation);
operation.setVendorExtension("x-contentType", contentType);
operation.setVendorExtension("x-accepts", accepts);
if (swagger == null || swagger.getPaths() == null){
return;
}
for (String pathname : swagger.getPaths().keySet()) {
Path path = swagger.getPath(pathname);
if (path.getOperations() == null){
continue;
}
for (Operation operation : path.getOperations()) {
boolean hasFormParameters = false;
for (Parameter parameter : operation.getParameters()) {
if (parameter instanceof FormParameter) {
hasFormParameters = true;
}
}
String defaultContentType = hasFormParameters ? "application/x-www-form-urlencoded" : "application/json";
String contentType = operation.getConsumes() == null || operation.getConsumes().isEmpty()
? defaultContentType : operation.getConsumes().get(0);
String accepts = getAccept(operation);
operation.setVendorExtension("x-contentType", contentType);
operation.setVendorExtension("x-accepts", accepts);
}
}
}
@ -821,9 +852,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Model> definitions, Swagger swagger) {
CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger);
op.path = sanitizePath(op.path);
return op;
}
@ -835,43 +864,43 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
// Because the child models extend the parents, the enums will be available via the parent.
// Only bother with reconciliation if the parent model has enums.
if (parentCodegenModel.hasEnums) {
if (!parentCodegenModel.hasEnums) {
return codegenModel;
}
// Get the properties for the parent and child models
final List<CodegenProperty> parentModelCodegenProperties = parentCodegenModel.vars;
List<CodegenProperty> codegenProperties = codegenModel.vars;
// Get the properties for the parent and child models
final List<CodegenProperty> parentModelCodegenProperties = parentCodegenModel.vars;
List<CodegenProperty> codegenProperties = codegenModel.vars;
// Iterate over all of the parent model properties
boolean removedChildEnum = false;
for (CodegenProperty parentModelCodegenPropery : parentModelCodegenProperties) {
// Look for enums
if (parentModelCodegenPropery.isEnum) {
// Now that we have found an enum in the parent class,
// and search the child class for the same enum.
Iterator<CodegenProperty> iterator = codegenProperties.iterator();
while (iterator.hasNext()) {
CodegenProperty codegenProperty = iterator.next();
if (codegenProperty.isEnum && codegenProperty.equals(parentModelCodegenPropery)) {
// We found an enum in the child class that is
// a duplicate of the one in the parent, so remove it.
iterator.remove();
removedChildEnum = true;
}
// Iterate over all of the parent model properties
boolean removedChildEnum = false;
for (CodegenProperty parentModelCodegenPropery : parentModelCodegenProperties) {
// Look for enums
if (parentModelCodegenPropery.isEnum) {
// Now that we have found an enum in the parent class,
// and search the child class for the same enum.
Iterator<CodegenProperty> iterator = codegenProperties.iterator();
while (iterator.hasNext()) {
CodegenProperty codegenProperty = iterator.next();
if (codegenProperty.isEnum && codegenProperty.equals(parentModelCodegenPropery)) {
// We found an enum in the child class that is
// a duplicate of the one in the parent, so remove it.
iterator.remove();
removedChildEnum = true;
}
}
}
if(removedChildEnum) {
// If we removed an entry from this model's vars, we need to ensure hasMore is updated
int count = 0, numVars = codegenProperties.size();
for(CodegenProperty codegenProperty : codegenProperties) {
count += 1;
codegenProperty.hasMore = (count < numVars) ? true : null;
}
codegenModel.vars = codegenProperties;
}
}
if(removedChildEnum) {
// If we removed an entry from this model's vars, we need to ensure hasMore is updated
int count = 0, numVars = codegenProperties.size();
for(CodegenProperty codegenProperty : codegenProperties) {
count += 1;
codegenProperty.hasMore = (count < numVars) ? true : false;
}
codegenModel.vars = codegenProperties;
}
return codegenModel;
}
@ -900,6 +929,14 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
this.artifactVersion = artifactVersion;
}
public void setLicenseName(String licenseName) {
this.licenseName = licenseName;
}
public void setLicenseUrl(String licenseUrl) {
this.licenseUrl = licenseUrl;
}
public void setSourceFolder(String sourceFolder) {
this.sourceFolder = sourceFolder;
}
@ -962,7 +999,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
}
return sb.toString();
}
public void setSupportJava6(boolean value) {
this.supportJava6 = value;
}

View File

@ -17,6 +17,7 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
*/
protected static final String JAXRS_TEMPLATE_DIRECTORY_NAME = "JavaJaxRS";
protected String implFolder = "src/main/java";
protected String testResourcesFolder = "src/test/resources";
protected String title = "Swagger Server";
static Logger LOGGER = LoggerFactory.getLogger(AbstractJavaJAXRSServerCodegen.class);

View File

@ -26,6 +26,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
protected String modelPropertyNaming= "camelCase";
protected Boolean supportsES6 = true;
protected HashSet<String> languageGenericTypes;
public AbstractTypeScriptClientCodegen() {
super();
@ -60,6 +61,11 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
"Error",
"Map"
));
languageGenericTypes = new HashSet<String>(Arrays.asList(
"Array"
));
instantiationTypes.put("array", "Array");
typeMapping = new HashMap<String, String>();
@ -101,7 +107,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
}
if (additionalProperties.containsKey(CodegenConstants.SUPPORTS_ES6)) {
setSupportsES6(Boolean.valueOf((String)additionalProperties.get(CodegenConstants.SUPPORTS_ES6)));
setSupportsES6(Boolean.valueOf(additionalProperties.get(CodegenConstants.SUPPORTS_ES6).toString()));
additionalProperties.put("supportsES6", getSupportsES6());
}
}
@ -179,6 +185,12 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
return modelName;
}
if (languageSpecificPrimitives.contains(name)) {
String modelName = camelize("model_" + name);
LOGGER.warn(name + " (model name matches existing language type) cannot be used as a model name. Renamed to " + modelName);
return modelName;
}
// camelize the model name
// phone_number => PhoneNumber
return camelize(name);

View File

@ -54,6 +54,9 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
"localVarFormParams", "localVarContentTypes", "localVarContentType",
"localVarResponse", "localVarBuilder", "authNames", "basePath", "apiInvoker",
// due to namespace collusion
"Object",
// android reserved words
"abstract", "continue", "for", "new", "switch", "assert",
"default", "if", "package", "synchronized", "boolean", "do", "goto", "private",
@ -387,7 +390,6 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
// need to put back serializableModel (boolean) into additionalProperties as value in additionalProperties is string
additionalProperties.put(CodegenConstants.SERIALIZABLE_MODEL, serializableModel);
LOGGER.info("CodegenConstants.SERIALIZABLE_MODEL = " + additionalProperties.get(CodegenConstants.SERIALIZABLE_MODEL));
//make api and model doc path available in mustache template
additionalProperties.put( "apiDocPath", apiDocPath );

View File

@ -199,6 +199,10 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
} else {
setGeneratePropertyChanged(Boolean.valueOf(additionalProperties.get(CodegenConstants.GENERATE_PROPERTY_CHANGED).toString()));
}
if(Boolean.FALSE.equals(this.generatePropertyChanged)) {
additionalProperties.remove(CodegenConstants.GENERATE_PROPERTY_CHANGED);
}
}
additionalProperties.put("targetFrameworkNuget", this.targetFrameworkNuget);

View File

@ -21,6 +21,9 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege
protected String packageVersion = "1.0.0";
protected String clientPackage = "IO.Swagger.Client";
protected String sourceFolder = "src" + File.separator + "main" + File.separator + "CsharpDotNet2";
protected String apiDocPath = "docs/";
protected String modelDocPath = "docs/";
public CsharpDotNet2ClientCodegen() {
super();
@ -35,6 +38,8 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege
embeddedTemplateDir = templateDir = "CsharpDotNet2";
apiPackage = "IO.Swagger.Api";
modelPackage = "IO.Swagger.Model";
modelDocTemplateFiles.put("model_doc.mustache", ".md");
apiDocTemplateFiles.put("api_doc.mustache", ".md");
setReservedWordsLowerCase(
Arrays.asList(
@ -65,6 +70,7 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege
"Integer",
"Long",
"Float",
"Guid?",
"System.IO.Stream", // not really a primitive, we include it to avoid model import
"Object")
);
@ -86,6 +92,7 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege
typeMapping.put("list", "List");
typeMapping.put("map", "Dictionary");
typeMapping.put("object", "Object");
typeMapping.put("uuid", "Guid?");
cliOptions.clear();
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "C# package name (convention: Camel.Case).")
@ -120,6 +127,9 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege
additionalProperties.put(CLIENT_PACKAGE, clientPackage);
}
additionalProperties.put("apiDocPath", apiDocPath);
additionalProperties.put("modelDocPath", modelDocPath);
supportingFiles.add(new SupportingFile("Configuration.mustache",
sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "Configuration.cs"));
supportingFiles.add(new SupportingFile("ApiClient.mustache",
@ -128,7 +138,7 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege
sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "ApiException.cs"));
supportingFiles.add(new SupportingFile("packages.config.mustache", "vendor", "packages.config"));
supportingFiles.add(new SupportingFile("compile-mono.sh.mustache", "", "compile-mono.sh"));
supportingFiles.add(new SupportingFile("README.md", "", "README.md"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
}
@ -290,4 +300,14 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege
return input.replace("*/", "*_/").replace("/*", "/_*");
}
@Override
public String apiDocFileFolder() {
return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar);
}
@Override
public String modelDocFileFolder() {
return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar);
}
}

View File

@ -25,6 +25,8 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String pubVersion = "1.0.0";
protected String pubDescription = "Swagger API client";
protected String sourceFolder = "";
protected String apiDocPath = "docs/";
protected String modelDocPath = "docs/";
public DartClientCodegen() {
super();
@ -39,6 +41,8 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
embeddedTemplateDir = templateDir = "dart";
apiPackage = "lib.api";
modelPackage = "lib.model";
modelDocTemplateFiles.put("object_doc.mustache", ".md");
apiDocTemplateFiles.put("api_doc.mustache", ".md");
setReservedWordsLowerCase(
Arrays.asList(
@ -145,6 +149,10 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER));
}
// make api and model doc path available in mustache template
additionalProperties.put("apiDocPath", apiDocPath);
additionalProperties.put("modelDocPath", modelDocPath);
final String libFolder = sourceFolder + File.separator + "lib";
supportingFiles.add(new SupportingFile("pubspec.mustache", "", "pubspec.yaml"));
supportingFiles.add(new SupportingFile("analysis_options.mustache", "", ".analysis_options"));
@ -160,6 +168,7 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("auth/oauth.mustache", authFolder, "oauth.dart"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
}
@ -179,6 +188,16 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar);
}
@Override
public String apiDocFileFolder() {
return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar);
}
@Override
public String modelDocFileFolder() {
return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar);
}
@Override
public String toVarName(String name) {
// replace - with _ e.g. created-at => created_at

View File

@ -5,17 +5,19 @@ import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import config.ConfigParser;
import io.swagger.codegen.*;
import io.swagger.models.HttpMethod;
import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Swagger;
import io.swagger.models.parameters.Parameter;
import io.swagger.models.properties.*;
import io.swagger.util.Yaml;
import java.io.File;
import java.util.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -27,23 +29,27 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
public static final String DEFAULT_CONTROLLER = "defaultController";
public static final String SUPPORT_PYTHON2= "supportPython2";
protected String apiVersion = "1.0.0";
protected int serverPort = 8080;
protected String projectName = "swagger-server";
protected String packageName;
protected String packageVersion;
protected String controllerPackage;
protected String defaultController;
public FlaskConnexionCodegen() {
super();
modelPackage = "models";
testPackage = "test";
languageSpecificPrimitives.clear();
languageSpecificPrimitives.add("int");
languageSpecificPrimitives.add("float");
languageSpecificPrimitives.add("list");
languageSpecificPrimitives.add("List");
languageSpecificPrimitives.add("Dict");
languageSpecificPrimitives.add("bool");
languageSpecificPrimitives.add("str");
languageSpecificPrimitives.add("datetime");
languageSpecificPrimitives.add("date");
languageSpecificPrimitives.add("file");
typeMapping.clear();
typeMapping.put("integer", "int");
@ -51,8 +57,8 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
typeMapping.put("number", "float");
typeMapping.put("long", "int");
typeMapping.put("double", "float");
typeMapping.put("array", "list");
typeMapping.put("map", "dict");
typeMapping.put("array", "List");
typeMapping.put("map", "Dict");
typeMapping.put("boolean", "bool");
typeMapping.put("string", "str");
typeMapping.put("date", "date");
@ -63,9 +69,9 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
// set the output folder here
outputFolder = "generated-code/connexion";
modelTemplateFiles.clear();
apiTemplateFiles.put("controller.mustache", ".py");
modelTemplateFiles.put("model.mustache", ".py");
apiTestTemplateFiles().put("controller_test.mustache", ".py");
/*
* Template Location. This is the location which templates will be read from. The generator
@ -85,7 +91,6 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
* Additional Properties. These values can be passed to the templates and
* are available in models, apis, and supporting files
*/
additionalProperties.put("apiVersion", apiVersion);
additionalProperties.put("serverPort", serverPort);
/*
@ -93,24 +98,19 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
* entire object tree available. If the input file has a suffix of `.mustache
* it will be processed by the template engine. Otherwise, it will be copied
*/
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("setup.mustache", "", "setup.py"));
supportingFiles.add(new SupportingFile("tox.mustache", "", "tox.ini"));
supportingFiles.add(new SupportingFile("test-requirements.mustache", "", "test-requirements.txt"));
supportingFiles.add(new SupportingFile("requirements.mustache", "", "requirements.txt"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
supportingFiles.add(new SupportingFile("travis.mustache", "", ".travis.yml"));
supportingFiles.add(new SupportingFile("swagger.mustache",
"swagger",
"swagger.yaml")
);
supportingFiles.add(new SupportingFile("app.mustache",
"",
"app.py")
);
supportingFiles.add(new SupportingFile("README.mustache",
"",
"README.md")
);
supportingFiles.add(new SupportingFile("__init__.mustache",
"",
"__init__.py")
);
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "python package name (convention: snake_case).")
.defaultValue("swagger_server"));
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "python package version.")
.defaultValue("1.0.0"));
cliOptions.add(new CliOption(CONTROLLER_PACKAGE, "controller package").
defaultValue("controllers"));
cliOptions.add(new CliOption(DEFAULT_CONTROLLER, "default controller").
@ -124,32 +124,51 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
super.processOpts();
//apiTemplateFiles.clear();
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) {
setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME));
} else {
setPackageName("swagger_server");
additionalProperties.put(CodegenConstants.PACKAGE_NAME, this.packageName);
}
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) {
setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION));
} else {
setPackageVersion("1.0.0");
additionalProperties.put(CodegenConstants.PACKAGE_VERSION, this.packageVersion);
}
if (additionalProperties.containsKey(CONTROLLER_PACKAGE)) {
this.controllerPackage = additionalProperties.get(CONTROLLER_PACKAGE).toString();
}
else {
} else {
this.controllerPackage = "controllers";
additionalProperties.put(CONTROLLER_PACKAGE, this.controllerPackage);
}
if (additionalProperties.containsKey(DEFAULT_CONTROLLER)) {
this.defaultController = additionalProperties.get(DEFAULT_CONTROLLER).toString();
}
else {
} else {
this.defaultController = "default_controller";
additionalProperties.put(DEFAULT_CONTROLLER, this.defaultController);
}
if (Boolean.TRUE.equals(additionalProperties.get(SUPPORT_PYTHON2))) {
additionalProperties.put(SUPPORT_PYTHON2, Boolean.TRUE);
typeMapping.put("long", "long");
}
supportingFiles.add(new SupportingFile("__init__.mustache", packageName, "__init__.py"));
supportingFiles.add(new SupportingFile("__main__.mustache", packageName, "__main__.py"));
supportingFiles.add(new SupportingFile("encoder.mustache", packageName, "encoder.py"));
supportingFiles.add(new SupportingFile("util.mustache", packageName, "util.py"));
supportingFiles.add(new SupportingFile("__init__.mustache", packageName + File.separatorChar + controllerPackage, "__init__.py"));
supportingFiles.add(new SupportingFile("__init__model.mustache", packageName + File.separatorChar + modelPackage, "__init__.py"));
supportingFiles.add(new SupportingFile("base_model_.mustache", packageName + File.separatorChar + modelPackage, "base_model_.py"));
supportingFiles.add(new SupportingFile("__init__test.mustache", packageName + File.separatorChar + testPackage, "__init__.py"));
supportingFiles.add(new SupportingFile("swagger.mustache", packageName + File.separatorChar + "swagger", "swagger.yaml"));
if(!new java.io.File(controllerPackage + File.separator + defaultController + ".py").exists()) {
supportingFiles.add(new SupportingFile("__init__.mustache",
controllerPackage,
"__init__.py")
);
}
modelPackage = packageName + "." + modelPackage;
controllerPackage = packageName + "." + controllerPackage;
testPackage = packageName + "." + testPackage;
}
private static String dropDots(String str) {
return str.replaceAll("\\.", "_");
}
@Override
@ -157,6 +176,7 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
return controllerPackage;
}
/**
* Configures the type of generator.
*
@ -204,6 +224,11 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
return underscore(toApiName(name));
}
@Override
public String toApiTestFilename(String name) {
return "test_" + toApiFilename(name);
}
/**
* Escapes a reserved word as defined in the `reservedWords` array. Handle escaping
* those terms here. This logic is only called if a variable matches the reseved words
@ -224,55 +249,71 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar);
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[str, " + getTypeDeclaration(inner) + "]";
}
return super.getTypeDeclaration(p);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type)) {
return type;
}
} else {
type = toModelName(swaggerType);
}
return type;
}
@Override
public void preprocessSwagger(Swagger swagger) {
if (swagger != null && swagger.getPaths() != null) {
for(String pathname : swagger.getPaths().keySet()) {
Path path = swagger.getPath(pathname);
if (path.getOperations() != null) {
for(Map.Entry<HttpMethod, Operation> entry : path.getOperationMap().entrySet()) {
// Normalize `operationId` and add package/class path in front, e.g.
// controllers.default_controller.add_pet
String httpMethod = entry.getKey().name().toLowerCase();
Operation operation = entry.getValue();
String operationId = getOrGenerateOperationId(operation, pathname, httpMethod);
String controllerName;
if (operation.getTags() != null) {
List<Map<String, String>> tags = new ArrayList<Map<String, String>>();
for(String tag : operation.getTags()) {
Map<String, String> value = new HashMap<String, String>();
value.put("tag", tag);
value.put("hasMore", "true");
tags.add(value);
}
if (tags.size() > 0) {
tags.get(tags.size() - 1).remove("hasMore");
}
// use only the first tag
if (operation.getTags().size() > 0) {
String tag = operation.getTags().get(0);
operation.setTags(Arrays.asList(tag));
controllerName = tag + "_controller";
} else {
controllerName = "default_controller";
}
operation.setVendorExtension("x-tags", tags);
// need vendor extensions for x-swagger-router-controller
Map<String, Path> paths = swagger.getPaths();
if(paths != null) {
for(String pathname : paths.keySet()) {
Path path = paths.get(pathname);
Map<HttpMethod, Operation> operationMap = path.getOperationMap();
if(operationMap != null) {
for(HttpMethod method : operationMap.keySet()) {
Operation operation = operationMap.get(method);
String tag = "default";
if(operation.getTags() != null && operation.getTags().size() > 0) {
tag = operation.getTags().get(0);
}
else {
// no tag found, use "default_controller" as the default
String tag = "default";
operation.setTags(Arrays.asList(tag));
controllerName = tag + "_controller";
String operationId = operation.getOperationId();
if(operationId == null) {
operationId = getOrGenerateOperationId(operation, pathname, method.toString());
}
operation.setOperationId(toOperationId(operationId));
if(operation.getVendorExtensions().get("x-swagger-router-controller") == null) {
operation.getVendorExtensions().put(
"x-swagger-router-controller",
controllerPackage + "." + toApiFilename(tag)
);
}
for (Parameter param: operation.getParameters()) {
// sanitize the param name but don't underscore it since it's used for request mapping
String name = param.getName();
String paramName = sanitizeName(name);
if (!paramName.equals(name)) {
LOGGER.warn(name + " cannot be used as parameter name with flask-connexion and was sanitized as " + paramName);
}
param.setName(paramName);
}
operationId = underscore(sanitizeName(operationId));
operationId = controllerPackage + "." + controllerName + "." + operationId;
operation.setOperationId(operationId);
}
}
}
@ -304,7 +345,7 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
opsByPathEntry.put("path", entry.getKey());
opsByPathEntry.put("operation", entry.getValue());
List<CodegenOperation> operationsForThisPath = Lists.newArrayList(entry.getValue());
operationsForThisPath.get(operationsForThisPath.size() - 1).hasMore = null;
operationsForThisPath.get(operationsForThisPath.size() - 1).hasMore = false;
if (opsByPathList.size() < opsByPath.asMap().size()) {
opsByPathEntry.put("hasMore", "true");
}
@ -333,6 +374,102 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
return super.postProcessSupportingFileData(objs);
}
@Override
public String toVarName(String name) {
// sanitize name
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// remove dollar sign
name = name.replaceAll("$", "");
// if it's all uppper case, convert to lower case
if (name.matches("^[A-Z_]*$")) {
name = name.toLowerCase();
}
// underscore the variable name
// petId => pet_id
name = underscore(name);
// remove leading underscore
name = name.replaceAll("^_*", "");
// for reserved word or word starting with number, append _
if (isReservedWord(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
}
return name;
}
@Override
public String toParamName(String name) {
// Param name is already sanitized in swagger spec processing
return name;
}
@Override
public String toModelFilename(String name) {
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// remove dollar sign
name = name.replaceAll("$", "");
// model name cannot use reserved keyword, e.g. return
if (isReservedWord(name)) {
LOGGER.warn(name + " (reserved word) cannot be used as model filename. Renamed to " + underscore(dropDots("model_" + name)));
name = "model_" + name; // e.g. return => ModelReturn (after camelize)
}
// model name starts with number
if (name.matches("^\\d.*")) {
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + underscore("model_" + name));
name = "model_" + name; // e.g. 200Response => Model200Response (after camelize)
}
if (!StringUtils.isEmpty(modelNamePrefix)) {
name = modelNamePrefix + "_" + name;
}
if (!StringUtils.isEmpty(modelNameSuffix)) {
name = name + "_" + modelNameSuffix;
}
// underscore the model file name
// PhoneNumber => phone_number
return underscore(dropDots(name));
}
@Override
public String toModelName(String name) {
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// remove dollar sign
name = name.replaceAll("$", "");
// model name cannot use reserved keyword, e.g. return
if (isReservedWord(name)) {
LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name));
name = "model_" + name; // e.g. return => ModelReturn (after camelize)
}
// model name starts with number
if (name.matches("^\\d.*")) {
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name));
name = "model_" + name; // e.g. 200Response => Model200Response (after camelize)
}
if (!StringUtils.isEmpty(modelNamePrefix)) {
name = modelNamePrefix + "_" + name;
}
if (!StringUtils.isEmpty(modelNameSuffix)) {
name = name + "_" + modelNameSuffix;
}
// camelize the model name
// phone_number => PhoneNumber
return camelize(name);
}
@Override
public String toOperationId(String operationId) {
operationId = super.toOperationId(operationId); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
@ -344,6 +481,151 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
return underscore(operationId);
}
/**
* Return the default value of the property
*
* @param p Swagger property object
* @return string presentation of the default value of the property
*/
@Override
public String toDefaultValue(Property p) {
if (p instanceof StringProperty) {
StringProperty dp = (StringProperty) p;
if (dp.getDefault() != null) {
return "'" + dp.getDefault() + "'";
}
} else if (p instanceof BooleanProperty) {
BooleanProperty dp = (BooleanProperty) p;
if (dp.getDefault() != null) {
if (dp.getDefault().toString().equalsIgnoreCase("false"))
return "False";
else
return "True";
}
} else if (p instanceof DateProperty) {
// TODO
} else if (p instanceof DateTimeProperty) {
// TODO
} else if (p instanceof DoubleProperty) {
DoubleProperty dp = (DoubleProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof FloatProperty) {
FloatProperty dp = (FloatProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof IntegerProperty) {
IntegerProperty dp = (IntegerProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof LongProperty) {
LongProperty dp = (LongProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
}
return null;
}
@Override
public void setParameterExampleValue(CodegenParameter p) {
String example;
if (p.defaultValue == null) {
example = p.example;
} else {
example = p.defaultValue;
}
String type = p.baseType;
if (type == null) {
type = p.dataType;
}
if ("String".equalsIgnoreCase(type) || "str".equalsIgnoreCase(type)) {
if (example == null) {
example = p.paramName + "_example";
}
example = "'" + escapeText(example) + "'";
} else if ("Integer".equals(type) || "int".equals(type)) {
if(p.minimum != null) {
example = "" + (Integer.valueOf(p.minimum) + 1);
}
if(p.maximum != null) {
example = "" + p.maximum;
} else if (example == null) {
example = "56";
}
} else if ("Long".equalsIgnoreCase(type)) {
if(p.minimum != null) {
example = "" + (Long.valueOf(p.minimum) + 1);
}
if(p.maximum != null) {
example = "" + p.maximum;
} else if (example == null) {
example = "789";
}
} else if ("Float".equalsIgnoreCase(type) || "Double".equalsIgnoreCase(type)) {
if(p.minimum != null) {
example = "" + p.minimum;
} else if(p.maximum != null) {
example = "" + p.maximum;
} else if (example == null) {
example = "3.4";
}
} else if ("BOOLEAN".equalsIgnoreCase(type) || "bool".equalsIgnoreCase(type)) {
if (example == null) {
example = "True";
}
} else if ("file".equalsIgnoreCase(type)) {
example = "(BytesIO(b'some file data'), 'file.txt')";
} else if ("Date".equalsIgnoreCase(type)) {
if (example == null) {
example = "2013-10-20";
}
example = "'" + escapeText(example) + "'";
} else if ("DateTime".equalsIgnoreCase(type)) {
if (example == null) {
example = "2013-10-20T19:20:30+01:00";
}
example = "'" + escapeText(example) + "'";
} else if (!languageSpecificPrimitives.contains(type)) {
// type is a model class, e.g. User
example = type + "()";
} else {
LOGGER.warn("Type " + type + " not handled properly in setParameterExampleValue");
}
if(p.items != null && p.items.defaultValue != null) {
example = p.items.defaultValue;
}
if (example == null) {
example = "None";
} else if (Boolean.TRUE.equals(p.isListContainer)) {
if (Boolean.TRUE.equals(p.isBodyParam)) {
example = "[" + example + "]";
}
} else if (Boolean.TRUE.equals(p.isMapContainer)) {
example = "{'key': " + example + "}";
}
p.example = example;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public void setPackageVersion(String packageVersion) {
this.packageVersion = packageVersion;
}
@Override
public String escapeQuotationMark(String input) {
// remove ' to avoid code injection
@ -355,4 +637,14 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
// remove multiline comment
return input.replace("'''", "'_'_'");
}
@Override
public String toModelImport(String name) {
String modelImport = "from ";
if (!"".equals(modelPackage())) {
modelImport += modelPackage() + ".";
}
modelImport += toModelFilename(name)+ " import " + name;
return modelImport;
}
}

View File

@ -165,7 +165,6 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("api_client.mustache", "", "api_client.go"));
supportingFiles.add(new SupportingFile("api_response.mustache", "", "api_response.go"));
supportingFiles.add(new SupportingFile(".travis.yml", "", ".travis.yml"));
supportingFiles.add(new SupportingFile("LICENSE", "", "LICENSE"));
}
@Override

View File

@ -14,11 +14,14 @@ import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.SupportingFile;
import io.swagger.codegen.languages.features.CXFFeatures;
import io.swagger.codegen.languages.features.LoggingFeatures;
import io.swagger.codegen.languages.features.BeanValidationFeatures;
import io.swagger.codegen.languages.features.GzipTestFeatures;
import io.swagger.codegen.languages.features.JaxbFeatures;
import io.swagger.codegen.languages.features.LoggingTestFeatures;
import io.swagger.models.Operation;
public class JavaCXFClientCodegen extends AbstractJavaCodegen implements CXFFeatures
public class JavaCXFClientCodegen extends AbstractJavaCodegen
implements BeanValidationFeatures, JaxbFeatures, GzipTestFeatures, LoggingTestFeatures
{
private static final Logger LOGGER = LoggerFactory.getLogger(JavaCXFClientCodegen.class);
@ -28,14 +31,13 @@ public class JavaCXFClientCodegen extends AbstractJavaCodegen implements CXFFeat
*/
protected static final String JAXRS_TEMPLATE_DIRECTORY_NAME = "JavaJaxRS";
protected boolean useJaxbAnnotations = true;
protected boolean useBeanValidation = false;
protected boolean useGzipFeature = false;
protected boolean useLoggingFeature = false;
protected boolean useBeanValidationFeature = false;
protected boolean useGzipFeatureForTests = false;
protected boolean useLoggingFeatureForTests = false;
public JavaCXFClientCodegen()
{
@ -67,11 +69,12 @@ public class JavaCXFClientCodegen extends AbstractJavaCodegen implements CXFFeat
embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "cxf";
cliOptions.add(CliOption.newBoolean(USE_JAXB_ANNOTATIONS, "Use JAXB annotations for XML"));
cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations"));
cliOptions.add(CliOption.newBoolean(USE_GZIP_FEATURE, "Use Gzip Feature"));
cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION_FEATURE, "Use BeanValidation Feature"));
cliOptions.add(CliOption.newBoolean(USE_LOGGING_FEATURE, "Use Logging Feature"));
cliOptions.add(CliOption.newBoolean(USE_GZIP_FEATURE_FOR_TESTS, "Use Gzip Feature for tests"));
cliOptions.add(CliOption.newBoolean(USE_LOGGING_FEATURE_FOR_TESTS, "Use Logging Feature for tests"));
}
@ -82,19 +85,19 @@ public class JavaCXFClientCodegen extends AbstractJavaCodegen implements CXFFeat
{
super.processOpts();
if (additionalProperties.containsKey(USE_JAXB_ANNOTATIONS)) {
boolean useJaxbAnnotationsProp = convertPropertyToBooleanAndWriteBack(USE_JAXB_ANNOTATIONS);
this.setUseJaxbAnnotations(useJaxbAnnotationsProp);
}
if (additionalProperties.containsKey(USE_BEANVALIDATION)) {
boolean useBeanValidationProp = convertPropertyToBooleanAndWriteBack(USE_BEANVALIDATION);
this.setUseBeanValidation(useBeanValidationProp);
}
this.setUseGzipFeature(convertPropertyToBooleanAndWriteBack(USE_GZIP_FEATURE));
this.setUseLoggingFeature(convertPropertyToBooleanAndWriteBack(USE_LOGGING_FEATURE));
this.setUseGzipFeatureForTests(convertPropertyToBooleanAndWriteBack(USE_GZIP_FEATURE_FOR_TESTS));
this.setUseLoggingFeatureForTests(convertPropertyToBooleanAndWriteBack(USE_LOGGING_FEATURE_FOR_TESTS));
boolean useBeanValidationFeature = convertPropertyToBooleanAndWriteBack(USE_BEANVALIDATION_FEATURE);
this.setUseBeanValidationFeature(useBeanValidationFeature);
if (useBeanValidationFeature) {
LOGGER.info("make sure your client supports Bean Validation 1.1");
}
supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen
@ -141,18 +144,16 @@ public class JavaCXFClientCodegen extends AbstractJavaCodegen implements CXFFeat
}
public void setUseGzipFeature(boolean useGzipFeature) {
this.useGzipFeature = useGzipFeature;
public void setUseJaxbAnnotations(boolean useJaxbAnnotations) {
this.useJaxbAnnotations = useJaxbAnnotations;
}
public void setUseLoggingFeature(boolean useLoggingFeature) {
this.useLoggingFeature = useLoggingFeature;
public void setUseGzipFeatureForTests(boolean useGzipFeatureForTests) {
this.useGzipFeatureForTests = useGzipFeatureForTests;
}
public void setUseBeanValidationFeature(boolean useBeanValidationFeature) {
this.useBeanValidationFeature = useBeanValidationFeature;
public void setUseLoggingFeatureForTests(boolean useLoggingFeatureForTests) {
this.useLoggingFeatureForTests = useLoggingFeatureForTests;
}
}

View File

@ -14,30 +14,48 @@ import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.SupportingFile;
import io.swagger.codegen.languages.features.CXFServerFeatures;
import io.swagger.codegen.languages.features.GzipTestFeatures;
import io.swagger.codegen.languages.features.JaxbFeatures;
import io.swagger.codegen.languages.features.LoggingTestFeatures;
import io.swagger.models.Operation;
public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen implements CXFServerFeatures
public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen
implements CXFServerFeatures, GzipTestFeatures, LoggingTestFeatures, JaxbFeatures
{
private static final Logger LOGGER = LoggerFactory.getLogger(JavaCXFServerCodegen.class);
protected boolean addConsumesProducesJson = true;
protected boolean useJaxbAnnotations = true;
protected boolean useBeanValidation = false;
protected boolean generateSpringApplication = false;
protected boolean useSpringAnnotationConfig = false;
protected boolean useSwaggerFeature = false;
protected boolean useSwaggerUI = false;
protected boolean useWadlFeature = false;
protected boolean useMultipartFeature = false;
protected boolean useGzipFeature = false;
protected boolean useLoggingFeature = false;
protected boolean useBeanValidationFeature = false;
protected boolean generateSpringBootApplication= false;
protected boolean generateJbossDeploymentDescriptor = false;
protected boolean useGzipFeature = false;
protected boolean useGzipFeatureForTests = false;
protected boolean useLoggingFeature = false;
protected boolean useLoggingFeatureForTests = false;
public JavaCXFServerCodegen()
{
super();
@ -64,18 +82,31 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen impleme
embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "cxf";
cliOptions.add(CliOption.newBoolean(USE_JAXB_ANNOTATIONS, "Use JAXB annotations for XML"));
cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations"));
cliOptions.add(CliOption.newBoolean(GENERATE_SPRING_APPLICATION, "Generate Spring application"));
cliOptions.add(CliOption.newBoolean(USE_SPRING_ANNOTATION_CONFIG, "Use Spring Annotation Config"));
cliOptions.add(CliOption.newBoolean(USE_SWAGGER_FEATURE, "Use Swagger Feature"));
cliOptions.add(CliOption.newBoolean(USE_SWAGGER_UI, "Use Swagger UI"));
cliOptions.add(CliOption.newBoolean(USE_WADL_FEATURE, "Use WADL Feature"));
cliOptions.add(CliOption.newBoolean(USE_MULTIPART_FEATURE, "Use Multipart Feature"));
cliOptions.add(CliOption.newBoolean(USE_GZIP_FEATURE, "Use Gzip Feature"));
cliOptions.add(CliOption.newBoolean(USE_GZIP_FEATURE_FOR_TESTS, "Use Gzip Feature for tests"));
cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION_FEATURE, "Use BeanValidation Feature"));
cliOptions.add(CliOption.newBoolean(USE_LOGGING_FEATURE, "Use Logging Feature"));
cliOptions.add(CliOption.newBoolean(USE_LOGGING_FEATURE_FOR_TESTS, "Use Logging Feature for tests"));
cliOptions.add(CliOption.newBoolean(GENERATE_SPRING_BOOT_APPLICATION, "Generate Spring Boot application"));
cliOptions.add(
CliOption.newBoolean(GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR, "Generate Jboss Deployment Descriptor"));
cliOptions
.add(CliOption.newBoolean(ADD_CONSUMES_PRODUCES_JSON, "Add @Consumes/@Produces Json to API interface"));
}
@ -85,19 +116,33 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen impleme
{
super.processOpts();
if (additionalProperties.containsKey(USE_JAXB_ANNOTATIONS)) {
boolean useJaxbAnnotationsProp = convertPropertyToBooleanAndWriteBack(USE_JAXB_ANNOTATIONS);
this.setUseJaxbAnnotations(useJaxbAnnotationsProp);
}
if (additionalProperties.containsKey(USE_BEANVALIDATION)) {
boolean useBeanValidationProp = convertPropertyToBooleanAndWriteBack(USE_BEANVALIDATION);
this.setUseBeanValidation(useBeanValidationProp);
}
if (additionalProperties.containsKey(ADD_CONSUMES_PRODUCES_JSON)) {
this.setAddConsumesProducesJson(convertPropertyToBooleanAndWriteBack(ADD_CONSUMES_PRODUCES_JSON));
}
if (additionalProperties.containsKey(GENERATE_SPRING_APPLICATION)) {
this.setGenerateSpringApplication(convertPropertyToBooleanAndWriteBack(GENERATE_SPRING_APPLICATION));
this.setUseSwaggerFeature(convertPropertyToBooleanAndWriteBack(USE_SWAGGER_FEATURE));
this.setUseSwaggerUI(convertPropertyToBooleanAndWriteBack(USE_SWAGGER_UI));
this.setUseWadlFeature(convertPropertyToBooleanAndWriteBack(USE_WADL_FEATURE));
this.setUseMultipartFeature(convertPropertyToBooleanAndWriteBack(USE_MULTIPART_FEATURE));
this.setUseGzipFeature(convertPropertyToBooleanAndWriteBack(USE_GZIP_FEATURE));
this.setUseGzipFeatureForTests(convertPropertyToBooleanAndWriteBack(USE_GZIP_FEATURE_FOR_TESTS));
this.setUseLoggingFeature(convertPropertyToBooleanAndWriteBack(USE_LOGGING_FEATURE));
this.setUseLoggingFeatureForTests(convertPropertyToBooleanAndWriteBack(USE_LOGGING_FEATURE_FOR_TESTS));
this.setUseSpringAnnotationConfig(convertPropertyToBooleanAndWriteBack(USE_SPRING_ANNOTATION_CONFIG));
boolean useBeanValidationFeature = convertPropertyToBooleanAndWriteBack(USE_BEANVALIDATION_FEATURE);
this.setUseBeanValidationFeature(useBeanValidationFeature);
@ -107,12 +152,20 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen impleme
this.setGenerateSpringBootApplication(convertPropertyToBooleanAndWriteBack(GENERATE_SPRING_BOOT_APPLICATION));
}
if (additionalProperties.containsKey(GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR)) {
boolean generateJbossDeploymentDescriptorProp = convertPropertyToBooleanAndWriteBack(
GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR);
this.setGenerateJbossDeploymentDescriptor(generateJbossDeploymentDescriptorProp);
}
supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen
writeOptional(outputFolder, new SupportingFile("server/pom.mustache", "", "pom.xml"));
writeOptional(outputFolder,
new SupportingFile("server/swagger-codegen-ignore.mustache", "", ".swagger-codegen-ignore"));
if (this.generateSpringApplication) {
writeOptional(outputFolder, new SupportingFile("server/readme.md", "", "readme.md"));
@ -124,14 +177,19 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen impleme
("src/main/webapp/WEB-INF"), "context.xml"));
// Jboss
writeOptional(outputFolder, new SupportingFile("server/jboss-web.xml.mustache",
("src/main/webapp/WEB-INF"), "jboss-web.xml"));
if (generateJbossDeploymentDescriptor) {
writeOptional(outputFolder, new SupportingFile("server/jboss-web.xml.mustache",
("src/main/webapp/WEB-INF"), "jboss-web.xml"));
}
// Spring Boot
if (this.generateSpringBootApplication) {
writeOptional(outputFolder, new SupportingFile("server/SpringBootApplication.mustache",
(testFolder + '/' + apiPackage).replace(".", "/"), "SpringBootApplication.java"));
writeOptional(outputFolder, new SupportingFile("server/application.properties.mustache",
(testResourcesFolder + '/'), "application.properties"));
}
}
@ -174,6 +232,9 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen impleme
this.generateSpringApplication = generateSpringApplication;
}
public void setUseSpringAnnotationConfig(boolean useSpringAnnotationConfig) {
this.useSpringAnnotationConfig = useSpringAnnotationConfig;
}
public void setUseSwaggerFeature(boolean useSwaggerFeature) {
this.useSwaggerFeature = useSwaggerFeature;
@ -204,7 +265,32 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen impleme
this.useBeanValidationFeature = useBeanValidationFeature;
}
public void setGenerateSpringBootApplication(boolean generateSpringBootApplication) {
public void setGenerateSpringBootApplication(boolean generateSpringBootApplication) {
this.generateSpringBootApplication = generateSpringBootApplication;
}
public void setUseJaxbAnnotations(boolean useJaxbAnnotations) {
this.useJaxbAnnotations = useJaxbAnnotations;
}
public void setGenerateJbossDeploymentDescriptor(boolean generateJbossDeploymentDescriptor) {
this.generateJbossDeploymentDescriptor = generateJbossDeploymentDescriptor;
}
public void setUseGzipFeatureForTests(boolean useGzipFeatureForTests) {
this.useGzipFeatureForTests = useGzipFeatureForTests;
}
public void setUseLoggingFeatureForTests(boolean useLoggingFeatureForTests) {
this.useLoggingFeatureForTests = useLoggingFeatureForTests;
}
public void setUseSwaggerUI(boolean useSwaggerUI) {
this.useSwaggerUI = useSwaggerUI;
}
public void setAddConsumesProducesJson(boolean addConsumesProducesJson) {
this.addConsumesProducesJson = addConsumesProducesJson;
}
}

View File

@ -2,7 +2,7 @@ package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.codegen.languages.features.BeanValidationFeatures;
import io.swagger.codegen.languages.features.PerformBeanValidationFeatures;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
@ -12,13 +12,15 @@ import java.io.File;
import java.util.*;
import java.util.regex.Pattern;
public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValidationFeatures {
public class JavaClientCodegen extends AbstractJavaCodegen
implements BeanValidationFeatures, PerformBeanValidationFeatures {
static final String MEDIA_TYPE = "mediaType";
@SuppressWarnings("hiding")
private static final Logger LOGGER = LoggerFactory.getLogger(JavaClientCodegen.class);
public static final String USE_RX_JAVA = "useRxJava";
public static final String USE_PLAY24_WS = "usePlay24WS";
public static final String PARCELABLE_MODEL = "parcelableModel";
public static final String RETROFIT_1 = "retrofit";
@ -26,8 +28,10 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
protected String gradleWrapperPackage = "gradle.wrapper";
protected boolean useRxJava = false;
protected boolean usePlay24WS = false;
protected boolean parcelableModel = false;
protected boolean useBeanValidation = false;
protected boolean performBeanValidation = false;
public JavaClientCodegen() {
super();
@ -40,8 +44,10 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
cliOptions.add(CliOption.newBoolean(USE_RX_JAVA, "Whether to use the RxJava adapter with the retrofit2 library."));
cliOptions.add(CliOption.newBoolean(PARCELABLE_MODEL, "Whether to generate models for Android that implement Parcelable with the okhttp-gson library."));
cliOptions.add(CliOption.newBoolean(USE_PLAY24_WS, "Use Play! 2.4 Async HTTP client (Play WS API)"));
cliOptions.add(CliOption.newBoolean(SUPPORT_JAVA6, "Whether to support Java6 with the Jersey1 library."));
cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations"));
cliOptions.add(CliOption.newBoolean(PERFORM_BEANVALIDATION, "Perform BeanValidation"));
supportedLibraries.put("jersey1", "HTTP client: Jersey client 1.19.1. JSON processing: Jackson 2.7.0. Enable Java6 support using '-DsupportJava6=true'.");
supportedLibraries.put("feign", "HTTP client: Netflix Feign 8.16.0. JSON processing: Jackson 2.7.0");
@ -81,6 +87,11 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
if (additionalProperties.containsKey(USE_RX_JAVA)) {
this.setUseRxJava(Boolean.valueOf(additionalProperties.get(USE_RX_JAVA).toString()));
}
if (additionalProperties.containsKey(USE_PLAY24_WS)) {
this.setUsePlay24WS(Boolean.valueOf(additionalProperties.get(USE_PLAY24_WS).toString()));
}
additionalProperties.put(USE_PLAY24_WS, usePlay24WS);
if (additionalProperties.containsKey(PARCELABLE_MODEL)) {
this.setParcelableModel(Boolean.valueOf(additionalProperties.get(PARCELABLE_MODEL).toString()));
}
@ -88,11 +99,11 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
additionalProperties.put(PARCELABLE_MODEL, parcelableModel);
if (additionalProperties.containsKey(USE_BEANVALIDATION)) {
boolean useBeanValidationProp = Boolean.valueOf(additionalProperties.get(USE_BEANVALIDATION).toString());
this.setUseBeanValidation(useBeanValidationProp);
this.setUseBeanValidation(convertPropertyToBooleanAndWriteBack(USE_BEANVALIDATION));
}
// write back as boolean
additionalProperties.put(USE_BEANVALIDATION, useBeanValidationProp);
if (additionalProperties.containsKey(PERFORM_BEANVALIDATION)) {
this.setPerformBeanValidation(convertPropertyToBooleanAndWriteBack(PERFORM_BEANVALIDATION));
}
final String invokerFolder = (sourceFolder + '/' + invokerPackage).replace(".", "/");
@ -122,6 +133,11 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
if (performBeanValidation) {
supportingFiles.add(new SupportingFile("BeanValidationException.mustache", invokerFolder,
"BeanValidationException.java"));
}
//TODO: add doc to retrofit1 and feign
if ( "feign".equals(getLibrary()) || "retrofit".equals(getLibrary()) ){
modelDocTemplateFiles.remove("model_doc.mustache");
@ -162,7 +178,34 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
LOGGER.error("Unknown library option (-l/--library): " + getLibrary());
}
if (additionalProperties.containsKey("jackson")) {
if (Boolean.TRUE.equals(additionalProperties.get(USE_PLAY24_WS))) {
// remove unsupported auth
Iterator<SupportingFile> iter = supportingFiles.iterator();
while (iter.hasNext()) {
SupportingFile sf = iter.next();
if (sf.templateFile.startsWith("auth/")) {
iter.remove();
}
}
// auth
supportingFiles.add(new SupportingFile("play24/auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java"));
supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java"));
supportingFiles.add(new SupportingFile("Pair.mustache", invokerFolder, "Pair.java"));
// api client
supportingFiles.add(new SupportingFile("play24/ApiClient.mustache", invokerFolder, "ApiClient.java"));
// adapters
supportingFiles
.add(new SupportingFile("play24/Play24CallFactory.mustache", invokerFolder, "Play24CallFactory.java"));
supportingFiles.add(new SupportingFile("play24/Play24CallAdapterFactory.mustache", invokerFolder,
"Play24CallAdapterFactory.java"));
additionalProperties.put("jackson", "true");
additionalProperties.remove("gson");
}
if (additionalProperties.containsKey("jackson") ) {
supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", invokerFolder, "RFC3339DateFormat.java"));
if ("threetenbp".equals(dateLibrary)) {
supportingFiles.add(new SupportingFile("CustomInstantDeserializer.mustache", invokerFolder, "CustomInstantDeserializer.java"));
@ -300,6 +343,11 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
this.useRxJava = useRxJava;
}
public void setUsePlay24WS(boolean usePlay24WS) {
this.usePlay24WS = usePlay24WS;
}
public void setParcelableModel(boolean parcelableModel) {
this.parcelableModel = parcelableModel;
}
@ -308,6 +356,10 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
this.useBeanValidation = useBeanValidation;
}
public void setPerformBeanValidation(boolean performBeanValidation) {
this.performBeanValidation = performBeanValidation;
}
final private static Pattern JSON_MIME_PATTERN = Pattern.compile("(?i)application\\/json(;.*)?");
final private static Pattern JSON_VENDOR_MIME_PATTERN = Pattern.compile("(?i)application\\/vnd.(.*)+json(;.*)?");

View File

@ -1,12 +1,22 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.SupportingFile;
import java.io.File;
/**
* Generates a Java JAXRS Server according to JAXRS 2.0 specification, assuming an
* Apache CXF runtime and a Java EE runtime with CDI enabled.
* Similar to the original JAXRS generator, this creates API and Service classes
* in /src/gen/java and a sample ServiceImpl in /src/main/java. The API uses CDI
* to get an instance of ServiceImpl that implements the Service interface.
*/
public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen {
/**
* Default constructor
*/
public JavaJAXRSCXFCDIServerCodegen() {
outputFolder = "generated-code/JavaJaxRS-CXF-CDI";
artifactId = "swagger-jaxrs-cxf-cdi-server";
@ -20,7 +30,8 @@ public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen {
typeMapping.put("DateTime", "java.util.Date");
// Updated template directory
embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "cxf-cdi";
embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME
+ File.separator + "cxf-cdi";
}
@Override
@ -31,8 +42,21 @@ public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen {
@Override
public void processOpts() {
super.processOpts();
supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen
// writeOptional means these files are only written if they don't already exist
// POM
writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml"));
// RestApplication into src/main/java
writeOptional(outputFolder, new SupportingFile("RestApplication.mustache",
(implFolder + '/' + invokerPackage).replace(".", "/"), "RestApplication.java"));
// Make CDI work in containers with implicit archive scanning disabled
writeOptional(outputFolder, new SupportingFile("beans.mustache",
"src/main/webapp/WEB-INF", "beans.xml"));
}
@Override
@ -45,7 +69,8 @@ public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen {
@Override
public String getHelp() {
return "Generates a Java JAXRS Server according to JAXRS 2.0 specification, assuming an Apache CXF runtime and a Java EE runtime with CDI enabled.";
return "Generates a Java JAXRS Server according to JAXRS 2.0 specification, assuming an "
+ "Apache CXF runtime and a Java EE runtime with CDI enabled.";
}
}

View File

@ -1,6 +1,7 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.codegen.languages.features.JbossFeature;
import io.swagger.models.Operation;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
@ -8,7 +9,9 @@ import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.util.*;
public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen {
public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen implements JbossFeature {
protected boolean generateJbossDeploymentDescriptor = true;
public JavaResteasyServerCodegen() {
@ -31,6 +34,9 @@ public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen {
dateLibrary = "legacy";// TODO: change to joda
embeddedTemplateDir = templateDir = "JavaJaxRS" + File.separator + "resteasy";
cliOptions.add(
CliOption.newBoolean(GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR, "Generate Jboss Deployment Descriptor"));
}
@Override
@ -47,6 +53,12 @@ public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen {
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey(GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR)) {
boolean generateJbossDeploymentDescriptorProp = convertPropertyToBooleanAndWriteBack(
GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR);
this.setGenerateJbossDeploymentDescriptor(generateJbossDeploymentDescriptorProp);
}
writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml"));
writeOptional(outputFolder, new SupportingFile("gradle.mustache", "", "build.gradle"));
writeOptional(outputFolder, new SupportingFile("settingsGradle.mustache", "", "settings.gradle"));
@ -61,8 +73,12 @@ public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen {
(sourceFolder + '/' + apiPackage).replace(".", "/"), "NotFoundException.java"));
writeOptional(outputFolder, new SupportingFile("web.mustache",
("src/main/webapp/WEB-INF"), "web.xml"));
writeOptional(outputFolder, new SupportingFile("jboss-web.mustache",
if (generateJbossDeploymentDescriptor) {
writeOptional(outputFolder, new SupportingFile("jboss-web.mustache",
("src/main/webapp/WEB-INF"), "jboss-web.xml"));
}
writeOptional(outputFolder, new SupportingFile("RestApplication.mustache",
(sourceFolder + '/' + invokerPackage).replace(".", "/"), "RestApplication.java"));
supportingFiles.add(new SupportingFile("StringUtil.mustache",
@ -198,4 +214,8 @@ public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen {
return objs;
}
public void setGenerateJbossDeploymentDescriptor(boolean generateJbossDeploymentDescriptor) {
this.generateJbossDeploymentDescriptor = generateJbossDeploymentDescriptor;
}
}

View File

@ -927,14 +927,14 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
// set vendor-extension: x-codegen-hasMoreRequired
CodegenProperty lastRequired = null;
for (CodegenProperty var : cm.vars) {
if (var.required != null && var.required) {
if (var.required) {
lastRequired = var;
}
}
for (CodegenProperty var : cm.vars) {
if (var == lastRequired) {
var.vendorExtensions.put("x-codegen-hasMoreRequired", false);
} else if (var.required != null && var.required) {
} else if (var.required) {
var.vendorExtensions.put("x-codegen-hasMoreRequired", true);
}
}
@ -996,7 +996,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
int count = 0, numVars = codegenProperties.size();
for(CodegenProperty codegenProperty : codegenProperties) {
count += 1;
codegenProperty.hasMore = (count < numVars) ? true : null;
codegenProperty.hasMore = (count < numVars) ? true : false;
}
codegenModel.vars = codegenProperties;
}

View File

@ -24,10 +24,16 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
private static final Logger LOGGER = LoggerFactory.getLogger(NodeJSServerCodegen.class);
public static final String GOOGLE_CLOUD_FUNCTIONS = "googleCloudFunctions";
public static final String EXPORTED_NAME = "exportedName";
protected String apiVersion = "1.0.0";
protected int serverPort = 8080;
protected String projectName = "swagger-server";
protected boolean googleCloudFunctions;
protected String exportedName;
public NodeJSServerCodegen() {
super();
@ -76,27 +82,15 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
additionalProperties.put("apiVersion", apiVersion);
additionalProperties.put("serverPort", serverPort);
/*
* Supporting Files. You can write single files for the generator with the
* entire object tree available. If the input file has a suffix of `.mustache
* it will be processed by the template engine. Otherwise, it will be copied
*/
// supportingFiles.add(new SupportingFile("controller.mustache",
// "controllers",
// "controller.js")
// );
supportingFiles.add(new SupportingFile("swagger.mustache",
"api",
"swagger.yaml")
);
writeOptional(outputFolder, new SupportingFile("index.mustache", "", "index.js"));
writeOptional(outputFolder, new SupportingFile("package.mustache", "", "package.json"));
writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md"));
if (System.getProperty("noservice") == null) {
apiTemplateFiles.put(
"service.mustache", // the template to use
"Service.js"); // the extension for each file to write
}
cliOptions.add(CliOption.newBoolean(GOOGLE_CLOUD_FUNCTIONS,
"When specified, it will generate the code which runs within Google Cloud Functions "
+ "instead of standalone Node.JS server. See "
+ "https://cloud.google.com/functions/docs/quickstart for the details of how to "
+ "deploy the generated code."));
cliOptions.add(new CliOption(EXPORTED_NAME,
"When the generated code will be deployed to Google Cloud Functions, this option can be "
+ "used to update the name of the exported function. By default, it refers to the "
+ "basePath. This does not affect normal standalone nodejs server code."));
}
@Override
@ -171,6 +165,22 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar);
}
public boolean getGoogleCloudFunctions() {
return googleCloudFunctions;
}
public void setGoogleCloudFunctions(boolean value) {
googleCloudFunctions = value;
}
public String getExportedName() {
return exportedName;
}
public void setExportedName(String name) {
exportedName = name;
}
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
@SuppressWarnings("unchecked")
@ -231,7 +241,7 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
opsByPathEntry.put("path", entry.getKey());
opsByPathEntry.put("operation", entry.getValue());
List<CodegenOperation> operationsForThisPath = Lists.newArrayList(entry.getValue());
operationsForThisPath.get(operationsForThisPath.size() - 1).hasMore = null;
operationsForThisPath.get(operationsForThisPath.size() - 1).hasMore = false;
if (opsByPathList.size() < opsByPath.asMap().size()) {
opsByPathEntry.put("hasMore", "true");
}
@ -240,6 +250,46 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
return opsByPathList;
}
@Override
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey(GOOGLE_CLOUD_FUNCTIONS)) {
setGoogleCloudFunctions(
Boolean.valueOf(additionalProperties.get(GOOGLE_CLOUD_FUNCTIONS).toString()));
}
if (additionalProperties.containsKey(EXPORTED_NAME)) {
setExportedName((String)additionalProperties.get(EXPORTED_NAME));
}
/*
* Supporting Files. You can write single files for the generator with the
* entire object tree available. If the input file has a suffix of `.mustache
* it will be processed by the template engine. Otherwise, it will be copied
*/
// supportingFiles.add(new SupportingFile("controller.mustache",
// "controllers",
// "controller.js")
// );
supportingFiles.add(new SupportingFile("swagger.mustache",
"api",
"swagger.yaml")
);
if (getGoogleCloudFunctions()) {
writeOptional(outputFolder, new SupportingFile("index-gcf.mustache", "", "index.js"));
} else {
writeOptional(outputFolder, new SupportingFile("index.mustache", "", "index.js"));
}
writeOptional(outputFolder, new SupportingFile("package.mustache", "", "package.json"));
writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md"));
if (System.getProperty("noservice") == null) {
apiTemplateFiles.put(
"service.mustache", // the template to use
"Service.js"); // the extension for each file to write
}
}
@Override
public void preprocessSwagger(Swagger swagger) {
String host = swagger.getHost();
@ -262,6 +312,22 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
}
}
if (getGoogleCloudFunctions()) {
// Note that Cloud Functions don't allow customizing port name, simply checking host
// is good enough.
if (!host.endsWith(".cloudfunctions.net")) {
LOGGER.warn("Host " + host + " seems not matching with cloudfunctions.net URL.");
}
if (!additionalProperties.containsKey(EXPORTED_NAME)) {
String basePath = swagger.getBasePath();
if (basePath == null || basePath.equals("/")) {
LOGGER.warn("Cannot find the exported name properly. Using 'openapi' as the exported name");
basePath = "/openapi";
}
additionalProperties.put(EXPORTED_NAME, basePath.substring(1));
}
}
// need vendor extensions for x-swagger-router-controller
Map<String, Path> paths = swagger.getPaths();
if(paths != null) {

View File

@ -22,7 +22,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
public static final String AUTHOR_EMAIL = "authorEmail";
public static final String LICENSE = "license";
public static final String GIT_REPO_URL = "gitRepoURL";
public static final String DEFAULT_LICENSE = "Apache License, Version 2.0";
public static final String DEFAULT_LICENSE = "Proprietary";
public static final String CORE_DATA = "coreData";
protected Set<String> foundationClasses = new HashSet<String>();

View File

@ -304,8 +304,6 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile(".travis.yml", getPackagePath(), ".travis.yml"));
supportingFiles.add(new SupportingFile(".php_cs", getPackagePath(), ".php_cs"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", getPackagePath(), "git_push.sh"));
// apache v2 license
supportingFiles.add(new SupportingFile("LICENSE", getPackagePath(), "LICENSE"));
}
@Override

View File

@ -170,7 +170,6 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
apiPackage = swaggerFolder + File.separatorChar + "apis";
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("LICENSE", "", "LICENSE"));
supportingFiles.add(new SupportingFile("setup.mustache", "", "setup.py"));
supportingFiles.add(new SupportingFile("tox.mustache", "", "tox.ini"));

View File

@ -42,7 +42,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String gemVersion = "1.0.0";
protected String specFolder = "spec";
protected String libFolder = "lib";
protected String gemLicense = "Apache-2.0";
protected String gemLicense = "proprietary";
protected String gemRequiredRubyVersion = ">= 1.9";
protected String gemHomepage = "http://swagger.io";
protected String gemSummary = "A ruby wrapper for the swagger APIs";
@ -143,7 +143,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
cliOptions.add(new CliOption(GEM_VERSION, "gem version.").defaultValue("1.0.0"));
cliOptions.add(new CliOption(GEM_LICENSE, "gem license. ").
defaultValue("Apache-2.0"));
defaultValue("proprietary"));
cliOptions.add(new CliOption(GEM_REQUIRED_RUBY_VERSION, "gem required Ruby version. ").
defaultValue(">= 1.9"));
@ -250,6 +250,8 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
supportingFiles.add(new SupportingFile("Rakefile.mustache", "", "Rakefile"));
supportingFiles.add(new SupportingFile("Gemfile.mustache", "", "Gemfile"));
// test files should not be overwritten
writeOptional(outputFolder, new SupportingFile("rspec.mustache", "", ".rspec"));

View File

@ -1,462 +1,466 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Swagger;
import java.io.File;
import java.util.*;
public class SpringCodegen extends AbstractJavaCodegen {
public static final String DEFAULT_LIBRARY = "spring-boot";
public static final String TITLE = "title";
public static final String CONFIG_PACKAGE = "configPackage";
public static final String BASE_PACKAGE = "basePackage";
public static final String INTERFACE_ONLY = "interfaceOnly";
public static final String SINGLE_CONTENT_TYPES = "singleContentTypes";
public static final String JAVA_8 = "java8";
public static final String ASYNC = "async";
public static final String RESPONSE_WRAPPER = "responseWrapper";
public static final String SPRING_MVC_LIBRARY = "spring-mvc";
public static final String SPRING_CLOUD_LIBRARY = "spring-cloud";
protected String title = "swagger-petstore";
protected String configPackage = "io.swagger.configuration";
protected String basePackage = "io.swagger";
protected boolean interfaceOnly = false;
protected boolean singleContentTypes = false;
protected boolean java8 = false;
protected boolean async = false;
protected String responseWrapper = "";
public SpringCodegen() {
super();
outputFolder = "generated-code/javaSpring";
apiTestTemplateFiles.clear(); // TODO: add test template
embeddedTemplateDir = templateDir = "JavaSpring";
apiPackage = "io.swagger.api";
modelPackage = "io.swagger.model";
invokerPackage = "io.swagger.api";
artifactId = "swagger-spring";
additionalProperties.put(CONFIG_PACKAGE, configPackage);
additionalProperties.put(BASE_PACKAGE, basePackage);
// spring uses the jackson lib
additionalProperties.put("jackson", "true");
cliOptions.add(new CliOption(TITLE, "server title name or client service name"));
cliOptions.add(new CliOption(CONFIG_PACKAGE, "configuration package for generated code"));
cliOptions.add(new CliOption(BASE_PACKAGE, "base package for generated code"));
cliOptions.add(CliOption.newBoolean(INTERFACE_ONLY, "Whether to generate only API interface stubs without the server files."));
cliOptions.add(CliOption.newBoolean(SINGLE_CONTENT_TYPES, "Whether to select only one produces/consumes content-type by operation."));
cliOptions.add(CliOption.newBoolean(JAVA_8, "use java8 default interface"));
cliOptions.add(CliOption.newBoolean(ASYNC, "use async Callable controllers"));
cliOptions.add(new CliOption(RESPONSE_WRAPPER, "wrap the responses in given type (Future,Callable,CompletableFuture,ListenableFuture,DeferredResult,HystrixCommand,RxObservable,RxSingle or fully qualified type)"));
supportedLibraries.put(DEFAULT_LIBRARY, "Spring-boot Server application using the SpringFox integration.");
supportedLibraries.put(SPRING_MVC_LIBRARY, "Spring-MVC Server application using the SpringFox integration.");
supportedLibraries.put(SPRING_CLOUD_LIBRARY, "Spring-Cloud-Feign client with Spring-Boot auto-configured settings.");
setLibrary(DEFAULT_LIBRARY);
CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use");
library.setDefault(DEFAULT_LIBRARY);
library.setEnum(supportedLibraries);
library.setDefault(DEFAULT_LIBRARY);
cliOptions.add(library);
}
@Override
public CodegenType getTag() {
return CodegenType.SERVER;
}
@Override
public String getName() {
return "spring";
}
@Override
public String getHelp() {
return "Generates a Java SpringBoot Server application using the SpringFox integration.";
}
@Override
public void processOpts() {
// Process java8 option before common java ones to change the default dateLibrary to java8.
if (additionalProperties.containsKey(JAVA_8)) {
this.setJava8(Boolean.valueOf(additionalProperties.get(JAVA_8).toString()));
}
if (this.java8) {
additionalProperties.put("javaVersion", "1.8");
additionalProperties.put("jdk8", "true");
if (!additionalProperties.containsKey(DATE_LIBRARY)) {
setDateLibrary("java8");
}
}
super.processOpts();
// clear model and api doc template as this codegen
// does not support auto-generated markdown doc at the moment
//TODO: add doc templates
modelDocTemplateFiles.remove("model_doc.mustache");
apiDocTemplateFiles.remove("api_doc.mustache");
if (additionalProperties.containsKey(TITLE)) {
this.setTitle((String) additionalProperties.get(TITLE));
}
if (additionalProperties.containsKey(CONFIG_PACKAGE)) {
this.setConfigPackage((String) additionalProperties.get(CONFIG_PACKAGE));
}
if (additionalProperties.containsKey(BASE_PACKAGE)) {
this.setBasePackage((String) additionalProperties.get(BASE_PACKAGE));
}
if (additionalProperties.containsKey(INTERFACE_ONLY)) {
this.setInterfaceOnly(Boolean.valueOf(additionalProperties.get(INTERFACE_ONLY).toString()));
}
if (additionalProperties.containsKey(SINGLE_CONTENT_TYPES)) {
this.setSingleContentTypes(Boolean.valueOf(additionalProperties.get(SINGLE_CONTENT_TYPES).toString()));
}
if (additionalProperties.containsKey(ASYNC)) {
this.setAsync(Boolean.valueOf(additionalProperties.get(ASYNC).toString()));
}
if (additionalProperties.containsKey(RESPONSE_WRAPPER)) {
this.setResponseWrapper((String) additionalProperties.get(RESPONSE_WRAPPER));
}
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
if (!this.interfaceOnly) {
if (library.equals(DEFAULT_LIBRARY)) {
supportingFiles.add(new SupportingFile("homeController.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "HomeController.java"));
supportingFiles.add(new SupportingFile("swagger2SpringBoot.mustache",
(sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator), "Swagger2SpringBoot.java"));
supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache",
(sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator), "RFC3339DateFormat.java"));
supportingFiles.add(new SupportingFile("application.mustache",
("src.main.resources").replace(".", java.io.File.separator), "application.properties"));
}
if (library.equals(SPRING_MVC_LIBRARY)) {
supportingFiles.add(new SupportingFile("webApplication.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "WebApplication.java"));
supportingFiles.add(new SupportingFile("webMvcConfiguration.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "WebMvcConfiguration.java"));
supportingFiles.add(new SupportingFile("swaggerUiConfiguration.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerUiConfiguration.java"));
supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "RFC3339DateFormat.java"));
supportingFiles.add(new SupportingFile("application.properties",
("src.main.resources").replace(".", java.io.File.separator), "swagger.properties"));
}
if (library.equals(SPRING_CLOUD_LIBRARY)) {
supportingFiles.add(new SupportingFile("apiKeyRequestInterceptor.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "ApiKeyRequestInterceptor.java"));
supportingFiles.add(new SupportingFile("clientConfiguration.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "ClientConfiguration.java"));
apiTemplateFiles.put("apiClient.mustache", "Client.java");
if (!additionalProperties.containsKey(SINGLE_CONTENT_TYPES)) {
additionalProperties.put(SINGLE_CONTENT_TYPES, "true");
this.setSingleContentTypes(true);
}
} else {
apiTemplateFiles.put("apiController.mustache", "Controller.java");
supportingFiles.add(new SupportingFile("apiException.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java"));
supportingFiles.add(new SupportingFile("apiResponseMessage.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java"));
supportingFiles.add(new SupportingFile("notFoundException.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java"));
supportingFiles.add(new SupportingFile("apiOriginFilter.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiOriginFilter.java"));
supportingFiles.add(new SupportingFile("swaggerDocumentationConfig.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerDocumentationConfig.java"));
}
}
if ("threetenbp".equals(dateLibrary)) {
supportingFiles.add(new SupportingFile("customInstantDeserializer.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "CustomInstantDeserializer.java"));
if (library.equals(DEFAULT_LIBRARY) || library.equals(SPRING_CLOUD_LIBRARY)) {
supportingFiles.add(new SupportingFile("jacksonConfiguration.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "JacksonConfiguration.java"));
}
}
if (this.java8) {
additionalProperties.put("javaVersion", "1.8");
additionalProperties.put("jdk8", "true");
if (this.async) {
additionalProperties.put(RESPONSE_WRAPPER, "CompletableFuture");
}
typeMapping.put("date", "LocalDate");
typeMapping.put("DateTime", "OffsetDateTime");
importMapping.put("LocalDate", "java.time.LocalDate");
importMapping.put("OffsetDateTime", "java.time.OffsetDateTime");
} else if (this.async) {
additionalProperties.put(RESPONSE_WRAPPER, "Callable");
}
// Some well-known Spring or Spring-Cloud response wrappers
switch (this.responseWrapper) {
case "Future":
case "Callable":
case "CompletableFuture":
additionalProperties.put(RESPONSE_WRAPPER, "java.util.concurrent" + this.responseWrapper);
break;
case "ListenableFuture":
additionalProperties.put(RESPONSE_WRAPPER, "org.springframework.util.concurrent.ListenableFuture");
break;
case "DeferredResult":
additionalProperties.put(RESPONSE_WRAPPER, "org.springframework.web.context.request.DeferredResult");
break;
case "HystrixCommand":
additionalProperties.put(RESPONSE_WRAPPER, "com.netflix.hystrix.HystrixCommand");
break;
case "RxObservable":
additionalProperties.put(RESPONSE_WRAPPER, "rx.Observable");
break;
case "RxSingle":
additionalProperties.put(RESPONSE_WRAPPER, "rx.Single");
break;
default:
break;
}
}
@Override
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
String basePath = resourcePath;
if (basePath.startsWith("/")) {
basePath = basePath.substring(1);
}
int pos = basePath.indexOf("/");
if (pos > 0) {
basePath = basePath.substring(0, pos);
}
if (basePath.equals("")) {
basePath = "default";
} else {
co.subresourceOperation = !co.path.isEmpty();
}
List<CodegenOperation> opList = operations.get(basePath);
if (opList == null) {
opList = new ArrayList<CodegenOperation>();
operations.put(basePath, opList);
}
opList.add(co);
co.baseName = basePath;
}
@Override
public void preprocessSwagger(Swagger swagger) {
super.preprocessSwagger(swagger);
if ("/".equals(swagger.getBasePath())) {
swagger.setBasePath("");
}
if(!additionalProperties.containsKey(TITLE)) {
// From the title, compute a reasonable name for the package and the API
String title = swagger.getInfo().getTitle();
// Drop any API suffix
if (title != null) {
title = title.trim().replace(" ", "-");
if (title.toUpperCase().endsWith("API")) {
title = title.substring(0, title.length() - 3);
}
this.title = camelize(sanitizeName(title), true);
}
additionalProperties.put(TITLE, this.title);
}
String host = swagger.getHost();
String port = "8080";
if (host != null) {
String[] parts = host.split(":");
if (parts.length > 1) {
port = parts[1];
}
}
this.additionalProperties.put("serverPort", port);
if (swagger.getPaths() != null) {
for (String pathname : swagger.getPaths().keySet()) {
Path path = swagger.getPath(pathname);
if (path.getOperations() != null) {
for (Operation operation : path.getOperations()) {
if (operation.getTags() != null) {
List<Map<String, String>> tags = new ArrayList<Map<String, String>>();
for (String tag : operation.getTags()) {
Map<String, String> value = new HashMap<String, String>();
value.put("tag", tag);
value.put("hasMore", "true");
tags.add(value);
}
if (tags.size() > 0) {
tags.get(tags.size() - 1).remove("hasMore");
}
if (operation.getTags().size() > 0) {
String tag = operation.getTags().get(0);
operation.setTags(Arrays.asList(tag));
}
operation.setVendorExtension("x-tags", tags);
}
}
}
}
}
}
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
if (operations != null) {
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation operation : ops) {
List<CodegenResponse> responses = operation.responses;
if (responses != null) {
for (CodegenResponse resp : responses) {
if ("0".equals(resp.code)) {
resp.code = "200";
}
}
}
if (operation.returnType == null) {
operation.returnType = "Void";
} else if (operation.returnType.startsWith("List")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("List<".length(), end).trim();
operation.returnContainer = "List";
}
} else if (operation.returnType.startsWith("Map")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("Map<".length(), end).split(",")[1].trim();
operation.returnContainer = "Map";
}
} else if (operation.returnType.startsWith("Set")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("Set<".length(), end).trim();
operation.returnContainer = "Set";
}
}
}
}
return objs;
}
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
if(library.equals(SPRING_CLOUD_LIBRARY)) {
List<CodegenSecurity> authMethods = (List<CodegenSecurity>) objs.get("authMethods");
if (authMethods != null) {
for (CodegenSecurity authMethod : authMethods) {
authMethod.name = camelize(sanitizeName(authMethod.name), true);
}
}
}
return objs;
}
@Override
public String toApiName(String name) {
if (name.length() == 0) {
return "DefaultApi";
}
name = sanitizeName(name);
return camelize(name) + "Api";
}
public void setTitle(String title) {
this.title = title;
}
public void setConfigPackage(String configPackage) {
this.configPackage = configPackage;
}
public void setBasePackage(String configPackage) {
this.basePackage = configPackage;
}
public void setInterfaceOnly(boolean interfaceOnly) { this.interfaceOnly = interfaceOnly; }
public void setSingleContentTypes(boolean singleContentTypes) {
this.singleContentTypes = singleContentTypes;
}
public void setJava8(boolean java8) { this.java8 = java8; }
public void setAsync(boolean async) { this.async = async; }
public void setResponseWrapper(String responseWrapper) { this.responseWrapper = responseWrapper; }
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
super.postProcessModelProperty(model, property);
if ("null".equals(property.example)) {
property.example = null;
}
//Add imports for Jackson
if (!Boolean.TRUE.equals(model.isEnum)) {
model.imports.add("JsonProperty");
if (Boolean.TRUE.equals(model.hasEnums)) {
model.imports.add("JsonValue");
}
} else { // enum class
//Needed imports for Jackson's JsonCreator
if (additionalProperties.containsKey("jackson")) {
model.imports.add("JsonCreator");
}
}
}
@Override
public Map<String, Object> postProcessModelsEnum(Map<String, Object> objs) {
objs = super.postProcessModelsEnum(objs);
//Add imports for Jackson
List<Map<String, String>> imports = (List<Map<String, String>>)objs.get("imports");
List<Object> models = (List<Object>) objs.get("models");
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
// for enum model
if (Boolean.TRUE.equals(cm.isEnum) && cm.allowableValues != null) {
cm.imports.add(importMapping.get("JsonValue"));
Map<String, String> item = new HashMap<String, String>();
item.put("import", importMapping.get("JsonValue"));
imports.add(item);
}
}
return objs;
}
}
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Swagger;
import java.io.File;
import java.util.*;
public class SpringCodegen extends AbstractJavaCodegen {
public static final String DEFAULT_LIBRARY = "spring-boot";
public static final String TITLE = "title";
public static final String CONFIG_PACKAGE = "configPackage";
public static final String BASE_PACKAGE = "basePackage";
public static final String INTERFACE_ONLY = "interfaceOnly";
public static final String SINGLE_CONTENT_TYPES = "singleContentTypes";
public static final String JAVA_8 = "java8";
public static final String ASYNC = "async";
public static final String RESPONSE_WRAPPER = "responseWrapper";
public static final String SPRING_MVC_LIBRARY = "spring-mvc";
public static final String SPRING_CLOUD_LIBRARY = "spring-cloud";
protected String title = "swagger-petstore";
protected String configPackage = "io.swagger.configuration";
protected String basePackage = "io.swagger";
protected boolean interfaceOnly = false;
protected boolean singleContentTypes = false;
protected boolean java8 = false;
protected boolean async = false;
protected String responseWrapper = "";
public SpringCodegen() {
super();
outputFolder = "generated-code/javaSpring";
apiTestTemplateFiles.clear(); // TODO: add test template
embeddedTemplateDir = templateDir = "JavaSpring";
apiPackage = "io.swagger.api";
modelPackage = "io.swagger.model";
invokerPackage = "io.swagger.api";
artifactId = "swagger-spring";
additionalProperties.put(CONFIG_PACKAGE, configPackage);
additionalProperties.put(BASE_PACKAGE, basePackage);
// spring uses the jackson lib
additionalProperties.put("jackson", "true");
cliOptions.add(new CliOption(TITLE, "server title name or client service name"));
cliOptions.add(new CliOption(CONFIG_PACKAGE, "configuration package for generated code"));
cliOptions.add(new CliOption(BASE_PACKAGE, "base package for generated code"));
cliOptions.add(CliOption.newBoolean(INTERFACE_ONLY, "Whether to generate only API interface stubs without the server files."));
cliOptions.add(CliOption.newBoolean(SINGLE_CONTENT_TYPES, "Whether to select only one produces/consumes content-type by operation."));
cliOptions.add(CliOption.newBoolean(JAVA_8, "use java8 default interface"));
cliOptions.add(CliOption.newBoolean(ASYNC, "use async Callable controllers"));
cliOptions.add(new CliOption(RESPONSE_WRAPPER, "wrap the responses in given type (Future,Callable,CompletableFuture,ListenableFuture,DeferredResult,HystrixCommand,RxObservable,RxSingle or fully qualified type)"));
supportedLibraries.put(DEFAULT_LIBRARY, "Spring-boot Server application using the SpringFox integration.");
supportedLibraries.put(SPRING_MVC_LIBRARY, "Spring-MVC Server application using the SpringFox integration.");
supportedLibraries.put(SPRING_CLOUD_LIBRARY, "Spring-Cloud-Feign client with Spring-Boot auto-configured settings.");
setLibrary(DEFAULT_LIBRARY);
CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use");
library.setDefault(DEFAULT_LIBRARY);
library.setEnum(supportedLibraries);
library.setDefault(DEFAULT_LIBRARY);
cliOptions.add(library);
}
@Override
public CodegenType getTag() {
return CodegenType.SERVER;
}
@Override
public String getName() {
return "spring";
}
@Override
public String getHelp() {
return "Generates a Java SpringBoot Server application using the SpringFox integration.";
}
@Override
public void processOpts() {
// Process java8 option before common java ones to change the default dateLibrary to java8.
if (additionalProperties.containsKey(JAVA_8)) {
this.setJava8(Boolean.valueOf(additionalProperties.get(JAVA_8).toString()));
}
if (this.java8) {
additionalProperties.put("javaVersion", "1.8");
additionalProperties.put("jdk8", "true");
if (!additionalProperties.containsKey(DATE_LIBRARY)) {
setDateLibrary("java8");
}
}
super.processOpts();
// clear model and api doc template as this codegen
// does not support auto-generated markdown doc at the moment
//TODO: add doc templates
modelDocTemplateFiles.remove("model_doc.mustache");
apiDocTemplateFiles.remove("api_doc.mustache");
if (additionalProperties.containsKey(TITLE)) {
this.setTitle((String) additionalProperties.get(TITLE));
}
if (additionalProperties.containsKey(CONFIG_PACKAGE)) {
this.setConfigPackage((String) additionalProperties.get(CONFIG_PACKAGE));
}
if (additionalProperties.containsKey(BASE_PACKAGE)) {
this.setBasePackage((String) additionalProperties.get(BASE_PACKAGE));
}
if (additionalProperties.containsKey(INTERFACE_ONLY)) {
this.setInterfaceOnly(Boolean.valueOf(additionalProperties.get(INTERFACE_ONLY).toString()));
}
if (additionalProperties.containsKey(SINGLE_CONTENT_TYPES)) {
this.setSingleContentTypes(Boolean.valueOf(additionalProperties.get(SINGLE_CONTENT_TYPES).toString()));
}
if (additionalProperties.containsKey(ASYNC)) {
this.setAsync(Boolean.valueOf(additionalProperties.get(ASYNC).toString()));
}
if (additionalProperties.containsKey(RESPONSE_WRAPPER)) {
this.setResponseWrapper((String) additionalProperties.get(RESPONSE_WRAPPER));
}
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
if (!this.interfaceOnly) {
if (library.equals(DEFAULT_LIBRARY)) {
supportingFiles.add(new SupportingFile("homeController.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "HomeController.java"));
supportingFiles.add(new SupportingFile("swagger2SpringBoot.mustache",
(sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator), "Swagger2SpringBoot.java"));
supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache",
(sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator), "RFC3339DateFormat.java"));
supportingFiles.add(new SupportingFile("application.mustache",
("src.main.resources").replace(".", java.io.File.separator), "application.properties"));
}
if (library.equals(SPRING_MVC_LIBRARY)) {
supportingFiles.add(new SupportingFile("webApplication.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "WebApplication.java"));
supportingFiles.add(new SupportingFile("webMvcConfiguration.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "WebMvcConfiguration.java"));
supportingFiles.add(new SupportingFile("swaggerUiConfiguration.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerUiConfiguration.java"));
supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "RFC3339DateFormat.java"));
supportingFiles.add(new SupportingFile("application.properties",
("src.main.resources").replace(".", java.io.File.separator), "swagger.properties"));
}
if (library.equals(SPRING_CLOUD_LIBRARY)) {
supportingFiles.add(new SupportingFile("apiKeyRequestInterceptor.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "ApiKeyRequestInterceptor.java"));
supportingFiles.add(new SupportingFile("clientConfiguration.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "ClientConfiguration.java"));
apiTemplateFiles.put("apiClient.mustache", "Client.java");
if (!additionalProperties.containsKey(SINGLE_CONTENT_TYPES)) {
additionalProperties.put(SINGLE_CONTENT_TYPES, "true");
this.setSingleContentTypes(true);
}
} else {
apiTemplateFiles.put("apiController.mustache", "Controller.java");
supportingFiles.add(new SupportingFile("apiException.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java"));
supportingFiles.add(new SupportingFile("apiResponseMessage.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java"));
supportingFiles.add(new SupportingFile("notFoundException.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java"));
supportingFiles.add(new SupportingFile("apiOriginFilter.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiOriginFilter.java"));
supportingFiles.add(new SupportingFile("swaggerDocumentationConfig.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerDocumentationConfig.java"));
}
}
if ("threetenbp".equals(dateLibrary)) {
supportingFiles.add(new SupportingFile("customInstantDeserializer.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "CustomInstantDeserializer.java"));
if (library.equals(DEFAULT_LIBRARY) || library.equals(SPRING_CLOUD_LIBRARY)) {
supportingFiles.add(new SupportingFile("jacksonConfiguration.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "JacksonConfiguration.java"));
}
}
if (this.java8) {
additionalProperties.put("javaVersion", "1.8");
additionalProperties.put("jdk8", "true");
if (this.async) {
additionalProperties.put(RESPONSE_WRAPPER, "CompletableFuture");
}
typeMapping.put("date", "LocalDate");
typeMapping.put("DateTime", "OffsetDateTime");
importMapping.put("LocalDate", "java.time.LocalDate");
importMapping.put("OffsetDateTime", "java.time.OffsetDateTime");
} else if (this.async) {
additionalProperties.put(RESPONSE_WRAPPER, "Callable");
}
// Some well-known Spring or Spring-Cloud response wrappers
switch (this.responseWrapper) {
case "Future":
case "Callable":
case "CompletableFuture":
additionalProperties.put(RESPONSE_WRAPPER, "java.util.concurrent" + this.responseWrapper);
break;
case "ListenableFuture":
additionalProperties.put(RESPONSE_WRAPPER, "org.springframework.util.concurrent.ListenableFuture");
break;
case "DeferredResult":
additionalProperties.put(RESPONSE_WRAPPER, "org.springframework.web.context.request.DeferredResult");
break;
case "HystrixCommand":
additionalProperties.put(RESPONSE_WRAPPER, "com.netflix.hystrix.HystrixCommand");
break;
case "RxObservable":
additionalProperties.put(RESPONSE_WRAPPER, "rx.Observable");
break;
case "RxSingle":
additionalProperties.put(RESPONSE_WRAPPER, "rx.Single");
break;
default:
break;
}
}
@Override
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
if(library.equals(DEFAULT_LIBRARY) || library.equals(SPRING_MVC_LIBRARY)) {
String basePath = resourcePath;
if (basePath.startsWith("/")) {
basePath = basePath.substring(1);
}
int pos = basePath.indexOf("/");
if (pos > 0) {
basePath = basePath.substring(0, pos);
}
if (basePath.equals("")) {
basePath = "default";
} else {
co.subresourceOperation = !co.path.isEmpty();
}
List<CodegenOperation> opList = operations.get(basePath);
if (opList == null) {
opList = new ArrayList<CodegenOperation>();
operations.put(basePath, opList);
}
opList.add(co);
co.baseName = basePath;
} else {
super.addOperationToGroup(tag, resourcePath, operation, co, operations);
}
}
@Override
public void preprocessSwagger(Swagger swagger) {
super.preprocessSwagger(swagger);
if ("/".equals(swagger.getBasePath())) {
swagger.setBasePath("");
}
if(!additionalProperties.containsKey(TITLE)) {
// From the title, compute a reasonable name for the package and the API
String title = swagger.getInfo().getTitle();
// Drop any API suffix
if (title != null) {
title = title.trim().replace(" ", "-");
if (title.toUpperCase().endsWith("API")) {
title = title.substring(0, title.length() - 3);
}
this.title = camelize(sanitizeName(title), true);
}
additionalProperties.put(TITLE, this.title);
}
String host = swagger.getHost();
String port = "8080";
if (host != null) {
String[] parts = host.split(":");
if (parts.length > 1) {
port = parts[1];
}
}
this.additionalProperties.put("serverPort", port);
if (swagger.getPaths() != null) {
for (String pathname : swagger.getPaths().keySet()) {
Path path = swagger.getPath(pathname);
if (path.getOperations() != null) {
for (Operation operation : path.getOperations()) {
if (operation.getTags() != null) {
List<Map<String, String>> tags = new ArrayList<Map<String, String>>();
for (String tag : operation.getTags()) {
Map<String, String> value = new HashMap<String, String>();
value.put("tag", tag);
value.put("hasMore", "true");
tags.add(value);
}
if (tags.size() > 0) {
tags.get(tags.size() - 1).remove("hasMore");
}
if (operation.getTags().size() > 0) {
String tag = operation.getTags().get(0);
operation.setTags(Arrays.asList(tag));
}
operation.setVendorExtension("x-tags", tags);
}
}
}
}
}
}
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
if (operations != null) {
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation operation : ops) {
List<CodegenResponse> responses = operation.responses;
if (responses != null) {
for (CodegenResponse resp : responses) {
if ("0".equals(resp.code)) {
resp.code = "200";
}
}
}
if (operation.returnType == null) {
operation.returnType = "Void";
} else if (operation.returnType.startsWith("List")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("List<".length(), end).trim();
operation.returnContainer = "List";
}
} else if (operation.returnType.startsWith("Map")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("Map<".length(), end).split(",")[1].trim();
operation.returnContainer = "Map";
}
} else if (operation.returnType.startsWith("Set")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("Set<".length(), end).trim();
operation.returnContainer = "Set";
}
}
}
}
return objs;
}
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
if(library.equals(SPRING_CLOUD_LIBRARY)) {
List<CodegenSecurity> authMethods = (List<CodegenSecurity>) objs.get("authMethods");
if (authMethods != null) {
for (CodegenSecurity authMethod : authMethods) {
authMethod.name = camelize(sanitizeName(authMethod.name), true);
}
}
}
return objs;
}
@Override
public String toApiName(String name) {
if (name.length() == 0) {
return "DefaultApi";
}
name = sanitizeName(name);
return camelize(name) + "Api";
}
public void setTitle(String title) {
this.title = title;
}
public void setConfigPackage(String configPackage) {
this.configPackage = configPackage;
}
public void setBasePackage(String configPackage) {
this.basePackage = configPackage;
}
public void setInterfaceOnly(boolean interfaceOnly) { this.interfaceOnly = interfaceOnly; }
public void setSingleContentTypes(boolean singleContentTypes) {
this.singleContentTypes = singleContentTypes;
}
public void setJava8(boolean java8) { this.java8 = java8; }
public void setAsync(boolean async) { this.async = async; }
public void setResponseWrapper(String responseWrapper) { this.responseWrapper = responseWrapper; }
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
super.postProcessModelProperty(model, property);
if ("null".equals(property.example)) {
property.example = null;
}
//Add imports for Jackson
if (!Boolean.TRUE.equals(model.isEnum)) {
model.imports.add("JsonProperty");
if (Boolean.TRUE.equals(model.hasEnums)) {
model.imports.add("JsonValue");
}
} else { // enum class
//Needed imports for Jackson's JsonCreator
if (additionalProperties.containsKey("jackson")) {
model.imports.add("JsonCreator");
}
}
}
@Override
public Map<String, Object> postProcessModelsEnum(Map<String, Object> objs) {
objs = super.postProcessModelsEnum(objs);
//Add imports for Jackson
List<Map<String, String>> imports = (List<Map<String, String>>)objs.get("imports");
List<Object> models = (List<Object>) objs.get("models");
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
// for enum model
if (Boolean.TRUE.equals(cm.isEnum) && cm.allowableValues != null) {
cm.imports.add(importMapping.get("JsonValue"));
Map<String, String> item = new HashMap<String, String>();
item.put("import", importMapping.get("JsonValue"));
imports.add(item);
}
}
return objs;
}
}

View File

@ -7,17 +7,23 @@ import io.swagger.models.Swagger;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.Info;
import org.apache.commons.lang3.StringUtils;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage = "io.swagger.client";
protected String invokerPackage = "io.swagger.client"; // default for Java and Android
protected String phpInvokerPackage = "Swagger\\Client"; // default for PHP
protected String packageName = "IO.Swagger"; // default for C#
protected String groupId = "io.swagger";
protected String artifactId = "swagger-client";
protected String artifactVersion = "1.0.0";
protected String jsProjectName;
protected String jsModuleName;
public StaticHtml2Generator() {
super();
@ -33,6 +39,8 @@ public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfi
cliOptions.add(new CliOption("licenseInfo", "a short description of the license"));
cliOptions.add(new CliOption("licenseUrl", "a URL pointing to the full license"));
cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC));
cliOptions.add(new CliOption(CodegenConstants.PHP_INVOKER_PACKAGE, CodegenConstants.PHP_INVOKER_PACKAGE_DESC));
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "C# package name"));
cliOptions.add(new CliOption(CodegenConstants.GROUP_ID, CodegenConstants.GROUP_ID_DESC));
cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_ID, CodegenConstants.ARTIFACT_ID_DESC));
cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, CodegenConstants.ARTIFACT_VERSION_DESC));
@ -44,6 +52,8 @@ public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfi
additionalProperties.put("licenseInfo", "All rights reserved");
additionalProperties.put("licenseUrl", "http://apache.org/licenses/LICENSE-2.0.html");
additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
additionalProperties.put(CodegenConstants.PHP_INVOKER_PACKAGE, phpInvokerPackage);
additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName);
additionalProperties.put(CodegenConstants.GROUP_ID, groupId);
additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId);
additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);
@ -101,6 +111,29 @@ public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfi
return objs;
}
@Override
public void preprocessSwagger(Swagger swagger) {
super.preprocessSwagger(swagger);
if (swagger.getInfo() != null) {
Info info = swagger.getInfo();
if (StringUtils.isBlank(jsProjectName) && info.getTitle() != null) {
// when jsProjectName is not specified, generate it from info.title
jsProjectName = sanitizeName(dashize(info.getTitle()));
}
}
// default values
if (StringUtils.isBlank(jsProjectName)) {
jsProjectName = "swagger-js-client";
}
if (StringUtils.isBlank(jsModuleName)) {
jsModuleName = camelize(underscore(jsProjectName));
}
additionalProperties.put("jsProjectName", jsProjectName);
additionalProperties.put("jsModuleName", jsModuleName);
}
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Model> definitions, Swagger swagger) {

View File

@ -102,14 +102,18 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig {
);
reservedWords = new HashSet<>(
Arrays.asList(
"Int", "Int32", "Int64", "Int64", "Float", "Double", "Bool", "Void", "String", "Character", "AnyObject", "Any", "Error", "URL",
"class", "Class", "break", "as", "associativity", "deinit", "case", "dynamicType", "convenience", "enum", "continue",
"false", "dynamic", "extension", "default", "is", "didSet", "func", "do", "nil", "final", "import", "else",
"self", "get", "init", "fallthrough", "Self", "infix", "internal", "for", "super", "inout", "let", "if",
"true", "lazy", "operator", "in", "COLUMN", "left", "private", "return", "FILE", "mutating", "protocol",
"switch", "FUNCTION", "none", "public", "where", "LINE", "nonmutating", "static", "while", "optional",
"struct", "override", "subscript", "postfix", "typealias", "precedence", "var", "prefix", "Protocol",
"required", "right", "set", "Type", "unowned", "weak")
// name used by swift client
"ErrorResponse",
// swift keywords
"Int", "Int32", "Int64", "Int64", "Float", "Double", "Bool", "Void", "String", "Character", "AnyObject", "Any", "Error", "URL",
"class", "Class", "break", "as", "associativity", "deinit", "case", "dynamicType", "convenience", "enum", "continue",
"false", "dynamic", "extension", "default", "is", "didSet", "func", "do", "nil", "final", "import", "else",
"self", "get", "init", "fallthrough", "Self", "infix", "internal", "for", "super", "inout", "let", "if",
"true", "lazy", "operator", "in", "COLUMN", "left", "private", "return", "FILE", "mutating", "protocol",
"switch", "FUNCTION", "none", "public", "where", "LINE", "nonmutating", "static", "while", "optional",
"struct", "override", "subscript", "postfix", "typealias", "precedence", "var", "prefix", "Protocol",
"required", "right", "set", "Type", "unowned", "weak")
);
typeMapping = new HashMap<>();
@ -426,10 +430,18 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig {
if(codegenModel.description != null) {
codegenModel.imports.add("ApiModel");
}
if (allDefinitions != null && codegenModel.parentSchema != null) {
final Model parentModel = allDefinitions.get(codegenModel.parentSchema);
final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel);
if (allDefinitions != null) {
String parentSchema = codegenModel.parentSchema;
// multilevel inheritance: reconcile properties of all the parents
while (parentSchema != null) {
final Model parentModel = allDefinitions.get(parentSchema);
final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel, allDefinitions);
codegenModel = Swift3Codegen.reconcileProperties(codegenModel, parentCodegenModel);
// get the next parent
parentSchema = parentCodegenModel.parentSchema;
}
}
return codegenModel;
@ -505,19 +517,33 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig {
return camelize(WordUtils.capitalizeFully(getSymbolName(name).toUpperCase()), true);
}
// Camelize only when we have a structure defined below
Boolean camelized = false;
if (name.matches("[A-Z][a-z0-9]+[a-zA-Z0-9]*")) {
name = camelize(name, true);
camelized = true;
}
// Reserved Name
String nameLowercase = StringUtils.lowerCase(name);
if (isReservedWord(nameLowercase)) {
return escapeReservedWord(nameLowercase);
}
// Check for numerical conversions
if ("Int".equals(datatype) || "Int32".equals(datatype) || "Int64".equals(datatype) ||
"Float".equals(datatype) || "Double".equals(datatype)) {
String varName = "number" + camelize(name);
varName = varName.replaceAll("-", "minus");
varName = varName.replaceAll("\\+", "plus");
varName = varName.replaceAll("\\.", "dot");
return varName;
}
// Prevent from breaking properly cased identifier
if (name.matches("[A-Z][a-z0-9]+[a-zA-Z0-9]*")) {
return camelize(name, true);
// If we have already camelized the word, don't progress
// any further
if (camelized) {
return name;
}
char[] separators = {'-', '_', ' ', ':', '(', ')'};
@ -581,7 +607,7 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig {
Iterator<CodegenProperty> iterator = codegenProperties.iterator();
while (iterator.hasNext()) {
CodegenProperty codegenProperty = iterator.next();
if (codegenProperty.equals(parentModelCodegenProperty)) {
if (codegenProperty.baseName == parentModelCodegenProperty.baseName) {
// We found a property in the child class that is
// a duplicate of the one in the parent, so remove it.
iterator.remove();
@ -595,7 +621,7 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig {
int count = 0, numVars = codegenProperties.size();
for(CodegenProperty codegenProperty : codegenProperties) {
count += 1;
codegenProperty.hasMore = (count < numVars) ? true : null;
codegenProperty.hasMore = (count < numVars) ? true : false;
}
codegenModel.vars = codegenProperties;
}

View File

@ -101,6 +101,10 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
);
reservedWords = new HashSet<String>(
Arrays.asList(
// name used by swift client
"ErrorResponse",
// swift keywords
"Int", "Int32", "Int64", "Int64", "Float", "Double", "Bool", "Void", "String", "Character", "AnyObject",
"class", "Class", "break", "as", "associativity", "deinit", "case", "dynamicType", "convenience", "enum", "continue",
"false", "dynamic", "extension", "default", "is", "didSet", "func", "do", "nil", "final", "import", "else",

View File

@ -137,7 +137,7 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
if(languageSpecificPrimitives.contains(swaggerType)) {
if(isLanguagePrimitive(swaggerType) || isLanguageGenericType(swaggerType)) {
return swaggerType;
}
applyLocalTypeMapping(swaggerType);
@ -151,9 +151,13 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod
return type;
}
private boolean startsWithLanguageSpecificPrimitiv(String type) {
for (String langPrimitive:languageSpecificPrimitives) {
if (type.startsWith(langPrimitive)) {
private boolean isLanguagePrimitive(String type) {
return languageSpecificPrimitives.contains(type);
}
private boolean isLanguageGenericType(String type) {
for (String genericType: languageGenericTypes) {
if (type.startsWith(genericType + "<")) {
return true;
}
}

View File

@ -40,6 +40,7 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege
supportingFiles.add(new SupportingFile("package.json.mustache", "", "package.json"));
supportingFiles.add(new SupportingFile("typings.json.mustache", "", "typings.json"));
supportingFiles.add(new SupportingFile("tsconfig.json.mustache", "", "tsconfig.json"));
supportingFiles.add(new SupportingFile("tslint.json.mustache", "", "tslint.json"));
supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore"));
supportingFiles.add(new SupportingFile("configuration.mustache", "", "configuration.ts"));

View File

@ -1,5 +1,7 @@
package io.swagger.codegen.languages;
import io.swagger.models.properties.FileProperty;
import io.swagger.models.properties.Property;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -27,6 +29,8 @@ public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen
public TypeScriptNodeClientCodegen() {
super();
typeMapping.put("file", "Buffer");
// clear import mapping (from default generator) as TS does not use it
// at the moment
importMapping.clear();
@ -92,6 +96,19 @@ public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen
return "Generates a TypeScript nodejs client library.";
}
@Override
public boolean isDataTypeFile(final String dataType) {
return dataType != null && dataType.equals("Buffer");
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof FileProperty) {
return "Buffer";
}
return super.getTypeDeclaration(p);
}
public void setNpmName(String npmName) {
this.npmName = npmName;

View File

@ -4,6 +4,8 @@ package io.swagger.codegen.languages.features;
* Features supported by CXF 3 (client + server)
*
*/
public interface CXFFeatures extends LoggingFeatures, GzipFeatures, BeanValidationFeatures, BeanValidationExtendedFeatures {
public interface CXFFeatures extends LoggingFeatures, GzipFeatures, BeanValidationFeatures {
}

View File

@ -1,17 +1,24 @@
package io.swagger.codegen.languages.features;
/**
* Features supported by CXF 3 server
*
*/
public interface CXFServerFeatures extends CXFFeatures, SwaggerFeatures, SpringFeatures {
public static final String USE_WADL_FEATURE = "useWadlFeature";
public static final String USE_MULTIPART_FEATURE = "useMultipartFeature";
public void setUseWadlFeature(boolean useWadlFeature);
public void setUseMultipartFeature(boolean useMultipartFeature);
}
package io.swagger.codegen.languages.features;
/**
* Features supported by CXF 3 server
*
*/
public interface CXFServerFeatures
extends CXFFeatures, SwaggerFeatures, SpringFeatures, JbossFeature, BeanValidationExtendedFeatures,
SwaggerUIFeatures
{
public static final String USE_WADL_FEATURE = "useWadlFeature";
public static final String USE_MULTIPART_FEATURE = "useMultipartFeature";
public static final String ADD_CONSUMES_PRODUCES_JSON = "addConsumesProducesJson";
public void setUseWadlFeature(boolean useWadlFeature);
public void setUseMultipartFeature(boolean useMultipartFeature);
public void setAddConsumesProducesJson(boolean addConsumesProducesJson);
}

View File

@ -3,7 +3,7 @@ package io.swagger.codegen.languages.features;
public interface GzipFeatures {
public static final String USE_GZIP_FEATURE = "useGzipFeature";
public void setUseGzipFeature(boolean useGzipFeature);
}

View File

@ -0,0 +1,9 @@
package io.swagger.codegen.languages.features;
public interface GzipTestFeatures {
public static final String USE_GZIP_FEATURE_FOR_TESTS = "useGzipFeatureForTests";
public void setUseGzipFeatureForTests(boolean useGzipFeatureForTests);
}

View File

@ -0,0 +1,7 @@
package io.swagger.codegen.languages.features;
public interface JaxbFeatures {
public static final String USE_JAXB_ANNOTATIONS = "useJaxbAnnotations";
public void setUseJaxbAnnotations(boolean useJaxbAnnotations);
}

View File

@ -0,0 +1,9 @@
package io.swagger.codegen.languages.features;
public interface JbossFeature {
public static final String GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR = "generateJbossDeploymentDescriptor";
public void setGenerateJbossDeploymentDescriptor(boolean generateJbossDeploymentDescriptor);
}

View File

@ -0,0 +1,8 @@
package io.swagger.codegen.languages.features;
public interface LoggingTestFeatures {
public static final String USE_LOGGING_FEATURE_FOR_TESTS = "useLoggingFeatureForTests";
public void setUseLoggingFeatureForTests(boolean useLoggingFeatureForTests);
}

View File

@ -0,0 +1,10 @@
package io.swagger.codegen.languages.features;
public interface PerformBeanValidationFeatures {
// Language supports performing BeanValidation
public static final String PERFORM_BEANVALIDATION = "performBeanValidation";
public void setPerformBeanValidation(boolean performBeanValidation);
}

View File

@ -6,9 +6,13 @@ public interface SpringFeatures extends BeanValidationFeatures {
public static final String GENERATE_SPRING_BOOT_APPLICATION = "generateSpringBootApplication";
public static final String USE_SPRING_ANNOTATION_CONFIG = "useSpringAnnotationConfig";
public void setGenerateSpringApplication(boolean useGenerateSpringApplication);
public void setGenerateSpringBootApplication(boolean generateSpringBootApplication);
public void setUseSpringAnnotationConfig(boolean useSpringAnnotationConfig);
}

View File

@ -0,0 +1,9 @@
package io.swagger.codegen.languages.features;
public interface SwaggerUIFeatures extends CXFFeatures {
public static final String USE_SWAGGER_UI = "useSwaggerUI";
public void setUseSwaggerUI(boolean useSwaggerUI);
}

View File

@ -1,10 +0,0 @@
# Csharp-DotNet2
This generator creates C# code targeting the .Net 2.0 framework. The resulting DLLs can be used in places where .Net 2.0 is the maximum supported version, such as in the Unity3d.
## Dependencies
- Mono compiler
- Note: NuGet is downloaded by the mono compilation script and packages are installed with it. No dependency DLLs are bundled with this generator.

View File

@ -0,0 +1,153 @@
# {{packageName}} - the C# library for the {{appName}}
{{#appDescription}}
{{{appDescription}}}
{{/appDescription}}
This C# SDK is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project:
- API version: {{appVersion}}
- SDK version: {{packageVersion}}
{{^hideGenerationTimestamp}}
- Build date: {{generatedDate}}
{{/hideGenerationTimestamp}}
- Build package: {{generatorClass}}
{{#infoUrl}}
For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}})
{{/infoUrl}}
<a name="frameworks-supported"></a>
## Frameworks supported
{{^supportUWP}}
- .NET 2.0
{{/supportUWP}}
{{#supportUWP}}
- UWP
{{/supportUWP}}
<a name="dependencies"></a>
## Dependencies
- Mono compiler
- Newtonsoft.Json.7.0.1
- RestSharp.Net2.1.1.11
Note: NuGet is downloaded by the mono compilation script and packages are installed with it. No dependency DLLs are bundled with this generator
<a name="installation"></a>
## Installation
Run the following command to generate the DLL
- [Mac/Linux] `/bin/sh compile-mono.sh`
- [Windows] TODO
Then include the DLL (under the `bin` folder) in the C# project, and use the namespaces:
```csharp
using {{packageName}}.{{apiPackage}};
using {{packageName}}.Client;
using {{packageName}}.{{modelPackage}};
```
<a name="getting-started"></a>
## Getting Started
```csharp
using System;
using System.Diagnostics;
using {{apiPackage}};
using {{packageName}}.Client;
using {{modelPackage}};
namespace Example
{
public class {{operationId}}Example
{
public void main()
{
{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}{{#hasAuthMethods}}{{#authMethods}}{{#isBasic}}
// Configure HTTP basic authorization: {{{name}}}
Configuration.Default.Username = "YOUR_USERNAME";
Configuration.Default.Password = "YOUR_PASSWORD";{{/isBasic}}{{#isApiKey}}
// Configure API key authorization: {{{name}}}
Configuration.Default.ApiKey.Add("{{{keyParamName}}}", "YOUR_API_KEY");
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// Configuration.Default.ApiKeyPrefix.Add("{{{keyParamName}}}", "Bearer");{{/isApiKey}}{{#isOAuth}}
// Configure OAuth2 access token for authorization: {{{name}}}
Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN";{{/isOAuth}}{{/authMethods}}
{{/hasAuthMethods}}
var apiInstance = new {{classname}}();
{{#allParams}}
{{#isPrimitiveType}}
var {{paramName}} = {{example}}; // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}
{{/isPrimitiveType}}
{{^isPrimitiveType}}
var {{paramName}} = new {{{dataType}}}(); // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}
{{/isPrimitiveType}}
{{/allParams}}
try
{
{{#summary}}
// {{{.}}}
{{/summary}}
{{#returnType}}{{{.}}} result = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}}
Debug.WriteLine(result);{{/returnType}}
}
catch (Exception e)
{
Debug.Print("Exception when calling {{classname}}.{{operationId}}: " + e.Message );
}
}
}
}{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}}
```
<a name="documentation-for-api-endpoints"></a>
## Documentation for API Endpoints
All URIs are relative to *{{{basePath}}}*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{{summary}}}{{/summary}}
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
<a name="documentation-for-models"></a>
## Documentation for Models
{{#modelPackage}}
{{#models}}{{#model}} - [{{{modelPackage}}}.{{{classname}}}]({{modelDocPath}}{{{classname}}}.md)
{{/model}}{{/models}}
{{/modelPackage}}
{{^modelPackage}}
No model defined in this package
{{/modelPackage}}
<a name="documentation-for-authorization"></a>
## Documentation for Authorization
{{^authMethods}}
All endpoints do not require authorization.
{{/authMethods}}
{{#authMethods}}
{{#last}}
Authentication schemes defined for the API:
{{/last}}
{{/authMethods}}
{{#authMethods}}
<a name="{{name}}"></a>
### {{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}}

View File

@ -0,0 +1,97 @@
# {{packageName}}.{{apiPackage}}.{{classname}}{{#description}}
{{description}}{{/description}}
All URIs are relative to *{{{basePath}}}*
Method | HTTP request | Description
------------- | ------------- | -------------
{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}}
{{/operation}}{{/operations}}
{{#operations}}
{{#operation}}
<a name="{{{operationIdLowerCase}}}"></a>
# **{{{operationId}}}**
> {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}} ({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = null{{/optionalMethodArgument}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}})
{{{summary}}}{{#notes}}
{{{notes}}}{{/notes}}
### Example
```csharp
using System;
using System.Diagnostics;
using {{packageName}}.Api;
using {{packageName}}.Client;
using {{modelPackage}};
namespace Example
{
public class {{operationId}}Example
{
public void main()
{
{{#hasAuthMethods}}{{#authMethods}}{{#isBasic}}
// Configure HTTP basic authorization: {{{name}}}
Configuration.Default.Username = "YOUR_USERNAME";
Configuration.Default.Password = "YOUR_PASSWORD";{{/isBasic}}{{#isApiKey}}
// Configure API key authorization: {{{name}}}
Configuration.Default.ApiKey.Add("{{{keyParamName}}}", "YOUR_API_KEY");
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// Configuration.Default.ApiKeyPrefix.Add("{{{keyParamName}}}", "Bearer");{{/isApiKey}}{{#isOAuth}}
// Configure OAuth2 access token for authorization: {{{name}}}
Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN";{{/isOAuth}}{{/authMethods}}
{{/hasAuthMethods}}
var apiInstance = new {{classname}}();
{{#allParams}}
{{#isPrimitiveType}}
var {{paramName}} = {{example}}; // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}
{{/isPrimitiveType}}
{{^isPrimitiveType}}
var {{paramName}} = new {{{dataType}}}(); // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}
{{/isPrimitiveType}}
{{/allParams}}
try
{
{{#summary}}
// {{{.}}}
{{/summary}}
{{#returnType}}{{returnType}} result = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}}
Debug.WriteLine(result);{{/returnType}}
}
catch (Exception e)
{
Debug.Print("Exception when calling {{classname}}.{{operationId}}: " + e.Message );
}
}
}
}
```
### Parameters
{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}}
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}}
{{#allParams}} **{{paramName}}** | {{#isFile}}**{{{dataType}}}**{{/isFile}}{{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{{dataType}}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}
{{/allParams}}
### Return type
{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void (empty response body){{/returnType}}
### Authorization
{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{{name}}}](../README.md#{{{name}}}){{^-last}}, {{/-last}}{{/authMethods}}
### HTTP request headers
- **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}}
- **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}}
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
{{/operation}}
{{/operations}}

View File

@ -0,0 +1,14 @@
{{#models}}
{{#model}}
# {{{packageName}}}.Model.{{{classname}}}
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{datatype}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{datatype}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#readOnly}}[readonly] {{/readOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}}
{{/vars}}
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
{{/model}}
{{/models}}

View File

@ -367,7 +367,7 @@ public class ApiClient {
StringBuilder b = new StringBuilder();
for(Object o : (Collection<?>)param) {
if(b.length() > 0) {
b.append(",");
b.append(',');
}
b.append(String.valueOf(o));
}
@ -386,7 +386,7 @@ public class ApiClient {
// preconditions
if (name == null || name.isEmpty() || value == null) return params;
Collection<?> valueCollection = null;
Collection<?> valueCollection;
if (value instanceof Collection<?>) {
valueCollection = (Collection<?>) value;
} else {
@ -399,10 +399,10 @@ public class ApiClient {
}
// get the collection format
collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv
String format = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv
// create the params based on the collection format
if (collectionFormat.equals("multi")) {
if ("multi".equals(format)) {
for (Object item : valueCollection) {
params.add(new Pair(name, parameterToString(item)));
}
@ -412,13 +412,13 @@ public class ApiClient {
String delimiter = ",";
if (collectionFormat.equals("csv")) {
if ("csv".equals(format)) {
delimiter = ",";
} else if (collectionFormat.equals("ssv")) {
} else if ("ssv".equals(format)) {
delimiter = " ";
} else if (collectionFormat.equals("tsv")) {
} else if ("tsv".equals(format)) {
delimiter = "\t";
} else if (collectionFormat.equals("pipes")) {
} else if ("pipes".equals(format)) {
delimiter = "|";
}

View File

@ -0,0 +1,27 @@
package {{invokerPackage}};
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.ValidationException;
public class BeanValidationException extends ValidationException {
/**
*
*/
private static final long serialVersionUID = -5294733947409491364L;
Set<ConstraintViolation<Object>> violations;
public BeanValidationException(Set<ConstraintViolation<Object>> violations) {
this.violations = violations;
}
public Set<ConstraintViolation<Object>> getViolations() {
return violations;
}
public void setViolations(Set<ConstraintViolation<Object>> violations) {
this.violations = violations;
}
}

View File

@ -1,43 +1,45 @@
{{>licenseInfo}}
package {{package}};
import {{invokerPackage}}.ApiException;
{{#imports}}import {{import}};
{{/imports}}
import org.junit.Test;
{{^fullJavaUtil}}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
{{/fullJavaUtil}}
/**
* API tests for {{classname}}
*/
public class {{classname}}Test {
private final {{classname}} api = new {{classname}}();
{{#operations}}{{#operation}}
/**
* {{summary}}
*
* {{notes}}
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void {{operationId}}Test() throws ApiException {
{{#allParams}}
{{{dataType}}} {{paramName}} = null;
{{/allParams}}
// {{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
// TODO: test validations
}
{{/operation}}{{/operations}}
}
{{>licenseInfo}}
package {{package}};
import {{invokerPackage}}.ApiException;
{{#imports}}import {{import}};
{{/imports}}
import org.junit.Test;
import org.junit.Ignore;
{{^fullJavaUtil}}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
{{/fullJavaUtil}}
/**
* API tests for {{classname}}
*/
@Ignore
public class {{classname}}Test {
private final {{classname}} api = new {{classname}}();
{{#operations}}{{#operation}}
/**
* {{summary}}
*
* {{notes}}
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void {{operationId}}Test() throws ApiException {
{{#allParams}}
{{{dataType}}} {{paramName}} = null;
{{/allParams}}
{{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
// TODO: test validations
}
{{/operation}}{{/operations}}
}

View File

@ -35,8 +35,18 @@
{{/maxItems}}
{{/minItems}}
{{#minimum}}
//@Min({{minimum}})
{{#isInteger}}
@Min({{minimum}})
{{/isInteger}}
{{#isLong}}
@Min({{minimum}})
{{/isLong}}
{{/minimum}}
{{#maximum}}
//@Max({{maximum}})
{{/maximum}}
{{#isInteger}}
@Max({{maximum}})
{{/isInteger}}
{{#isLong}}
@Max({{maximum}})
{{/isLong}}
{{/maximum}}

View File

@ -0,0 +1 @@
{{#required}} @NotNull{{/required}}{{#pattern}} @Pattern(regexp="{{pattern}}"){{/pattern}}{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} @Size(max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minItems}}{{#maxItems}} @Size(min={{minItems}},max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minItems}}{{^maxItems}} @Size(min={{minItems}}){{/maxItems}}{{/minItems}}{{^minItems}}{{#maxItems}} @Size(max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minimum}}/* @Min({{minimum}}) */{{/minimum}}{{#maximum}}/* @Max({{maximum}}) */{{/maximum}}

View File

@ -1,198 +1,208 @@
<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>
<scm>
<connection>scm:git:git@github.com:swagger-api/swagger-mustache.git</connection>
<developerConnection>scm:git:git@github.com:swagger-api/swagger-codegen.git</developerConnection>
<url>https://github.com/swagger-api/swagger-codegen</url>
</scm>
<prerequisites>
<maven>2.2.0</maven>
</prerequisites>
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>
<scm>
<connection>scm:git:git@github.com:swagger-api/swagger-mustache.git</connection>
<developerConnection>scm:git:git@github.com:swagger-api/swagger-codegen.git</developerConnection>
<url>https://github.com/swagger-api/swagger-codegen</url>
</scm>
<prerequisites>
<maven>2.2.0</maven>
</prerequisites>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12</version>
<configuration>
<systemProperties>
<property>
<name>loggerPath</name>
<value>conf/log4j.properties</value>
</property>
</systemProperties>
<argLine>-Xms512m -Xmx1500m</argLine>
<parallel>methods</parallel>
<forkMode>pertest</forkMode>
</configuration>
</plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<licenses>
<license>
<name>{{licenseName}}</name>
<url>{{licenseUrl}}</url>
<distribution>repo</distribution>
</license>
</licenses>
<!-- attach test jar -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<goals>
<goal>jar</goal>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
<configuration>
</configuration>
</plugin>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12</version>
<configuration>
<systemProperties>
<property>
<name>loggerPath</name>
<value>conf/log4j.properties</value>
</property>
</systemProperties>
<argLine>-Xms512m -Xmx1500m</argLine>
<parallel>methods</parallel>
<forkMode>pertest</forkMode>
</configuration>
</plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<execution>
<id>add_sources</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<!-- attach test jar -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<goals>
<goal>jar</goal>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
<configuration>
<sources>
<source>src/main/java</source>
</sources>
</configuration>
</execution>
<execution>
<id>add_test_sources</id>
<phase>generate-test-sources</phase>
<goals>
<goal>add-test-source</goal>
</goals>
<configuration>
<sources>
<source>src/test/java</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.4</version>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>${swagger-core-version}</version>
</dependency>
<!-- HTTP client: Netflix Feign -->
<dependency>
<groupId>com.netflix.feign</groupId>
<artifactId>feign-core</artifactId>
<version>${feign-version}</version>
</dependency>
<dependency>
<groupId>com.netflix.feign</groupId>
<artifactId>feign-jackson</artifactId>
<version>${feign-version}</version>
</dependency>
<dependency>
<groupId>com.netflix.feign</groupId>
<artifactId>feign-slf4j</artifactId>
<version>${feign-version}</version>
</dependency>
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form</artifactId>
<version>${feign-form-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>
{{#joda}}
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>${jackson-version}</version>
</dependency>
{{/joda}}
{{#java8}}
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>${jackson-version}</version>
</dependency>
{{/java8}}
{{#threetenbp}}
<dependency>
<groupId>com.github.joschi.jackson</groupId>
<artifactId>jackson-datatype-threetenbp</artifactId>
<version>${threepane-version}</version>
</dependency>
{{/threetenbp}}
<dependency>
<groupId>org.apache.oltu.oauth2</groupId>
<artifactId>org.apache.oltu.oauth2.client</artifactId>
<version>${oltu-version}</version>
</dependency>
<!-- test dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<java.version>{{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}}</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<swagger-core-version>1.5.9</swagger-core-version>
<feign-version>8.17.0</feign-version>
<feign-form-version>2.0.2</feign-form-version>
<jackson-version>2.7.5</jackson-version>
<threepane-version>2.6.4</threepane-version>
<junit-version>4.12</junit-version>
<maven-plugin-version>1.0.0</maven-plugin-version>
<oltu-version>1.0.1</oltu-version>
</properties>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<execution>
<id>add_sources</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>src/main/java</source>
</sources>
</configuration>
</execution>
<execution>
<id>add_test_sources</id>
<phase>generate-test-sources</phase>
<goals>
<goal>add-test-source</goal>
</goals>
<configuration>
<sources>
<source>src/test/java</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.4</version>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>${swagger-core-version}</version>
</dependency>
<!-- HTTP client: Netflix Feign -->
<dependency>
<groupId>com.netflix.feign</groupId>
<artifactId>feign-core</artifactId>
<version>${feign-version}</version>
</dependency>
<dependency>
<groupId>com.netflix.feign</groupId>
<artifactId>feign-jackson</artifactId>
<version>${feign-version}</version>
</dependency>
<dependency>
<groupId>com.netflix.feign</groupId>
<artifactId>feign-slf4j</artifactId>
<version>${feign-version}</version>
</dependency>
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form</artifactId>
<version>${feign-form-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>
{{#joda}}
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>${jackson-version}</version>
</dependency>
{{/joda}}
{{#java8}}
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>${jackson-version}</version>
</dependency>
{{/java8}}
{{#threetenbp}}
<dependency>
<groupId>com.github.joschi.jackson</groupId>
<artifactId>jackson-datatype-threetenbp</artifactId>
<version>${jackson-threetenbp-version}</version>
</dependency>
{{/threetenbp}}
<dependency>
<groupId>org.apache.oltu.oauth2</groupId>
<artifactId>org.apache.oltu.oauth2.client</artifactId>
<version>${oltu-version}</version>
</dependency>
<!-- test dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<java.version>{{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}}</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<swagger-core-version>1.5.9</swagger-core-version>
<feign-version>8.17.0</feign-version>
<feign-form-version>2.0.2</feign-form-version>
<jackson-version>2.7.5</jackson-version>
{{#threetenbp}}
<jackson-threetenbp-version>2.6.4</jackson-threetenbp-version>
{{/threetenbp}}
<junit-version>4.12</junit-version>
<maven-plugin-version>1.0.0</maven-plugin-version>
<oltu-version>1.0.1</oltu-version>
</properties>
</project>

View File

@ -329,7 +329,7 @@ public class ApiClient {
StringBuilder b = new StringBuilder();
for(Object o : (Collection)param) {
if(b.length() > 0) {
b.append(",");
b.append(',');
}
b.append(String.valueOf(o));
}
@ -348,7 +348,7 @@ public class ApiClient {
// preconditions
if (name == null || name.isEmpty() || value == null) return params;
Collection valueCollection = null;
Collection valueCollection;
if (value instanceof Collection) {
valueCollection = (Collection) value;
} else {
@ -361,10 +361,10 @@ public class ApiClient {
}
// get the collection format
collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv
String format = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv
// create the params based on the collection format
if (collectionFormat.equals("multi")) {
if ("multi".equals(format)) {
for (Object item : valueCollection) {
params.add(new Pair(name, parameterToString(item)));
}
@ -374,13 +374,13 @@ public class ApiClient {
String delimiter = ",";
if (collectionFormat.equals("csv")) {
if ("csv".equals(format)) {
delimiter = ",";
} else if (collectionFormat.equals("ssv")) {
} else if ("ssv".equals(format)) {
delimiter = " ";
} else if (collectionFormat.equals("tsv")) {
} else if ("tsv".equals(format)) {
delimiter = "\t";
} else if (collectionFormat.equals("pipes")) {
} else if ("pipes".equals(format)) {
delimiter = "|";
}
@ -464,7 +464,7 @@ public class ApiClient {
* Content-Type (only JSON is supported for now).
*/
public Entity<?> serialize(Object obj, Map<String, Object> formParams, String contentType) throws ApiException {
Entity<?> entity = null;
Entity<?> entity;
if (contentType.startsWith("multipart/form-data")) {
MultiPart multiPart = new MultiPart();
for (Entry<String, Object> param: formParams.entrySet()) {
@ -495,6 +495,7 @@ public class ApiClient {
/**
* Deserialize response body to Java object according to the Content-Type.
*/
@SuppressWarnings("unchecked")
public <T> T deserialize(Response response, GenericType<T> returnType) throws ApiException {
if (response == null || returnType == null) {
return null;
@ -503,9 +504,8 @@ public class ApiClient {
if ("byte[]".equals(returnType.toString())) {
// Handle binary response (byte array).
return (T) response.readEntity(byte[].class);
} else if (returnType.equals(File.class)) {
} else if (returnType.getRawType() == File.class) {
// Handle file downloading.
@SuppressWarnings("unchecked")
T file = (T) downloadFileFromResponse(response);
return file;
}
@ -551,13 +551,13 @@ public class ApiClient {
filename = matcher.group(1);
}
String prefix = null;
String prefix;
String suffix = null;
if (filename == null) {
prefix = "download-";
suffix = "";
} else {
int pos = filename.lastIndexOf(".");
int pos = filename.lastIndexOf('.');
if (pos == -1) {
prefix = filename + "-";
} else {
@ -607,16 +607,17 @@ public class ApiClient {
Invocation.Builder invocationBuilder = target.request().accept(accept);
for (String key : headerParams.keySet()) {
String value = headerParams.get(key);
for (Entry<String, String> entry : headerParams.entrySet()) {
String value = entry.getValue();
if (value != null) {
invocationBuilder = invocationBuilder.header(key, value);
invocationBuilder = invocationBuilder.header(entry.getKey(), value);
}
}
for (String key : defaultHeaderMap.keySet()) {
for (Entry<String, String> entry : defaultHeaderMap.entrySet()) {
String key = entry.getKey();
if (!headerParams.containsKey(key)) {
String value = defaultHeaderMap.get(key);
String value = entry.getValue();
if (value != null) {
invocationBuilder = invocationBuilder.header(key, value);
}
@ -625,7 +626,7 @@ public class ApiClient {
Entity<?> entity = serialize(body, formParams, contentType);
Response response = null;
Response response;
if ("GET".equals(method)) {
response = invocationBuilder.get();
@ -646,7 +647,7 @@ public class ApiClient {
if (response.getStatus() == Status.NO_CONTENT.getStatusCode()) {
return null;
} else if (response.getStatusInfo().getFamily().equals(Status.Family.SUCCESSFUL)) {
} else if (response.getStatusInfo().getFamily() == Status.Family.SUCCESSFUL) {
if (returnType == null)
return null;
else

View File

@ -15,6 +15,14 @@
<maven>2.2.0</maven>
</prerequisites>
<licenses>
<license>
<name>{{licenseName}}</name>
<url>{{licenseUrl}}</url>
<distribution>repo</distribution>
</license>
</licenses>
<build>
<plugins>
<plugin>

View File

@ -1,165 +1,221 @@
{{>licenseInfo}}
package {{package}};
import {{invokerPackage}}.ApiCallback;
import {{invokerPackage}}.ApiClient;
import {{invokerPackage}}.ApiException;
import {{invokerPackage}}.ApiResponse;
import {{invokerPackage}}.Configuration;
import {{invokerPackage}}.Pair;
import {{invokerPackage}}.ProgressRequestBody;
import {{invokerPackage}}.ProgressResponseBody;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
{{#imports}}import {{import}};
{{/imports}}
import java.lang.reflect.Type;
{{^fullJavaUtil}}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
{{/fullJavaUtil}}
{{#operations}}
public class {{classname}} {
private ApiClient {{localVariablePrefix}}apiClient;
public {{classname}}() {
this(Configuration.getDefaultApiClient());
}
public {{classname}}(ApiClient apiClient) {
this.{{localVariablePrefix}}apiClient = apiClient;
}
public ApiClient getApiClient() {
return {{localVariablePrefix}}apiClient;
}
public void setApiClient(ApiClient apiClient) {
this.{{localVariablePrefix}}apiClient = apiClient;
}
{{#operation}}
/* Build call for {{operationId}} */
private com.squareup.okhttp.Call {{operationId}}Call({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object {{localVariablePrefix}}localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
{{#allParams}}{{#required}}
// verify the required parameter '{{paramName}}' is set
if ({{paramName}} == null) {
throw new ApiException("Missing the required parameter '{{paramName}}' when calling {{operationId}}(Async)");
}
{{/required}}{{/allParams}}
// create path and map variables
String {{localVariablePrefix}}localVarPath = "{{{path}}}".replaceAll("\\{format\\}","json"){{#pathParams}}
.replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}};
{{javaUtilPrefix}}List<Pair> {{localVariablePrefix}}localVarQueryParams = new {{javaUtilPrefix}}ArrayList<Pair>();{{#queryParams}}
if ({{paramName}} != null)
{{localVariablePrefix}}localVarQueryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));{{/queryParams}}
{{javaUtilPrefix}}Map<String, String> {{localVariablePrefix}}localVarHeaderParams = new {{javaUtilPrefix}}HashMap<String, String>();{{#headerParams}}
if ({{paramName}} != null)
{{localVariablePrefix}}localVarHeaderParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}}));{{/headerParams}}
{{javaUtilPrefix}}Map<String, Object> {{localVariablePrefix}}localVarFormParams = new {{javaUtilPrefix}}HashMap<String, Object>();{{#formParams}}
if ({{paramName}} != null)
{{localVariablePrefix}}localVarFormParams.put("{{baseName}}", {{paramName}});{{/formParams}}
final String[] {{localVariablePrefix}}localVarAccepts = {
{{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}}
};
final String {{localVariablePrefix}}localVarAccept = {{localVariablePrefix}}apiClient.selectHeaderAccept({{localVariablePrefix}}localVarAccepts);
if ({{localVariablePrefix}}localVarAccept != null) {{localVariablePrefix}}localVarHeaderParams.put("Accept", {{localVariablePrefix}}localVarAccept);
final String[] {{localVariablePrefix}}localVarContentTypes = {
{{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}
};
final String {{localVariablePrefix}}localVarContentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}localVarContentTypes);
{{localVariablePrefix}}localVarHeaderParams.put("Content-Type", {{localVariablePrefix}}localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] {{localVariablePrefix}}localVarAuthNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} };
return {{localVariablePrefix}}apiClient.buildCall({{localVariablePrefix}}localVarPath, "{{httpMethod}}", {{localVariablePrefix}}localVarQueryParams, {{localVariablePrefix}}localVarPostBody, {{localVariablePrefix}}localVarHeaderParams, {{localVariablePrefix}}localVarFormParams, {{localVariablePrefix}}localVarAuthNames, progressRequestListener);
}
/**
* {{summary}}
* {{notes}}{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}{{#returnType}}
* @return {{returnType}}{{/returnType}}
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
{{#returnType}}ApiResponse<{{{returnType}}}> {{localVariablePrefix}}resp = {{/returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}}
return {{localVariablePrefix}}resp.getData();{{/returnType}}
}
/**
* {{summary}}
* {{notes}}{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
* @return ApiResponse&lt;{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Void{{/returnType}}&gt;
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}null, null);
{{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType();
return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType);{{/returnType}}{{^returnType}}return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call);{{/returnType}}
}
/**
* {{summary}} (asynchronously)
* {{notes}}{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{localVariablePrefix}}callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener);
{{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType();
{{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType, {{localVariablePrefix}}callback);{{/returnType}}{{^returnType}}{{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}callback);{{/returnType}}
return {{localVariablePrefix}}call;
}
{{/operation}}
}
{{/operations}}
{{>licenseInfo}}
package {{package}};
import {{invokerPackage}}.ApiCallback;
import {{invokerPackage}}.ApiClient;
import {{invokerPackage}}.ApiException;
import {{invokerPackage}}.ApiResponse;
import {{invokerPackage}}.Configuration;
import {{invokerPackage}}.Pair;
import {{invokerPackage}}.ProgressRequestBody;
import {{invokerPackage}}.ProgressResponseBody;
{{#performBeanValidation}}
import {{invokerPackage}}.BeanValidationException;
{{/performBeanValidation}}
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
{{#useBeanValidation}}
import javax.validation.constraints.*;
{{/useBeanValidation}}
{{#performBeanValidation}}
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import javax.validation.executable.ExecutableValidator;
import java.util.Set;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
{{/performBeanValidation}}
{{#imports}}import {{import}};
{{/imports}}
import java.lang.reflect.Type;
{{^fullJavaUtil}}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
{{/fullJavaUtil}}
{{#operations}}
public class {{classname}} {
private ApiClient {{localVariablePrefix}}apiClient;
public {{classname}}() {
this(Configuration.getDefaultApiClient());
}
public {{classname}}(ApiClient apiClient) {
this.{{localVariablePrefix}}apiClient = apiClient;
}
public ApiClient getApiClient() {
return {{localVariablePrefix}}apiClient;
}
public void setApiClient(ApiClient apiClient) {
this.{{localVariablePrefix}}apiClient = apiClient;
}
{{#operation}}
/* Build call for {{operationId}} */
private com.squareup.okhttp.Call {{operationId}}Call({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object {{localVariablePrefix}}localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
// create path and map variables
String {{localVariablePrefix}}localVarPath = "{{{path}}}".replaceAll("\\{format\\}","json"){{#pathParams}}
.replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}};
{{javaUtilPrefix}}List<Pair> {{localVariablePrefix}}localVarQueryParams = new {{javaUtilPrefix}}ArrayList<Pair>();{{#queryParams}}
if ({{paramName}} != null)
{{localVariablePrefix}}localVarQueryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));{{/queryParams}}
{{javaUtilPrefix}}Map<String, String> {{localVariablePrefix}}localVarHeaderParams = new {{javaUtilPrefix}}HashMap<String, String>();{{#headerParams}}
if ({{paramName}} != null)
{{localVariablePrefix}}localVarHeaderParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}}));{{/headerParams}}
{{javaUtilPrefix}}Map<String, Object> {{localVariablePrefix}}localVarFormParams = new {{javaUtilPrefix}}HashMap<String, Object>();{{#formParams}}
if ({{paramName}} != null)
{{localVariablePrefix}}localVarFormParams.put("{{baseName}}", {{paramName}});{{/formParams}}
final String[] {{localVariablePrefix}}localVarAccepts = {
{{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}}
};
final String {{localVariablePrefix}}localVarAccept = {{localVariablePrefix}}apiClient.selectHeaderAccept({{localVariablePrefix}}localVarAccepts);
if ({{localVariablePrefix}}localVarAccept != null) {{localVariablePrefix}}localVarHeaderParams.put("Accept", {{localVariablePrefix}}localVarAccept);
final String[] {{localVariablePrefix}}localVarContentTypes = {
{{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}
};
final String {{localVariablePrefix}}localVarContentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}localVarContentTypes);
{{localVariablePrefix}}localVarHeaderParams.put("Content-Type", {{localVariablePrefix}}localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] {{localVariablePrefix}}localVarAuthNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} };
return {{localVariablePrefix}}apiClient.buildCall({{localVariablePrefix}}localVarPath, "{{httpMethod}}", {{localVariablePrefix}}localVarQueryParams, {{localVariablePrefix}}localVarPostBody, {{localVariablePrefix}}localVarHeaderParams, {{localVariablePrefix}}localVarFormParams, {{localVariablePrefix}}localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call {{operationId}}ValidateBeforeCall({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
{{^performBeanValidation}}
{{#allParams}}{{#required}}
// verify the required parameter '{{paramName}}' is set
if ({{paramName}} == null) {
throw new ApiException("Missing the required parameter '{{paramName}}' when calling {{operationId}}(Async)");
}
{{/required}}{{/allParams}}
com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener);
return {{localVariablePrefix}}call;
{{/performBeanValidation}}
{{#performBeanValidation}}
try {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
ExecutableValidator executableValidator = factory.getValidator().forExecutables();
Object[] parameterValues = { {{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}} };
Method method = this.getClass().getMethod("{{operationId}}WithHttpInfo"{{#allParams}}, {{#isListContainer}}java.util.List{{/isListContainer}}{{#isMapContainer}}java.util.Map{{/isMapContainer}}{{^isListContainer}}{{^isMapContainer}}{{{dataType}}}{{/isMapContainer}}{{/isListContainer}}.class{{/allParams}});
Set<ConstraintViolation<{{classname}}>> violations = executableValidator.validateParameters(this, method,
parameterValues);
if (violations.size() == 0) {
com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener);
return {{localVariablePrefix}}call;
} else {
throw new BeanValidationException((Set) violations);
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
throw new ApiException(e.getMessage());
} catch (SecurityException e) {
e.printStackTrace();
throw new ApiException(e.getMessage());
}
{{/performBeanValidation}}
}
/**
* {{summary}}
* {{notes}}{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}{{#returnType}}
* @return {{returnType}}{{/returnType}}
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
{{#returnType}}ApiResponse<{{{returnType}}}> {{localVariablePrefix}}resp = {{/returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}}
return {{localVariablePrefix}}resp.getData();{{/returnType}}
}
/**
* {{summary}}
* {{notes}}{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
* @return ApiResponse&lt;{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Void{{/returnType}}&gt;
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}null, null);
{{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType();
return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType);{{/returnType}}{{^returnType}}return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call);{{/returnType}}
}
/**
* {{summary}} (asynchronously)
* {{notes}}{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{localVariablePrefix}}callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener);
{{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType();
{{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType, {{localVariablePrefix}}callback);{{/returnType}}{{^returnType}}{{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}callback);{{/returnType}}
return {{localVariablePrefix}}call;
}
{{/operation}}
}
{{/operations}}

View File

@ -15,6 +15,14 @@
<maven>2.2.0</maven>
</prerequisites>
<licenses>
<license>
<name>{{licenseName}}</name>
<url>{{licenseUrl}}</url>
<distribution>repo</distribution>
</license>
</licenses>
<build>
<plugins>
<plugin>
@ -147,7 +155,19 @@
<scope>provided</scope>
</dependency>
{{/useBeanValidation}}
{{#performBeanValidation}}
<!-- Bean Validation Impl. used to perform BeanValidation -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.2.Final</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>el-api</artifactId>
<version>2.2</version>
</dependency>
{{/performBeanValidation}}
<!-- test dependencies -->
<dependency>
<groupId>junit</groupId>

View File

@ -15,6 +15,14 @@
<maven>2.2.0</maven>
</prerequisites>
<licenses>
<license>
<name>{{licenseName}}</name>
<url>{{licenseUrl}}</url>
<distribution>repo</distribution>
</license>
</licenses>
<build>
<plugins>
<plugin>

View File

@ -18,6 +18,11 @@ import java.util.List;
import java.util.Map;
{{/fullJavaUtil}}
{{#usePlay24WS}}
import play.libs.F;
import retrofit2.Response;
{{/usePlay24WS}}
{{#operations}}
public interface {{classname}} {
{{#operation}}
@ -39,7 +44,7 @@ public interface {{classname}} {
{{/prioritizedContentTypes}}
{{/formParams}}
@{{httpMethod}}("{{path}}")
{{#useRxJava}}Observable{{/useRxJava}}{{^useRxJava}}Call{{/useRxJava}}<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}({{^allParams}});{{/allParams}}
{{^usePlay24WS}}{{#useRxJava}}Observable{{/useRxJava}}{{^useRxJava}}Call{{/useRxJava}}{{/usePlay24WS}}{{#usePlay24WS}}F.Promise<Response{{/usePlay24WS}}<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}>{{#usePlay24WS}}>{{/usePlay24WS}} {{operationId}}({{^allParams}});{{/allParams}}
{{#allParams}}{{>libraries/retrofit2/queryParams}}{{>libraries/retrofit2/pathParams}}{{>libraries/retrofit2/headerParams}}{{>libraries/retrofit2/bodyParams}}{{>libraries/retrofit2/formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}}
);{{/hasMore}}{{/allParams}}

View File

@ -0,0 +1,136 @@
package {{invokerPackage}};
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.*;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import retrofit2.converter.jackson.JacksonConverterFactory;
import play.libs.Json;
import play.libs.ws.WSClient;
import {{invokerPackage}}.Play24CallAdapterFactory;
import {{invokerPackage}}.Play24CallFactory;
import okhttp3.Interceptor;
import {{invokerPackage}}.auth.ApiKeyAuth;
import {{invokerPackage}}.auth.Authentication;
/**
* API client
*/
public class ApiClient {
/** Underlying HTTP-client */
private WSClient wsClient;
/** Supported auths */
private Map<String, Authentication> authentications;
/** API base path */
private String basePath = "{{{basePath}}}";
public ApiClient(WSClient wsClient) {
this();
this.wsClient = wsClient;
}
public ApiClient() {
// Setup authentications (key: authentication name, value: authentication).
authentications = new HashMap<>();{{#authMethods}}{{#isBasic}}
// authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}}
authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}}
// authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}}
// Prevent the authentications from being modified.
authentications = Collections.unmodifiableMap(authentications);
}
/**
* Creates a retrofit2 client for given API interface
*/
public <S> S createService(Class<S> serviceClass) {
if(!basePath.endsWith("/")) {
basePath = basePath + "/";
}
Map<String, String> extraHeaders = new HashMap<>();
List<Pair> extraQueryParams = new ArrayList<>();
for (String authName : authentications.keySet()) {
Authentication auth = authentications.get(authName);
if (auth == null) throw new RuntimeException("Authentication undefined: " + authName);
auth.applyToParams(extraQueryParams, extraHeaders);
}
return new Retrofit.Builder()
.baseUrl(basePath)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(JacksonConverterFactory.create(Json.mapper()))
.callFactory(new Play24CallFactory(wsClient, extraHeaders, extraQueryParams))
.addCallAdapterFactory(new Play24CallAdapterFactory())
.build()
.create(serviceClass);
}
/**
* Helper method to set API base path
*/
public ApiClient setBasePath(String basePath) {
this.basePath = basePath;
return this;
}
/**
* Get authentications (key: authentication name, value: authentication).
*/
public Map<String, Authentication> getAuthentications() {
return authentications;
}
/**
* Get authentication for the given name.
*
* @param authName The authentication name
* @return The authentication, null if not found
*/
public Authentication getAuthentication(String authName) {
return authentications.get(authName);
}
/**
* Helper method to set API key value for the first API key authentication.
*/
public ApiClient setApiKey(String apiKey) {
for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKey(apiKey);
return this;
}
}
throw new RuntimeException("No API key authentication configured!");
}
/**
* Helper method to set API key prefix for the first API key authentication.
*/
public ApiClient setApiKeyPrefix(String apiKeyPrefix) {
for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix);
return this;
}
}
throw new RuntimeException("No API key authentication configured!");
}
}

View File

@ -0,0 +1,90 @@
package {{invokerPackage}};
import play.libs.F;
import retrofit2.*;
import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
/**
* Creates {@link CallAdapter} instances that convert {@link Call} into {@link play.libs.F.Promise}
*/
public class Play24CallAdapterFactory extends CallAdapter.Factory {
@Override
public CallAdapter<?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
if (!(returnType instanceof ParameterizedType)) {
return null;
}
ParameterizedType type = (ParameterizedType) returnType;
if (type.getRawType() != F.Promise.class) {
return null;
}
return createAdapter((ParameterizedType) returnType);
}
private Type getTypeParam(ParameterizedType type) {
Type[] types = type.getActualTypeArguments();
if (types.length != 1) {
throw new IllegalStateException("Must be exactly one type parameter");
}
Type paramType = types[0];
if (paramType instanceof WildcardType) {
return ((WildcardType) paramType).getUpperBounds()[0];
}
return paramType;
}
private CallAdapter<F.Promise<?>> createAdapter(ParameterizedType returnType) {
Type parameterType = getTypeParam(returnType);
return new ValueAdapter(parameterType);
}
/**
* Adpater that coverts values returned by API interface into Play promises
*/
static final class ValueAdapter implements CallAdapter<F.Promise<?>> {
private final Type responseType;
ValueAdapter(Type responseType) {
this.responseType = responseType;
}
@Override
public Type responseType() {
return responseType;
}
@Override
public <R> F.Promise<R> adapt(final Call<R> call) {
final F.RedeemablePromise<R> promise = F.RedeemablePromise.empty();
call.enqueue(new Callback<R>() {
@Override
public void onResponse(Call<R> call, Response<R> response) {
if (response.isSuccessful()) {
promise.success(response.body());
} else {
promise.failure(new Exception(response.errorBody().toString()));
}
}
@Override
public void onFailure(Call<R> call, Throwable t) {
promise.failure(t);
}
});
return promise;
}
}
}

View File

@ -0,0 +1,210 @@
package {{invokerPackage}};
import okhttp3.*;
import okio.Buffer;
import okio.BufferedSource;
import play.libs.F;
import play.libs.ws.WSClient;
import play.libs.ws.WSRequest;
import play.libs.ws.WSResponse;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Creates {@link Call} instances that invoke underlying {@link WSClient}
*/
public class Play24CallFactory implements okhttp3.Call.Factory {
/** PlayWS http client */
private final WSClient wsClient;
/** Extra headers to add to request */
private Map<String, String> extraHeaders = new HashMap<>();
/** Extra query parameters to add to request */
private List<Pair> extraQueryParams = new ArrayList<>();
public Play24CallFactory(WSClient wsClient) {
this.wsClient = wsClient;
}
public Play24CallFactory(WSClient wsClient, Map<String, String> extraHeaders,
List<Pair> extraQueryParams) {
this.wsClient = wsClient;
this.extraHeaders.putAll(extraHeaders);
this.extraQueryParams.addAll(extraQueryParams);
}
@Override
public Call newCall(Request request) {
// add extra headers
Request.Builder rb = request.newBuilder();
for (Map.Entry<String, String> header : this.extraHeaders.entrySet()) {
rb.addHeader(header.getKey(), header.getValue());
}
// add extra query params
if (!this.extraQueryParams.isEmpty()) {
String newQuery = request.url().uri().getQuery();
for (Pair queryParam : this.extraQueryParams) {
String param = String.format("%s=%s", queryParam.getName(), queryParam.getValue());
if (newQuery == null) {
newQuery = param;
} else {
newQuery += "&" + param;
}
}
URI newUri;
try {
newUri = new URI(request.url().uri().getScheme(), request.url().uri().getAuthority(),
request.url().uri().getPath(), newQuery, request.url().uri().getFragment());
rb.url(newUri.toURL());
} catch (MalformedURLException | URISyntaxException e) {
throw new RuntimeException("Error while updating an url", e);
}
}
return new PlayWSCall(wsClient, rb.build());
}
/**
* Call implementation that delegates to Play WS Client
*/
static class PlayWSCall implements Call {
private final WSClient wsClient;
private WSRequest wsRequest;
private final Request request;
public PlayWSCall(WSClient wsClient, Request request) {
this.wsClient = wsClient;
this.request = request;
}
@Override
public Request request() {
return request;
}
@Override
public void enqueue(final okhttp3.Callback responseCallback) {
final Call call = this;
final F.Promise<WSResponse> promise = executeAsync();
promise.onRedeem(new F.Callback<WSResponse>() {
@Override
public void invoke(WSResponse wsResponse) throws Throwable {
responseCallback.onResponse(call, PlayWSCall.this.toWSResponse(wsResponse));
}
});
promise.onFailure(new F.Callback<Throwable>() {
@Override
public void invoke(Throwable throwable) throws Throwable {
if (throwable instanceof IOException) {
responseCallback.onFailure(call, (IOException) throwable);
} else {
responseCallback.onFailure(call, new IOException(throwable));
}
}
});
}
F.Promise<WSResponse> executeAsync() {
try {
wsRequest = wsClient.url(request.url().uri().toString());
addHeaders(wsRequest);
if (request.body() != null) {
addBody(wsRequest);
}
return wsRequest.execute(request.method());
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
private void addHeaders(WSRequest wsRequest) {
for(Map.Entry<String, List<String>> entry : request.headers().toMultimap().entrySet()) {
List<String> values = entry.getValue();
for (String value : values) {
wsRequest.setHeader(entry.getKey(), value);
}
}
}
private void addBody(WSRequest wsRequest) throws IOException {
Buffer buffer = new Buffer();
request.body().writeTo(buffer);
wsRequest.setBody(buffer.inputStream());
wsRequest.setContentType(request.body().contentType().toString());
}
private Response toWSResponse(final WSResponse r) {
final Response.Builder builder = new Response.Builder();
builder.request(request)
.code(r.getStatus())
.body(new ResponseBody() {
@Override
public MediaType contentType() {
return MediaType.parse(r.getHeader("Content-Type"));
}
@Override
public long contentLength() {
return r.getBody().getBytes().length;
}
@Override
public BufferedSource source() {
return new Buffer().write(r.getBody().getBytes());
}
});
for (Map.Entry<String, List<String>> entry : r.getAllHeaders().entrySet()) {
for (String value : entry.getValue()) {
builder.addHeader(entry.getKey(), value);
}
}
builder.protocol(Protocol.HTTP_1_1);
return builder.build();
}
@Override
public Response execute() throws IOException {
throw new UnsupportedOperationException("Not supported");
}
@Override
public void cancel() {
throw new UnsupportedOperationException("Not supported");
}
@Override
public boolean isExecuted() {
return false;
}
@Override
public boolean isCanceled() {
return false;
}
}
}

View File

@ -0,0 +1,67 @@
{{>licenseInfo}}
package {{invokerPackage}}.auth;
import {{invokerPackage}}.Pair;
import java.util.Map;
import java.util.List;
/**
* Holds ApiKey auth info
*/
{{>generatedAnnotation}}
public class ApiKeyAuth implements Authentication {
private final String location;
private final String paramName;
private String apiKey;
private String apiKeyPrefix;
public ApiKeyAuth(String location, String paramName) {
this.location = location;
this.paramName = paramName;
}
public String getLocation() {
return location;
}
public String getParamName() {
return paramName;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String getApiKeyPrefix() {
return apiKeyPrefix;
}
public void setApiKeyPrefix(String apiKeyPrefix) {
this.apiKeyPrefix = apiKeyPrefix;
}
@Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) {
if (apiKey == null) {
return;
}
String value;
if (apiKeyPrefix != null) {
value = apiKeyPrefix + " " + apiKey;
} else {
value = apiKey;
}
if ("query".equals(location)) {
queryParams.add(new Pair(paramName, value));
} else if ("header".equals(location)) {
headerParams.put(paramName, value);
}
}
}

View File

@ -15,6 +15,14 @@
<maven>2.2.0</maven>
</prerequisites>
<licenses>
<license>
<name>{{licenseName}}</name>
<url>{{licenseUrl}}</url>
<distribution>repo</distribution>
</license>
</licenses>
<build>
<plugins>
<plugin>
@ -155,6 +163,40 @@
<version>${retrofit-version}</version>
</dependency>
{{/useRxJava}}
{{#usePlay24WS}}
<!-- JSON processing: jackson -->
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-jackson</artifactId>
<version>${retrofit-version}</version>
</dependency>
<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-{{^java8}}joda{{/java8}}{{#java8}}jsr310{{/java8}}</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.typesafe.play</groupId>
<artifactId>play-java-ws_2.10</artifactId>
<version>2.4.6</version>
</dependency>
{{/usePlay24WS}}
<!-- test dependencies -->
<dependency>
@ -171,6 +213,9 @@
<maven.compiler.target>${java.version}</maven.compiler.target>
<swagger-core-version>1.5.9</swagger-core-version>
<retrofit-version>2.1.0</retrofit-version>
{{#usePlay24WS}}
<jackson-version>2.7.5</jackson-version>
{{/usePlay24WS}}
{{#useRxJava}}
<rxjava-version>1.1.6</rxjava-version>
{{/useRxJava}}

View File

@ -8,16 +8,4 @@
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

View File

@ -2,8 +2,12 @@
* {{#description}}{{.}}{{/description}}{{^description}}{{classname}}{{/description}}
*/{{#description}}
@ApiModel(description = "{{{description}}}"){{/description}}
{{>generatedAnnotation}}
{{>generatedAnnotation}}{{#discriminator}}{{>typeInfoAnnotation}}{{/discriminator}}
public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#parcelableModel}}implements Parcelable {{#serializableModel}}, Serializable {{/serializableModel}}{{/parcelableModel}}{{^parcelableModel}}{{#serializableModel}}implements Serializable {{/serializableModel}}{{/parcelableModel}}{
{{#serializableModel}}
private static final long serialVersionUID = 1L;
{{/serializableModel}}
{{#vars}}
{{#isEnum}}
{{^isContainer}}
@ -92,7 +96,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#parcela
return {{#vars}}Objects.equals(this.{{name}}, {{classVarName}}.{{name}}){{#hasMore}} &&
{{/hasMore}}{{/vars}}{{#parent}} &&
super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}}
return true;{{/hasVars}}
return {{#parent}}super.equals(o){{/parent}}{{^parent}}true{{/parent}};{{/hasVars}}
}
@Override

View File

@ -11,6 +11,14 @@
<maven>2.2.0</maven>
</prerequisites>
<licenses>
<license>
<name>{{licenseName}}</name>
<url>{{licenseUrl}}</url>
<distribution>repo</distribution>
</license>
</licenses>
<build>
<plugins>
<plugin>
@ -196,7 +204,7 @@
<version>${commons_io_version}</version>
</dependency>
{{/supportJava6}}
{{#useBeanValidation}}
{{#useBeanValidation}}
<!-- Bean Validation API support -->
<dependency>
<groupId>javax.validation</groupId>
@ -204,7 +212,7 @@
<version>1.1.0.Final</version>
<scope>provided</scope>
</dependency>
{{/useBeanValidation}}
{{/useBeanValidation}}
<!-- test dependencies -->
<dependency>
<groupId>junit</groupId>

View File

@ -1,18 +1,6 @@
#
# Generated by: https://github.com/swagger-api/swagger-codegen.git
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
language: java
jdk:
- oraclejdk8

View File

@ -0,0 +1,5 @@
{{#jackson}}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "{{discriminator}}" )
@JsonSubTypes({
{{#children}}@JsonSubTypes.Type(value = {{name}}.class, name = "{{name}}"),{{/children}}
}){{/jackson}}

View File

@ -14,6 +14,14 @@
<maven>2.2.0</maven>
</prerequisites>
<licenses>
<license>
<name>{{licenseName}}</name>
<url>{{licenseUrl}}</url>
<distribution>repo</distribution>
</license>
</licenses>
<build>
<defaultGoal>install</defaultGoal>
<directory>target</directory>
@ -117,4 +125,4 @@
<junit-version>4.8.2</junit-version>
<slf4j-version>1.6.3</slf4j-version>
</properties>
</project>
</project>

View File

@ -0,0 +1,9 @@
package {{invokerPackage}};
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
@ApplicationPath("/")
public class RestApplication extends Application {
// Add implementation-specific details here
}

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
<!--
This is just an empty file so that CDI archive scanning kicks in when
implicit archive scanning is disabled (such as on IBM Bluemix)
-->
</beans>

View File

@ -1,36 +1,44 @@
package {{package}};
{{#imports}}import {{import}};
{{/imports}}
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import org.apache.cxf.jaxrs.ext.multipart.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
{{#useBeanValidation}}
import javax.validation.constraints.*;
{{/useBeanValidation}}
@Path("/")
@Api(value = "/", description = "{{description}}")
public interface {{classname}} {
{{#operations}}
{{#operation}}
@{{httpMethod}}
{{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}}
{{#hasConsumes}}@Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}}
{{#hasProduces}}@Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}}
@ApiOperation(value = "{{summary}}", tags={ {{#vendorExtensions.x-tags}}"{{tag}}"{{#hasMore}}, {{/hasMore}}{{/vendorExtensions.x-tags}} })
public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
{{/operation}}
}
{{/operations}}
package {{package}};
{{#imports}}import {{import}};
{{/imports}}
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;
import org.apache.cxf.jaxrs.ext.multipart.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
{{#useBeanValidation}}
import javax.validation.constraints.*;
{{/useBeanValidation}}
@Path("/")
@Api(value = "/", description = "{{description}}")
{{#addConsumesProducesJson}}
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
{{/addConsumesProducesJson}}
public interface {{classname}} {
{{#operations}}
{{#operation}}
@{{httpMethod}}
{{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}}
{{#hasConsumes}}
@Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} })
{{/hasConsumes}}
{{#hasProduces}}
@Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} })
{{/hasProduces}}
@ApiOperation(value = "{{summary}}", tags={ {{#vendorExtensions.x-tags}}"{{tag}}"{{#hasMore}}, {{/hasMore}}{{/vendorExtensions.x-tags}} })
public {{>returnTypes}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
{{/operation}}
}
{{/operations}}

View File

@ -16,13 +16,19 @@ import org.apache.cxf.jaxrs.model.wadl.DocTarget;
import org.apache.cxf.jaxrs.ext.multipart.*;
import io.swagger.annotations.Api;
{{#useSpringAnnotationConfig}}
import org.springframework.stereotype.Service;
{{/useSpringAnnotationConfig}}
{{#useSpringAnnotationConfig}}
@Service("{{classname}}")
{{/useSpringAnnotationConfig}}
{{#description}}
{{/description}}
public class {{classname}}ServiceImpl implements {{classname}} {
{{#operations}}
{{#operation}}
public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}}({{#allParams}}{{>queryParamsImpl}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {
public {{>returnTypes}} {{nickname}}({{#allParams}}{{>queryParamsImpl}}{{>pathParamsImpl}}{{>headerParamsImpl}}{{>bodyParams}}{{>formParamsImpl}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {
// TODO: Implement...
{{^vendorExtensions.x-java-is-response-void}}return null;{{/vendorExtensions.x-java-is-response-void}}

View File

@ -6,6 +6,7 @@ package {{package}};
{{/imports}}
import org.junit.Test;
import org.junit.Before;
import static org.junit.Assert.*;
import javax.ws.rs.core.Response;
import org.apache.cxf.jaxrs.client.JAXRSClientFactory;
@ -65,7 +66,7 @@ public class {{classname}}Test {
providers.add(provider);
{{#generateSpringBootApplication}}
api = JAXRSClientFactory.create("http://localhost:" + serverPort + "/services/services", {{classname}}.class, providers);
api = JAXRSClientFactory.create("http://localhost:" + serverPort + "/services", {{classname}}.class, providers);
{{/generateSpringBootApplication}}
{{^generateSpringBootApplication}}
api = JAXRSClientFactory.create("{{basePath}}", {{classname}}.class, providers);
@ -73,7 +74,7 @@ public class {{classname}}Test {
org.apache.cxf.jaxrs.client.Client client = WebClient.client(api);
ClientConfiguration config = WebClient.getConfig(client);
{{#useGzipFeature}}
{{#useGzipFeatureForTests}}
// Example for using Gzipping
GZIPOutInterceptor gzipOutInterceptor = new GZIPOutInterceptor();
// use Gzipping for first request sent to server
@ -81,11 +82,11 @@ public class {{classname}}Test {
config.getOutInterceptors().add(gzipOutInterceptor);
config.getInInterceptors().add(new GZIPInInterceptor());
{{/useGzipFeature}}
{{#useLoggingFeature}}
{{/useGzipFeatureForTests}}
{{#useLoggingFeatureForTests}}
LoggingOutInterceptor loggingOutInterceptor = new LoggingOutInterceptor();
config.getOutInterceptors().add(loggingOutInterceptor);
{{/useLoggingFeature}}
{{/useLoggingFeatureForTests}}
}
{{#operations}}{{#operation}}
@ -100,11 +101,13 @@ public class {{classname}}Test {
@Test
public void {{operationId}}Test() {
{{#allParams}}
{{{dataType}}} {{paramName}} = null;
{{^isFile}}{{{dataType}}} {{paramName}} = null;{{/isFile}}{{#isFile}}org.apache.cxf.jaxrs.ext.multipart.Attachment {{paramName}} = null;{{/isFile}}
{{/allParams}}
// {{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
//{{^vendorExtensions.x-java-is-response-void}}{{>returnTypes}} response = {{/vendorExtensions.x-java-is-response-void}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
{{^vendorExtensions.x-java-is-response-void}}//assertNotNull(response);{{/vendorExtensions.x-java-is-response-void}}
// TODO: test validations
}
{{/operation}}{{/operations}}
}

View File

@ -35,8 +35,8 @@
{{/maxItems}}
{{/minItems}}
{{#minimum}}
//@Min({{minimum}})
@Min({{minimum}})
{{/minimum}}
{{#maximum}}
//@Max({{maximum}})
@Max({{maximum}})
{{/maximum}}

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