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 ### 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 - Android: https://source.android.com/source/code-style.html
- C#: https://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx - C#: https://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx
- C++: https://google.github.io/styleguide/cppguide.html - 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 - Haskell: https://github.com/tibbe/haskell-style-guide/blob/master/haskell-style.md
- Java: https://google.github.io/styleguide/javaguide.html - 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 - Groovy: http://groovy-lang.org/style-guide.html
- Go: https://github.com/golang/go/wiki/CodeReviewComments - Go: https://github.com/golang/go/wiki/CodeReviewComments
- ObjC: https://github.com/NYTimes/objective-c-style-guide - 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 [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 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 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 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 ### 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: :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 ## 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 # 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) - [Guidelines for Contribution](https://github.com/swagger-api/swagger-codegen/wiki/Guidelines-for-Contribution)
- [Companies/Projects using Swagger Codegen](#companiesprojects-using-swagger-codegen) - [Companies/Projects using Swagger Codegen](#companiesprojects-using-swagger-codegen)
- [Swagger Codegen Core Team](#swagger-codegen-core-team) - [Swagger Codegen Core Team](#swagger-codegen-core-team)
- [Swagger Codegen Evangelist](#swagger-codegen-evangelist)
- [License](#license) - [License](#license)
## Compatibility ## 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 Swagger Codegen Version | Release Date | OpenAPI Spec compatibility | Notes
-------------------------- | ------------ | -------------------------- | ----- -------------------------- | ------------ | -------------------------- | -----
@ -128,7 +134,8 @@ cd /vagrant
#### Public Docker image #### 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 ### Homebrew
To install, run `brew install swagger-codegen` To install, run `brew install swagger-codegen`
@ -550,10 +557,10 @@ CONFIG OPTIONS
library library
library template (sub-template) to use: 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 jersey2 - HTTP client: Jersey client 2.6
feign - HTTP client: Netflix Feign 8.1.1. JSON processing: Jackson 2.6.3 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) 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) 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: 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/) 1) Create a new repository in GitHub (Ref: https://help.github.com/articles/creating-a-new-repository/)
2) Generate the SDK 2) Generate the SDK
``` ```
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ 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/) - [Activehours](https://www.activehours.com/)
- [Acunetix](https://www.acunetix.com/) - [Acunetix](https://www.acunetix.com/)
- [Atlassian](https://www.atlassian.com/) - [Atlassian](https://www.atlassian.com/)
- [Autodesk](http://www.autodesk.com/)
- [Avenida Compras S.A.](https://www.avenida.com.ar) - [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) - [beemo](http://www.beemo.eu)
- [bitly](https://bitly.com) - [bitly](https://bitly.com)
- [Bufferfly Network](https://www.butterflynetinc.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/) - [eureka](http://eure.jp/)
- [everystory.us](http://everystory.us) - [everystory.us](http://everystory.us)
- [Expected Behavior](http://www.expectedbehavior.com/) - [Expected Behavior](http://www.expectedbehavior.com/)
- [Fastly](https://www.fastly.com/)
- [Flat](https://flat.io)
- [Finder](http://en.finder.pl/) - [Finder](http://en.finder.pl/)
- [FH Münster - University of Applied Sciences](http://www.fh-muenster.de) - [FH Münster - University of Applied Sciences](http://www.fh-muenster.de)
- [Gear Zero Network](https://www.gearzero.ca) - [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/) - [GraphHopper](https://graphhopper.com/)
- [Gravitate Solutions](http://gravitatesolutions.com/) - [Gravitate Solutions](http://gravitatesolutions.com/)
- [IMS Health](http://www.imshealth.com/en/solution-areas/technology-and-applications) - [IMS Health](http://www.imshealth.com/en/solution-areas/technology-and-applications)
- [Intent HQ](http://www.intenthq.com)
- [Interactive Intelligence](http://developer.mypurecloud.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) - [Kabuku](http://www.kabuku.co.jp/en)
- [Kuroi](http://kuroiwebdesign.com/) - [Kuroi](http://kuroiwebdesign.com/)
- [Kuary](https://kuary.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/) - [Mindera](http://mindera.com/)
- [Mporium](http://mporium.com/) - [Mporium](http://mporium.com/)
- [nViso](http://www.nviso.ch/) - [nViso](http://www.nviso.ch/)
- [Okiok](https://www.okiok.com) - [Okiok](https://www.okiok.com)
- [Onedata](http://onedata.org) - [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) - [Plexxi](http://www.plexxi.com)
- [Pixoneye](http://www.pixoneye.com/) - [Pixoneye](http://www.pixoneye.com/)
- [PostAffiliatePro](https://www.postaffiliatepro.com/) - [PostAffiliatePro](https://www.postaffiliatepro.com/)
- [Prill Tecnologia](http://www.prill.com.br)
- [QAdept](http://qadept.com/) - [QAdept](http://qadept.com/)
- [QuantiModo](https://quantimo.do/) - [QuantiModo](https://quantimo.do/)
- [Rapid7](https://rapid7.com/) - [Rapid7](https://rapid7.com/)
- [Reload! A/S](https://reload.dk/) - [Reload! A/S](https://reload.dk/)
- [REstore](https://www.restore.eu) - [REstore](https://www.restore.eu)
- [Revault Sàrl](http://revault.ch) - [Revault Sàrl](http://revault.ch)
- [Riffyn](https://riffyn.com)
- [Royal Bank of Canada (RBC)](http://www.rbc.com/canada.html) - [Royal Bank of Canada (RBC)](http://www.rbc.com/canada.html)
- [Saritasa](https://www.saritasa.com/)
- [SCOOP Software GmbH](http://www.scoop-software.de) - [SCOOP Software GmbH](http://www.scoop-software.de)
- [Shine Solutions](https://shinesolutions.com/)
- [Skurt](http://www.skurt.com) - [Skurt](http://www.skurt.com)
- [SmartRecruiters](https://www.smartrecruiters.com/) - [SmartRecruiters](https://www.smartrecruiters.com/)
- [snapCX](https://snapcx.io)
- [SRC](https://www.src.si/)
- [StyleRecipe](http://stylerecipe.co.jp) - [StyleRecipe](http://stylerecipe.co.jp)
- [Svenska Spel AB](https://www.svenskaspel.se/) - [Svenska Spel AB](https://www.svenskaspel.se/)
- [TaskData](http://www.taskdata.com/)
- [ThoughtWorks](https://www.thoughtworks.com) - [ThoughtWorks](https://www.thoughtworks.com)
- [Upwork](http://upwork.com/)
- [uShip](https://www.uship.com/) - [uShip](https://www.uship.com/)
- [VMware](https://vmware.com/)
- [W.UP](http://wup.hu/?siteLang=en) - [W.UP](http://wup.hu/?siteLang=en)
- [Wealthfront](https://www.wealthfront.com/) - [Wealthfront](https://www.wealthfront.com/)
- [WEXO A/S](https://www.wexo.dk/) - [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. 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 ## API Clients
| Languages | Core Team (join date) | | Languages | Core Team (join date) |
|:-------------|:-------------| |:-------------|:-------------|
| ActionScript | | | ActionScript | |
| C++ | | | C++ | |
| C# | @jimschubert (2016/05/01) | | | 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) | | Go | @guohuang (2016/05/01) @neilotoole (2016/05/01) |
| Java | @cbornet (2016/05/01) @xhh (2016/05/01) @epaul (2016/06/04) | | Java | @cbornet (2016/05/01) @xhh (2016/05/01) @epaul (2016/06/04) |
| Java (Spring Cloud) | @cbornet (2016/07/19) | | Java (Spring Cloud) | @cbornet (2016/07/19) |
| NodeJS/Javascript | @xhh (2016/05/01) | | NodeJS/Javascript | @xhh (2016/05/01) |
| ObjC | @mateuszmackowiak (2016/05/09) | | ObjC | @mateuszmackowiak (2016/05/09) |
| Perl | @wing328 (2016/05/01) | | Perl | @wing328 (2016/05/01) |
| PHP | @arnested (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) | | Ruby | @wing328 (2016/05/01) @zlx (2016/05/22) |
| Scala | | | Scala | |
| Swift | @jaz-ah (2016/05/01) @Edubits (2016/05/01) | | Swift | @jaz-ah (2016/05/01) @Edubits (2016/05/01) |
| TypeScript (Node) | @Vrolijkx (2016/05/01) | | TypeScript (Node) | @Vrolijkx (2016/05/01) |
| TypeScript (Angular1) | @Vrolijkx (2016/05/01) | | TypeScript (Angular1) | @Vrolijkx (2016/05/01) |
| TypeScript (Angular2) | @Vrolijkx (2016/05/01) | | TypeScript (Angular2) | @Vrolijkx (2016/05/01) |
| TypeScript (Fetch) | | | TypeScript (Fetch) | |
## Server Stubs ## Server Stubs
| Languages | Core Team (date joined) | | Languages | Core Team (date joined) |
|:------------- |:-------------| |:------------- |:-------------|
| C# ASP.NET5 | @jimschubert (2016/05/01) | | C# ASP.NET5 | @jimschubert (2016/05/01) |
| Go Server | @guohuang (2016/06/13) | | Go Server | @guohuang (2016/06/13) |
| Haskell Servant | | | Haskell Servant | |
@ -862,24 +886,26 @@ Swagger Codegen core team members are contributors who have been making signific
## Template Creator ## Template Creator
Here is a list of template creators: Here is a list of template creators:
* API Clients: * API Clients:
* Akka-Scala: @cchafer * Akka-Scala: @cchafer
* C++ REST: @Danielku15 * C++ REST: @Danielku15
* C# (.NET 2.0): @who * C# (.NET 2.0): @who
* Clojure: @xhh * Clojure: @xhh
* Dart: @yissachar * Dart: @yissachar
* Groovy: @victorgit * Groovy: @victorgit
* Go: @wing328 * Go: @wing328
* Java (Feign): @davidkiss
* Java (Retrofit): @0legg * Java (Retrofit): @0legg
* Java (Retrofi2): @emilianobonassi * Java (Retrofi2): @emilianobonassi
* Java (Jersey2): @xhh * Java (Jersey2): @xhh
* Java (okhttp-gson): @xhh * Java (okhttp-gson): @xhh
* Javascript/NodeJS: @jfiala * Javascript/NodeJS: @jfiala
* Javascript (Closure-annotated Angular) @achew22 * Javascript (Closure-annotated Angular) @achew22
* JMeter @davidkiss
* Perl: @wing328 * Perl: @wing328
* Swift: @tkqubo * Swift: @tkqubo
* Swift 3: @hexelon * Swift 3: @hexelon
* TypeScript (Node): @mhardorf * TypeScript (Node): @mhardorf
* TypeScript (Angular1): @mhardorf * TypeScript (Angular1): @mhardorf
* TypeScript (Fetch): @leonyu * TypeScript (Fetch): @leonyu
* TypeScript (Angular2): @roni-frantchi * TypeScript (Angular2): @roni-frantchi
* Server Stubs * Server Stubs
@ -896,7 +922,7 @@ Here is a list of template creators:
* JAX-RS CXF (CDI): @nickcmaynard * JAX-RS CXF (CDI): @nickcmaynard
* PHP Lumen: @abcsum * PHP Lumen: @abcsum
* PHP Slim: @jfastnacht * PHP Slim: @jfastnacht
* Ruby on Rails 5: @zlx * Ruby on Rails 5: @zlx
* Documentation * Documentation
* HTML Doc 2: @jhitchcock * HTML Doc 2: @jhitchcock
* Confluence Wiki: @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: Here are the requirements to become a core team member:
- rank within top 50 in https://github.com/swagger-api/swagger-codegen/graphs/contributors - 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 - regular contributions to the project
- about 3 hours per week - 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 - 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 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. 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: 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 MAVEN_OPTS=-XX:MaxPermSize=2g -Xmx4g
- cmd: SET JAVA_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: 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 - 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" - 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: build_script:
@ -37,6 +39,6 @@ test_script:
# generate all petstore clients # generate all petstore clients
- .\bin\windows\run-all-petstore.cmd - .\bin\windows\run-all-petstore.cmd
cache: #cache:
# - C:\maven\ # - C:\maven\
# - C:\Users\appveyor\.m2 # - C:\Users\appveyor\.m2

View File

@ -27,7 +27,7 @@ fi
# if you've executed sbt assembly previously it will use that instead. # 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" 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: # 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" #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. # 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" 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 -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 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. # 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" 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 java $JAVA_OPTS -Dservice -jar $executable $ags

View File

@ -9,3 +9,4 @@
./bin/java-petstore-retrofit2.sh ./bin/java-petstore-retrofit2.sh
./bin/java-petstore-retrofit2rx.sh ./bin/java-petstore-retrofit2rx.sh
./bin/java8-petstore-jersey2.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. # 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" 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 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> </execution>
</executions> </executions>
</plugin> </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> </plugins>
</build> </build>

View File

@ -27,7 +27,7 @@
<!-- pass any necessary config options --> <!-- pass any necessary config options -->
<configOptions> <configOptions>
<dateLibrary>java8</dateLibrary> <dateLibrary>joda</dateLibrary>
</configOptions> </configOptions>
<!-- override the default library to jersey2 --> <!-- override the default library to jersey2 -->
@ -39,17 +39,26 @@
</plugins> </plugins>
</build> </build>
<dependencies> <dependencies>
<!-- dependencies are needed for the client being generated --> <!-- dependencies are needed for the client being generated -->
<dependency> <dependency>
<groupId>io.swagger</groupId> <groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId> <artifactId>swagger-annotations</artifactId>
<version>${swagger-annotations-version}</version> <version>${swagger-annotations-version}</version>
</dependency> </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 --> <!-- HTTP client: jersey-client -->
<dependency> <dependency>
<groupId>org.glassfish.jersey.core</groupId> <groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId> <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> <version>${jersey-version}</version>
</dependency> </dependency>
<dependency> <dependency>
@ -57,58 +66,59 @@
<artifactId>jersey-media-multipart</artifactId> <artifactId>jersey-media-multipart</artifactId>
<version>${jersey-version}</version> <version>${jersey-version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.22.1</version>
</dependency>
<!-- JSON processing: jackson --> <!-- JSON processing: jackson -->
<dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId> <groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-core</artifactId> <artifactId>jackson-jaxrs-base</artifactId>
<version>${jackson-version}</version> <version>${jackson-version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId> <groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId> <artifactId>jackson-core</artifactId>
<version>${jackson-version}</version> <version>${jackson-version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId> <groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId> <artifactId>jackson-annotations</artifactId>
<version>${jackson-version}</version> <version>${jackson-version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.fasterxml.jackson.datatype</groupId> <groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-datatype-joda</artifactId> <artifactId>jackson-databind</artifactId>
<version>2.1.5</version> <version>${jackson-version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>joda-time</groupId> <groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>joda-time</artifactId> <artifactId>jackson-jaxrs-json-provider</artifactId>
<version>${jodatime-version}</version> <version>${jackson-version}</version>
</dependency> </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 --> <!-- Base64 encoding that works in both JVM and Android -->
<dependency> <dependency>
<groupId>com.brsanthu</groupId> <groupId>com.brsanthu</groupId>
<artifactId>migbase64</artifactId> <artifactId>migbase64</artifactId>
<version>2.2</version> <version>2.2</version>
</dependency> </dependency>
<!-- test dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-version}</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<properties> <properties>
<swagger-annotations-version>1.5.0</swagger-annotations-version> <swagger-annotations-version>1.5.8</swagger-annotations-version>
<jersey-version>2.12</jersey-version> <jersey-version>2.22.2</jersey-version>
<jackson-version>2.4.2</jackson-version> <jackson-version>2.7.0</jackson-version>
<jodatime-version>2.3</jodatime-version> <jodatime-version>2.7</jodatime-version>
<maven-plugin-version>1.0.0</maven-plugin-version> <maven-plugin-version>1.0.0</maven-plugin-version>
<junit-version>4.8.1</junit-version> <junit-version>4.8.1</junit-version>
</properties> </properties>

View File

@ -83,5 +83,15 @@
</plugin> </plugin>
</plugins> </plugins>
</pluginManagement> </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> </build>
</project> </project>

View File

@ -110,6 +110,14 @@
<artifactId>maven-release-plugin</artifactId> <artifactId>maven-release-plugin</artifactId>
<version>2.5.3</version> <version>2.5.3</version>
</plugin> </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> </plugins>
</build> </build>
<profiles> <profiles>

View File

@ -16,6 +16,9 @@ public class CodegenConstants {
public static final String INVOKER_PACKAGE = "invokerPackage"; public static final String INVOKER_PACKAGE = "invokerPackage";
public static final String INVOKER_PACKAGE_DESC = "root package for generated code"; 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 = "groupId";
public static final String GROUP_ID_DESC = "groupId in generated pom.xml"; 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 = "artifactVersion";
public static final String ARTIFACT_VERSION_DESC = "artifact version in generated pom.xml"; 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 = "sourceFolder";
public static final String SOURCE_FOLDER_DESC = "source folder for generated code"; 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 = "implFolder";
public static final String IMPL_FOLDER_DESC = "folder for generated implementation code"; 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 = "localVariablePrefix";
public static final String LOCAL_VARIABLE_PREFIX_DESC = "prefix for generated code members and local variables"; 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 = "useDateTimeOffset";
public static final String USE_DATETIME_OFFSET_DESC = "Use DateTimeOffset to model date-time properties"; 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 = "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 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_NAME = "packageName";
public static final String PACKAGE_VERSION = "packageVersion"; public static final String PACKAGE_VERSION = "packageVersion";
public static final String PACKAGE_TITLE = "packageTitle"; 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_TITLE_DESC = "Specifies an AssemblyTitle for the .NET Framework global assembly attributes stored in the AssemblyInfo file.";
public static final String PACKAGE_PRODUCTNAME = "packageProductName"; 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_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 = "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 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 POD_VERSION = "podVersion";
public static final String OPTIONAL_METHOD_ARGUMENT = "optionalMethodArgument"; 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 = "returnICollection";
public static final String RETURN_ICOLLECTION_DESC = "Return ICollection<T> instead of the concrete type."; 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 = "optionalProjectFile";
public static final String OPTIONAL_PROJECT_FILE_DESC = "Generate {PackageName}.csproj."; 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 = "packageGuid";
public static final String OPTIONAL_PROJECT_GUID_DESC = "The GUID that will be associated with the C# project"; 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 = "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"; 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 = "generatePropertyChanged";
public static final String GENERATE_PROPERTY_CHANGED_DESC = "Specifies that models support raising property changed events."; 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. // References to parent and interface CodegenModels. Only set when code generator supports inheritance.
public CodegenModel parentModel; public CodegenModel parentModel;
public List<CodegenModel> interfaceModels; public List<CodegenModel> interfaceModels;
public List<CodegenModel> children;
public String name, classname, title, description, classVarName, modelJson, dataType; public String name, classname, title, description, classVarName, modelJson, dataType;
public String classFilename; // store the class file name, mainly used for import 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> allMandatory;
public Set<String> imports = new TreeSet<String>(); public Set<String> imports = new TreeSet<String>();
public Boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum, hasRequired, isArrayModel, hasChildren; public boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum, hasRequired, isArrayModel, hasChildren;
public Boolean hasOnlyReadOnly = true; // true if all properties are read-only public boolean hasOnlyReadOnly = true; // true if all properties are read-only
public ExternalDocs externalDocs; public ExternalDocs externalDocs;
public Map<String, Object> vendorExtensions; public Map<String, Object> vendorExtensions;
@ -114,15 +115,15 @@ public class CodegenModel {
return false; return false;
if (imports != null ? !imports.equals(that.imports) : that.imports != null) if (imports != null ? !imports.equals(that.imports) : that.imports != null)
return false; return false;
if (hasVars != null ? !hasVars.equals(that.hasVars) : that.hasVars != null) if (hasVars != that.hasVars)
return false; return false;
if (emptyVars != null ? !emptyVars.equals(that.emptyVars) : that.emptyVars != null) if (emptyVars != that.emptyVars)
return false; return false;
if (hasMoreModels != null ? !hasMoreModels.equals(that.hasMoreModels) : that.hasMoreModels != null) if (hasMoreModels != that.hasMoreModels)
return false; return false;
if (hasEnums != null ? !hasEnums.equals(that.hasEnums) : that.hasEnums != null) if (hasEnums != that.hasEnums)
return false; return false;
if (isEnum != null ? !isEnum.equals(that.isEnum) : that.isEnum != null) if (isEnum != that.isEnum)
return false; return false;
if (externalDocs != null ? !externalDocs.equals(that.externalDocs) : that.externalDocs != null) if (externalDocs != null ? !externalDocs.equals(that.externalDocs) : that.externalDocs != null)
return false; return false;
@ -162,11 +163,11 @@ public class CodegenModel {
result = 31 * result + (mandatory != null ? mandatory.hashCode() : 0); result = 31 * result + (mandatory != null ? mandatory.hashCode() : 0);
result = 31 * result + (allMandatory != null ? allMandatory.hashCode() : 0); result = 31 * result + (allMandatory != null ? allMandatory.hashCode() : 0);
result = 31 * result + (imports != null ? imports.hashCode() : 0); result = 31 * result + (imports != null ? imports.hashCode() : 0);
result = 31 * result + (hasVars != null ? hasVars.hashCode() : 0); result = 31 * result + (hasVars ? 13:31);
result = 31 * result + (emptyVars != null ? emptyVars.hashCode() : 0); result = 31 * result + (emptyVars ? 13:31);
result = 31 * result + (hasMoreModels != null ? hasMoreModels.hashCode() : 0); result = 31 * result + (hasMoreModels ? 13:31);
result = 31 * result + (hasEnums != null ? hasEnums.hashCode() : 0); result = 31 * result + (hasEnums ? 13:31);
result = 31 * result + (isEnum != null ? isEnum.hashCode() : 0); result = 31 * result + (isEnum ? 13:31);
result = 31 * result + (externalDocs != null ? externalDocs.hashCode() : 0); result = 31 * result + (externalDocs != null ? externalDocs.hashCode() : 0);
result = 31 * result + (vendorExtensions != null ? vendorExtensions.hashCode() : 0); result = 31 * result + (vendorExtensions != null ? vendorExtensions.hashCode() : 0);
result = 31 * result + Objects.hash(hasOnlyReadOnly); result = 31 * result + Objects.hash(hasOnlyReadOnly);

View File

@ -11,10 +11,10 @@ import java.util.Arrays;
public class CodegenOperation { public class CodegenOperation {
public final List<CodegenProperty> responseHeaders = new ArrayList<CodegenProperty>(); 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, returnTypeIsPrimitive, returnSimpleType, subresourceOperation, isMapContainer,
isListContainer, isMultipart, hasMore = Boolean.TRUE, isListContainer, isMultipart, hasMore = true,
isResponseBinary = Boolean.FALSE, hasReference = Boolean.FALSE, isResponseBinary = false, isResponseFile = false, hasReference = false,
isRestfulIndex, isRestfulShow, isRestfulCreate, isRestfulUpdate, isRestfulDestroy, isRestfulIndex, isRestfulShow, isRestfulCreate, isRestfulUpdate, isRestfulDestroy,
isRestful; isRestful;
public String path, operationId, returnType, httpMethod, returnBaseType, public String path, operationId, returnType, httpMethod, returnBaseType,
@ -189,33 +189,35 @@ public class CodegenOperation {
if (responseHeaders != null ? !responseHeaders.equals(that.responseHeaders) : that.responseHeaders != null) if (responseHeaders != null ? !responseHeaders.equals(that.responseHeaders) : that.responseHeaders != null)
return false; return false;
if (hasAuthMethods != null ? !hasAuthMethods.equals(that.hasAuthMethods) : that.hasAuthMethods != null) if (hasAuthMethods != that.hasAuthMethods)
return false; return false;
if (hasConsumes != null ? !hasConsumes.equals(that.hasConsumes) : that.hasConsumes != null) if (hasConsumes != that.hasConsumes)
return false; return false;
if (hasProduces != null ? !hasProduces.equals(that.hasProduces) : that.hasProduces != null) if (hasProduces != that.hasProduces)
return false; return false;
if (hasParams != null ? !hasParams.equals(that.hasParams) : that.hasParams != null) if (hasParams != that.hasParams)
return false; return false;
if (hasOptionalParams != null ? !hasOptionalParams.equals(that.hasOptionalParams) : that.hasOptionalParams != null) if (hasOptionalParams != that.hasOptionalParams)
return false; return false;
if (returnTypeIsPrimitive != null ? !returnTypeIsPrimitive.equals(that.returnTypeIsPrimitive) : that.returnTypeIsPrimitive != null) if (returnTypeIsPrimitive != that.returnTypeIsPrimitive)
return false; return false;
if (returnSimpleType != null ? !returnSimpleType.equals(that.returnSimpleType) : that.returnSimpleType != null) if (returnSimpleType != that.returnSimpleType)
return false; return false;
if (subresourceOperation != null ? !subresourceOperation.equals(that.subresourceOperation) : that.subresourceOperation != null) if (subresourceOperation != that.subresourceOperation)
return false; return false;
if (isMapContainer != null ? !isMapContainer.equals(that.isMapContainer) : that.isMapContainer != null) if (isMapContainer != that.isMapContainer)
return false; return false;
if (isListContainer != null ? !isListContainer.equals(that.isListContainer) : that.isListContainer != null) if (isListContainer != that.isListContainer)
return false; return false;
if (isMultipart != null ? !isMultipart.equals(that.isMultipart) : that.isMultipart != null) if (isMultipart != that.isMultipart)
return false; return false;
if (hasMore != null ? !hasMore.equals(that.hasMore) : that.hasMore != null) if (hasMore != that.hasMore)
return false; return false;
if (isResponseBinary != null ? !isResponseBinary.equals(that.isResponseBinary) : that.isResponseBinary != null) if (isResponseBinary != that.isResponseBinary)
return false; return false;
if (hasReference != null ? !hasReference.equals(that.hasReference) : that.hasReference != null) if (hasReference != that.hasReference)
return false;
if (isResponseFile != that.isResponseFile)
return false; return false;
if (path != null ? !path.equals(that.path) : that.path != null) if (path != null ? !path.equals(that.path) : that.path != null)
return false; return false;
@ -284,20 +286,21 @@ public class CodegenOperation {
@Override @Override
public int hashCode() { public int hashCode() {
int result = responseHeaders.hashCode(); int result = responseHeaders.hashCode();
result = 31 * result + (hasAuthMethods != null ? hasAuthMethods.hashCode() : 0); result = 31 * result + (hasAuthMethods ? 13:31);
result = 31 * result + (hasConsumes != null ? hasConsumes.hashCode() : 0); result = 31 * result + (hasConsumes ? 13:31);
result = 31 * result + (hasProduces != null ? hasProduces.hashCode() : 0); result = 31 * result + (hasProduces ? 13:31);
result = 31 * result + (hasParams != null ? hasParams.hashCode() : 0); result = 31 * result + (hasParams ? 13:31);
result = 31 * result + (hasOptionalParams != null ? hasOptionalParams.hashCode() : 0); result = 31 * result + (hasOptionalParams ? 13:31);
result = 31 * result + (returnTypeIsPrimitive != null ? returnTypeIsPrimitive.hashCode() : 0); result = 31 * result + (returnTypeIsPrimitive ? 13:31);
result = 31 * result + (returnSimpleType != null ? returnSimpleType.hashCode() : 0); result = 31 * result + (returnSimpleType ? 13:31);
result = 31 * result + (subresourceOperation != null ? subresourceOperation.hashCode() : 0); result = 31 * result + (subresourceOperation ? 13:31);
result = 31 * result + (isMapContainer != null ? isMapContainer.hashCode() : 0); result = 31 * result + (isMapContainer ? 13:31);
result = 31 * result + (isListContainer != null ? isListContainer.hashCode() : 0); result = 31 * result + (isListContainer ? 13:31);
result = 31 * result + (isMultipart != null ? isMultipart.hashCode() : 0); result = 31 * result + (isMultipart ? 13:31);
result = 31 * result + (hasMore != null ? hasMore.hashCode() : 0); result = 31 * result + (hasMore ? 13:31);
result = 31 * result + (isResponseBinary != null ? isResponseBinary.hashCode() : 0); result = 31 * result + (isResponseBinary ? 13:31);
result = 31 * result + (hasReference != null ? hasReference.hashCode() : 0); result = 31 * result + (isResponseFile ? 13:31);
result = 31 * result + (hasReference ? 13:31);
result = 31 * result + (path != null ? path.hashCode() : 0); result = 31 * result + (path != null ? path.hashCode() : 0);
result = 31 * result + (operationId != null ? operationId.hashCode() : 0); result = 31 * result + (operationId != null ? operationId.hashCode() : 0);
result = 31 * result + (returnType != null ? returnType.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. * 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 * 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 * 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 * See http://json-schema.org/latest/json-schema-validation.html#anchor21
*/ */
@ -122,7 +122,9 @@ public class CodegenParameter {
if (this.items != null) { if (this.items != null) {
output.items = this.items; 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.hasValidation = this.hasValidation;
output.isBinary = this.isBinary; output.isBinary = this.isBinary;
output.isByteArray = this.isByteArray; output.isByteArray = this.isByteArray;

View File

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

View File

@ -16,6 +16,7 @@ public class CodegenResponse {
public Boolean isMapContainer; public Boolean isMapContainer;
public Boolean isListContainer; public Boolean isListContainer;
public Boolean isBinary = Boolean.FALSE; public Boolean isBinary = Boolean.FALSE;
public Boolean isFile = Boolean.FALSE;
public Object schema; public Object schema;
public String jsonSchema; public String jsonSchema;
@ -63,6 +64,8 @@ public class CodegenResponse {
return false; return false;
if (isBinary != null ? !isBinary.equals(that.isBinary) : that.isBinary != null) if (isBinary != null ? !isBinary.equals(that.isBinary) : that.isBinary != null)
return false; return false;
if (isFile != null ? !isFile.equals(that.isFile) : that.isFile != null)
return false;
if (schema != null ? !schema.equals(that.schema) : that.schema != null) if (schema != null ? !schema.equals(that.schema) : that.schema != null)
return false; return false;
return jsonSchema != null ? jsonSchema.equals(that.jsonSchema) : that.jsonSchema == null; 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 + (isMapContainer != null ? isMapContainer.hashCode() : 0);
result = 31 * result + (isListContainer != null ? isListContainer.hashCode() : 0); result = 31 * result + (isListContainer != null ? isListContainer.hashCode() : 0);
result = 31 * result + (isBinary != null ? isBinary.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 + (schema != null ? schema.hashCode() : 0);
result = 31 * result + (jsonSchema != null ? jsonSchema.hashCode() : 0); result = 31 * result + (jsonSchema != null ? jsonSchema.hashCode() : 0);
return result; 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.DateTimeProperty;
import io.swagger.models.properties.DecimalProperty; import io.swagger.models.properties.DecimalProperty;
import io.swagger.models.properties.DoubleProperty; import io.swagger.models.properties.DoubleProperty;
import io.swagger.models.properties.FileProperty;
import io.swagger.models.properties.FloatProperty; import io.swagger.models.properties.FloatProperty;
import io.swagger.models.properties.IntegerProperty; import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty; 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; return objs;
} }
@ -205,7 +218,6 @@ public class DefaultCodegen {
// for enum model // for enum model
if (Boolean.TRUE.equals(cm.isEnum) && cm.allowableValues != null) { if (Boolean.TRUE.equals(cm.isEnum) && cm.allowableValues != null) {
Map<String, Object> allowableValues = cm.allowableValues; Map<String, Object> allowableValues = cm.allowableValues;
List<Object> values = (List<Object>) allowableValues.get("values"); List<Object> values = (List<Object>) allowableValues.get("values");
List<Map<String, String>> enumVars = new ArrayList<Map<String, String>>(); List<Map<String, String>> enumVars = new ArrayList<Map<String, String>>();
String commonPrefix = findCommonPrefixOfVars(values); String commonPrefix = findCommonPrefixOfVars(values);
@ -247,7 +259,6 @@ public class DefaultCodegen {
public String findCommonPrefixOfVars(List<Object> vars) { public String findCommonPrefixOfVars(List<Object> vars) {
try { try {
String[] listStr = vars.toArray(new String[vars.size()]); String[] listStr = vars.toArray(new String[vars.size()]);
String prefix = StringUtils.getCommonPrefix(listStr); String prefix = StringUtils.getCommonPrefix(listStr);
// exclude trailing characters that should be part of a valid variable // exclude trailing characters that should be part of a valid variable
// e.g. ["status-on", "status-off"] => "status-" (not "status-o") // e.g. ["status-on", "status-off"] => "status-" (not "status-o")
@ -350,7 +361,13 @@ public class DefaultCodegen {
// replace " with \" // replace " with \"
// outter unescape to retain the original multi-byte characters // outter unescape to retain the original multi-byte characters
// finally escalate characters avoiding code injection // 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 * @return string with unsafe characters removed or escaped
*/ */
public String escapeUnsafeCharacters(String input) { 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 // doing nothing by default and code generator should implement
// the logic to prevent code injection // the logic to prevent code injection
// later we'll make this method abstract to make sure // 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 * @return string with quotation mark removed or escaped
*/ */
public String escapeQuotationMark(String input) { 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("\"", "\\\""); return input.replace("\"", "\\\"");
} }
@ -765,6 +784,7 @@ public class DefaultCodegen {
typeMapping.put("integer", "Integer"); typeMapping.put("integer", "Integer");
typeMapping.put("ByteArray", "byte[]"); typeMapping.put("ByteArray", "byte[]");
typeMapping.put("binary", "byte[]"); typeMapping.put("binary", "byte[]");
typeMapping.put("file", "File");
instantiationTypes = new HashMap<String, String>(); instantiationTypes = new HashMap<String, String>();
@ -1069,6 +1089,8 @@ public class DefaultCodegen {
datatype = "ByteArray"; datatype = "ByteArray";
} else if (p instanceof BinaryProperty) { } else if (p instanceof BinaryProperty) {
datatype = "binary"; datatype = "binary";
} else if (p instanceof FileProperty) {
datatype = "file";
} else if (p instanceof BooleanProperty) { } else if (p instanceof BooleanProperty) {
datatype = "boolean"; datatype = "boolean";
} else if (p instanceof DateProperty) { } 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 * @param name the name of the model
* @return capitalized model name * @return capitalized model name
@ -1220,11 +1243,9 @@ public class DefaultCodegen {
m.discriminator = ((ModelImpl) model).getDiscriminator(); m.discriminator = ((ModelImpl) model).getDiscriminator();
} }
if (model instanceof ArrayModel) { if (model instanceof ArrayModel) {
ArrayModel am = (ArrayModel) model; ArrayModel am = (ArrayModel) model;
ArrayProperty arrayProperty = new ArrayProperty(am.getItems()); ArrayProperty arrayProperty = new ArrayProperty(am.getItems());
m.hasEnums = false; // Otherwise there will be a NullPointerException in JavaClientCodegen.fromModel
m.isArrayModel = true; m.isArrayModel = true;
m.arrayModelType = fromProperty(name, arrayProperty).complexType; m.arrayModelType = fromProperty(name, arrayProperty).complexType;
addParentContainer(m, name, arrayProperty); addParentContainer(m, name, arrayProperty);
@ -1307,7 +1328,7 @@ public class DefaultCodegen {
addVars(m, properties, required, allProperties, allRequired); addVars(m, properties, required, allProperties, allRequired);
} else { } else {
ModelImpl impl = (ModelImpl) model; ModelImpl impl = (ModelImpl) model;
if (m != null && impl.getType() != null) { if (impl.getType() != null) {
Property p = PropertyBuilder.build(impl.getType(), impl.getFormat(), null); Property p = PropertyBuilder.build(impl.getType(), impl.getFormat(), null);
m.dataType = getSwaggerType(p); m.dataType = getSwaggerType(p);
} }
@ -1338,7 +1359,7 @@ public class DefaultCodegen {
if (model == null || allDefinitions == null) if (model == null || allDefinitions == null)
return false; return false;
Model child = ((ComposedModel) model).getChild(); Model child = model.getChild();
if (child instanceof ModelImpl && ((ModelImpl) child).getDiscriminator() != null) { if (child instanceof ModelImpl && ((ModelImpl) child).getDiscriminator() != null) {
return true; return true;
} }
@ -1360,7 +1381,9 @@ public class DefaultCodegen {
addParentContainer(codegenModel, codegenModel.name, mapProperty); 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) { if (model instanceof ModelImpl) {
ModelImpl mi = (ModelImpl) model; ModelImpl mi = (ModelImpl) model;
@ -1391,9 +1414,7 @@ public class DefaultCodegen {
if (name == null || name.length() == 0) { if (name == null || name.length() == 0) {
return name; return name;
} }
return camelize(toVarName(name)); return camelize(toVarName(name));
} }
/** /**
@ -1410,7 +1431,6 @@ public class DefaultCodegen {
} }
CodegenProperty property = CodegenModelFactory.newInstance(CodegenModelType.PROPERTY); CodegenProperty property = CodegenModelFactory.newInstance(CodegenModelType.PROPERTY);
property.name = toVarName(name); property.name = toVarName(name);
property.baseName = name; property.baseName = name;
property.nameInCamelCase = camelize(property.name, false); property.nameInCamelCase = camelize(property.name, false);
@ -1422,16 +1442,35 @@ public class DefaultCodegen {
property.defaultValue = toDefaultValue(p); property.defaultValue = toDefaultValue(p);
property.defaultValueWithParam = toDefaultValueWithParam(name, p); property.defaultValueWithParam = toDefaultValueWithParam(name, p);
property.jsonSchema = Json.pretty(p); property.jsonSchema = Json.pretty(p);
property.isReadOnly = p.getReadOnly(); if (p.getReadOnly() != null) {
property.isReadOnly = p.getReadOnly();
}
property.vendorExtensions = p.getVendorExtensions(); property.vendorExtensions = p.getVendorExtensions();
String type = getSwaggerType(p); String type = getSwaggerType(p);
if (p instanceof AbstractNumericProperty) { if (p instanceof AbstractNumericProperty) {
AbstractNumericProperty np = (AbstractNumericProperty) p; AbstractNumericProperty np = (AbstractNumericProperty) p;
property.minimum = np.getMinimum(); if (np.getMinimum() != null) {
property.maximum = np.getMaximum(); if (p instanceof BaseIntegerProperty) { // int, long
property.exclusiveMinimum = np.getExclusiveMinimum(); property.minimum = String.valueOf(np.getMinimum().longValue());
property.exclusiveMaximum = np.getExclusiveMaximum(); } 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 // check if any validation rule defined
// exclusive* are noop without corresponding min/max // exclusive* are noop without corresponding min/max
@ -1492,7 +1531,6 @@ public class DefaultCodegen {
property.allowableValues = allowableValues; property.allowableValues = allowableValues;
}*/ }*/
} }
if (p instanceof IntegerProperty) { if (p instanceof IntegerProperty) {
IntegerProperty sp = (IntegerProperty) p; IntegerProperty sp = (IntegerProperty) p;
property.isInteger = true; property.isInteger = true;
@ -1510,7 +1548,6 @@ public class DefaultCodegen {
property.allowableValues = allowableValues; property.allowableValues = allowableValues;
} }
} }
if (p instanceof LongProperty) { if (p instanceof LongProperty) {
LongProperty sp = (LongProperty) p; LongProperty sp = (LongProperty) p;
property.isLong = true; property.isLong = true;
@ -1528,21 +1565,21 @@ public class DefaultCodegen {
property.allowableValues = allowableValues; property.allowableValues = allowableValues;
} }
} }
if (p instanceof BooleanProperty) { if (p instanceof BooleanProperty) {
property.isBoolean = true; property.isBoolean = true;
} }
if (p instanceof BinaryProperty) { if (p instanceof BinaryProperty) {
property.isBinary = true; property.isBinary = true;
} }
if (p instanceof FileProperty) {
property.isFile = true;
}
if (p instanceof UUIDProperty) { if (p instanceof UUIDProperty) {
property.isString = true; property.isString = true;
} }
if (p instanceof ByteArrayProperty) { if (p instanceof ByteArrayProperty) {
property.isByteArray = true; property.isByteArray = true;
} }
// type is number and without format // type is number and without format
if (p instanceof DecimalProperty && !(p instanceof DoubleProperty) && !(p instanceof FloatProperty)) { if (p instanceof DecimalProperty && !(p instanceof DoubleProperty) && !(p instanceof FloatProperty)) {
DecimalProperty sp = (DecimalProperty) p; DecimalProperty sp = (DecimalProperty) p;
@ -1561,7 +1598,6 @@ public class DefaultCodegen {
property.allowableValues = allowableValues; property.allowableValues = allowableValues;
}*/ }*/
} }
if (p instanceof DoubleProperty) { if (p instanceof DoubleProperty) {
DoubleProperty sp = (DoubleProperty) p; DoubleProperty sp = (DoubleProperty) p;
property.isDouble = true; property.isDouble = true;
@ -1579,7 +1615,6 @@ public class DefaultCodegen {
property.allowableValues = allowableValues; property.allowableValues = allowableValues;
} }
} }
if (p instanceof FloatProperty) { if (p instanceof FloatProperty) {
FloatProperty sp = (FloatProperty) p; FloatProperty sp = (FloatProperty) p;
property.isFloat = true; property.isFloat = true;
@ -1615,7 +1650,6 @@ public class DefaultCodegen {
property.allowableValues = allowableValues; property.allowableValues = allowableValues;
} }
} }
if (p instanceof DateTimeProperty) { if (p instanceof DateTimeProperty) {
DateTimeProperty sp = (DateTimeProperty) p; DateTimeProperty sp = (DateTimeProperty) p;
property.isDateTime = true; property.isDateTime = true;
@ -1678,25 +1712,26 @@ public class DefaultCodegen {
protected void updatePropertyForArray(CodegenProperty property, CodegenProperty innerProperty) { protected void updatePropertyForArray(CodegenProperty property, CodegenProperty innerProperty) {
if (innerProperty == null) { if (innerProperty == null) {
LOGGER.warn("skipping invalid array property " + Json.pretty(property)); LOGGER.warn("skipping invalid array property " + Json.pretty(property));
} else { 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);
}
} }
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) { if (innerProperty == null) {
LOGGER.warn("skipping invalid map property " + Json.pretty(property)); LOGGER.warn("skipping invalid map property " + Json.pretty(property));
return; return;
}
if (!languageSpecificPrimitives.contains(innerProperty.baseType)) {
property.complexType = innerProperty.baseType;
} else { } else {
if (!languageSpecificPrimitives.contains(innerProperty.baseType)) { property.isPrimitiveType = true;
property.complexType = innerProperty.baseType; }
} else { property.items = innerProperty;
property.isPrimitiveType = true; // inner item is Enum
} if (isPropertyInnerMostEnum(property)) {
property.items = innerProperty; // isEnum is set to true when the type is an enum
// inner item is Enum // or the inner type of an array/map is an enum
if (isPropertyInnerMostEnum(property)) { property.isEnum = true;
// isEnum is set to true when the type is an enum // update datatypeWithEnum and default value for map
// or the inner type of an array/map is an enum // e.g. Dictionary<string, string> => Dictionary<string, StatusEnum>
property.isEnum = true; updateDataTypeWithEnumForMap(property);
// update datatypeWithEnum and default value for map // set allowable values to enum values (including array/map of enum)
// e.g. Dictionary<string, string> => Dictionary<string, StatusEnum> property.allowableValues = getInnerEnumAllowableValues(property);
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 * @param swagger a Swagger object representing the spec
* @return Codegen Operation object * @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); CodegenOperation op = CodegenModelFactory.newInstance(CodegenModelType.OPERATION);
Set<String> imports = new HashSet<String>(); Set<String> imports = new HashSet<String>();
op.vendorExtensions = operation.getVendorExtensions(); op.vendorExtensions = operation.getVendorExtensions();
@ -1924,7 +1962,7 @@ public class DefaultCodegen {
} }
// if "produces" is defined (per operation or using global definition) // 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>>(); List<Map<String, String>> c = new ArrayList<Map<String, String>>();
int count = 0; int count = 0;
for (String key : produces) { for (String key : produces) {
@ -1964,6 +2002,9 @@ public class DefaultCodegen {
if (r.isBinary && r.isDefault){ if (r.isBinary && r.isDefault){
op.isResponseBinary = Boolean.TRUE; op.isResponseBinary = Boolean.TRUE;
} }
if (r.isFile && r.isDefault){
op.isResponseFile = Boolean.TRUE;
}
} }
op.responses.get(op.responses.size() - 1).hasMore = false; 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; op.returnContainer = cm.containerType;
if ("map".equals(cm.containerType)) { if ("map".equals(cm.containerType)) {
op.isMapContainer = Boolean.TRUE; op.isMapContainer = true;
} else if ("list".equalsIgnoreCase(cm.containerType)) { } else if ("list".equalsIgnoreCase(cm.containerType)) {
op.isListContainer = Boolean.TRUE; op.isListContainer = true;
} else if ("array".equalsIgnoreCase(cm.containerType)) { } else if ("array".equalsIgnoreCase(cm.containerType)) {
op.isListContainer = Boolean.TRUE; op.isListContainer = true;
} }
} else { } else {
op.returnSimpleType = true; op.returnSimpleType = true;
@ -2163,11 +2204,12 @@ public class DefaultCodegen {
} }
r.dataType = cm.datatype; r.dataType = cm.datatype;
r.isBinary = isDataTypeBinary(cm.datatype); r.isBinary = isDataTypeBinary(cm.datatype);
if (cm.isContainer != null) { r.isFile = isDataTypeFile(cm.datatype);
if (cm.isContainer) {
r.simpleType = false; r.simpleType = false;
r.containerType = cm.containerType; r.containerType = cm.containerType;
r.isMapContainer = "map".equals(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 { } else {
r.simpleType = true; r.simpleType = true;
} }
@ -2200,27 +2242,36 @@ public class DefaultCodegen {
p.jsonSchema = Json.pretty(param); p.jsonSchema = Json.pretty(param);
if (System.getProperty("debugParser") != null) { 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 // move the defaultValue for headers, forms and params
if (param instanceof QueryParameter) { 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) { } 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) { } 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(); p.vendorExtensions = param.getVendorExtensions();
if (param instanceof SerializableParameter) { if (param instanceof SerializableParameter) {
SerializableParameter qp = (SerializableParameter) param; SerializableParameter qp = (SerializableParameter) param;
Property property = null; Property property;
String collectionFormat = null; String collectionFormat = null;
String type = qp.getType(); String type = qp.getType();
if (null == type) { 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 if ("array".equals(type)) { // for array parameter
Property inner = qp.getItems(); Property inner = qp.getItems();
@ -2234,6 +2285,7 @@ public class DefaultCodegen {
collectionFormat = "csv"; collectionFormat = "csv";
} }
CodegenProperty pr = fromProperty("inner", inner); CodegenProperty pr = fromProperty("inner", inner);
p.items = pr;
p.baseType = pr.datatype; p.baseType = pr.datatype;
p.isContainer = true; p.isContainer = true;
p.isListContainer = true; p.isListContainer = true;
@ -2247,6 +2299,7 @@ public class DefaultCodegen {
property = new MapProperty(inner); property = new MapProperty(inner);
collectionFormat = qp.getCollectionFormat(); collectionFormat = qp.getCollectionFormat();
CodegenProperty pr = fromProperty("inner", inner); CodegenProperty pr = fromProperty("inner", inner);
p.items = pr;
p.baseType = pr.datatype; p.baseType = pr.datatype;
p.isContainer = true; p.isContainer = true;
p.isMapContainer = true; p.isMapContainer = true;
@ -2300,9 +2353,16 @@ public class DefaultCodegen {
} }
// validation // 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.exclusiveMaximum = qp.isExclusiveMaximum();
p.minimum = qp.getMinimum();
p.exclusiveMinimum = qp.isExclusiveMinimum(); p.exclusiveMinimum = qp.isExclusiveMinimum();
p.maxLength = qp.getMaxLength(); p.maxLength = qp.getMaxLength();
p.minLength = qp.getMinLength(); p.minLength = qp.getMinLength();
@ -2331,7 +2391,7 @@ public class DefaultCodegen {
if (model instanceof ModelImpl) { if (model instanceof ModelImpl) {
ModelImpl impl = (ModelImpl) model; ModelImpl impl = (ModelImpl) model;
CodegenModel cm = fromModel(bp.getName(), impl); CodegenModel cm = fromModel(bp.getName(), impl);
if (cm.emptyVars != null && cm.emptyVars == false) { if (!cm.emptyVars) {
p.dataType = getTypeDeclaration(cm.classname); p.dataType = getTypeDeclaration(cm.classname);
imports.add(p.dataType); imports.add(p.dataType);
} else { } else {
@ -2343,6 +2403,7 @@ public class DefaultCodegen {
p.dataType = cp.datatype; p.dataType = cp.datatype;
p.isPrimitiveType = cp.isPrimitiveType; p.isPrimitiveType = cp.isPrimitiveType;
p.isBinary = isDataTypeBinary(cp.datatype); p.isBinary = isDataTypeBinary(cp.datatype);
p.isFile = isDataTypeFile(cp.datatype);
} }
// set boolean flag (e.g. isString) // set boolean flag (e.g. isString)
@ -2360,6 +2421,7 @@ public class DefaultCodegen {
imports.add(cp.complexType); imports.add(cp.complexType);
} }
imports.add(cp.baseType); imports.add(cp.baseType);
p.items = cp;
p.dataType = cp.datatype; p.dataType = cp.datatype;
p.baseType = cp.complexType; p.baseType = cp.complexType;
p.isPrimitiveType = cp.isPrimitiveType; p.isPrimitiveType = cp.isPrimitiveType;
@ -2389,6 +2451,31 @@ public class DefaultCodegen {
p.paramName = toParamName(bp.getName()); 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 // set the example value
// if not specified in x-example, generate a default value // if not specified in x-example, generate a default value
if (p.vendorExtensions.containsKey("x-example")) { if (p.vendorExtensions.containsKey("x-example")) {
@ -2409,14 +2496,13 @@ public class DefaultCodegen {
p.example = "BINARY_DATA_HERE"; p.example = "BINARY_DATA_HERE";
} else if (Boolean.TRUE.equals(p.isByteArray)) { } else if (Boolean.TRUE.equals(p.isByteArray)) {
p.example = "B"; p.example = "B";
} else if (Boolean.TRUE.equals(p.isFile)) {
p.example = "/path/to/file.txt";
} else if (Boolean.TRUE.equals(p.isDate)) { } else if (Boolean.TRUE.equals(p.isDate)) {
p.example = "2013-10-20"; p.example = "2013-10-20";
} else if (Boolean.TRUE.equals(p.isDateTime)) { } else if (Boolean.TRUE.equals(p.isDateTime)) {
p.example = "2013-10-20T19:20:30+01:00"; p.example = "2013-10-20T19:20:30+01:00";
} else if (param instanceof FormParameter && } else if (Boolean.TRUE.equals(p.isFile)) {
("file".equalsIgnoreCase(((FormParameter) param).getType()) ||
"file".equals(p.baseType))) {
p.isFile = true;
p.example = "/path/to/file.txt"; p.example = "/path/to/file.txt";
} }
@ -2424,33 +2510,6 @@ public class DefaultCodegen {
// should be overridden by lang codegen // should be overridden by lang codegen
setParameterExampleValue(p); 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); postProcessParameter(p);
return p; return p;
} }
@ -2459,6 +2518,10 @@ public class DefaultCodegen {
return dataType.toLowerCase().startsWith("byte"); 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 * 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); LOGGER.warn("null property for " + key);
} else { } else {
final CodegenProperty cp = fromProperty(key, prop); final CodegenProperty cp = fromProperty(key, prop);
cp.required = mandatory.contains(key) ? true : null; cp.required = mandatory.contains(key) ? true : false;
m.hasRequired = Boolean.TRUE.equals(m.hasRequired) || Boolean.TRUE.equals(cp.required); m.hasRequired = m.hasRequired || cp.required;
if (cp.isEnum) { if (cp.isEnum) {
// FIXME: if supporting inheritance, when called a second time for allProperties it is possible for // 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. // 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")); addImport(m, typeMapping.get("array"));
} }
@ -3254,6 +3317,10 @@ public class DefaultCodegen {
} else if (Boolean.TRUE.equals(property.isBinary)) { } else if (Boolean.TRUE.equals(property.isBinary)) {
parameter.isByteArray = true; parameter.isByteArray = true;
parameter.isPrimitiveType = 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)) { } else if (Boolean.TRUE.equals(property.isDate)) {
parameter.isDate = true; parameter.isDate = true;
parameter.isPrimitiveType = true; parameter.isPrimitiveType = true;
@ -3335,7 +3402,6 @@ public class DefaultCodegen {
if (pattern != null && !pattern.matches("^/.*")) { if (pattern != null && !pattern.matches("^/.*")) {
return "/" + pattern + "/"; return "/" + pattern + "/";
} }
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> systemProperties = new HashMap<String, String>();
private Map<String, String> instantiationTypes = 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> 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 Map<String, String> importMappings = new HashMap<String, String>();
private Set<String> languageSpecificPrimitives = new HashSet<String>(); private Set<String> languageSpecificPrimitives = new HashSet<String>();
private String gitUserId="GIT_USER_ID"; private String gitUserId="GIT_USER_ID";
@ -65,7 +65,7 @@ public class CodegenConfigurator {
private String releaseNote="Minor update"; private String releaseNote="Minor update";
private String httpUserAgent; 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() { public CodegenConfigurator() {
this.setOutputDir("."); this.setOutputDir(".");
@ -255,16 +255,16 @@ public class CodegenConfigurator {
return this; return this;
} }
public Map<String, String> getAdditionalProperties() { public Map<String, Object> getAdditionalProperties() {
return additionalProperties; return additionalProperties;
} }
public CodegenConfigurator setAdditionalProperties(Map<String, String> additionalProperties) { public CodegenConfigurator setAdditionalProperties(Map<String, Object> additionalProperties) {
this.additionalProperties = additionalProperties; this.additionalProperties = additionalProperties;
return this; return this;
} }
public CodegenConfigurator addAdditionalProperty(String key, String value) { public CodegenConfigurator addAdditionalProperty(String key, Object value) {
this.additionalProperties.put(key, value); this.additionalProperties.put(key, value);
return this; return this;
} }
@ -398,12 +398,12 @@ public class CodegenConfigurator {
@JsonAnySetter @JsonAnySetter
public CodegenConfigurator addDynamicProperty(String name, Object value) { public CodegenConfigurator addDynamicProperty(String name, Object value) {
dynamicProperties.put(name, value.toString()); dynamicProperties.put(name, value);
return this; return this;
} }
@JsonAnyGetter @JsonAnyGetter
public Map<String, String> getDynamicProperties() { public Map<String, Object> getDynamicProperties() {
return dynamicProperties; return dynamicProperties;
} }

View File

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

View File

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

View File

@ -60,10 +60,10 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
setReservedWordsLowerCase( setReservedWordsLowerCase(
Arrays.asList( 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 // this is a workaround and can be removed if c# api client is updated to use
// fully qualified name // fully qualified name
"client", "client", "parameter",
// local variable names in API methods (endpoints) // local variable names in API methods (endpoints)
"localVarPath", "localVarPathParams", "localVarQueryParams", "localVarHeaderParams", "localVarPath", "localVarPathParams", "localVarQueryParams", "localVarHeaderParams",
"localVarFormParams", "localVarFileParams", "localVarStatusCode", "localVarResponse", "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 groupId = "io.swagger";
protected String artifactId = "swagger-java"; protected String artifactId = "swagger-java";
protected String artifactVersion = "1.0.0"; 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 projectFolder = "src" + File.separator + "main";
protected String projectTestFolder = "src" + File.separator + "test"; protected String projectTestFolder = "src" + File.separator + "test";
protected String sourceFolder = projectFolder + File.separator + "java"; 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.GROUP_ID, CodegenConstants.GROUP_ID_DESC));
cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_ID, CodegenConstants.ARTIFACT_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.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.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC));
cliOptions.add(new CliOption(CodegenConstants.LOCAL_VARIABLE_PREFIX, CodegenConstants.LOCAL_VARIABLE_PREFIX_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)); 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); 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)) { if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) {
this.setSourceFolder((String) additionalProperties.get(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("ApiModelProperty", "io.swagger.annotations.ApiModelProperty");
importMapping.put("ApiModel", "io.swagger.annotations.ApiModel"); importMapping.put("ApiModel", "io.swagger.annotations.ApiModel");
importMapping.put("JsonProperty", "com.fasterxml.jackson.annotation.JsonProperty"); 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("JsonCreator", "com.fasterxml.jackson.annotation.JsonCreator");
importMapping.put("JsonValue", "com.fasterxml.jackson.annotation.JsonValue"); importMapping.put("JsonValue", "com.fasterxml.jackson.annotation.JsonValue");
importMapping.put("SerializedName", "com.google.gson.annotations.SerializedName"); importMapping.put("SerializedName", "com.google.gson.annotations.SerializedName");
@ -366,7 +384,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
// sanitize name // sanitize name
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. 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"; return "propertyClass";
} }
@ -450,11 +468,20 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
if (p instanceof ArrayProperty) { if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p; ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems(); 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) + ">"; return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (p instanceof MapProperty) { } else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p; MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties(); 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 getSwaggerType(p) + "<String, " + getTypeDeclaration(inner) + ">";
} }
return super.getTypeDeclaration(p); return super.getTypeDeclaration(p);
@ -470,6 +497,9 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
} else { } else {
pattern = "new ArrayList<%s>()"; pattern = "new ArrayList<%s>()";
} }
if (ap.getItems() == null) {
return null;
}
return String.format(pattern, getTypeDeclaration(ap.getItems())); return String.format(pattern, getTypeDeclaration(ap.getItems()));
} else if (p instanceof MapProperty) { } else if (p instanceof MapProperty) {
final MapProperty ap = (MapProperty) p; final MapProperty ap = (MapProperty) p;
@ -479,6 +509,9 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
} else { } else {
pattern = "new HashMap<String, %s>()"; pattern = "new HashMap<String, %s>()";
} }
if (ap.getAdditionalProperties() == null) {
return null;
}
return String.format(pattern, getTypeDeclaration(ap.getAdditionalProperties())); return String.format(pattern, getTypeDeclaration(ap.getAdditionalProperties()));
} else if (p instanceof IntegerProperty) { } else if (p instanceof IntegerProperty) {
IntegerProperty dp = (IntegerProperty) p; IntegerProperty dp = (IntegerProperty) p;
@ -593,21 +626,16 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
@Override @Override
public String getSwaggerType(Property p) { public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p); String swaggerType = super.getSwaggerType(p);
String type;
// don't apply renaming on types from the typeMapping
if (typeMapping.containsKey(swaggerType)) { if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType); return 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;
} }
if (null == type) {
if (null == swaggerType) {
LOGGER.error("No Type defined for Property " + p); LOGGER.error("No Type defined for Property " + p);
} }
return toModelName(type); return toModelName(swaggerType);
} }
@Override @Override
@ -635,12 +663,15 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
if(codegenModel.description != null) { if(codegenModel.description != null) {
codegenModel.imports.add("ApiModel"); 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) { if (allDefinitions != null && codegenModel.parentSchema != null && codegenModel.hasEnums) {
final Model parentModel = allDefinitions.get(codegenModel.parentSchema); final Model parentModel = allDefinitions.get(codegenModel.parentSchema);
final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel); final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel);
codegenModel = AbstractJavaCodegen.reconcileInlineEnums(codegenModel, parentCodegenModel); codegenModel = AbstractJavaCodegen.reconcileInlineEnums(codegenModel, parentCodegenModel);
} }
return codegenModel; return codegenModel;
} }
@ -668,7 +699,6 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
model.imports.add("ApiModelProperty"); model.imports.add("ApiModelProperty");
model.imports.add("ApiModel"); model.imports.add("ApiModel");
} }
return;
} }
@Override @Override
@ -713,26 +743,27 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
@Override @Override
public void preprocessSwagger(Swagger swagger) { public void preprocessSwagger(Swagger swagger) {
if (swagger != null && swagger.getPaths() != null) { if (swagger == null || swagger.getPaths() == null){
for (String pathname : swagger.getPaths().keySet()) { return;
Path path = swagger.getPath(pathname); }
if (path.getOperations() != null) { for (String pathname : swagger.getPaths().keySet()) {
for (Operation operation : path.getOperations()) { Path path = swagger.getPath(pathname);
boolean hasFormParameters = false; if (path.getOperations() == null){
for (Parameter parameter : operation.getParameters()) { continue;
if (parameter instanceof FormParameter) { }
hasFormParameters = true; for (Operation operation : path.getOperations()) {
} boolean hasFormParameters = false;
} for (Parameter parameter : operation.getParameters()) {
if (parameter instanceof FormParameter) {
String defaultContentType = hasFormParameters ? "application/x-www-form-urlencoded" : "application/json"; hasFormParameters = true;
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);
} }
} }
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 @Override
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 = super.fromOperation(path, httpMethod, operation, definitions, swagger); CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger);
op.path = sanitizePath(op.path); op.path = sanitizePath(op.path);
return op; 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. // 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. // 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 // Get the properties for the parent and child models
final List<CodegenProperty> parentModelCodegenProperties = parentCodegenModel.vars; final List<CodegenProperty> parentModelCodegenProperties = parentCodegenModel.vars;
List<CodegenProperty> codegenProperties = codegenModel.vars; List<CodegenProperty> codegenProperties = codegenModel.vars;
// Iterate over all of the parent model properties // Iterate over all of the parent model properties
boolean removedChildEnum = false; boolean removedChildEnum = false;
for (CodegenProperty parentModelCodegenPropery : parentModelCodegenProperties) { for (CodegenProperty parentModelCodegenPropery : parentModelCodegenProperties) {
// Look for enums // Look for enums
if (parentModelCodegenPropery.isEnum) { if (parentModelCodegenPropery.isEnum) {
// Now that we have found an enum in the parent class, // Now that we have found an enum in the parent class,
// and search the child class for the same enum. // and search the child class for the same enum.
Iterator<CodegenProperty> iterator = codegenProperties.iterator(); Iterator<CodegenProperty> iterator = codegenProperties.iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
CodegenProperty codegenProperty = iterator.next(); CodegenProperty codegenProperty = iterator.next();
if (codegenProperty.isEnum && codegenProperty.equals(parentModelCodegenPropery)) { if (codegenProperty.isEnum && codegenProperty.equals(parentModelCodegenPropery)) {
// We found an enum in the child class that is // We found an enum in the child class that is
// a duplicate of the one in the parent, so remove it. // a duplicate of the one in the parent, so remove it.
iterator.remove(); iterator.remove();
removedChildEnum = true; 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; return codegenModel;
} }
@ -900,6 +929,14 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
this.artifactVersion = artifactVersion; this.artifactVersion = artifactVersion;
} }
public void setLicenseName(String licenseName) {
this.licenseName = licenseName;
}
public void setLicenseUrl(String licenseUrl) {
this.licenseUrl = licenseUrl;
}
public void setSourceFolder(String sourceFolder) { public void setSourceFolder(String sourceFolder) {
this.sourceFolder = sourceFolder; this.sourceFolder = sourceFolder;
} }
@ -962,7 +999,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
} }
return sb.toString(); return sb.toString();
} }
public void setSupportJava6(boolean value) { public void setSupportJava6(boolean value) {
this.supportJava6 = 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 static final String JAXRS_TEMPLATE_DIRECTORY_NAME = "JavaJaxRS";
protected String implFolder = "src/main/java"; protected String implFolder = "src/main/java";
protected String testResourcesFolder = "src/test/resources";
protected String title = "Swagger Server"; protected String title = "Swagger Server";
static Logger LOGGER = LoggerFactory.getLogger(AbstractJavaJAXRSServerCodegen.class); 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 String modelPropertyNaming= "camelCase";
protected Boolean supportsES6 = true; protected Boolean supportsES6 = true;
protected HashSet<String> languageGenericTypes;
public AbstractTypeScriptClientCodegen() { public AbstractTypeScriptClientCodegen() {
super(); super();
@ -60,6 +61,11 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
"Error", "Error",
"Map" "Map"
)); ));
languageGenericTypes = new HashSet<String>(Arrays.asList(
"Array"
));
instantiationTypes.put("array", "Array"); instantiationTypes.put("array", "Array");
typeMapping = new HashMap<String, String>(); typeMapping = new HashMap<String, String>();
@ -101,7 +107,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
} }
if (additionalProperties.containsKey(CodegenConstants.SUPPORTS_ES6)) { 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()); additionalProperties.put("supportsES6", getSupportsES6());
} }
} }
@ -179,6 +185,12 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
return modelName; 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 // camelize the model name
// phone_number => PhoneNumber // phone_number => PhoneNumber
return camelize(name); return camelize(name);

View File

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

View File

@ -199,6 +199,10 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
} else { } else {
setGeneratePropertyChanged(Boolean.valueOf(additionalProperties.get(CodegenConstants.GENERATE_PROPERTY_CHANGED).toString())); 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); 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 packageVersion = "1.0.0";
protected String clientPackage = "IO.Swagger.Client"; protected String clientPackage = "IO.Swagger.Client";
protected String sourceFolder = "src" + File.separator + "main" + File.separator + "CsharpDotNet2"; protected String sourceFolder = "src" + File.separator + "main" + File.separator + "CsharpDotNet2";
protected String apiDocPath = "docs/";
protected String modelDocPath = "docs/";
public CsharpDotNet2ClientCodegen() { public CsharpDotNet2ClientCodegen() {
super(); super();
@ -35,6 +38,8 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege
embeddedTemplateDir = templateDir = "CsharpDotNet2"; embeddedTemplateDir = templateDir = "CsharpDotNet2";
apiPackage = "IO.Swagger.Api"; apiPackage = "IO.Swagger.Api";
modelPackage = "IO.Swagger.Model"; modelPackage = "IO.Swagger.Model";
modelDocTemplateFiles.put("model_doc.mustache", ".md");
apiDocTemplateFiles.put("api_doc.mustache", ".md");
setReservedWordsLowerCase( setReservedWordsLowerCase(
Arrays.asList( Arrays.asList(
@ -65,6 +70,7 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege
"Integer", "Integer",
"Long", "Long",
"Float", "Float",
"Guid?",
"System.IO.Stream", // not really a primitive, we include it to avoid model import "System.IO.Stream", // not really a primitive, we include it to avoid model import
"Object") "Object")
); );
@ -86,6 +92,7 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege
typeMapping.put("list", "List"); typeMapping.put("list", "List");
typeMapping.put("map", "Dictionary"); typeMapping.put("map", "Dictionary");
typeMapping.put("object", "Object"); typeMapping.put("object", "Object");
typeMapping.put("uuid", "Guid?");
cliOptions.clear(); cliOptions.clear();
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "C# package name (convention: Camel.Case).") 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(CLIENT_PACKAGE, clientPackage);
} }
additionalProperties.put("apiDocPath", apiDocPath);
additionalProperties.put("modelDocPath", modelDocPath);
supportingFiles.add(new SupportingFile("Configuration.mustache", supportingFiles.add(new SupportingFile("Configuration.mustache",
sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "Configuration.cs")); sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "Configuration.cs"));
supportingFiles.add(new SupportingFile("ApiClient.mustache", 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")); 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("packages.config.mustache", "vendor", "packages.config"));
supportingFiles.add(new SupportingFile("compile-mono.sh.mustache", "", "compile-mono.sh")); 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("/*", "/_*"); 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 pubVersion = "1.0.0";
protected String pubDescription = "Swagger API client"; protected String pubDescription = "Swagger API client";
protected String sourceFolder = ""; protected String sourceFolder = "";
protected String apiDocPath = "docs/";
protected String modelDocPath = "docs/";
public DartClientCodegen() { public DartClientCodegen() {
super(); super();
@ -39,6 +41,8 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
embeddedTemplateDir = templateDir = "dart"; embeddedTemplateDir = templateDir = "dart";
apiPackage = "lib.api"; apiPackage = "lib.api";
modelPackage = "lib.model"; modelPackage = "lib.model";
modelDocTemplateFiles.put("object_doc.mustache", ".md");
apiDocTemplateFiles.put("api_doc.mustache", ".md");
setReservedWordsLowerCase( setReservedWordsLowerCase(
Arrays.asList( Arrays.asList(
@ -145,6 +149,10 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); 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"; final String libFolder = sourceFolder + File.separator + "lib";
supportingFiles.add(new SupportingFile("pubspec.mustache", "", "pubspec.yaml")); supportingFiles.add(new SupportingFile("pubspec.mustache", "", "pubspec.yaml"));
supportingFiles.add(new SupportingFile("analysis_options.mustache", "", ".analysis_options")); 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("auth/oauth.mustache", authFolder, "oauth.dart"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); 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); 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 @Override
public String toVarName(String name) { public String toVarName(String name) {
// replace - with _ e.g. created-at => created_at // 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.Lists;
import com.google.common.collect.Multimap; import com.google.common.collect.Multimap;
import config.ConfigParser;
import io.swagger.codegen.*; import io.swagger.codegen.*;
import io.swagger.models.HttpMethod; import io.swagger.models.HttpMethod;
import io.swagger.models.Operation; import io.swagger.models.Operation;
import io.swagger.models.Path; import io.swagger.models.Path;
import io.swagger.models.Swagger; import io.swagger.models.Swagger;
import io.swagger.models.parameters.Parameter;
import io.swagger.models.properties.*;
import io.swagger.util.Yaml; import io.swagger.util.Yaml;
import java.io.File; import java.io.File;
import java.util.*; import java.util.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; 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 DEFAULT_CONTROLLER = "defaultController";
public static final String SUPPORT_PYTHON2= "supportPython2"; public static final String SUPPORT_PYTHON2= "supportPython2";
protected String apiVersion = "1.0.0";
protected int serverPort = 8080; protected int serverPort = 8080;
protected String projectName = "swagger-server"; protected String packageName;
protected String packageVersion;
protected String controllerPackage; protected String controllerPackage;
protected String defaultController; protected String defaultController;
public FlaskConnexionCodegen() { public FlaskConnexionCodegen() {
super(); super();
modelPackage = "models";
testPackage = "test";
languageSpecificPrimitives.clear(); languageSpecificPrimitives.clear();
languageSpecificPrimitives.add("int"); languageSpecificPrimitives.add("int");
languageSpecificPrimitives.add("float"); languageSpecificPrimitives.add("float");
languageSpecificPrimitives.add("list"); languageSpecificPrimitives.add("List");
languageSpecificPrimitives.add("Dict");
languageSpecificPrimitives.add("bool"); languageSpecificPrimitives.add("bool");
languageSpecificPrimitives.add("str"); languageSpecificPrimitives.add("str");
languageSpecificPrimitives.add("datetime"); languageSpecificPrimitives.add("datetime");
languageSpecificPrimitives.add("date"); languageSpecificPrimitives.add("date");
languageSpecificPrimitives.add("file");
typeMapping.clear(); typeMapping.clear();
typeMapping.put("integer", "int"); typeMapping.put("integer", "int");
@ -51,8 +57,8 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
typeMapping.put("number", "float"); typeMapping.put("number", "float");
typeMapping.put("long", "int"); typeMapping.put("long", "int");
typeMapping.put("double", "float"); typeMapping.put("double", "float");
typeMapping.put("array", "list"); typeMapping.put("array", "List");
typeMapping.put("map", "dict"); typeMapping.put("map", "Dict");
typeMapping.put("boolean", "bool"); typeMapping.put("boolean", "bool");
typeMapping.put("string", "str"); typeMapping.put("string", "str");
typeMapping.put("date", "date"); typeMapping.put("date", "date");
@ -63,9 +69,9 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
// set the output folder here // set the output folder here
outputFolder = "generated-code/connexion"; outputFolder = "generated-code/connexion";
modelTemplateFiles.clear();
apiTemplateFiles.put("controller.mustache", ".py"); 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 * 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 * Additional Properties. These values can be passed to the templates and
* are available in models, apis, and supporting files * are available in models, apis, and supporting files
*/ */
additionalProperties.put("apiVersion", apiVersion);
additionalProperties.put("serverPort", serverPort); 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 * 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 * 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", cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "python package name (convention: snake_case).")
"swagger", .defaultValue("swagger_server"));
"swagger.yaml") cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "python package version.")
); .defaultValue("1.0.0"));
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(CONTROLLER_PACKAGE, "controller package"). cliOptions.add(new CliOption(CONTROLLER_PACKAGE, "controller package").
defaultValue("controllers")); defaultValue("controllers"));
cliOptions.add(new CliOption(DEFAULT_CONTROLLER, "default controller"). cliOptions.add(new CliOption(DEFAULT_CONTROLLER, "default controller").
@ -124,32 +124,51 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
super.processOpts(); super.processOpts();
//apiTemplateFiles.clear(); //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)) { if (additionalProperties.containsKey(CONTROLLER_PACKAGE)) {
this.controllerPackage = additionalProperties.get(CONTROLLER_PACKAGE).toString(); this.controllerPackage = additionalProperties.get(CONTROLLER_PACKAGE).toString();
} } else {
else {
this.controllerPackage = "controllers"; this.controllerPackage = "controllers";
additionalProperties.put(CONTROLLER_PACKAGE, this.controllerPackage); additionalProperties.put(CONTROLLER_PACKAGE, this.controllerPackage);
} }
if (additionalProperties.containsKey(DEFAULT_CONTROLLER)) { if (additionalProperties.containsKey(DEFAULT_CONTROLLER)) {
this.defaultController = additionalProperties.get(DEFAULT_CONTROLLER).toString(); this.defaultController = additionalProperties.get(DEFAULT_CONTROLLER).toString();
} } else {
else {
this.defaultController = "default_controller"; this.defaultController = "default_controller";
additionalProperties.put(DEFAULT_CONTROLLER, this.defaultController); additionalProperties.put(DEFAULT_CONTROLLER, this.defaultController);
} }
if (Boolean.TRUE.equals(additionalProperties.get(SUPPORT_PYTHON2))) { if (Boolean.TRUE.equals(additionalProperties.get(SUPPORT_PYTHON2))) {
additionalProperties.put(SUPPORT_PYTHON2, Boolean.TRUE); 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()) { modelPackage = packageName + "." + modelPackage;
supportingFiles.add(new SupportingFile("__init__.mustache", controllerPackage = packageName + "." + controllerPackage;
controllerPackage, testPackage = packageName + "." + testPackage;
"__init__.py") }
);
} private static String dropDots(String str) {
return str.replaceAll("\\.", "_");
} }
@Override @Override
@ -157,6 +176,7 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
return controllerPackage; return controllerPackage;
} }
/** /**
* Configures the type of generator. * Configures the type of generator.
* *
@ -204,6 +224,11 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
return underscore(toApiName(name)); 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 * 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 * 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); 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 @Override
public void preprocessSwagger(Swagger swagger) { public void preprocessSwagger(Swagger swagger) {
if (swagger != null && swagger.getPaths() != null) { // need vendor extensions for x-swagger-router-controller
for(String pathname : swagger.getPaths().keySet()) { Map<String, Path> paths = swagger.getPaths();
Path path = swagger.getPath(pathname); if(paths != null) {
if (path.getOperations() != null) { for(String pathname : paths.keySet()) {
for(Map.Entry<HttpMethod, Operation> entry : path.getOperationMap().entrySet()) { Path path = paths.get(pathname);
// Normalize `operationId` and add package/class path in front, e.g. Map<HttpMethod, Operation> operationMap = path.getOperationMap();
// controllers.default_controller.add_pet if(operationMap != null) {
String httpMethod = entry.getKey().name().toLowerCase(); for(HttpMethod method : operationMap.keySet()) {
Operation operation = entry.getValue(); Operation operation = operationMap.get(method);
String operationId = getOrGenerateOperationId(operation, pathname, httpMethod); String tag = "default";
String controllerName; if(operation.getTags() != null && operation.getTags().size() > 0) {
tag = operation.getTags().get(0);
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);
} }
else { String operationId = operation.getOperationId();
// no tag found, use "default_controller" as the default if(operationId == null) {
String tag = "default"; operationId = getOrGenerateOperationId(operation, pathname, method.toString());
operation.setTags(Arrays.asList(tag)); }
controllerName = tag + "_controller"; 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("path", entry.getKey());
opsByPathEntry.put("operation", entry.getValue()); opsByPathEntry.put("operation", entry.getValue());
List<CodegenOperation> operationsForThisPath = Lists.newArrayList(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()) { if (opsByPathList.size() < opsByPath.asMap().size()) {
opsByPathEntry.put("hasMore", "true"); opsByPathEntry.put("hasMore", "true");
} }
@ -333,6 +374,102 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
return super.postProcessSupportingFileData(objs); 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 @Override
public String toOperationId(String operationId) { public String toOperationId(String operationId) {
operationId = super.toOperationId(operationId); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. 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 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 @Override
public String escapeQuotationMark(String input) { public String escapeQuotationMark(String input) {
// remove ' to avoid code injection // remove ' to avoid code injection
@ -355,4 +637,14 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
// remove multiline comment // remove multiline comment
return input.replace("'''", "'_'_'"); 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_client.mustache", "", "api_client.go"));
supportingFiles.add(new SupportingFile("api_response.mustache", "", "api_response.go")); supportingFiles.add(new SupportingFile("api_response.mustache", "", "api_response.go"));
supportingFiles.add(new SupportingFile(".travis.yml", "", ".travis.yml")); supportingFiles.add(new SupportingFile(".travis.yml", "", ".travis.yml"));
supportingFiles.add(new SupportingFile("LICENSE", "", "LICENSE"));
} }
@Override @Override

View File

@ -14,11 +14,14 @@ import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType; import io.swagger.codegen.CodegenType;
import io.swagger.codegen.SupportingFile; import io.swagger.codegen.SupportingFile;
import io.swagger.codegen.languages.features.CXFFeatures; import io.swagger.codegen.languages.features.BeanValidationFeatures;
import io.swagger.codegen.languages.features.LoggingFeatures; 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; 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); 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 static final String JAXRS_TEMPLATE_DIRECTORY_NAME = "JavaJaxRS";
protected boolean useJaxbAnnotations = true;
protected boolean useBeanValidation = false; protected boolean useBeanValidation = false;
protected boolean useGzipFeature = false; protected boolean useGzipFeatureForTests = false;
protected boolean useLoggingFeature = false;
protected boolean useBeanValidationFeature = false;
protected boolean useLoggingFeatureForTests = false;
public JavaCXFClientCodegen() public JavaCXFClientCodegen()
{ {
@ -67,11 +69,12 @@ public class JavaCXFClientCodegen extends AbstractJavaCodegen implements CXFFeat
embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "cxf"; 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_BEANVALIDATION, "Use BeanValidation API annotations"));
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_FOR_TESTS, "Use Logging Feature for tests"));
cliOptions.add(CliOption.newBoolean(USE_LOGGING_FEATURE, "Use Logging Feature"));
} }
@ -82,19 +85,19 @@ public class JavaCXFClientCodegen extends AbstractJavaCodegen implements CXFFeat
{ {
super.processOpts(); super.processOpts();
if (additionalProperties.containsKey(USE_JAXB_ANNOTATIONS)) {
boolean useJaxbAnnotationsProp = convertPropertyToBooleanAndWriteBack(USE_JAXB_ANNOTATIONS);
this.setUseJaxbAnnotations(useJaxbAnnotationsProp);
}
if (additionalProperties.containsKey(USE_BEANVALIDATION)) { if (additionalProperties.containsKey(USE_BEANVALIDATION)) {
boolean useBeanValidationProp = convertPropertyToBooleanAndWriteBack(USE_BEANVALIDATION); boolean useBeanValidationProp = convertPropertyToBooleanAndWriteBack(USE_BEANVALIDATION);
this.setUseBeanValidation(useBeanValidationProp); this.setUseBeanValidation(useBeanValidationProp);
} }
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));
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 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) { public void setUseJaxbAnnotations(boolean useJaxbAnnotations) {
this.useGzipFeature = useGzipFeature; this.useJaxbAnnotations = useJaxbAnnotations;
} }
public void setUseGzipFeatureForTests(boolean useGzipFeatureForTests) {
public void setUseLoggingFeature(boolean useLoggingFeature) { this.useGzipFeatureForTests = useGzipFeatureForTests;
this.useLoggingFeature = useLoggingFeature;
} }
public void setUseLoggingFeatureForTests(boolean useLoggingFeatureForTests) {
public void setUseBeanValidationFeature(boolean useBeanValidationFeature) { this.useLoggingFeatureForTests = useLoggingFeatureForTests;
this.useBeanValidationFeature = useBeanValidationFeature;
} }
} }

View File

@ -14,30 +14,48 @@ import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.SupportingFile; import io.swagger.codegen.SupportingFile;
import io.swagger.codegen.languages.features.CXFServerFeatures; 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; 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); private static final Logger LOGGER = LoggerFactory.getLogger(JavaCXFServerCodegen.class);
protected boolean addConsumesProducesJson = true;
protected boolean useJaxbAnnotations = true;
protected boolean useBeanValidation = false; protected boolean useBeanValidation = false;
protected boolean generateSpringApplication = false; protected boolean generateSpringApplication = false;
protected boolean useSpringAnnotationConfig = false;
protected boolean useSwaggerFeature = false; protected boolean useSwaggerFeature = false;
protected boolean useSwaggerUI = false;
protected boolean useWadlFeature = false; protected boolean useWadlFeature = false;
protected boolean useMultipartFeature = false; protected boolean useMultipartFeature = false;
protected boolean useGzipFeature = false;
protected boolean useLoggingFeature = false;
protected boolean useBeanValidationFeature = false; protected boolean useBeanValidationFeature = false;
protected boolean generateSpringBootApplication= 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() public JavaCXFServerCodegen()
{ {
super(); super();
@ -64,18 +82,31 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen impleme
embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "cxf"; 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_BEANVALIDATION, "Use BeanValidation API annotations"));
cliOptions.add(CliOption.newBoolean(GENERATE_SPRING_APPLICATION, "Generate Spring application")); 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_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_WADL_FEATURE, "Use WADL Feature"));
cliOptions.add(CliOption.newBoolean(USE_MULTIPART_FEATURE, "Use Multipart 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, "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_BEANVALIDATION_FEATURE, "Use BeanValidation Feature"));
cliOptions.add(CliOption.newBoolean(USE_LOGGING_FEATURE, "Use Logging 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_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(); super.processOpts();
if (additionalProperties.containsKey(USE_JAXB_ANNOTATIONS)) {
boolean useJaxbAnnotationsProp = convertPropertyToBooleanAndWriteBack(USE_JAXB_ANNOTATIONS);
this.setUseJaxbAnnotations(useJaxbAnnotationsProp);
}
if (additionalProperties.containsKey(USE_BEANVALIDATION)) { if (additionalProperties.containsKey(USE_BEANVALIDATION)) {
boolean useBeanValidationProp = convertPropertyToBooleanAndWriteBack(USE_BEANVALIDATION); boolean useBeanValidationProp = convertPropertyToBooleanAndWriteBack(USE_BEANVALIDATION);
this.setUseBeanValidation(useBeanValidationProp); this.setUseBeanValidation(useBeanValidationProp);
} }
if (additionalProperties.containsKey(ADD_CONSUMES_PRODUCES_JSON)) {
this.setAddConsumesProducesJson(convertPropertyToBooleanAndWriteBack(ADD_CONSUMES_PRODUCES_JSON));
}
if (additionalProperties.containsKey(GENERATE_SPRING_APPLICATION)) { if (additionalProperties.containsKey(GENERATE_SPRING_APPLICATION)) {
this.setGenerateSpringApplication(convertPropertyToBooleanAndWriteBack(GENERATE_SPRING_APPLICATION)); this.setGenerateSpringApplication(convertPropertyToBooleanAndWriteBack(GENERATE_SPRING_APPLICATION));
this.setUseSwaggerFeature(convertPropertyToBooleanAndWriteBack(USE_SWAGGER_FEATURE)); this.setUseSwaggerFeature(convertPropertyToBooleanAndWriteBack(USE_SWAGGER_FEATURE));
this.setUseSwaggerUI(convertPropertyToBooleanAndWriteBack(USE_SWAGGER_UI));
this.setUseWadlFeature(convertPropertyToBooleanAndWriteBack(USE_WADL_FEATURE)); this.setUseWadlFeature(convertPropertyToBooleanAndWriteBack(USE_WADL_FEATURE));
this.setUseMultipartFeature(convertPropertyToBooleanAndWriteBack(USE_MULTIPART_FEATURE)); this.setUseMultipartFeature(convertPropertyToBooleanAndWriteBack(USE_MULTIPART_FEATURE));
this.setUseGzipFeature(convertPropertyToBooleanAndWriteBack(USE_GZIP_FEATURE)); this.setUseGzipFeature(convertPropertyToBooleanAndWriteBack(USE_GZIP_FEATURE));
this.setUseGzipFeatureForTests(convertPropertyToBooleanAndWriteBack(USE_GZIP_FEATURE_FOR_TESTS));
this.setUseLoggingFeature(convertPropertyToBooleanAndWriteBack(USE_LOGGING_FEATURE)); 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); boolean useBeanValidationFeature = convertPropertyToBooleanAndWriteBack(USE_BEANVALIDATION_FEATURE);
this.setUseBeanValidationFeature(useBeanValidationFeature); this.setUseBeanValidationFeature(useBeanValidationFeature);
@ -107,12 +152,20 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen impleme
this.setGenerateSpringBootApplication(convertPropertyToBooleanAndWriteBack(GENERATE_SPRING_BOOT_APPLICATION)); 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 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/pom.mustache", "", "pom.xml"));
writeOptional(outputFolder,
new SupportingFile("server/swagger-codegen-ignore.mustache", "", ".swagger-codegen-ignore"));
if (this.generateSpringApplication) { if (this.generateSpringApplication) {
writeOptional(outputFolder, new SupportingFile("server/readme.md", "", "readme.md")); 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")); ("src/main/webapp/WEB-INF"), "context.xml"));
// Jboss // Jboss
writeOptional(outputFolder, new SupportingFile("server/jboss-web.xml.mustache", if (generateJbossDeploymentDescriptor) {
("src/main/webapp/WEB-INF"), "jboss-web.xml")); writeOptional(outputFolder, new SupportingFile("server/jboss-web.xml.mustache",
("src/main/webapp/WEB-INF"), "jboss-web.xml"));
}
// Spring Boot // Spring Boot
if (this.generateSpringBootApplication) { if (this.generateSpringBootApplication) {
writeOptional(outputFolder, new SupportingFile("server/SpringBootApplication.mustache", writeOptional(outputFolder, new SupportingFile("server/SpringBootApplication.mustache",
(testFolder + '/' + apiPackage).replace(".", "/"), "SpringBootApplication.java")); (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; this.generateSpringApplication = generateSpringApplication;
} }
public void setUseSpringAnnotationConfig(boolean useSpringAnnotationConfig) {
this.useSpringAnnotationConfig = useSpringAnnotationConfig;
}
public void setUseSwaggerFeature(boolean useSwaggerFeature) { public void setUseSwaggerFeature(boolean useSwaggerFeature) {
this.useSwaggerFeature = useSwaggerFeature; this.useSwaggerFeature = useSwaggerFeature;
@ -204,7 +265,32 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen impleme
this.useBeanValidationFeature = useBeanValidationFeature; this.useBeanValidationFeature = useBeanValidationFeature;
} }
public void setGenerateSpringBootApplication(boolean generateSpringBootApplication) { public void setGenerateSpringBootApplication(boolean generateSpringBootApplication) {
this.generateSpringBootApplication = 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.*;
import io.swagger.codegen.languages.features.BeanValidationFeatures; 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.BooleanUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -12,13 +12,15 @@ import java.io.File;
import java.util.*; import java.util.*;
import java.util.regex.Pattern; 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"; static final String MEDIA_TYPE = "mediaType";
@SuppressWarnings("hiding") @SuppressWarnings("hiding")
private static final Logger LOGGER = LoggerFactory.getLogger(JavaClientCodegen.class); private static final Logger LOGGER = LoggerFactory.getLogger(JavaClientCodegen.class);
public static final String USE_RX_JAVA = "useRxJava"; 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 PARCELABLE_MODEL = "parcelableModel";
public static final String RETROFIT_1 = "retrofit"; public static final String RETROFIT_1 = "retrofit";
@ -26,8 +28,10 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
protected String gradleWrapperPackage = "gradle.wrapper"; protected String gradleWrapperPackage = "gradle.wrapper";
protected boolean useRxJava = false; protected boolean useRxJava = false;
protected boolean usePlay24WS = false;
protected boolean parcelableModel = false; protected boolean parcelableModel = false;
protected boolean useBeanValidation = false; protected boolean useBeanValidation = false;
protected boolean performBeanValidation = false;
public JavaClientCodegen() { public JavaClientCodegen() {
super(); 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(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(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(SUPPORT_JAVA6, "Whether to support Java6 with the Jersey1 library."));
cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations")); 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("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"); 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)) { if (additionalProperties.containsKey(USE_RX_JAVA)) {
this.setUseRxJava(Boolean.valueOf(additionalProperties.get(USE_RX_JAVA).toString())); 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)) { if (additionalProperties.containsKey(PARCELABLE_MODEL)) {
this.setParcelableModel(Boolean.valueOf(additionalProperties.get(PARCELABLE_MODEL).toString())); 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); additionalProperties.put(PARCELABLE_MODEL, parcelableModel);
if (additionalProperties.containsKey(USE_BEANVALIDATION)) { if (additionalProperties.containsKey(USE_BEANVALIDATION)) {
boolean useBeanValidationProp = Boolean.valueOf(additionalProperties.get(USE_BEANVALIDATION).toString()); this.setUseBeanValidation(convertPropertyToBooleanAndWriteBack(USE_BEANVALIDATION));
this.setUseBeanValidation(useBeanValidationProp); }
// write back as boolean if (additionalProperties.containsKey(PERFORM_BEANVALIDATION)) {
additionalProperties.put(USE_BEANVALIDATION, useBeanValidationProp); this.setPerformBeanValidation(convertPropertyToBooleanAndWriteBack(PERFORM_BEANVALIDATION));
} }
final String invokerFolder = (sourceFolder + '/' + invokerPackage).replace(".", "/"); 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("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); 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 //TODO: add doc to retrofit1 and feign
if ( "feign".equals(getLibrary()) || "retrofit".equals(getLibrary()) ){ if ( "feign".equals(getLibrary()) || "retrofit".equals(getLibrary()) ){
modelDocTemplateFiles.remove("model_doc.mustache"); modelDocTemplateFiles.remove("model_doc.mustache");
@ -162,7 +178,34 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
LOGGER.error("Unknown library option (-l/--library): " + getLibrary()); 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")); supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", invokerFolder, "RFC3339DateFormat.java"));
if ("threetenbp".equals(dateLibrary)) { if ("threetenbp".equals(dateLibrary)) {
supportingFiles.add(new SupportingFile("CustomInstantDeserializer.mustache", invokerFolder, "CustomInstantDeserializer.java")); supportingFiles.add(new SupportingFile("CustomInstantDeserializer.mustache", invokerFolder, "CustomInstantDeserializer.java"));
@ -300,6 +343,11 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
this.useRxJava = useRxJava; this.useRxJava = useRxJava;
} }
public void setUsePlay24WS(boolean usePlay24WS) {
this.usePlay24WS = usePlay24WS;
}
public void setParcelableModel(boolean parcelableModel) { public void setParcelableModel(boolean parcelableModel) {
this.parcelableModel = parcelableModel; this.parcelableModel = parcelableModel;
} }
@ -308,6 +356,10 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
this.useBeanValidation = useBeanValidation; 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_MIME_PATTERN = Pattern.compile("(?i)application\\/json(;.*)?");
final private static Pattern JSON_VENDOR_MIME_PATTERN = Pattern.compile("(?i)application\\/vnd.(.*)+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; package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.codegen.CodegenModel; import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.SupportingFile;
import java.io.File; 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 { public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen {
/**
* Default constructor
*/
public JavaJAXRSCXFCDIServerCodegen() { public JavaJAXRSCXFCDIServerCodegen() {
outputFolder = "generated-code/JavaJaxRS-CXF-CDI"; outputFolder = "generated-code/JavaJaxRS-CXF-CDI";
artifactId = "swagger-jaxrs-cxf-cdi-server"; artifactId = "swagger-jaxrs-cxf-cdi-server";
@ -20,7 +30,8 @@ public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen {
typeMapping.put("DateTime", "java.util.Date"); typeMapping.put("DateTime", "java.util.Date");
// Updated template directory // Updated template directory
embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "cxf-cdi"; embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME
+ File.separator + "cxf-cdi";
} }
@Override @Override
@ -31,8 +42,21 @@ public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen {
@Override @Override
public void processOpts() { public void processOpts() {
super.processOpts(); super.processOpts();
supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen 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")); 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 @Override
@ -45,7 +69,8 @@ public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen {
@Override @Override
public String getHelp() { 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; package io.swagger.codegen.languages;
import io.swagger.codegen.*; import io.swagger.codegen.*;
import io.swagger.codegen.languages.features.JbossFeature;
import io.swagger.models.Operation; import io.swagger.models.Operation;
import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
@ -8,7 +9,9 @@ import org.apache.commons.lang3.StringUtils;
import java.io.File; import java.io.File;
import java.util.*; import java.util.*;
public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen { public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen implements JbossFeature {
protected boolean generateJbossDeploymentDescriptor = true;
public JavaResteasyServerCodegen() { public JavaResteasyServerCodegen() {
@ -31,6 +34,9 @@ public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen {
dateLibrary = "legacy";// TODO: change to joda dateLibrary = "legacy";// TODO: change to joda
embeddedTemplateDir = templateDir = "JavaJaxRS" + File.separator + "resteasy"; embeddedTemplateDir = templateDir = "JavaJaxRS" + File.separator + "resteasy";
cliOptions.add(
CliOption.newBoolean(GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR, "Generate Jboss Deployment Descriptor"));
} }
@Override @Override
@ -47,6 +53,12 @@ public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen {
public void processOpts() { public void processOpts() {
super.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("pom.mustache", "", "pom.xml"));
writeOptional(outputFolder, new SupportingFile("gradle.mustache", "", "build.gradle")); writeOptional(outputFolder, new SupportingFile("gradle.mustache", "", "build.gradle"));
writeOptional(outputFolder, new SupportingFile("settingsGradle.mustache", "", "settings.gradle")); writeOptional(outputFolder, new SupportingFile("settingsGradle.mustache", "", "settings.gradle"));
@ -61,8 +73,12 @@ public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen {
(sourceFolder + '/' + apiPackage).replace(".", "/"), "NotFoundException.java")); (sourceFolder + '/' + apiPackage).replace(".", "/"), "NotFoundException.java"));
writeOptional(outputFolder, new SupportingFile("web.mustache", writeOptional(outputFolder, new SupportingFile("web.mustache",
("src/main/webapp/WEB-INF"), "web.xml")); ("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")); ("src/main/webapp/WEB-INF"), "jboss-web.xml"));
}
writeOptional(outputFolder, new SupportingFile("RestApplication.mustache", writeOptional(outputFolder, new SupportingFile("RestApplication.mustache",
(sourceFolder + '/' + invokerPackage).replace(".", "/"), "RestApplication.java")); (sourceFolder + '/' + invokerPackage).replace(".", "/"), "RestApplication.java"));
supportingFiles.add(new SupportingFile("StringUtil.mustache", supportingFiles.add(new SupportingFile("StringUtil.mustache",
@ -198,4 +214,8 @@ public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen {
return objs; 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 // set vendor-extension: x-codegen-hasMoreRequired
CodegenProperty lastRequired = null; CodegenProperty lastRequired = null;
for (CodegenProperty var : cm.vars) { for (CodegenProperty var : cm.vars) {
if (var.required != null && var.required) { if (var.required) {
lastRequired = var; lastRequired = var;
} }
} }
for (CodegenProperty var : cm.vars) { for (CodegenProperty var : cm.vars) {
if (var == lastRequired) { if (var == lastRequired) {
var.vendorExtensions.put("x-codegen-hasMoreRequired", false); 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); var.vendorExtensions.put("x-codegen-hasMoreRequired", true);
} }
} }
@ -996,7 +996,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
int count = 0, numVars = codegenProperties.size(); int count = 0, numVars = codegenProperties.size();
for(CodegenProperty codegenProperty : codegenProperties) { for(CodegenProperty codegenProperty : codegenProperties) {
count += 1; count += 1;
codegenProperty.hasMore = (count < numVars) ? true : null; codegenProperty.hasMore = (count < numVars) ? true : false;
} }
codegenModel.vars = codegenProperties; 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); 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 String apiVersion = "1.0.0";
protected int serverPort = 8080; protected int serverPort = 8080;
protected String projectName = "swagger-server"; protected String projectName = "swagger-server";
protected boolean googleCloudFunctions;
protected String exportedName;
public NodeJSServerCodegen() { public NodeJSServerCodegen() {
super(); super();
@ -76,27 +82,15 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
additionalProperties.put("apiVersion", apiVersion); additionalProperties.put("apiVersion", apiVersion);
additionalProperties.put("serverPort", serverPort); additionalProperties.put("serverPort", serverPort);
/* cliOptions.add(CliOption.newBoolean(GOOGLE_CLOUD_FUNCTIONS,
* Supporting Files. You can write single files for the generator with the "When specified, it will generate the code which runs within Google Cloud Functions "
* entire object tree available. If the input file has a suffix of `.mustache + "instead of standalone Node.JS server. See "
* it will be processed by the template engine. Otherwise, it will be copied + "https://cloud.google.com/functions/docs/quickstart for the details of how to "
*/ + "deploy the generated code."));
// supportingFiles.add(new SupportingFile("controller.mustache", cliOptions.add(new CliOption(EXPORTED_NAME,
// "controllers", "When the generated code will be deployed to Google Cloud Functions, this option can be "
// "controller.js") + "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."));
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
}
} }
@Override @Override
@ -171,6 +165,22 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar); 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 @Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) { public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -231,7 +241,7 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
opsByPathEntry.put("path", entry.getKey()); opsByPathEntry.put("path", entry.getKey());
opsByPathEntry.put("operation", entry.getValue()); opsByPathEntry.put("operation", entry.getValue());
List<CodegenOperation> operationsForThisPath = Lists.newArrayList(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()) { if (opsByPathList.size() < opsByPath.asMap().size()) {
opsByPathEntry.put("hasMore", "true"); opsByPathEntry.put("hasMore", "true");
} }
@ -240,6 +250,46 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
return opsByPathList; 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 @Override
public void preprocessSwagger(Swagger swagger) { public void preprocessSwagger(Swagger swagger) {
String host = swagger.getHost(); 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 // need vendor extensions for x-swagger-router-controller
Map<String, Path> paths = swagger.getPaths(); Map<String, Path> paths = swagger.getPaths();
if(paths != null) { 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 AUTHOR_EMAIL = "authorEmail";
public static final String LICENSE = "license"; public static final String LICENSE = "license";
public static final String GIT_REPO_URL = "gitRepoURL"; 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"; public static final String CORE_DATA = "coreData";
protected Set<String> foundationClasses = new HashSet<String>(); 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(".travis.yml", getPackagePath(), ".travis.yml"));
supportingFiles.add(new SupportingFile(".php_cs", getPackagePath(), ".php_cs")); supportingFiles.add(new SupportingFile(".php_cs", getPackagePath(), ".php_cs"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", getPackagePath(), "git_push.sh")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", getPackagePath(), "git_push.sh"));
// apache v2 license
supportingFiles.add(new SupportingFile("LICENSE", getPackagePath(), "LICENSE"));
} }
@Override @Override

View File

@ -170,7 +170,6 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
apiPackage = swaggerFolder + File.separatorChar + "apis"; apiPackage = swaggerFolder + File.separatorChar + "apis";
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); 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("setup.mustache", "", "setup.py"));
supportingFiles.add(new SupportingFile("tox.mustache", "", "tox.ini")); 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 gemVersion = "1.0.0";
protected String specFolder = "spec"; protected String specFolder = "spec";
protected String libFolder = "lib"; protected String libFolder = "lib";
protected String gemLicense = "Apache-2.0"; protected String gemLicense = "proprietary";
protected String gemRequiredRubyVersion = ">= 1.9"; protected String gemRequiredRubyVersion = ">= 1.9";
protected String gemHomepage = "http://swagger.io"; protected String gemHomepage = "http://swagger.io";
protected String gemSummary = "A ruby wrapper for the swagger APIs"; 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_VERSION, "gem version.").defaultValue("1.0.0"));
cliOptions.add(new CliOption(GEM_LICENSE, "gem license. "). 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. "). cliOptions.add(new CliOption(GEM_REQUIRED_RUBY_VERSION, "gem required Ruby version. ").
defaultValue(">= 1.9")); 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("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); 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 // test files should not be overwritten
writeOptional(outputFolder, new SupportingFile("rspec.mustache", "", ".rspec")); writeOptional(outputFolder, new SupportingFile("rspec.mustache", "", ".rspec"));

View File

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

View File

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

View File

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

View File

@ -137,7 +137,7 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod
@Override @Override
public String getSwaggerType(Property p) { public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p); String swaggerType = super.getSwaggerType(p);
if(languageSpecificPrimitives.contains(swaggerType)) { if(isLanguagePrimitive(swaggerType) || isLanguageGenericType(swaggerType)) {
return swaggerType; return swaggerType;
} }
applyLocalTypeMapping(swaggerType); applyLocalTypeMapping(swaggerType);
@ -151,9 +151,13 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod
return type; return type;
} }
private boolean startsWithLanguageSpecificPrimitiv(String type) { private boolean isLanguagePrimitive(String type) {
for (String langPrimitive:languageSpecificPrimitives) { return languageSpecificPrimitives.contains(type);
if (type.startsWith(langPrimitive)) { }
private boolean isLanguageGenericType(String type) {
for (String genericType: languageGenericTypes) {
if (type.startsWith(genericType + "<")) {
return true; 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("package.json.mustache", "", "package.json"));
supportingFiles.add(new SupportingFile("typings.json.mustache", "", "typings.json")); supportingFiles.add(new SupportingFile("typings.json.mustache", "", "typings.json"));
supportingFiles.add(new SupportingFile("tsconfig.json.mustache", "", "tsconfig.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("gitignore", "", ".gitignore"));
supportingFiles.add(new SupportingFile("configuration.mustache", "", "configuration.ts")); supportingFiles.add(new SupportingFile("configuration.mustache", "", "configuration.ts"));

View File

@ -1,5 +1,7 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.models.properties.FileProperty;
import io.swagger.models.properties.Property;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -27,6 +29,8 @@ public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen
public TypeScriptNodeClientCodegen() { public TypeScriptNodeClientCodegen() {
super(); super();
typeMapping.put("file", "Buffer");
// clear import mapping (from default generator) as TS does not use it // clear import mapping (from default generator) as TS does not use it
// at the moment // at the moment
importMapping.clear(); importMapping.clear();
@ -92,6 +96,19 @@ public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen
return "Generates a TypeScript nodejs client library."; 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) { public void setNpmName(String npmName) {
this.npmName = npmName; this.npmName = npmName;

View File

@ -4,6 +4,8 @@ package io.swagger.codegen.languages.features;
* Features supported by CXF 3 (client + server) * 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; package io.swagger.codegen.languages.features;
/** /**
* Features supported by CXF 3 server * Features supported by CXF 3 server
* *
*/ */
public interface CXFServerFeatures extends CXFFeatures, SwaggerFeatures, SpringFeatures { public interface CXFServerFeatures
extends CXFFeatures, SwaggerFeatures, SpringFeatures, JbossFeature, BeanValidationExtendedFeatures,
public static final String USE_WADL_FEATURE = "useWadlFeature"; SwaggerUIFeatures
{
public static final String USE_MULTIPART_FEATURE = "useMultipartFeature";
public static final String USE_WADL_FEATURE = "useWadlFeature";
public void setUseWadlFeature(boolean useWadlFeature);
public static final String USE_MULTIPART_FEATURE = "useMultipartFeature";
public void setUseMultipartFeature(boolean 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 interface GzipFeatures {
public static final String USE_GZIP_FEATURE = "useGzipFeature"; public static final String USE_GZIP_FEATURE = "useGzipFeature";
public void setUseGzipFeature(boolean 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 GENERATE_SPRING_BOOT_APPLICATION = "generateSpringBootApplication";
public static final String USE_SPRING_ANNOTATION_CONFIG = "useSpringAnnotationConfig";
public void setGenerateSpringApplication(boolean useGenerateSpringApplication); public void setGenerateSpringApplication(boolean useGenerateSpringApplication);
public void setGenerateSpringBootApplication(boolean generateSpringBootApplication); 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(); StringBuilder b = new StringBuilder();
for(Object o : (Collection<?>)param) { for(Object o : (Collection<?>)param) {
if(b.length() > 0) { if(b.length() > 0) {
b.append(","); b.append(',');
} }
b.append(String.valueOf(o)); b.append(String.valueOf(o));
} }
@ -386,7 +386,7 @@ public class ApiClient {
// preconditions // preconditions
if (name == null || name.isEmpty() || value == null) return params; if (name == null || name.isEmpty() || value == null) return params;
Collection<?> valueCollection = null; Collection<?> valueCollection;
if (value instanceof Collection<?>) { if (value instanceof Collection<?>) {
valueCollection = (Collection<?>) value; valueCollection = (Collection<?>) value;
} else { } else {
@ -399,10 +399,10 @@ public class ApiClient {
} }
// get the collection format // 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 // create the params based on the collection format
if (collectionFormat.equals("multi")) { if ("multi".equals(format)) {
for (Object item : valueCollection) { for (Object item : valueCollection) {
params.add(new Pair(name, parameterToString(item))); params.add(new Pair(name, parameterToString(item)));
} }
@ -412,13 +412,13 @@ public class ApiClient {
String delimiter = ","; String delimiter = ",";
if (collectionFormat.equals("csv")) { if ("csv".equals(format)) {
delimiter = ","; delimiter = ",";
} else if (collectionFormat.equals("ssv")) { } else if ("ssv".equals(format)) {
delimiter = " "; delimiter = " ";
} else if (collectionFormat.equals("tsv")) { } else if ("tsv".equals(format)) {
delimiter = "\t"; delimiter = "\t";
} else if (collectionFormat.equals("pipes")) { } else if ("pipes".equals(format)) {
delimiter = "|"; 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}} {{>licenseInfo}}
package {{package}}; package {{package}};
import {{invokerPackage}}.ApiException; import {{invokerPackage}}.ApiException;
{{#imports}}import {{import}}; {{#imports}}import {{import}};
{{/imports}} {{/imports}}
import org.junit.Test; import org.junit.Test;
import org.junit.Ignore;
{{^fullJavaUtil}}
import java.util.ArrayList; {{^fullJavaUtil}}
import java.util.HashMap; import java.util.ArrayList;
import java.util.List; import java.util.HashMap;
import java.util.Map; import java.util.List;
{{/fullJavaUtil}} import java.util.Map;
{{/fullJavaUtil}}
/**
* API tests for {{classname}} /**
*/ * API tests for {{classname}}
public class {{classname}}Test { */
@Ignore
private final {{classname}} api = new {{classname}}(); public class {{classname}}Test {
{{#operations}}{{#operation}} private final {{classname}} api = new {{classname}}();
/**
* {{summary}} {{#operations}}{{#operation}}
* /**
* {{notes}} * {{summary}}
* *
* @throws ApiException * {{notes}}
* if the Api call fails *
*/ * @throws ApiException
@Test * if the Api call fails
public void {{operationId}}Test() throws ApiException { */
{{#allParams}} @Test
{{{dataType}}} {{paramName}} = null; public void {{operationId}}Test() throws ApiException {
{{/allParams}} {{#allParams}}
// {{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); {{{dataType}}} {{paramName}} = null;
{{/allParams}}
// TODO: test validations {{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
}
{{/operation}}{{/operations}} // TODO: test validations
} }
{{/operation}}{{/operations}}
}

View File

@ -35,8 +35,18 @@
{{/maxItems}} {{/maxItems}}
{{/minItems}} {{/minItems}}
{{#minimum}} {{#minimum}}
//@Min({{minimum}}) {{#isInteger}}
@Min({{minimum}})
{{/isInteger}}
{{#isLong}}
@Min({{minimum}})
{{/isLong}}
{{/minimum}} {{/minimum}}
{{#maximum}} {{#maximum}}
//@Max({{maximum}}) {{#isInteger}}
{{/maximum}} @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" <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"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>{{groupId}}</groupId> <groupId>{{groupId}}</groupId>
<artifactId>{{artifactId}}</artifactId> <artifactId>{{artifactId}}</artifactId>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>{{artifactId}}</name> <name>{{artifactId}}</name>
<version>{{artifactVersion}}</version> <version>{{artifactVersion}}</version>
<scm> <scm>
<connection>scm:git:git@github.com:swagger-api/swagger-mustache.git</connection> <connection>scm:git:git@github.com:swagger-api/swagger-mustache.git</connection>
<developerConnection>scm:git:git@github.com:swagger-api/swagger-codegen.git</developerConnection> <developerConnection>scm:git:git@github.com:swagger-api/swagger-codegen.git</developerConnection>
<url>https://github.com/swagger-api/swagger-codegen</url> <url>https://github.com/swagger-api/swagger-codegen</url>
</scm> </scm>
<prerequisites> <prerequisites>
<maven>2.2.0</maven> <maven>2.2.0</maven>
</prerequisites> </prerequisites>
<build> <licenses>
<plugins> <license>
<plugin> <name>{{licenseName}}</name>
<groupId>org.apache.maven.plugins</groupId> <url>{{licenseUrl}}</url>
<artifactId>maven-surefire-plugin</artifactId> <distribution>repo</distribution>
<version>2.12</version> </license>
<configuration> </licenses>
<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>
<!-- attach test jar --> <build>
<plugin> <plugins>
<groupId>org.apache.maven.plugins</groupId> <plugin>
<artifactId>maven-jar-plugin</artifactId> <groupId>org.apache.maven.plugins</groupId>
<version>2.2</version> <artifactId>maven-surefire-plugin</artifactId>
<executions> <version>2.12</version>
<execution> <configuration>
<goals> <systemProperties>
<goal>jar</goal> <property>
<goal>test-jar</goal> <name>loggerPath</name>
</goals> <value>conf/log4j.properties</value>
</execution> </property>
</executions> </systemProperties>
<configuration> <argLine>-Xms512m -Xmx1500m</argLine>
</configuration> <parallel>methods</parallel>
</plugin> <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> <!-- attach test jar -->
<groupId>org.codehaus.mojo</groupId> <plugin>
<artifactId>build-helper-maven-plugin</artifactId> <groupId>org.apache.maven.plugins</groupId>
<executions> <artifactId>maven-jar-plugin</artifactId>
<execution> <version>2.2</version>
<id>add_sources</id> <executions>
<phase>generate-sources</phase> <execution>
<goals> <goals>
<goal>add-source</goal> <goal>jar</goal>
</goals> <goal>test-jar</goal>
</goals>
</execution>
</executions>
<configuration> <configuration>
<sources>
<source>src/main/java</source>
</sources>
</configuration> </configuration>
</execution> </plugin>
<execution>
<id>add_test_sources</id> <plugin>
<phase>generate-test-sources</phase> <groupId>org.codehaus.mojo</groupId>
<goals> <artifactId>build-helper-maven-plugin</artifactId>
<goal>add-test-source</goal> <executions>
</goals> <execution>
<configuration> <id>add_sources</id>
<sources> <phase>generate-sources</phase>
<source>src/test/java</source> <goals>
</sources> <goal>add-source</goal>
</configuration> </goals>
</execution> <configuration>
</executions> <sources>
</plugin> <source>src/main/java</source>
<plugin> </sources>
<groupId>org.apache.maven.plugins</groupId> </configuration>
<artifactId>maven-javadoc-plugin</artifactId> </execution>
<version>2.10.4</version> <execution>
</plugin> <id>add_test_sources</id>
</plugins> <phase>generate-test-sources</phase>
</build> <goals>
<dependencies> <goal>add-test-source</goal>
<dependency> </goals>
<groupId>io.swagger</groupId> <configuration>
<artifactId>swagger-annotations</artifactId> <sources>
<version>${swagger-core-version}</version> <source>src/test/java</source>
</dependency> </sources>
</configuration>
<!-- HTTP client: Netflix Feign --> </execution>
<dependency> </executions>
<groupId>com.netflix.feign</groupId> </plugin>
<artifactId>feign-core</artifactId> <plugin>
<version>${feign-version}</version> <groupId>org.apache.maven.plugins</groupId>
</dependency> <artifactId>maven-javadoc-plugin</artifactId>
<dependency> <version>2.10.4</version>
<groupId>com.netflix.feign</groupId> </plugin>
<artifactId>feign-jackson</artifactId> </plugins>
<version>${feign-version}</version> </build>
</dependency> <dependencies>
<dependency> <dependency>
<groupId>com.netflix.feign</groupId> <groupId>io.swagger</groupId>
<artifactId>feign-slf4j</artifactId> <artifactId>swagger-annotations</artifactId>
<version>${feign-version}</version> <version>${swagger-core-version}</version>
</dependency> </dependency>
<dependency>
<groupId>io.github.openfeign.form</groupId> <!-- HTTP client: Netflix Feign -->
<artifactId>feign-form</artifactId> <dependency>
<version>${feign-form-version}</version> <groupId>com.netflix.feign</groupId>
</dependency> <artifactId>feign-core</artifactId>
<version>${feign-version}</version>
<!-- JSON processing: jackson --> </dependency>
<dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId> <groupId>com.netflix.feign</groupId>
<artifactId>jackson-core</artifactId> <artifactId>feign-jackson</artifactId>
<version>${jackson-version}</version> <version>${feign-version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId> <groupId>com.netflix.feign</groupId>
<artifactId>jackson-annotations</artifactId> <artifactId>feign-slf4j</artifactId>
<version>${jackson-version}</version> <version>${feign-version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId> <groupId>io.github.openfeign.form</groupId>
<artifactId>jackson-databind</artifactId> <artifactId>feign-form</artifactId>
<version>${jackson-version}</version> <version>${feign-form-version}</version>
</dependency> </dependency>
{{#joda}}
<dependency> <!-- JSON processing: jackson -->
<groupId>com.fasterxml.jackson.datatype</groupId> <dependency>
<artifactId>jackson-datatype-joda</artifactId> <groupId>com.fasterxml.jackson.core</groupId>
<version>${jackson-version}</version> <artifactId>jackson-core</artifactId>
</dependency> <version>${jackson-version}</version>
{{/joda}} </dependency>
{{#java8}} <dependency>
<dependency> <groupId>com.fasterxml.jackson.core</groupId>
<groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-annotations</artifactId>
<artifactId>jackson-datatype-jsr310</artifactId> <version>${jackson-version}</version>
<version>${jackson-version}</version> </dependency>
</dependency> <dependency>
{{/java8}} <groupId>com.fasterxml.jackson.core</groupId>
{{#threetenbp}} <artifactId>jackson-databind</artifactId>
<dependency> <version>${jackson-version}</version>
<groupId>com.github.joschi.jackson</groupId> </dependency>
<artifactId>jackson-datatype-threetenbp</artifactId> {{#joda}}
<version>${threepane-version}</version> <dependency>
</dependency> <groupId>com.fasterxml.jackson.datatype</groupId>
{{/threetenbp}} <artifactId>jackson-datatype-joda</artifactId>
<dependency> <version>${jackson-version}</version>
<groupId>org.apache.oltu.oauth2</groupId> </dependency>
<artifactId>org.apache.oltu.oauth2.client</artifactId> {{/joda}}
<version>${oltu-version}</version> {{#java8}}
</dependency> <dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<!-- test dependencies --> <artifactId>jackson-datatype-jsr310</artifactId>
<dependency> <version>${jackson-version}</version>
<groupId>junit</groupId> </dependency>
<artifactId>junit</artifactId> {{/java8}}
<version>${junit-version}</version> {{#threetenbp}}
<scope>test</scope> <dependency>
</dependency> <groupId>com.github.joschi.jackson</groupId>
</dependencies> <artifactId>jackson-datatype-threetenbp</artifactId>
<properties> <version>${jackson-threetenbp-version}</version>
<java.version>{{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}}</java.version> </dependency>
<maven.compiler.source>${java.version}</maven.compiler.source> {{/threetenbp}}
<maven.compiler.target>${java.version}</maven.compiler.target> <dependency>
<swagger-core-version>1.5.9</swagger-core-version> <groupId>org.apache.oltu.oauth2</groupId>
<feign-version>8.17.0</feign-version> <artifactId>org.apache.oltu.oauth2.client</artifactId>
<feign-form-version>2.0.2</feign-form-version> <version>${oltu-version}</version>
<jackson-version>2.7.5</jackson-version> </dependency>
<threepane-version>2.6.4</threepane-version>
<junit-version>4.12</junit-version> <!-- test dependencies -->
<maven-plugin-version>1.0.0</maven-plugin-version> <dependency>
<oltu-version>1.0.1</oltu-version> <groupId>junit</groupId>
</properties> <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> </project>

View File

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

View File

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

View File

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

View File

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

View File

@ -18,6 +18,11 @@ import java.util.List;
import java.util.Map; import java.util.Map;
{{/fullJavaUtil}} {{/fullJavaUtil}}
{{#usePlay24WS}}
import play.libs.F;
import retrofit2.Response;
{{/usePlay24WS}}
{{#operations}} {{#operations}}
public interface {{classname}} { public interface {{classname}} {
{{#operation}} {{#operation}}
@ -39,7 +44,7 @@ public interface {{classname}} {
{{/prioritizedContentTypes}} {{/prioritizedContentTypes}}
{{/formParams}} {{/formParams}}
@{{httpMethod}}("{{path}}") @{{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}} {{#allParams}}{{>libraries/retrofit2/queryParams}}{{>libraries/retrofit2/pathParams}}{{>libraries/retrofit2/headerParams}}{{>libraries/retrofit2/bodyParams}}{{>libraries/retrofit2/formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}}
);{{/hasMore}}{{/allParams}} );{{/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> <maven>2.2.0</maven>
</prerequisites> </prerequisites>
<licenses>
<license>
<name>{{licenseName}}</name>
<url>{{licenseUrl}}</url>
<distribution>repo</distribution>
</license>
</licenses>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
@ -155,6 +163,40 @@
<version>${retrofit-version}</version> <version>${retrofit-version}</version>
</dependency> </dependency>
{{/useRxJava}} {{/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 --> <!-- test dependencies -->
<dependency> <dependency>
@ -171,6 +213,9 @@
<maven.compiler.target>${java.version}</maven.compiler.target> <maven.compiler.target>${java.version}</maven.compiler.target>
<swagger-core-version>1.5.9</swagger-core-version> <swagger-core-version>1.5.9</swagger-core-version>
<retrofit-version>2.1.0</retrofit-version> <retrofit-version>2.1.0</retrofit-version>
{{#usePlay24WS}}
<jackson-version>2.7.5</jackson-version>
{{/usePlay24WS}}
{{#useRxJava}} {{#useRxJava}}
<rxjava-version>1.1.6</rxjava-version> <rxjava-version>1.1.6</rxjava-version>
{{/useRxJava}} {{/useRxJava}}

View File

@ -8,16 +8,4 @@
* NOTE: This class is auto generated by the swagger code generator program. * NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git * https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually. * 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}}{{.}}{{/description}}{{^description}}{{classname}}{{/description}}
*/{{#description}} */{{#description}}
@ApiModel(description = "{{{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}}{ 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}} {{#vars}}
{{#isEnum}} {{#isEnum}}
{{^isContainer}} {{^isContainer}}
@ -92,7 +96,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#parcela
return {{#vars}}Objects.equals(this.{{name}}, {{classVarName}}.{{name}}){{#hasMore}} && return {{#vars}}Objects.equals(this.{{name}}, {{classVarName}}.{{name}}){{#hasMore}} &&
{{/hasMore}}{{/vars}}{{#parent}} && {{/hasMore}}{{/vars}}{{#parent}} &&
super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}} super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}}
return true;{{/hasVars}} return {{#parent}}super.equals(o){{/parent}}{{^parent}}true{{/parent}};{{/hasVars}}
} }
@Override @Override

View File

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

View File

@ -1,18 +1,6 @@
# #
# Generated by: https://github.com/swagger-api/swagger-codegen.git # 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 language: java
jdk: jdk:
- oraclejdk8 - 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> <maven>2.2.0</maven>
</prerequisites> </prerequisites>
<licenses>
<license>
<name>{{licenseName}}</name>
<url>{{licenseUrl}}</url>
<distribution>repo</distribution>
</license>
</licenses>
<build> <build>
<defaultGoal>install</defaultGoal> <defaultGoal>install</defaultGoal>
<directory>target</directory> <directory>target</directory>
@ -117,4 +125,4 @@
<junit-version>4.8.2</junit-version> <junit-version>4.8.2</junit-version>
<slf4j-version>1.6.3</slf4j-version> <slf4j-version>1.6.3</slf4j-version>
</properties> </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}}; package {{package}};
{{#imports}}import {{import}}; {{#imports}}import {{import}};
{{/imports}} {{/imports}}
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import javax.ws.rs.*; import javax.ws.rs.*;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;
import org.apache.cxf.jaxrs.ext.multipart.*; import org.apache.cxf.jaxrs.ext.multipart.*;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
{{#useBeanValidation}} {{#useBeanValidation}}
import javax.validation.constraints.*; import javax.validation.constraints.*;
{{/useBeanValidation}} {{/useBeanValidation}}
@Path("/") @Path("/")
@Api(value = "/", description = "{{description}}") @Api(value = "/", description = "{{description}}")
public interface {{classname}} { {{#addConsumesProducesJson}}
{{#operations}} @Consumes(MediaType.APPLICATION_JSON)
{{#operation}} @Produces(MediaType.APPLICATION_JSON)
{{/addConsumesProducesJson}}
@{{httpMethod}} public interface {{classname}} {
{{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} {{#operations}}
{{#hasConsumes}}@Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} {{#operation}}
{{#hasProduces}}@Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}}
@ApiOperation(value = "{{summary}}", tags={ {{#vendorExtensions.x-tags}}"{{tag}}"{{#hasMore}}, {{/hasMore}}{{/vendorExtensions.x-tags}} }) @{{httpMethod}}
public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}}
{{/operation}} {{#hasConsumes}}
} @Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} })
{{/operations}} {{/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 org.apache.cxf.jaxrs.ext.multipart.*;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
{{#useSpringAnnotationConfig}}
import org.springframework.stereotype.Service;
{{/useSpringAnnotationConfig}}
{{#useSpringAnnotationConfig}}
@Service("{{classname}}")
{{/useSpringAnnotationConfig}}
{{#description}} {{#description}}
{{/description}} {{/description}}
public class {{classname}}ServiceImpl implements {{classname}} { public class {{classname}}ServiceImpl implements {{classname}} {
{{#operations}} {{#operations}}
{{#operation}} {{#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... // TODO: Implement...
{{^vendorExtensions.x-java-is-response-void}}return null;{{/vendorExtensions.x-java-is-response-void}} {{^vendorExtensions.x-java-is-response-void}}return null;{{/vendorExtensions.x-java-is-response-void}}

View File

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

View File

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

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