Merge remote-tracking branch 'refs/remotes/swagger-api/master' into JSR310-Clients

This commit is contained in:
ant3 2016-07-08 23:54:14 +01:00
commit 1ea80ab83a
2079 changed files with 108415 additions and 15867 deletions

7
.gitignore vendored
View File

@ -41,7 +41,7 @@ samples/server-generator/scalatra/target
samples/server-generator/scalatra/output/.history
# nodejs
**/node_modules/
**/node_modules
samples/server-generator/node/output/node_modules
samples/server/petstore/nodejs/node_modules
samples/server/petstore/nodejs-server/node_modules
@ -54,7 +54,7 @@ samples/client/petstore/qt5cpp/PetStore/PetStore
samples/client/petstore/qt5cpp/PetStore/Makefile
#Java/Android
**/.gradle/
**/.gradle
samples/client/petstore/java/hello.txt
samples/client/petstore/android/default/hello.txt
samples/client/petstore/android/volley/.gradle/
@ -75,6 +75,8 @@ samples/client/petstore/php/SwaggerClient-php/composer.lock
samples/client/petstore/php/SwaggerClient-php/vendor/
samples/client/petstore/silex/SwaggerServer/composer.lock
samples/client/petstore/silex/SwaggerServer/venodr/
**/vendor/
**/composer.lock
# Perl
samples/client/petstore/perl/deep_module_test/
@ -97,6 +99,7 @@ samples/client/petstore/swift/SwaggerClientTests/SwaggerClient.xcodeproj/xcuserd
samples/client/petstore/swift/SwaggerClientTests/SwaggerClient.xcworkspace/xcuserdata
samples/client/petstore/swift/SwaggerClientTests/Pods/Pods.xcodeproj/xcuserdata
samples/client/petstore/swift/SwaggerClientTests/Pods/Pods.xcodeproj/xcshareddata/xcschemes
samples/client/petstore/swift/**/SwaggerClientTests/Podfile.lock
# C#
*.csproj.user

View File

@ -11,7 +11,7 @@
- Search the [open issue](https://github.com/swagger-api/swagger-codegen/issues) to ensure no one else has reported something similar and no one is actively working on similar proposed change.
- If no one has suggested something similar, open an ["issue"](https://github.com/swagger-api/swagger-codegen/issues) with your suggestion to gather feedback from the community.
- It's recommended to **create a new git branch** for the change
- It's recommended to **create a new git branch** for the change so that the merge commit message looks nicer in the commit history.
## How to contribute
@ -30,6 +30,7 @@ For a list of variables available in the template, please refer to this [page](h
Code change should conform to the programming style guide of the respective langauages:
- Android: https://source.android.com/source/code-style.html
- C#: https://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx
- C++: https://google.github.io/styleguide/cppguide.html
- Haskell: https://github.com/tibbe/haskell-style-guide/blob/master/haskell-style.md
- Java: https://google.github.io/styleguide/javaguide.html
- JavaScript: https://github.com/airbnb/javascript/tree/master/es5
@ -51,13 +52,14 @@ You may find the current code base not 100% conform to the coding style and we w
For [Vendor Extensions](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#vendorExtensions), please follow the naming convention below:
- For general vendor extension, use lower case and hyphen. e.g. `x-is-unique`, `x-content-type`
- For language-specified vendor extension, put it in the form of `x-{lang}-{extension-name}`. e.g. `x-objc-operation-id`, `x-java-feign-retry-limit`
- For a list of existing vendor extensions in use, please refer to https://github.com/swagger-api/swagger-codegen/wiki/Vendor-Extensions. If you've addaed new vendor extensions as part of your PR, please update the wiki page.
### Testing
To add test cases (optional) covering the change in the code generator, please refer to [modules/swagger-codegen/src/test/java/io/swagger/codegen](https://github.com/swagger-api/swagger-codegen/tree/master/modules/swagger-codegen/src/test/java/io/swagger/codegen)
To test the templates, please perform the following:
- Update the [Petstore](http://petstore.swagger.io/) sample by running the shell script under `bin` folder. For example, run `./bin/ruby-petstore.sh` to update the Ruby PetStore API client under [`samples/client/petstore/ruby`](https://github.com/swagger-api/swagger-codegen/tree/master/samples/client/petstore/ruby) (For Windows, the batch files can be found under `bin\windows` folder)
- Update the [Petstore](http://petstore.swagger.io/) sample by running the shell script under `bin` folder. For example, run `./bin/ruby-petstore.sh` to update the Ruby PetStore API client under [`samples/client/petstore/ruby`](https://github.com/swagger-api/swagger-codegen/tree/master/samples/client/petstore/ruby) For Windows, the batch files can be found under `bin\windows` folder. (If you find that there are new files generated or unexpected changes as a result of the update, that's not unusual as the test cases are added to the OpenAPI/Swagger spec from time to time. If you've questions or concerns, please open a ticket to start a discussion)
- Run the tests in the sample folder, e.g. in `samples/client/petstore/ruby`, run `mvn integration-test -rf :RubyPetstoreClientTests`. (some languages may not contain unit testing for Petstore and we're looking for contribution from the community to implement those tests)
- Finally, git commit the updated samples files: `git commit -a`
(`git add -A` if added files with new test cases)

View File

@ -3,13 +3,16 @@
[![Build Status](https://travis-ci.org/swagger-api/swagger-codegen.svg)](https://travis-ci.org/swagger-api/swagger-codegen)
[![Maven Central](https://maven-badges.herokuapp.com/maven-central/io.swagger/swagger-codegen-project/badge.svg?style=plastic)](https://maven-badges.herokuapp.com/maven-central/io.swagger/swagger-codegen-project)
[![PR Stats](http://issuestats.com/github/swagger-api/swagger-codegen/badge/pr)](http://issuestats.com/github/swagger-api/swagger-codegen) [![Issue Stats](http://issuestats.com/github/swagger-api/swagger-codegen/badge/issue)](http://issuestats.com/github/swagger-api/swagger-codegen)
[![Windows Test](https://ci.appveyor.com/api/projects/status/github/swagger-api/swagger-codegen?branch=master&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](#)
:star::star::star: If you would like to contribute, please refer to [guidelines](https://github.com/swagger-api/swagger-codegen/blob/master/CONTRIBUTING.md) and a list of [open tasks](https://github.com/swagger-api/swagger-codegen/issues?q=is%3Aopen+is%3Aissue+label%3A%22Need+community+contribution%22).:star::star::star:
:notebook_with_decorative_cover: For more information, please refer to the [Wiki page](https://github.com/swagger-api/swagger-codegen/wiki) and [FAQ](https://github.com/swagger-api/swagger-codegen/wiki/FAQ) :notebook_with_decorative_cover:
:warning: If the OpenAPI/Swagger spec is obtained from an untrusted source, please make sure you've reviewed the spec before using Swagger Codegen to generate the API client, server stub or documentation as [code injection](https://en.wikipedia.org/wiki/Code_injection) may occur :warning:
## Overview
This is the swagger codegen project, which allows generation of client libraries automatically from a Swagger-compliant server.
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).
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.
@ -373,7 +376,7 @@ To control the specific files being generated, you can pass a CSV list of what y
-Dmodels=User -DsupportingFiles=StringUtil.java
```
To control generation of docs and tests for api and models, pass false to the option. For api, these options are `-DapiTest=false` and `-DapiDocs=false`. For models, `-DmodelTest=false` and `-DmodelDocs=false`.
To control generation of docs and tests for api and models, pass false to the option. For api, these options are `-DapiTests=false` and `-DapiDocs=false`. For models, `-DmodelTests=false` and `-DmodelDocs=false`.
These options default to true and don't limit the generation of the feature options listed above (like `-Dapi`):
```
@ -461,6 +464,7 @@ JavaJerseyServerCodegen.java
JavaResteasyServerCodegen.java
JavascriptClientCodegen.java
NodeJSServerCodegen.java
NancyFXServerCodegen
ObjcClientCodegen.java
PerlClientCodegen.java
PhpClientCodegen.java
@ -492,8 +496,15 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
-o samples/client/petstore/java \
-c path/to/config.json
```
Supported config options can be different per language. Running `config-help -l {lang}` will show available options. **These options are applied
by passing them with `-D{optionName}={optionValue}**.
and `config.json` contains the following as an example:
```
{
"apiPackage" : "petstore"
}
```
Supported config options can be different per language. Running `config-help -l {lang}` will show available options.
**These options are applied via configuration file (e.g. config.json) or by passing them with `-D{optionName}={optionValue}**. (If `-D{optionName}` does not work, please open a [ticket](https://github.com/swagger-api/swagger-codegen/issues/new) and we'll look into it)
```
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar config-help -l java
@ -675,6 +686,52 @@ curl -X POST -H "content-type:application/json" -d '{"swaggerUrl":"http://petsto
```
Then you will receieve a JSON response with the URL to download the zipped code.
To customize the SDK, you can `POST` to `https://generator.swagger.io/gen/clients/{language}` with the following HTTP body:
```
{
"options": {},
"swaggerUrl": "http://petstore.swagger.io/v2/swagger.json"
}
```
in which the `options` for a language can be obtained by submitting a `GET` request to `https://generator.swagger.io/api/gen/clients/{language}`:
For example, `curl https://generator.swagger.io/api/gen/clients/python` returns
```
{
"packageName":{
"opt":"packageName",
"description":"python package name (convention: snake_case).",
"type":"string",
"default":"swagger_client"
},
"packageVersion":{
"opt":"packageVersion",
"description":"python package version.",
"type":"string",
"default":"1.0.0"
},
"sortParamsByRequiredFlag":{
"opt":"sortParamsByRequiredFlag",
"description":"Sort method arguments to place required parameters before optional parameters.",
"type":"boolean",
"default":"true"
}
}
```
To set package name to `pet_store`, the HTTP body of the request is as follows:
```
{
"options": {
"packageName": "pet_store"
},
"swaggerUrl": "http://petstore.swagger.io/v2/swagger.json"
}
```
and here is the curl command:
```
curl -H "Content-type: application/json" -X POST -d '{"options": {"packageName": "pet_store"},"swaggerUrl": "http://petstore.swagger.io/v2/swagger.json"}' https://generator.swagger.io/api/gen/clients/python
```
Guidelines for Contribution
---------------------------
@ -691,6 +748,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you
- [bitly](https://bitly.com)
- [Cachet Financial](http://www.cachetfinancial.com/)
- [CloudBoost](https://www.CloudBoost.io/)
- [Conplement](http://www.conplement.de/)
- [Cupix](http://www.cupix.com)
- [DBBest Technologies](https://www.dbbest.com)
- [DocuSign](https://www.docusign.com)
@ -698,15 +756,19 @@ Here are some companies/projects using Swagger Codegen in production. To add you
- [eureka](http://eure.jp/)
- [everystory.us](http://everystory.us)
- [Expected Behavior](http://www.expectedbehavior.com/)
- [Finder](http://en.finder.pl/)
- [FH Münster - University of Applied Sciences](http://www.fh-muenster.de)
- [GraphHopper](https://graphhopper.com/)
- [Gravitate Solutions](http://gravitatesolutions.com/)
- [IMS Health](http://www.imshealth.com/en/solution-areas/technology-and-applications)
- [Interactive Intelligence](http://developer.mypurecloud.com/)
- [LANDR Audio](https://www.landr.com/)
- [Lascaux](http://www.lascaux.it/)
- [LiveAgent](https://www.ladesk.com/)
- [Kabuku](http://www.kabuku.co.jp/en)
- [Kuroi](http://kuroiwebdesign.com/)
- [Kuary](https://kuary.com/)
- [Mporium](http://mporium.com/)
- [nViso](http://www.nviso.ch/)
- [Okiok](https://www.okiok.com)
- [OSDN](https://osdn.jp)
@ -714,6 +776,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you
- [Pepipost](https://www.pepipost.com)
- [Pixoneye](http://www.pixoneye.com/)
- [PostAffiliatePro](https://www.postaffiliatepro.com/)
- [Rapid7](https://rapid7.com/)
- [Reload! A/S](https://reload.dk/)
- [REstore](https://www.restore.eu)
- [Revault Sàrl](http://revault.ch)
@ -724,6 +787,8 @@ Here are some companies/projects using Swagger Codegen in production. To add you
- [Svenska Spel AB](https://www.svenskaspel.se/)
- [ThoughtWorks](https://www.thoughtworks.com)
- [uShip](https://www.uship.com/)
- [W.UP](http://wup.hu/?siteLang=en)
- [Wealthfront](https://www.wealthfront.com/)
- [WEXO A/S](https://www.wexo.dk/)
- [Zalando](https://tech.zalando.com)
- [ZEEF.com](https://zeef.com/)
@ -733,7 +798,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you
Swaagger Codegen core team members are contributors who have been making signficiant contributions (review issues, fix bugs, make enhancements, etc) to the project on a regular basis.
## API Clients
| Langauges | Core Team (join date) |
| Languages | Core Team (join date) |
|:-------------|:-------------|
| ActionScript | |
| C++ | |
@ -756,7 +821,7 @@ Swaagger Codegen core team members are contributors who have been making signfic
| TypeScript (Angular2) | @Vrolijkx (2016/05/01) |
| TypeScript (Fetch) | |
## Server Stubs
| Langauges | Core Team (date joined) |
| Languages | Core Team (date joined) |
|:------------- |:-------------|
| C# ASP.NET5 | @jimschubert (2016/05/01) |
| Go Server | @guohuang (2016/06/13) |
@ -764,6 +829,7 @@ Swaagger Codegen core team members are contributors who have been making signfic
| Java Spring Boot | |
| Java SpringMVC | @kolyjjj (2016/05/01) |
| Java JAX-RS | |
| NancyFX | |
| NodeJS | @kolyjjj (2016/05/01) |
| PHP Lumen | @abcsum (2016/05/01) |
| PHP Silex | |
@ -796,6 +862,7 @@ Here is a list of template creators:
* TypeScript (Angular2): @roni-frantchi
* Server Stubs
* C# ASP.NET5: @jimschubert
* C# NancyFX: @mstefaniuk
* Go Server: @guohuang
* Haskell Servant: @algas
* Java Spring Boot: @diyfr

24
appveyor.yml Normal file
View File

@ -0,0 +1,24 @@
# for CI with appveyor.yml
# Ref: http://www.yegor256.com/2015/01/10/windows-appveyor-maven.html
version: '{build}'
os: Windows Server 2012
install:
- ps: |
Add-Type -AssemblyName System.IO.Compression.FileSystem
if (!(Test-Path -Path "C:\maven" )) {
(new-object System.Net.WebClient).DownloadFile(
'http://www.us.apache.org/dist/maven/maven-3/3.2.5/binaries/apache-maven-3.2.5-bin.zip',
'C:\maven-bin.zip'
)
[System.IO.Compression.ZipFile]::ExtractToDirectory("C:\maven-bin.zip", "C:\maven")
}
- cmd: SET PATH=C:\maven\apache-maven-3.2.5\bin;%JAVA_HOME%\bin;%PATH%
- cmd: SET MAVEN_OPTS=-XX:MaxPermSize=2g -Xmx4g
- cmd: SET JAVA_OPTS=-XX:MaxPermSize=2g -Xmx4g
build_script:
- mvn clean package --batch-mode -DskipTest
test_script:
- mvn clean install --batch-mode
cache:
- C:\maven\
- C:\Users\appveyor\.m2

View File

@ -20,6 +20,7 @@ fi
cd $APP_DIR
./bin/akka-scala-petstore.sh
./bin/android-petstore.sh
./bin/aspnet5-petstore-server.sh
./bin/clojure-petstore.sh
./bin/csharp-petstore.sh
./bin/dynamic-html.sh

View File

@ -1,7 +1,7 @@
#!/bin/sh
# update java petstore for all supported http libraries
./bin/java-petstore.sh
./bin/java-petstore-jersey1.sh
./bin/java-petstore-jersey2.sh
./bin/java-petstore-feign.sh
./bin/java-petstore-okhttp-gson.sh

View File

@ -26,6 +26,9 @@ 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-feign.json -o samples/client/petstore/java/feign -DhideGenerationTimestamp=true"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/Java/libraries/feign -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-feign.json -o samples/client/petstore/java/feign -DhideGenerationTimestamp=true"
echo "Removing files and folders under samples/client/petstore/java/feign/src/main"
rm -rf samples/client/petstore/java/feign/src/main
find samples/client/petstore/java/feign -maxdepth 1 -type f ! -name "README.md" -exec rm {} +
java $JAVA_OPTS -jar $executable $ags

View File

@ -26,9 +26,9 @@ 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 -o samples/client/petstore/java/default -DhideGenerationTimestamp=true"
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -o samples/client/petstore/java/jersey1 -DhideGenerationTimestamp=true --library=jersey1"
echo "Removing files and folders under samples/client/petstore/java/default/src/main"
rm -rf samples/client/petstore/java/default/src/main
find samples/client/petstore/java/default -maxdepth 1 -type f ! -name "README.md" -exec rm {} +
echo "Removing files and folders under samples/client/petstore/java/jersey1/src/main"
rm -rf samples/client/petstore/java/jersey1/src/main
find samples/client/petstore/java/jersey1 -maxdepth 1 -type f ! -name "README.md" -exec rm {} +
java $JAVA_OPTS -jar $executable $ags

View File

@ -26,7 +26,7 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-okhttp-gson.json -o samples/client/petstore/java/okhttp-gson -DhideGenerationTimestamp=true"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-okhttp-gson.json -o samples/client/petstore/java/okhttp-gson -DhideGenerationTimestamp=true"
rm -rf samples/client/petstore/java/okhttp-gson/src/main
find samples/client/petstore/java/okhttp-gson -maxdepth 1 -type f ! -name "README.md" -exec rm {} +

View File

@ -26,6 +26,9 @@ 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.json -o samples/client/petstore/java/retrofit2 -DhideGenerationTimestamp=true"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2 -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-retrofit2.json -o samples/client/petstore/java/retrofit2 -DhideGenerationTimestamp=true"
echo "Removing files and folders under samples/client/petstore/java/retrofit2/src/main"
rm -rf samples/client/petstore/java/retrofit2/src/main
find samples/client/petstore/java/retrofit2 -maxdepth 1 -type f ! -name "README.md" -exec rm {} +
java $JAVA_OPTS -jar $executable $ags

View File

@ -26,6 +26,9 @@ 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-retrofit2rx.json -o samples/client/petstore/java/retrofit2rx -DuseRxJava=true,hideGenerationTimestamp=true"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2 -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-retrofit2rx.json -o samples/client/petstore/java/retrofit2rx -DuseRxJava=true,hideGenerationTimestamp=true"
echo "Removing files and folders under samples/client/petstore/java/retrofit2rx/src/main"
rm -rf samples/client/petstore/java/retrofit2rx/src/main
find samples/client/petstore/java/retrofit2rx -maxdepth 1 -type f ! -name "README.md" -exec rm {} +
java $JAVA_OPTS -jar $executable $ags

0
bin/java8-petstore-jersey2.sh Normal file → Executable file
View File

View File

@ -26,6 +26,9 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaJaxRS -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l jaxrs -o samples/server/petstore/jaxrs/jersey1 -DhideGenerationTimestamp=true --library=jersey1 --artifact-id=swagger-jaxrs-jersey1-server"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1 -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l jaxrs -o samples/server/petstore/jaxrs/jersey1 -DhideGenerationTimestamp=true --library=jersey1 --artifact-id=swagger-jaxrs-jersey1-server"
echo "Removing files and folders under samples/server/petstore/jaxrs/jersey1/src/main"
rm -rf samples/server/petstore/jaxrs/jersey1/src/main
find samples/server/petstore/jaxrs/jersey1 -maxdepth 1 -type f ! -name "README.md" -exec rm {} +
java $JAVA_OPTS -jar $executable $ags

View File

@ -28,4 +28,7 @@ fi
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaJaxRS -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l jaxrs -o samples/server/petstore/jaxrs/jersey2 -DhideGenerationTimestamp=true"
echo "Removing files and folders under samples/server/petstore/jaxrs/jersey2/src/main"
rm -rf samples/server/petstore/jaxrs/jersey2/src/main
find samples/server/petstore/jaxrs/jersey2 -maxdepth 1 -type f ! -name "README.md" -exec rm {} +
java $JAVA_OPTS -jar $executable $ags

View File

@ -0,0 +1,3 @@
{
"dateLibrary": "joda"
}

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 -t modules/swagger-codegen/src/main/resources/JavaJaxRS -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l jaxrs-resteasy -o samples/server/petstore/jaxrs-resteasy/joda -DhideGenerationTimestamp=true -c ./bin/jaxrs-resteasy-joda-petstore-server.json"
java $JAVA_OPTS -jar $executable $ags

View File

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

View File

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

31
bin/security/csharp-petstore.sh Executable file
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-security-test.yaml -l csharp -o samples/client/petstore-security-test/csharp/SwaggerClient"
java $JAVA_OPTS -jar $executable $ags

View File

@ -0,0 +1,33 @@
#!/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 -t modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson -i modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml -l java -c bin/java-petstore-okhttp-gson.json -o samples/client/petstore-security-test/java/okhttp-gson -DhideGenerationTimestamp=true"
rm -rf samples/client/petstore-security-test/java/okhttp-gson/src/main
find samples/client/petstore-security-test/java/okhttp-gson -maxdepth 1 -type f ! -name "README.md" -exec rm {} +
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-security-test.yaml -l javascript-closure-angular -o samples/client/petstore-security-test/javascript-closure-angular"
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 -t modules/swagger-codegen/src/main/resources/Javascript -i modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml -l javascript -o samples/client/petstore-security-test/javascript"
java -DappName=PetstoreClient $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 -t modules/swagger-codegen/src/main/resources/lumen -i modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml -l lumen -o samples/server/petstore-security-test/lumen"
java $JAVA_OPTS -jar $executable $ags

34
bin/security/perl-petstore.sh Executable file
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"
# complex module name used for testing
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml -l perl -o samples/client/petstore-security-test/perl"
java $JAVA_OPTS -jar $executable $ags
java $JAVA_OPTS -jar $executable $ags --additional-properties moduleName=Something::Deep -o samples/client/petstore-security-test/perl/deep_module_test

31
bin/security/php-petstore.sh Executable file
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 -t modules/swagger-codegen/src/main/resources/php -i modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml -l php -o samples/client/petstore-security-test/php"
java $JAVA_OPTS -jar $executable $ags

31
bin/security/python-petstore.sh Executable file
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 -t modules/swagger-codegen/src/main/resources/python -i modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml -l python -o samples/client/petstore-security-test/python -DpackageName=petstore_api"
java $JAVA_OPTS -jar $executable $ags

31
bin/security/ruby-petstore.sh Executable file
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 -t modules/swagger-codegen/src/main/resources/ruby -i modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml -l ruby -c bin/ruby-petstore.json -o samples/client/petstore-security-test/ruby"
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 -t modules/swagger-codegen/src/main/resources/silex -i modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml -l silex-PHP -o samples/server/petstore-security-test/silex"
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 -t modules/swagger-codegen/src/main/resources/slim -i modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml -l slim -o samples/server/petstore-security-test/slim"
java $JAVA_OPTS -jar $executable $ags

View File

@ -0,0 +1,4 @@
{
"library": "spring-cloud",
"artifactId": "swagger-petstore-spring-cloud"
}

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 -t modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l spring -c bin/spring-cloud-feign-petstore.json -o samples/client/petstore/spring-cloud -DhideGenerationTimestamp=true"
echo "Removing files and folders under samples/client/petstore/spring-cloud/src/main"
rm -rf samples/client/petstore/spring-cloud/src/main
find samples/client/petstore/spring-cloud -maxdepth 1 -type f ! -name "README.md" -exec rm {} +
java $JAVA_OPTS -jar $executable $ags

View File

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

View File

@ -0,0 +1,4 @@
{
"library": "spring-mvc",
"artifactId": "swagger-spring-mvc-server"
}

View File

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

View File

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

View File

@ -26,7 +26,7 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaSpringBoot -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l springboot -o samples/server/petstore/springboot -DhideGenerationTimestamp=true"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaSpring -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l spring -o samples/server/petstore/springboot -DhideGenerationTimestamp=true"
echo "Removing files and folders under samples/server/petstore/springboot/src/main"
rm -rf samples/server/petstore/springboot/src/main

View File

@ -0,0 +1,10 @@
set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar
If Not Exist %executable% (
mvn clean package
)
set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -t modules\swagger-codegen\src\main\resources\nancyfx -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l nancyfx -o samples\server\petstore\nancyfx\
java %JAVA_OPTS% -jar %executable% %ags%

View File

@ -57,8 +57,12 @@ public interface CodegenConfig {
String escapeText(String text);
String escapeUnsafeCharacters(String input);
String escapeReservedWord(String name);
String escapeQuotationMark(String input);
String getTypeDeclaration(Property p);
String getTypeDeclaration(String name);

View File

@ -54,6 +54,18 @@ public class CodegenConstants {
public static final String PACKAGE_NAME = "packageName";
public static final String PACKAGE_VERSION = "packageVersion";
public static final String PACKAGE_TITLE = "packageTitle";
public static final String PACKAGE_TITLE_DESC = "Specifies an AssemblyTitle for the .NET Framework global assembly attributes stored in the AssemblyInfo file.";
public static final String PACKAGE_PRODUCTNAME = "packageProductName";
public static final String PACKAGE_PRODUCTNAME_DESC = "Specifies an AssemblyProduct for the .NET Framework global assembly attributes stored in the AssemblyInfo file.";
public static final String PACKAGE_DESCRIPTION = "packageDescription";
public static final String PACKAGE_DESCRIPTION_DESC = "Specifies a AssemblyDescription for the .NET Framework global assembly attributes stored in the AssemblyInfo file.";
public static final String PACKAGE_COMPANY = "packageCompany";
public static final String PACKAGE_COMPANY_DESC = "Specifies an AssemblyCompany for the .NET Framework global assembly attributes stored in the AssemblyInfo file.";
public static final String PACKAGE_COPYRIGHT = "packageCopyright";
public static final String PACKAGE_COPYRIGHT_DESC = "Specifies an AssemblyCopyright for the .NET Framework global assembly attributes stored in the AssemblyInfo file.";
public static final String POD_VERSION = "podVersion";
public static final String OPTIONAL_METHOD_ARGUMENT = "optionalMethodArgument";

View File

@ -5,6 +5,7 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.Objects;
import io.swagger.models.ExternalDocs;
@ -29,6 +30,7 @@ public class CodegenModel {
public List<CodegenProperty> readOnlyVars = new ArrayList<CodegenProperty>(); // a list of read-only properties
public List<CodegenProperty> readWriteVars = new ArrayList<CodegenProperty>(); // a list of properties for read, write
public List<CodegenProperty> allVars;
public List<CodegenProperty> parentVars = new ArrayList<>();
public Map<String, Object> allowableValues;
// Sorted sets of required parameters.
@ -36,7 +38,8 @@ public class CodegenModel {
public Set<String> allMandatory;
public Set<String> imports = new TreeSet<String>();
public Boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum, hasRequired, isArrayModel;
public Boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum, hasRequired, isArrayModel, hasChildren;
public Boolean hasOnlyReadOnly = true; // true if all properties are read-only
public ExternalDocs externalDocs;
public Map<String, Object> vendorExtensions;
@ -121,6 +124,12 @@ public class CodegenModel {
return false;
if (externalDocs != null ? !externalDocs.equals(that.externalDocs) : that.externalDocs != null)
return false;
if (!Objects.equals(hasOnlyReadOnly, that.hasOnlyReadOnly))
return false;
if (!Objects.equals(hasChildren, that.hasChildren))
return false;
if (!Objects.equals(parentVars, that.parentVars))
return false;
return vendorExtensions != null ? vendorExtensions.equals(that.vendorExtensions) : that.vendorExtensions == null;
}
@ -157,6 +166,9 @@ public class CodegenModel {
result = 31 * result + (isEnum != null ? isEnum.hashCode() : 0);
result = 31 * result + (externalDocs != null ? externalDocs.hashCode() : 0);
result = 31 * result + (vendorExtensions != null ? vendorExtensions.hashCode() : 0);
result = 31 * result + Objects.hash(hasOnlyReadOnly);
result = 31 * result + Objects.hash(hasChildren);
result = 31 * result + Objects.hash(parentVars);
return result;
}
}

View File

@ -42,7 +42,7 @@ public class CodegenOperation {
*
* @return true if parameter exists, false otherwise
*/
private static boolean nonempty(List<CodegenParameter> params) {
private static boolean nonempty(List<?> params) {
return params != null && params.size() > 0;
}
@ -91,6 +91,15 @@ public class CodegenOperation {
return nonempty(formParams);
}
/**
* Check if there's at least one example parameter
*
* @return true if examples parameter exists, false otherwise
*/
public boolean getHasExamples() {
return nonempty(examples);
}
/**
* Check if act as Restful index method
*

View File

@ -9,7 +9,7 @@ public class CodegenParameter {
public Boolean isFormParam, isQueryParam, isPathParam, isHeaderParam,
isCookieParam, isBodyParam, hasMore, isContainer,
secondaryParam, isCollectionFormatMulti, isPrimitiveType;
public String baseName, paramName, dataType, datatypeWithEnum, collectionFormat, description, unescapedDescription, baseType, defaultValue;
public String baseName, paramName, dataType, datatypeWithEnum, dataFormat, collectionFormat, description, unescapedDescription, baseType, defaultValue;
public String example; // example value (x-example)
public String jsonSchema;
public Boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, isBoolean, isDate, isDateTime;
@ -85,6 +85,7 @@ public class CodegenParameter {
output.paramName = this.paramName;
output.dataType = this.dataType;
output.datatypeWithEnum = this.datatypeWithEnum;
output.dataFormat = this.dataFormat;
output.collectionFormat = this.collectionFormat;
output.isCollectionFormatMulti = this.isCollectionFormatMulti;
output.description = this.description;
@ -181,6 +182,8 @@ public class CodegenParameter {
return false;
if (datatypeWithEnum != null ? !datatypeWithEnum.equals(that.datatypeWithEnum) : that.datatypeWithEnum != null)
return false;
if (dataFormat != null ? !dataFormat.equals(that.dataFormat) : that.dataFormat != null)
return false;
if (collectionFormat != null ? !collectionFormat.equals(that.collectionFormat) : that.collectionFormat != null)
return false;
if (description != null ? !description.equals(that.description) : that.description != null)
@ -276,6 +279,7 @@ public class CodegenParameter {
result = 31 * result + (paramName != null ? paramName.hashCode() : 0);
result = 31 * result + (dataType != null ? dataType.hashCode() : 0);
result = 31 * result + (datatypeWithEnum != null ? datatypeWithEnum.hashCode() : 0);
result = 31 * result + (dataFormat != null ? dataFormat.hashCode() : 0);
result = 31 * result + (collectionFormat != null ? collectionFormat.hashCode() : 0);
result = 31 * result + (description != null ? description.hashCode() : 0);
result = 31 * result + (unescapedDescription != null ? unescapedDescription.hashCode() : 0);

View File

@ -2,10 +2,11 @@ package io.swagger.codegen;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class CodegenProperty {
public class CodegenProperty implements Cloneable {
public String baseName, complexType, getter, setter, description, datatype, datatypeWithEnum,
name, min, max, defaultValue, defaultValueWithParam, baseType, containerType;
dataFormat, name, min, max, defaultValue, defaultValueWithParam, baseType, containerType;
public String unescapedDescription;
@ -43,6 +44,8 @@ public class CodegenProperty {
public CodegenProperty items;
public Map<String, Object> vendorExtensions;
public Boolean hasValidation; // true if pattern, maximum, etc are set (only used in the mustache template)
public Boolean isInherited;
public String nameInCamelCase; // property name in camel case
@Override
public String toString() {
@ -63,6 +66,7 @@ public class CodegenProperty {
result = prime * result + ((containerType == null) ? 0 : containerType.hashCode());
result = prime * result + ((datatype == null) ? 0 : datatype.hashCode());
result = prime * result + ((datatypeWithEnum == null) ? 0 : datatypeWithEnum.hashCode());
result = prime * result + ((dataFormat == null) ? 0 : dataFormat.hashCode());
result = prime * result + ((defaultValue == null) ? 0 : defaultValue.hashCode());
result = prime * result + ((defaultValueWithParam == null) ? 0 : defaultValueWithParam.hashCode());
result = prime * result + ((description == null) ? 0 : description.hashCode());
@ -105,6 +109,8 @@ public class CodegenProperty {
result = prime * result + ((isDateTime == null) ? 0 : isDateTime.hashCode());
result = prime * result + ((isMapContainer == null) ? 0 : isMapContainer.hashCode());
result = prime * result + ((isListContainer == null) ? 0 : isListContainer.hashCode());
result = prime * result + Objects.hashCode(isInherited);
result = prime * result + Objects.hashCode(nameInCamelCase);
return result;
}
@ -138,6 +144,9 @@ public class CodegenProperty {
if ((this.datatypeWithEnum == null) ? (other.datatypeWithEnum != null) : !this.datatypeWithEnum.equals(other.datatypeWithEnum)) {
return false;
}
if ((this.dataFormat == null) ? (other.dataFormat != null) : !this.dataFormat.equals(other.dataFormat)) {
return false;
}
if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
return false;
}
@ -256,6 +265,21 @@ public class CodegenProperty {
if (this.isMapContainer != other.isMapContainer && (this.isMapContainer == null || !this.isMapContainer.equals(other.isMapContainer))) {
return false;
}
if (!Objects.equals(this.isInherited, other.isInherited)) {
return false;
}
if (!Objects.equals(this.nameInCamelCase, other.nameInCamelCase)) {
return false;
}
return true;
}
@Override
public CodegenProperty clone() {
try {
return (CodegenProperty) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
}
}

View File

@ -13,6 +13,7 @@ public class CodegenSecurity {
// Oauth specific
public String flow, authorizationUrl, tokenUrl;
public List<Map<String, Object>> scopes;
public Boolean isCode, isPassword, isApplication, isImplicit;
@Override
public String toString() {
@ -50,6 +51,14 @@ public class CodegenSecurity {
return false;
if (tokenUrl != null ? !tokenUrl.equals(that.tokenUrl) : that.tokenUrl != null)
return false;
if (isCode != null ? !isCode.equals(that.isCode) : that.isCode != null)
return false;
if (isPassword != null ? !isPassword.equals(that.isPassword) : that.isPassword != null)
return false;
if (isApplication != null ? !isApplication.equals(that.isApplication) : that.isApplication != null)
return false;
if (isImplicit != null ? !isImplicit.equals(that.isImplicit) : that.isImplicit != null)
return false;
return scopes != null ? scopes.equals(that.scopes) : that.scopes == null;
}
@ -68,6 +77,10 @@ public class CodegenSecurity {
result = 31 * result + (flow != null ? flow.hashCode() : 0);
result = 31 * result + (authorizationUrl != null ? authorizationUrl.hashCode() : 0);
result = 31 * result + (tokenUrl != null ? tokenUrl.hashCode() : 0);
result = 31 * result + (isCode != null ? isCode.hashCode() : 0);
result = 31 * result + (isPassword != null ? isPassword.hashCode() : 0);
result = 31 * result + (isApplication != null ? isApplication.hashCode() : 0);
result = 31 * result + (isImplicit != null ? isImplicit.hashCode() : 0);
result = 31 * result + (scopes != null ? scopes.hashCode() : 0);
return result;
}

View File

@ -2,32 +2,6 @@ package io.swagger.codegen;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
import io.swagger.codegen.examples.ExampleGenerator;
import io.swagger.models.ArrayModel;
import io.swagger.models.ComposedModel;
@ -71,7 +45,29 @@ import io.swagger.models.properties.RefProperty;
import io.swagger.models.properties.StringProperty;
import io.swagger.models.properties.UUIDProperty;
import io.swagger.util.Json;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DefaultCodegen {
protected static final Logger LOGGER = LoggerFactory.getLogger(DefaultCodegen.class);
@ -227,58 +223,12 @@ public class DefaultCodegen {
cm.allowableValues.put("enumVars", enumVars);
}
// for enum model's properties
// update codegen property enum with proper naming convention
// and handling of numbers, special characters
for (CodegenProperty var : cm.vars) {
Map<String, Object> allowableValues = var.allowableValues;
// handle ArrayProperty
if (var.items != null) {
allowableValues = var.items.allowableValues;
}
if (allowableValues == null) {
continue;
}
//List<String> values = (List<String>) allowableValues.get("values");
List<Object> values = (List<Object>) allowableValues.get("values");
if (values == null) {
continue;
}
// put "enumVars" map into `allowableValues", including `name` and `value`
List<Map<String, String>> enumVars = new ArrayList<Map<String, String>>();
String commonPrefix = findCommonPrefixOfVars(values);
int truncateIdx = commonPrefix.length();
for (Object value : values) {
Map<String, String> enumVar = new HashMap<String, String>();
String enumName;
if (truncateIdx == 0) {
enumName = value.toString();
} else {
enumName = value.toString().substring(truncateIdx);
if ("".equals(enumName)) {
enumName = value.toString();
}
}
enumVar.put("name", toEnumVarName(enumName, var.datatype));
enumVar.put("value", toEnumValue(value.toString(), var.datatype));
enumVars.add(enumVar);
}
allowableValues.put("enumVars", enumVars);
// handle default value for enum, e.g. available => StatusEnum.AVAILABLE
if (var.defaultValue != null) {
String enumName = null;
for (Map<String, String> enumVar : enumVars) {
if (toEnumValue(var.defaultValue, var.datatype).equals(enumVar.get("value"))) {
enumName = enumVar.get("name");
break;
}
}
if (enumName != null) {
var.defaultValue = toEnumDefaultValue(enumName, var.datatypeWithEnum);
}
}
updateCodegenPropertyEnum(var);
}
}
return objs;
}
@ -380,16 +330,43 @@ public class DefaultCodegen {
// override with any special text escaping logic
@SuppressWarnings("static-method")
public String escapeText(String input) {
if (input != null) {
// remove \t, \n, \r
// repalce \ with \\
// repalce " with \"
// outter unescape to retain the original multi-byte characters
return StringEscapeUtils.unescapeJava(StringEscapeUtils.escapeJava(input).replace("\\/", "/")).replaceAll("[\\t\\n\\r]"," ").replace("\\", "\\\\").replace("\"", "\\\"");
if (input == null) {
return input;
}
// remove \t, \n, \r
// replace \ with \\
// replace " with \"
// outter unescape to retain the original multi-byte characters
// finally escalate characters avoiding code injection
return escapeUnsafeCharacters(StringEscapeUtils.unescapeJava(StringEscapeUtils.escapeJava(input).replace("\\/", "/")).replaceAll("[\\t\\n\\r]"," ").replace("\\", "\\\\").replace("\"", "\\\""));
}
/**
* override with any special text escaping logic to handle unsafe
* characters so as to avoid code injection
* @param input String to be cleaned up
* @return string with unsafe characters removed or escaped
*/
public String escapeUnsafeCharacters(String input) {
LOGGER.warn("escapeUnsafeCharacters should be overriden in the code generator with proper logic to escape unsafe characters");
// doing nothing by default and code generator should implement
// the logic to prevent code injection
// later we'll make this method abstract to make sure
// code generator implements this method
return input;
}
/**
* Escape single and/or double quote to avoid code injection
* @param input String to be cleaned up
* @return string with quotation mark removed or escaped
*/
public String escapeQuotationMark(String input) {
LOGGER.warn("escapeQuotationMark should be overriden in the code generator with proper logic to escape single/double quote");
return input.replace("\"", "\\\"");
}
public Set<String> defaultIncludes() {
return defaultIncludes;
}
@ -1346,6 +1323,7 @@ public class DefaultCodegen {
property.name = toVarName(name);
property.baseName = name;
property.nameInCamelCase = camelize(name, false);
property.description = escapeText(p.getDescription());
property.unescapedDescription = p.getDescription();
property.getter = "get" + getterAndSetterCapitalize(name);
@ -1565,6 +1543,7 @@ public class DefaultCodegen {
}
}
property.datatype = getTypeDeclaration(p);
property.dataFormat = p.getFormat();
// this can cause issues for clients which don't support enums
if (property.isEnum) {
@ -1576,48 +1555,135 @@ public class DefaultCodegen {
property.baseType = getSwaggerType(p);
if (p instanceof ArrayProperty) {
property.isContainer = true;
property.isListContainer = true;
property.containerType = "array";
ArrayProperty ap = (ArrayProperty) p;
CodegenProperty cp = fromProperty(property.name, ap.getItems());
if (cp == null) {
LOGGER.warn("skipping invalid property " + Json.pretty(p));
} else {
property.baseType = getSwaggerType(p);
if (!languageSpecificPrimitives.contains(cp.baseType)) {
property.complexType = cp.baseType;
} else {
property.isPrimitiveType = true;
}
property.items = cp;
if (property.items.isEnum) {
property.datatypeWithEnum = property.datatypeWithEnum.replace(property.items.baseType,
property.items.datatypeWithEnum);
if(property.defaultValue != null)
property.defaultValue = property.defaultValue.replace(property.items.baseType, property.items.datatypeWithEnum);
}
}
property.isContainer = true;
property.isListContainer = true;
property.containerType = "array";
property.baseType = getSwaggerType(p);
// handle inner property
ArrayProperty ap = (ArrayProperty) p;
CodegenProperty cp = fromProperty(property.name, ap.getItems());
updatePropertyForArray(property, cp);
} else if (p instanceof MapProperty) {
property.isContainer = true;
property.isMapContainer = true;
property.containerType = "map";
property.baseType = getSwaggerType(p);
// handle inner property
MapProperty ap = (MapProperty) p;
CodegenProperty cp = fromProperty("inner", ap.getAdditionalProperties());
property.items = cp;
property.baseType = getSwaggerType(p);
if (!languageSpecificPrimitives.contains(cp.baseType)) {
property.complexType = cp.baseType;
} else {
property.isPrimitiveType = true;
}
updatePropertyForMap(property, cp);
} else {
setNonArrayMapProperty(property, type);
}
return property;
}
/**
* Update property for array(list) container
* @param property Codegen property
* @param innerProperty Codegen inner property of map or list
*/
protected void updatePropertyForArray(CodegenProperty property, CodegenProperty innerProperty) {
if (innerProperty == null) {
LOGGER.warn("skipping invalid array property " + Json.pretty(property));
} else {
if (!languageSpecificPrimitives.contains(innerProperty.baseType)) {
property.complexType = innerProperty.baseType;
} else {
property.isPrimitiveType = true;
}
property.items = innerProperty;
// inner item is Enum
if (isPropertyInnerMostEnum(property)) {
property.isEnum = true;
// update datatypeWithEnum and default value for array
// e.g. List<string> => List<StatusEnum>
updateDataTypeWithEnumForArray(property);
}
}
}
/**
* Update property for map container
* @param property Codegen property
* @param innerProperty Codegen inner property of map or list
*/
protected void updatePropertyForMap(CodegenProperty property, CodegenProperty innerProperty) {
if (innerProperty == null) {
LOGGER.warn("skipping invalid map property " + Json.pretty(property));
return;
} else {
if (!languageSpecificPrimitives.contains(innerProperty.baseType)) {
property.complexType = innerProperty.baseType;
} else {
property.isPrimitiveType = true;
}
property.items = innerProperty;
// inner item is Enum
if (isPropertyInnerMostEnum(property)) {
property.isEnum = true;
// update datatypeWithEnum and default value for map
// e.g. Dictionary<string, string> => Dictionary<string, StatusEnum>
updateDataTypeWithEnumForMap(property);
}
}
}
/**
* Update property for map container
* @param property Codegen property
* @return True if the inner most type is enum
*/
protected Boolean isPropertyInnerMostEnum(CodegenProperty property) {
CodegenProperty currentProperty = property;
while (currentProperty != null && (Boolean.TRUE.equals(currentProperty.isMapContainer)
|| Boolean.TRUE.equals(currentProperty.isListContainer))) {
currentProperty = currentProperty.items;
}
return currentProperty.isEnum;
}
/**
* Update datatypeWithEnum for array container
* @param property Codegen property
*/
protected void updateDataTypeWithEnumForArray(CodegenProperty property) {
CodegenProperty baseItem = property.items;
while (baseItem != null && (Boolean.TRUE.equals(baseItem.isMapContainer)
|| Boolean.TRUE.equals(baseItem.isListContainer))) {
baseItem = baseItem.items;
}
// set both datatype and datetypeWithEnum as only the inner type is enum
property.datatypeWithEnum = property.datatypeWithEnum.replace(baseItem.baseType, toEnumName(baseItem));
// set default value for variable with inner enum
if (property.defaultValue != null) {
property.defaultValue = property.defaultValue.replace(property.items.baseType, toEnumName(property.items));
}
}
/**
* Update datatypeWithEnum for map container
* @param property Codegen property
*/
protected void updateDataTypeWithEnumForMap(CodegenProperty property) {
CodegenProperty baseItem = property.items;
while (baseItem != null && (Boolean.TRUE.equals(baseItem.isMapContainer)
|| Boolean.TRUE.equals(baseItem.isListContainer))) {
baseItem = baseItem.items;
}
// set both datatype and datetypeWithEnum as only the inner type is enum
property.datatypeWithEnum = property.datatypeWithEnum.replace(", " + baseItem.baseType, ", " + toEnumName(baseItem));
// set default value for variable with inner enum
if (property.defaultValue != null) {
property.defaultValue = property.defaultValue.replace(", " + property.items.baseType, ", " + toEnumName(property.items));
}
}
protected void setNonArrayMapProperty(CodegenProperty property, String type) {
property.isNotContainer = true;
if (languageSpecificPrimitives().contains(type)) {
@ -1707,7 +1773,8 @@ public class DefaultCodegen {
int count = 0;
for (String key : consumes) {
Map<String, String> mediaType = new HashMap<String, String>();
mediaType.put("mediaType", key);
// escape quotation to avoid code injection
mediaType.put("mediaType", escapeQuotationMark(key));
count += 1;
if (count < consumes.size()) {
mediaType.put("hasMore", "true");
@ -1740,7 +1807,8 @@ public class DefaultCodegen {
int count = 0;
for (String key : produces) {
Map<String, String> mediaType = new HashMap<String, String>();
mediaType.put("mediaType", key);
// escape quotation to avoid code injection
mediaType.put("mediaType", escapeQuotationMark(key));
count += 1;
if (count < produces.size()) {
mediaType.put("hasMore", "true");
@ -2068,22 +2136,29 @@ public class DefaultCodegen {
LOGGER.warn("warning! Property type \"" + type + "\" not found for parameter \"" + param.getName() + "\", using String");
property = new StringProperty().description("//TODO automatically added by swagger-codegen. Type was " + type + " but not supported");
}
property.setRequired(param.getRequired());
CodegenProperty model = fromProperty(qp.getName(), property);
CodegenProperty cp = fromProperty(qp.getName(), property);
// set boolean flag (e.g. isString)
setParameterBooleanFlagWithCodegenProperty(p, model);
setParameterBooleanFlagWithCodegenProperty(p, cp);
p.dataType = model.datatype;
if(model.isEnum) {
p.datatypeWithEnum = model.datatypeWithEnum;
p.dataType = cp.datatype;
p.dataFormat = cp.dataFormat;
if(cp.isEnum) {
p.datatypeWithEnum = cp.datatypeWithEnum;
}
p.isEnum = model.isEnum;
p._enum = model._enum;
p.allowableValues = model.allowableValues;
if(model.items != null && model.items.isEnum) {
p.datatypeWithEnum = model.datatypeWithEnum;
p.items = model.items;
// enum
updateCodegenPropertyEnum(cp);
p.isEnum = cp.isEnum;
p._enum = cp._enum;
p.allowableValues = cp.allowableValues;
if (cp.items != null && cp.items.isEnum) {
p.datatypeWithEnum = cp.datatypeWithEnum;
p.items = cp.items;
}
p.collectionFormat = collectionFormat;
if(collectionFormat != null && collectionFormat.equals("multi")) {
@ -2091,10 +2166,12 @@ public class DefaultCodegen {
}
p.paramName = toParamName(qp.getName());
if (model.complexType != null) {
imports.add(model.complexType);
// import
if (cp.complexType != null) {
imports.add(cp.complexType);
}
// validation
p.maximum = qp.getMaximum();
p.exclusiveMaximum = qp.isExclusiveMaximum();
p.minimum = qp.getMinimum();
@ -2274,6 +2351,7 @@ public class DefaultCodegen {
CodegenSecurity sec = CodegenModelFactory.newInstance(CodegenModelType.SECURITY);
sec.name = entry.getKey();
sec.type = schemeDefinition.getType();
sec.isCode = sec.isPassword = sec.isApplication = sec.isImplicit = false;
if (schemeDefinition instanceof ApiKeyAuthDefinition) {
final ApiKeyAuthDefinition apiKeyDefinition = (ApiKeyAuthDefinition) schemeDefinition;
@ -2290,6 +2368,22 @@ public class DefaultCodegen {
sec.isKeyInHeader = sec.isKeyInQuery = sec.isApiKey = sec.isBasic = false;
sec.isOAuth = true;
sec.flow = oauth2Definition.getFlow();
switch(sec.flow) {
case "accessCode":
sec.isCode = true;
break;
case "password":
sec.isPassword = true;
break;
case "application":
sec.isApplication = true;
break;
case "implicit":
sec.isImplicit = true;
break;
default:
throw new RuntimeException("unknown oauth flow: " + sec.flow);
}
sec.authorizationUrl = oauth2Definition.getAuthorizationUrl();
sec.tokenUrl = oauth2Definition.getTokenUrl();
if (oauth2Definition.getScopes() != null) {
@ -2596,6 +2690,11 @@ public class DefaultCodegen {
m.hasEnums = true;
}
// set model's hasOnlyReadOnly to false if the property is read-only
if (!Boolean.TRUE.equals(cp.isReadOnly)) {
m.hasOnlyReadOnly = false;
}
if (i+1 != totalCount) {
cp.hasMore = true;
// check the next entry to see if it's read only
@ -2609,7 +2708,11 @@ public class DefaultCodegen {
}
addImport(m, cp.baseType);
addImport(m, cp.complexType);
CodegenProperty innerCp = cp;
while(innerCp != null) {
addImport(m, innerCp.complexType);
innerCp = innerCp.items;
}
vars.add(cp);
// if required, add to the list "requiredVars"
@ -2931,7 +3034,12 @@ public class DefaultCodegen {
return name.replaceAll("[^a-zA-Z0-9_]", "");
}
@SuppressWarnings("static-method")
/**
* Sanitize tag
*
* @param tag Tag
* @return Sanitized tag
*/
public String sanitizeTag(String tag) {
// remove spaces and make strong case
String[] parts = tag.split(" ");
@ -3021,4 +3129,63 @@ public class DefaultCodegen {
LOGGER.debug("Property type is not primitive: " + property.datatype);
}
}
/**
* Update codegen property's enum by adding "enumVars" (with name and value)
*
* @param var list of CodegenProperty
*/
public void updateCodegenPropertyEnum(CodegenProperty var) {
Map<String, Object> allowableValues = var.allowableValues;
// handle ArrayProperty
if (var.items != null) {
allowableValues = var.items.allowableValues;
}
if (allowableValues == null) {
return;
}
List<Object> values = (List<Object>) allowableValues.get("values");
if (values == null) {
return;
}
// put "enumVars" map into `allowableValues", including `name` and `value`
List<Map<String, String>> enumVars = new ArrayList<Map<String, String>>();
String commonPrefix = findCommonPrefixOfVars(values);
int truncateIdx = commonPrefix.length();
for (Object value : values) {
Map<String, String> enumVar = new HashMap<String, String>();
String enumName;
if (truncateIdx == 0) {
enumName = value.toString();
} else {
enumName = value.toString().substring(truncateIdx);
if ("".equals(enumName)) {
enumName = value.toString();
}
}
enumVar.put("name", toEnumVarName(enumName, var.datatype));
enumVar.put("value", toEnumValue(value.toString(), var.datatype));
enumVars.add(enumVar);
}
allowableValues.put("enumVars", enumVars);
// handle default value for enum, e.g. available => StatusEnum.AVAILABLE
if (var.defaultValue != null) {
String enumName = null;
for (Map<String, String> enumVar : enumVars) {
if (toEnumValue(var.defaultValue, var.datatype).equals(enumVar.get("value"))) {
enumName = enumVar.get("name");
break;
}
}
if (enumName != null) {
var.defaultValue = toEnumDefaultValue(enumName, var.datatypeWithEnum);
}
}
}
}

View File

@ -144,10 +144,10 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
if (swagger.getInfo() != null) {
Info info = swagger.getInfo();
if (info.getTitle() != null) {
config.additionalProperties().put("appName", info.getTitle());
config.additionalProperties().put("appName", config.escapeText(info.getTitle()));
}
if (info.getVersion() != null) {
config.additionalProperties().put("appVersion", info.getVersion());
config.additionalProperties().put("appVersion", config.escapeText(info.getVersion()));
}
if (info.getDescription() != null) {
config.additionalProperties().put("appDescription",
@ -155,25 +155,25 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
}
if (info.getContact() != null) {
Contact contact = info.getContact();
config.additionalProperties().put("infoUrl", contact.getUrl());
config.additionalProperties().put("infoUrl", config.escapeText(contact.getUrl()));
if (contact.getEmail() != null) {
config.additionalProperties().put("infoEmail", contact.getEmail());
config.additionalProperties().put("infoEmail", config.escapeText(contact.getEmail()));
}
}
if (info.getLicense() != null) {
License license = info.getLicense();
if (license.getName() != null) {
config.additionalProperties().put("licenseInfo", license.getName());
config.additionalProperties().put("licenseInfo", config.escapeText(license.getName()));
}
if (license.getUrl() != null) {
config.additionalProperties().put("licenseUrl", license.getUrl());
config.additionalProperties().put("licenseUrl", config.escapeText(license.getUrl()));
}
}
if (info.getVersion() != null) {
config.additionalProperties().put("version", info.getVersion());
config.additionalProperties().put("version", config.escapeText(info.getVersion()));
}
if (info.getTermsOfService() != null) {
config.additionalProperties().put("termsOfService", info.getTermsOfService());
config.additionalProperties().put("termsOfService", config.escapeText(info.getTermsOfService()));
}
}
@ -184,10 +184,11 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
StringBuilder hostBuilder = new StringBuilder();
String scheme;
if (swagger.getSchemes() != null && swagger.getSchemes().size() > 0) {
scheme = swagger.getSchemes().get(0).toValue();
scheme = config.escapeText(swagger.getSchemes().get(0).toValue());
} else {
scheme = "https";
}
scheme = config.escapeText(scheme);
hostBuilder.append(scheme);
hostBuilder.append("://");
if (swagger.getHost() != null) {
@ -198,9 +199,9 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
if (swagger.getBasePath() != null) {
hostBuilder.append(swagger.getBasePath());
}
String contextPath = swagger.getBasePath() == null ? "" : swagger.getBasePath();
String basePath = hostBuilder.toString();
String basePathWithoutHost = swagger.getBasePath();
String contextPath = config.escapeText(swagger.getBasePath() == null ? "" : swagger.getBasePath());
String basePath = config.escapeText(hostBuilder.toString());
String basePathWithoutHost = config.escapeText(swagger.getBasePath());
// resolve inline models
InlineModelResolver inlineModelResolver = new InlineModelResolver();
@ -283,7 +284,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
allProcessedModels.put(name, models);
} catch (Exception e) {
throw new RuntimeException("Could not process model '" + name + "'", e);
throw new RuntimeException("Could not process model '" + name + "'" + ".Please make sure that your schema is correct!", e);
}
}

View File

@ -93,9 +93,9 @@ public class ExampleGenerator {
};
}
} else if (property instanceof DateProperty) {
return "2000-01-23T04:56:07.000+0000";
return "2000-01-23T04:56:07.000+00:00";
} else if (property instanceof DateTimeProperty) {
return "2000-01-23T04:56:07.000+0000";
return "2000-01-23T04:56:07.000+00:00";
} else if (property instanceof DecimalProperty) {
return new BigDecimal(1.3579);
} else if (property instanceof DoubleProperty) {

View File

@ -21,6 +21,11 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
protected String packageVersion = "1.0.0";
protected String packageName = "IO.Swagger";
protected String packageTitle = "Swagger Library";
protected String packageProductName = "SwaggerLibrary";
protected String packageDescription = "A library generated from a Swagger doc";
protected String packageCompany = "Swagger";
protected String packageCopyright = "No Copyright";
protected String sourceFolder = "src";
@ -190,6 +195,41 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName);
}
// {{packageTitle}}
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_TITLE)) {
setPackageTitle((String) additionalProperties.get(CodegenConstants.PACKAGE_TITLE));
} else {
additionalProperties.put(CodegenConstants.PACKAGE_TITLE, packageTitle);
}
// {{packageProductName}}
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_PRODUCTNAME)) {
setPackageProductName((String) additionalProperties.get(CodegenConstants.PACKAGE_PRODUCTNAME));
} else {
additionalProperties.put(CodegenConstants.PACKAGE_PRODUCTNAME, packageProductName);
}
// {{packageDescription}}
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_DESCRIPTION)) {
setPackageDescription((String) additionalProperties.get(CodegenConstants.PACKAGE_DESCRIPTION));
} else {
additionalProperties.put(CodegenConstants.PACKAGE_DESCRIPTION, packageDescription);
}
// {{packageCompany}}
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_COMPANY)) {
setPackageCompany((String) additionalProperties.get(CodegenConstants.PACKAGE_COMPANY));
} else {
additionalProperties.put(CodegenConstants.PACKAGE_COMPANY, packageCompany);
}
// {{packageCopyright}}
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_COPYRIGHT)) {
setPackageCopyright((String) additionalProperties.get(CodegenConstants.PACKAGE_COPYRIGHT));
} else {
additionalProperties.put(CodegenConstants.PACKAGE_COPYRIGHT, packageCopyright);
}
// {{useDateTimeOffset}}
if (additionalProperties.containsKey(CodegenConstants.USE_DATETIME_OFFSET)) {
useDateTimeOffset(Boolean.valueOf(additionalProperties.get(CodegenConstants.USE_DATETIME_OFFSET).toString()));
@ -219,7 +259,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
// check to see if model name is same as the property name
// which will result in compilation error
// if found, prepend with _ to workaround the limitation
if (var.name.equals(cm.name)) {
if (var.name.equalsIgnoreCase(cm.name)) {
var.name = "_" + var.name;
}
}
@ -542,6 +582,26 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
this.packageVersion = packageVersion;
}
public void setPackageTitle(String packageTitle) {
this.packageTitle = packageTitle;
}
public void setPackageProductName(String packageProductName) {
this.packageProductName = packageProductName;
}
public void setPackageDescription(String packageDescription) {
this.packageDescription = packageDescription;
}
public void setPackageCompany(String packageCompany) {
this.packageCompany = packageCompany;
}
public void setPackageCopyright(String packageCopyright) {
this.packageCopyright = packageCopyright;
}
public void setSourceFolder(String sourceFolder) {
this.sourceFolder = sourceFolder;
}
@ -555,8 +615,6 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
enumName = camelize(enumName) + "Enum";
LOGGER.info("toEnumVarName = " + enumName);
if (enumName.matches("\\d.*")) { // starts with number
return "_" + enumName;
} else {
@ -598,4 +656,16 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
public String testPackageName() {
return this.packageName + ".Test";
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
}

View File

@ -96,7 +96,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
cliOptions.add(CliOption.newBoolean(CodegenConstants.SERIALIZABLE_MODEL, CodegenConstants.SERIALIZABLE_MODEL_DESC));
cliOptions.add(CliOption.newBoolean(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, CodegenConstants
.SERIALIZE_BIG_DECIMAL_AS_STRING_DESC));
cliOptions.add(CliOption.newBoolean(FULL_JAVA_UTIL, "whether to use fully qualified name for classes under java.util"));
cliOptions.add(CliOption.newBoolean(FULL_JAVA_UTIL, "whether to use fully qualified name for classes under java.util. This option only works for Java API client"));
cliOptions.add(new CliOption("hideGenerationTimestamp", "hides the timestamp when files were generated"));
CliOption dateLibrary = new CliOption(DATE_LIBRARY, "Option. Date library to use");
@ -210,6 +210,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
importMapping.put("ApiModel", "io.swagger.annotations.ApiModel");
importMapping.put("JsonProperty", "com.fasterxml.jackson.annotation.JsonProperty");
importMapping.put("JsonValue", "com.fasterxml.jackson.annotation.JsonValue");
importMapping.put("SerializedName", "com.google.gson.annotations.SerializedName");
importMapping.put("Objects", "java.util.Objects");
importMapping.put("StringUtil", invokerPackage + ".StringUtil");
@ -722,6 +723,15 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
}
}
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Model> definitions, Swagger swagger) {
CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger);
op.path = sanitizePath(op.path);
return op;
}
private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) {
// This generator uses inline classes to define enums, which breaks when
// dealing with models that have subTypes. To clean this up, we will analyze
@ -811,6 +821,11 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
this.serializableModel = serializableModel;
}
private String sanitizePath(String p) {
//prefer replace a ", instead of a fuLL URL encode for readability
return p.replaceAll("\"", "%22");
}
public void setFullJavaUtil(boolean fullJavaUtil) {
this.fullJavaUtil = fullJavaUtil;
}
@ -818,4 +833,16 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
public void setDateLibrary(String library) {
this.dateLibrary = library;
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
}

View File

@ -311,4 +311,15 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
public Boolean getSupportsES6() {
return supportsES6;
}
@Override
public String escapeQuotationMark(String input) {
// remove ', " to avoid code injection
return input.replace("\"", "").replace("'", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
}

View File

@ -414,4 +414,14 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon
}
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
}

View File

@ -504,4 +504,15 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
this.sourceFolder = sourceFolder;
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
}

View File

@ -84,14 +84,22 @@ public class AspNet5ServerCodegen extends AbstractCSharpCodegen {
apiPackage = packageName + ".Controllers";
modelPackage = packageName + ".Models";
supportingFiles.add(new SupportingFile("NuGet.Config", "", "NuGet.Config"));
supportingFiles.add(new SupportingFile("global.json", "", "global.json"));
supportingFiles.add(new SupportingFile("build.mustache", "", "build.sh"));
supportingFiles.add(new SupportingFile("build.sh.mustache", "", "build.sh"));
supportingFiles.add(new SupportingFile("build.bat.mustache", "", "build.bat"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("Solution.mustache", "", this.packageName + ".sln"));
supportingFiles.add(new SupportingFile("Dockerfile.mustache", this.sourceFolder, "Dockerfile"));
supportingFiles.add(new SupportingFile("gitignore", this.sourceFolder, ".gitignore"));
supportingFiles.add(new SupportingFile("appsettings.json", this.sourceFolder, "appsettings.json"));
supportingFiles.add(new SupportingFile("project.mustache", this.sourceFolder, "project.json"));
supportingFiles.add(new SupportingFile("project.json.mustache", this.sourceFolder, "project.json"));
supportingFiles.add(new SupportingFile("Startup.mustache", this.sourceFolder, "Startup.cs"));
supportingFiles.add(new SupportingFile("Program.mustache", this.sourceFolder, "Program.cs"));
supportingFiles.add(new SupportingFile("web.config", this.sourceFolder, "web.config"));
supportingFiles.add(new SupportingFile("Project.xproj.mustache", this.sourceFolder, this.packageName + ".xproj"));
supportingFiles.add(new SupportingFile("Properties" + File.separator + "launchSettings.json", this.sourceFolder + File.separator + "Properties", "launchSettings.json"));

View File

@ -39,11 +39,6 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
private static final String DATA_TYPE_WITH_ENUM_EXTENSION = "plainDatatypeWithEnum";
protected String packageGuid = "{" + java.util.UUID.randomUUID().toString().toUpperCase() + "}";
protected String packageTitle = "Swagger Library";
protected String packageProductName = "SwaggerLibrary";
protected String packageDescription = "A library generated from a Swagger doc";
protected String packageCompany = "Swagger";
protected String packageCopyright = "No Copyright";
protected String clientPackage = "IO.Swagger.Client";
protected String localVariablePrefix = "";
protected String apiDocPath = "docs/";
@ -149,12 +144,6 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
additionalProperties.put("clientPackage", clientPackage);
// Add properties used by AssemblyInfo.mustache
additionalProperties.put("packageTitle", packageTitle);
additionalProperties.put("packageProductName", packageProductName);
additionalProperties.put("packageDescription", packageDescription);
additionalProperties.put("packageCompany", packageCompany);
additionalProperties.put("packageCopyright", packageCopyright);
additionalProperties.put("emitDefaultValue", optionalEmitDefaultValue);
if (additionalProperties.containsKey(CodegenConstants.DOTNET_FRAMEWORK)) {

View File

@ -212,4 +212,16 @@ public class ClojureClientCodegen extends DefaultCodegen implements CodegenConfi
protected String namespaceToFolder(String ns) {
return ns.replace(".", File.separator).replace("-", "_");
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
// ref: https://clojurebridge.github.io/community-docs/docs/clojure/comment/
return input.replace("(comment", "(_comment");
}
}

View File

@ -377,4 +377,16 @@ public class CppRestClientCodegen extends DefaultCodegen implements CodegenConfi
public String toApiName(String type) {
return Character.toUpperCase(type.charAt(0)) + type.substring(1) + "Api";
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
}

View File

@ -274,4 +274,15 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege
return camelize(operationId);
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
}

View File

@ -289,4 +289,16 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
public void setSourceFolder(String sourceFolder) {
this.sourceFolder = sourceFolder;
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
}

View File

@ -373,4 +373,15 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig
public void setSourceFolder(String sourceFolder) {
this.sourceFolder = sourceFolder;
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
}

View File

@ -336,4 +336,16 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
// addPet => add_pet
return underscore(operationId);
}
@Override
public String escapeQuotationMark(String input) {
// remove ' to avoid code injection
return input.replace("'", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
// remove multiline comment
return input.replace("'''", "'_'_'");
}
}

View File

@ -452,4 +452,15 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
public void setPackageVersion(String packageVersion) {
this.packageVersion = packageVersion;
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
}

View File

@ -263,4 +263,16 @@ public class GoServerCodegen extends DefaultCodegen implements CodegenConfig {
// e.g. PetApi.go => pet_api.go
return underscore(name);
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
}

View File

@ -83,4 +83,14 @@ public class GroovyClientCodegen extends AbstractJavaCodegen {
this.configPackage = configPackage;
}
@Override
public String escapeQuotationMark(String input) {
// remove ' to avoid code injection
return input.replace("'", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
}

View File

@ -491,4 +491,16 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
p.dataType = fixModelChars(p.dataType);
return p;
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("{-", "{_-").replace("-}", "-_}");
}
}

View File

@ -183,4 +183,16 @@ public class JMeterCodegen extends DefaultCodegen implements CodegenConfig {
type = swaggerType;
return toModelName(type);
}
@Override
public String escapeQuotationMark(String input) {
// remove ' to avoid code injection
return input.replace("'", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
}

View File

@ -32,18 +32,19 @@ public class JavaClientCodegen extends AbstractJavaCodegen {
cliOptions.add(CliOption.newBoolean(USE_RX_JAVA, "Whether to use the RxJava adapter with the retrofit2 library."));
supportedLibraries.put(DEFAULT_LIBRARY, "HTTP client: Jersey client 1.19.1. JSON processing: Jackson 2.7.0");
supportedLibraries.put("jersey1", "HTTP client: Jersey client 1.19.1. JSON processing: Jackson 2.7.0");
supportedLibraries.put("feign", "HTTP client: Netflix Feign 8.16.0. JSON processing: Jackson 2.7.0");
supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.22.2. JSON processing: Jackson 2.7.0");
supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.6.2");
supportedLibraries.put(RETROFIT_1, "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)");
supportedLibraries.put(RETROFIT_1, "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.3.1 (Retrofit 1.9.0). IMPORTANT NOTE: retrofit1.x is no longer actively maintained so please upgrade to 'retrofit2' instead.");
supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 3.2.0. JSON processing: Gson 2.6.1 (Retrofit 2.0.2). Enable the RxJava adapter using '-DuseRxJava=true'. (RxJava 1.1.3)");
CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use");
library.setDefault(DEFAULT_LIBRARY);
library.setEnum(supportedLibraries);
library.setDefault(DEFAULT_LIBRARY);
cliOptions.add(library);
CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use");
libraryOption.setEnum(supportedLibraries);
libraryOption.setDefault("okhttp-gson");
cliOptions.add(libraryOption);
setLibrary("okhttp-gson");
}
@ -77,6 +78,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen {
writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml"));
writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md"));
writeOptional(outputFolder, new SupportingFile("build.gradle.mustache", "", "build.gradle"));
writeOptional(outputFolder, new SupportingFile("build.sbt.mustache", "", "build.sbt"));
writeOptional(outputFolder, new SupportingFile("settings.gradle.mustache", "", "settings.gradle"));
writeOptional(outputFolder, new SupportingFile("gradle.properties.mustache", "", "gradle.properties"));
writeOptional(outputFolder, new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml"));
@ -96,11 +98,6 @@ public class JavaClientCodegen extends AbstractJavaCodegen {
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
if (!StringUtils.isEmpty(getLibrary())) {
//TODO: add sbt support to default client
supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt"));
}
//TODO: add doc to retrofit1 and feign
if ( "feign".equals(getLibrary()) || "retrofit".equals(getLibrary()) ){
modelDocTemplateFiles.remove("model_doc.mustache");
@ -116,18 +113,26 @@ public class JavaClientCodegen extends AbstractJavaCodegen {
if ("feign".equals(getLibrary())) {
supportingFiles.add(new SupportingFile("FormAwareEncoder.mustache", invokerFolder, "FormAwareEncoder.java"));
} else if ("okhttp-gson".equals(getLibrary())) {
additionalProperties.put("jackson", "true");
} else if ("okhttp-gson".equals(getLibrary()) || StringUtils.isEmpty(getLibrary())) {
// the "okhttp-gson" library template requires "ApiCallback.mustache" for async call
supportingFiles.add(new SupportingFile("ApiCallback.mustache", invokerFolder, "ApiCallback.java"));
supportingFiles.add(new SupportingFile("ApiResponse.mustache", invokerFolder, "ApiResponse.java"));
supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java"));
supportingFiles.add(new SupportingFile("ProgressRequestBody.mustache", invokerFolder, "ProgressRequestBody.java"));
supportingFiles.add(new SupportingFile("ProgressResponseBody.mustache", invokerFolder, "ProgressResponseBody.java"));
additionalProperties.put("gson", "true");
} else if (usesAnyRetrofitLibrary()) {
supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java"));
supportingFiles.add(new SupportingFile("CollectionFormats.mustache", invokerFolder, "CollectionFormats.java"));
additionalProperties.put("gson", "true");
} else if("jersey2".equals(getLibrary())) {
supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java"));
additionalProperties.put("jackson", "true");
} else if("jersey1".equals(getLibrary())) {
additionalProperties.put("jackson", "true");
} else {
LOGGER.error("Unknown library option (-l/--library): " + getLibrary());
}
}
@ -170,14 +175,13 @@ public class JavaClientCodegen extends AbstractJavaCodegen {
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
super.postProcessModelProperty(model, property);
if(!BooleanUtils.toBoolean(model.isEnum)) {
final String lib = getLibrary();
//final String lib = getLibrary();
//Needed imports for Jackson based libraries
if(StringUtils.isEmpty(lib) || "feign".equals(lib) || "jersey2".equals(lib)) {
if(additionalProperties.containsKey("jackson")) {
model.imports.add("JsonProperty");
if(BooleanUtils.toBoolean(model.hasEnums)) {
model.imports.add("JsonValue");
}
}
if(additionalProperties.containsKey("gson")) {
model.imports.add("SerializedName");
}
}
}
@ -185,9 +189,8 @@ public class JavaClientCodegen extends AbstractJavaCodegen {
@Override
public Map<String, Object> postProcessModelsEnum(Map<String, Object> objs) {
objs = super.postProcessModelsEnum(objs);
String lib = getLibrary();
//Needed imports for Jackson based libraries
if (StringUtils.isEmpty(lib) || "feign".equals(lib) || "jersey2".equals(lib)) {
//Needed import for Gson based libraries
if (additionalProperties.containsKey("gson")) {
List<Map<String, String>> imports = (List<Map<String, String>>)objs.get("imports");
List<Object> models = (List<Object>) objs.get("models");
for (Object _mo : models) {
@ -195,9 +198,9 @@ public class JavaClientCodegen extends AbstractJavaCodegen {
CodegenModel cm = (CodegenModel) mo.get("model");
// for enum model
if (Boolean.TRUE.equals(cm.isEnum) && cm.allowableValues != null) {
cm.imports.add(importMapping.get("JsonValue"));
cm.imports.add(importMapping.get("SerializedName"));
Map<String, String> item = new HashMap<String, String>();
item.put("import", importMapping.get("JsonValue"));
item.put("import", importMapping.get("SerializedName"));
imports.add(item);
}
}
@ -208,4 +211,5 @@ public class JavaClientCodegen extends AbstractJavaCodegen {
public void setUseRxJava(boolean useRxJava) {
this.useRxJava = useRxJava;
}
}

View File

@ -0,0 +1,145 @@
package io.swagger.codegen.languages;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Operation;
import io.swagger.models.Swagger;
import io.swagger.util.Json;
import org.apache.commons.io.FileUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen
{
public JavaJAXRSSpecServerCodegen()
{
super();
supportsInheritance = true;
sourceFolder = "src/main/java";
invokerPackage = "io.swagger.api";
artifactId = "swagger-jaxrs-server";
outputFolder = "generated-code/JavaJaxRS-Spec";
modelTemplateFiles.put("model.mustache", ".java");
apiTemplateFiles.put("api.mustache", ".java");
apiPackage = "io.swagger.api";
modelPackage = "io.swagger.model";
additionalProperties.put("title", title);
typeMapping.put("date", "LocalDate");
typeMapping.put("DateTime", "javax.xml.datatype.XMLGregorianCalendar"); // Map DateTime fields to Java standart class 'XMLGregorianCalendar'
importMapping.put("LocalDate", "org.joda.time.LocalDate");
super.embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "spec";
for ( int i = 0; i < cliOptions.size(); i++ ) {
if ( CodegenConstants.LIBRARY.equals(cliOptions.get(i).getOpt()) ) {
cliOptions.remove(i);
break;
}
}
CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use");
library.setDefault(DEFAULT_LIBRARY);
Map<String, String> supportedLibraries = new LinkedHashMap<String,String>();
supportedLibraries.put(DEFAULT_LIBRARY, "JAXRS");
library.setEnum(supportedLibraries);
cliOptions.add(library);
cliOptions.add(new CliOption(CodegenConstants.IMPL_FOLDER, CodegenConstants.IMPL_FOLDER_DESC));
cliOptions.add(new CliOption("title", "a title describing the application"));
}
@Override
public void processOpts()
{
super.processOpts();
supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen
writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml"));
writeOptional(outputFolder, new SupportingFile("RestApplication.mustache",
(sourceFolder + '/' + invokerPackage).replace(".", "/"), "RestApplication.java"));
}
@Override
public String getName()
{
return "jaxrs-spec";
}
@Override
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
String basePath = resourcePath;
if (basePath.startsWith("/")) {
basePath = basePath.substring(1);
}
int pos = basePath.indexOf("/");
if (pos > 0) {
basePath = basePath.substring(0, pos);
}
if (basePath == "") {
basePath = "default";
} else {
if (co.path.startsWith("/" + basePath)) {
co.path = co.path.substring(("/" + basePath).length());
}
co.subresourceOperation = !co.path.isEmpty();
}
List<CodegenOperation> opList = operations.get(basePath);
if (opList == null) {
opList = new ArrayList<CodegenOperation>();
operations.put(basePath, opList);
}
opList.add(co);
co.baseName = basePath;
}
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
super.postProcessModelProperty(model, property);
model.imports.remove("ApiModelProperty");
model.imports.remove("ApiModel");
model.imports.remove("JsonSerialize");
model.imports.remove("ToStringSerializer");
model.imports.remove("JsonValue");
model.imports.remove("JsonProperty");
}
@Override
public void preprocessSwagger(Swagger swagger) {
//copy input swagger to output folder
try {
String swaggerJson = Json.pretty(swagger);
FileUtils.writeStringToFile(new File(outputFolder + File.separator + "swagger.json"), swaggerJson);
} catch (JsonProcessingException e) {
throw new RuntimeException(e.getMessage(), e.getCause());
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e.getCause());
}
super.preprocessSwagger(swagger);
}
@Override
public String getHelp()
{
return "Generates a Java JAXRS Server according to JAXRS 2.0 specification.";
}
}

View File

@ -240,21 +240,21 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
Info info = swagger.getInfo();
if (StringUtils.isBlank(projectName) && info.getTitle() != null) {
// when projectName is not specified, generate it from info.title
projectName = dashize(info.getTitle());
projectName = sanitizeName(dashize(info.getTitle()));
}
if (StringUtils.isBlank(projectVersion)) {
// when projectVersion is not specified, use info.version
projectVersion = info.getVersion();
projectVersion = escapeUnsafeCharacters(escapeQuotationMark(info.getVersion()));
}
if (projectDescription == null) {
// when projectDescription is not specified, use info.description
projectDescription = info.getDescription();
projectDescription = sanitizeName(info.getDescription());
}
if (additionalProperties.get(PROJECT_LICENSE_NAME) == null) {
// when projectLicense is not specified, use info.license
if (info.getLicense() != null) {
License license = info.getLicense();
additionalProperties.put(PROJECT_LICENSE_NAME, license.getName());
additionalProperties.put(PROJECT_LICENSE_NAME, sanitizeName(license.getName()));
}
}
}
@ -684,6 +684,9 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
op.returnType = normalizeType(op.returnType);
}
//path is an unescaped variable in the mustache template api.mustache line 82 '<&path>'
op.path = sanitizePath(op.path);
// Set vendor-extension to be used in template:
// x-codegen-hasMoreRequired
// x-codegen-hasMoreOptional
@ -738,6 +741,11 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
return codegenModel;
}
private String sanitizePath(String p) {
//prefer replace a ', instead of a fuLL URL encode for readability
return p.replaceAll("'", "%27");
}
private String trimBrackets(String s) {
if (s != null) {
int beginIdx = s.charAt(0) == '[' ? 1 : 0;
@ -874,8 +882,8 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
// Collect each model's required property names in *document order*.
// NOTE: can't use 'mandatory' as it is built from ModelImpl.getRequired(), which sorts names
// alphabetically and in any case the document order of 'required' and 'properties' can differ.
List<String> required = new ArrayList<String>();
List<String> allRequired = supportsInheritance ? new ArrayList<String>() : required;
List<CodegenProperty> required = new ArrayList<>();
List<CodegenProperty> allRequired = supportsInheritance ? new ArrayList<CodegenProperty>() : required;
cm.vendorExtensions.put("x-required", required);
cm.vendorExtensions.put("x-all-required", allRequired);
@ -885,14 +893,14 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
var.vendorExtensions.put("x-jsdoc-type", jsDocType);
if (Boolean.TRUE.equals(var.required)) {
required.add(var.name);
required.add(var);
}
}
if (supportsInheritance) {
for (CodegenProperty var : cm.allVars) {
if (Boolean.TRUE.equals(var.required)) {
allRequired.add(var.name);
allRequired.add(var);
}
}
}
@ -1024,4 +1032,16 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
}
}
@Override
public String escapeQuotationMark(String input) {
// remove ', " to avoid code injection
return input.replace("\"", "").replace("'", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
}

View File

@ -104,6 +104,9 @@ public class JavascriptClosureAngularClientCodegen extends DefaultCodegen implem
@Override
public String toVarName(String name) {
// sanitize name
name = sanitizeName(name);
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_");
@ -224,4 +227,34 @@ public class JavascriptClosureAngularClientCodegen extends DefaultCodegen implem
return objs;
}
@Override
public String toOperationId(String operationId) {
// throw exception if method name is empty
if (StringUtils.isEmpty(operationId)) {
throw new RuntimeException("Empty method/operation name (operationId) not allowed");
}
operationId = camelize(sanitizeName(operationId), true);
// method name cannot use reserved keyword, e.g. return
if (isReservedWord(operationId)) {
String newOperationId = camelize("call_" + operationId, true);
LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId);
return newOperationId;
}
return operationId;
}
@Override
public String escapeQuotationMark(String input) {
// remove ', " to avoid code injection
return input.replace("\"", "").replace("'", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
}

View File

@ -5,23 +5,16 @@ import io.swagger.models.properties.*;
import java.util.*;
import java.io.File;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class LumenServerCodegen extends DefaultCodegen implements CodegenConfig {
// source folder where to write the files
protected String sourceFolder = "";
public static final String SRC_BASE_PATH = "srcBasePath";
public static final String COMPOSER_VENDOR_NAME = "composerVendorName";
public static final String COMPOSER_PROJECT_NAME = "composerProjectName";
protected String invokerPackage = "Swagger\\Client";
protected String composerVendorName = null;
protected String composerProjectName = null;
protected String packagePath = "SwaggerClient-php";
protected String artifactVersion = null;
protected String srcBasePath = "lib";
protected String apiVersion = "1.0.0";
protected String apiDirName = "Api";
/**
* Configures the type of generator.
@ -95,12 +88,12 @@ public class LumenServerCodegen extends DefaultCodegen implements CodegenConfig
/**
* Api Package. Optional, if needed, this can be used in templates
*/
apiPackage = "io.swagger.client.api";
apiPackage = "app.Http.Controllers";
/**
* Model Package. Optional, if needed, this can be used in templates
*/
modelPackage = "io.swagger.client.model";
modelPackage = "models";
/**
* Reserved words. Override this with reserved words specific to your language
@ -161,7 +154,7 @@ public class LumenServerCodegen extends DefaultCodegen implements CodegenConfig
* instantiated
*/
public String modelFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar);
return outputFolder + "/" + modelPackage().replace('.', File.separatorChar);
}
/**
@ -170,10 +163,28 @@ public class LumenServerCodegen extends DefaultCodegen implements CodegenConfig
*/
@Override
public String apiFileFolder() {
return outputFolder + "/app/Http/controllers";
// return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar);
return outputFolder + "/" + apiPackage().replace('.', File.separatorChar);//"/app/Http/controllers";
}
// override with any special post-processing
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
@SuppressWarnings("unchecked")
Map<String, Object> objectMap = (Map<String, Object>) objs.get("operations");
@SuppressWarnings("unchecked")
List<CodegenOperation> operations = (List<CodegenOperation>) objectMap.get("operation");
// sort the endpoints in ascending to avoid the route priority issure.
// https://github.com/swagger-api/swagger-codegen/issues/2643
Collections.sort(operations, new Comparator<CodegenOperation>() {
@Override
public int compare(CodegenOperation lhs, CodegenOperation rhs) {
return lhs.path.compareTo(rhs.path);
}
});
return objs;
}
/**
* Optional - type declaration. This is a String which is used by the templates to instantiate your
* types. There is typically special handling for different property types
@ -215,4 +226,16 @@ public class LumenServerCodegen extends DefaultCodegen implements CodegenConfig
type = swaggerType;
return toModelName(type);
}
@Override
public String escapeQuotationMark(String input) {
// remove ' to avoid code injection
return input.replace("'", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
}

View File

@ -0,0 +1,404 @@
package io.swagger.codegen.languages;
import static com.google.common.base.Strings.isNullOrEmpty;
import static io.swagger.codegen.CodegenConstants.OPTIONAL_PROJECT_FILE;
import static io.swagger.codegen.CodegenConstants.OPTIONAL_PROJECT_FILE_DESC;
import static io.swagger.codegen.CodegenConstants.PACKAGE_NAME;
import static io.swagger.codegen.CodegenConstants.PACKAGE_VERSION;
import static io.swagger.codegen.CodegenConstants.RETURN_ICOLLECTION;
import static io.swagger.codegen.CodegenConstants.RETURN_ICOLLECTION_DESC;
import static io.swagger.codegen.CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG;
import static io.swagger.codegen.CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC;
import static io.swagger.codegen.CodegenConstants.SOURCE_FOLDER;
import static io.swagger.codegen.CodegenConstants.SOURCE_FOLDER_DESC;
import static io.swagger.codegen.CodegenConstants.USE_COLLECTION;
import static io.swagger.codegen.CodegenConstants.USE_COLLECTION_DESC;
import static io.swagger.codegen.CodegenConstants.USE_DATETIME_OFFSET;
import static io.swagger.codegen.CodegenConstants.USE_DATETIME_OFFSET_DESC;
import static io.swagger.codegen.CodegenType.SERVER;
import static java.util.Arrays.asList;
import static java.util.UUID.randomUUID;
import static org.apache.commons.lang3.StringUtils.capitalize;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Swagger;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.StringProperty;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Predicate;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multimap;
public class NancyFXServerCodegen extends AbstractCSharpCodegen {
private static final Logger log = LoggerFactory.getLogger(NancyFXServerCodegen.class);
private static final String API_NAMESPACE = "Modules";
private static final String MODEL_NAMESPACE = "Models";
private static final String IMMUTABLE_OPTION = "immutable";
private static final Map<String, Predicate<Property>> propertyToSwaggerTypeMapping =
createPropertyToSwaggerTypeMapping();
private final String packageGuid = "{" + randomUUID().toString().toUpperCase() + "}";
private final Map<String, DependencyInfo> dependencies = new HashMap<>();
private final Set<String> parentModels = new HashSet<>();
private final Multimap<String, CodegenModel> childrenByParent = ArrayListMultimap.create();
private final BiMap<String, String> modelNameMapping = HashBiMap.create();
public NancyFXServerCodegen() {
outputFolder = "generated-code" + File.separator + getName();
apiTemplateFiles.put("api.mustache", ".cs");
// contextually reserved words
setReservedWordsLowerCase(
asList("var", "async", "await", "dynamic", "yield")
);
cliOptions.clear();
// CLI options
addOption(PACKAGE_NAME, "C# package name (convention: Title.Case).", packageName);
addOption(PACKAGE_VERSION, "C# package version.", packageVersion);
addOption(SOURCE_FOLDER, SOURCE_FOLDER_DESC, sourceFolder);
// CLI Switches
addSwitch(SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_BY_REQUIRED_FLAG_DESC, sortParamsByRequiredFlag);
addSwitch(OPTIONAL_PROJECT_FILE, OPTIONAL_PROJECT_FILE_DESC, optionalProjectFileFlag);
addSwitch(USE_DATETIME_OFFSET, USE_DATETIME_OFFSET_DESC, useDateTimeOffsetFlag);
addSwitch(USE_COLLECTION, USE_COLLECTION_DESC, useCollection);
addSwitch(RETURN_ICOLLECTION, RETURN_ICOLLECTION_DESC, returnICollection);
addSwitch(IMMUTABLE_OPTION, "Enabled by default. If disabled generates model classes with setters", true);
typeMapping.putAll(nodaTimeTypesMappings());
languageSpecificPrimitives.addAll(nodaTimePrimitiveTypes());
importMapping.clear();
}
@Override
public CodegenType getTag() {
return SERVER;
}
@Override
public String getName() {
return "nancyfx";
}
@Override
public String getHelp() {
return "Generates a NancyFX Web API server.";
}
@Override
public void processOpts() {
super.processOpts();
apiPackage = isNullOrEmpty(packageName) ? API_NAMESPACE : packageName + "." + API_NAMESPACE;
modelPackage = isNullOrEmpty(packageName) ? MODEL_NAMESPACE : packageName + "." + MODEL_NAMESPACE;
supportingFiles.add(new SupportingFile("parameters.mustache", sourceFile("Utils"), "Parameters.cs"));
supportingFiles.add(new SupportingFile("packages.config.mustache", sourceFolder(), "packages.config"));
supportingFiles.add(new SupportingFile("nuspec.mustache", sourceFolder(), packageName + ".nuspec"));
if (optionalProjectFileFlag) {
supportingFiles.add(new SupportingFile("Solution.mustache", "", packageName + ".sln"));
supportingFiles.add(new SupportingFile("Project.mustache", sourceFolder(), packageName + ".csproj"));
}
additionalProperties.put("packageGuid", packageGuid);
setupModelTemplate();
processImportedMappings();
appendDependencies();
}
private void setupModelTemplate() {
final Object immutableOption = additionalProperties.get(IMMUTABLE_OPTION);
if (immutableOption != null && "false".equalsIgnoreCase(immutableOption.toString())) {
log.info("Using mutable model template");
modelTemplateFiles.put("modelMutable.mustache", ".cs");
} else {
log.info("Using immutable model template");
modelTemplateFiles.put("model.mustache", ".cs");
}
}
private void processImportedMappings() {
for (final Entry<String, String> entry : ImmutableSet.copyOf(importMapping.entrySet())) {
final String model = entry.getKey();
final String[] namespaceInfo = entry.getValue().split("\\s");
final String[] namespace = (namespaceInfo.length > 0 ? namespaceInfo[0].trim() : "").split(":");
final String namespaceName = namespace.length > 0 ? namespace[0].trim() : null;
final String modelClass = namespace.length > 1 ? namespace[1].trim() : null;
final String assembly = namespaceInfo.length > 1 ? namespaceInfo[1].trim() : null;
final String assemblyVersion = namespaceInfo.length > 2 ? namespaceInfo[2].trim() : null;
final String assemblyFramework = namespaceInfo.length > 3 ? namespaceInfo[3].trim() : "net45";
if (isNullOrEmpty(model) || isNullOrEmpty(namespaceName)) {
log.warn(String.format("Could not import: '%s' - invalid namespace: '%s'", model, entry.getValue()));
importMapping.remove(model);
} else {
log.info(String.format("Importing: '%s' from '%s' namespace.", model, namespaceName));
importMapping.put(model, namespaceName);
}
if (!isNullOrEmpty(modelClass)) {
log.info(String.format("Mapping: '%s' class to '%s'", model, modelClass));
modelNameMapping.put(model, modelClass);
}
if (assembly != null && assemblyVersion != null) {
log.info(String.format("Adding dependency: '%s', version: '%s', framework: '%s'",
assembly, assemblyVersion, assemblyVersion));
dependencies.put(assembly, new DependencyInfo(assemblyVersion, assemblyFramework));
}
}
}
private void appendDependencies() {
final List<Map<String, String>> listOfDependencies = new ArrayList<>();
for (final Entry<String, DependencyInfo> dependency : dependencies.entrySet()) {
final Map<String, String> dependencyInfo = new HashMap<>();
dependencyInfo.put("dependency", dependency.getKey());
dependencyInfo.put("dependencyVersion", dependency.getValue().version);
dependencyInfo.put("dependencyFramework", dependency.getValue().framework);
listOfDependencies.add(dependencyInfo);
}
additionalProperties.put("dependencies", listOfDependencies);
}
private String sourceFolder() {
return "src" + File.separator + packageName;
}
private String sourceFile(final String fileName) {
return sourceFolder() + File.separator + fileName;
}
@Override
public String apiFileFolder() {
return outputFolder + File.separator + sourceFolder() + File.separator + API_NAMESPACE;
}
@Override
public String modelFileFolder() {
return outputFolder + File.separator + sourceFolder() + File.separator + MODEL_NAMESPACE;
}
@Override
protected void processOperation(final CodegenOperation operation) {
super.processOperation(operation);
if (!isNullOrEmpty(operation.path) && operation.path.contains("?")) {
operation.path = operation.path.replace("?", "/");
}
if (!isNullOrEmpty(operation.httpMethod)) {
operation.httpMethod = capitalize(operation.httpMethod.toLowerCase());
}
}
@Override
public Map<String, Object> postProcessAllModels(final Map<String, Object> models) {
final Map<String, Object> processed = super.postProcessAllModels(models);
postProcessParentModels(models);
return processed;
}
private void postProcessParentModels(final Map<String, Object> models) {
log.info("Processing parents: " + parentModels);
for (final String parent : parentModels) {
final CodegenModel parentModel = modelByName(parent, models);
parentModel.hasChildren = true;
final Collection<CodegenModel> childrenModels = childrenByParent.get(parent);
for (final CodegenModel child : childrenModels) {
processParentPropertiesInChildModel(parentModel, child);
}
}
}
private CodegenModel modelByName(final String name, final Map<String, Object> models) {
final Object data = models.get(name);
if (data instanceof Map) {
final Map<?, ?> dataMap = (Map<?, ?>) data;
final Object dataModels = dataMap.get("models");
if (dataModels instanceof List) {
final List<?> dataModelsList = (List<?>) dataModels;
for (final Object entry : dataModelsList) {
if (entry instanceof Map) {
final Map<?, ?> entryMap = (Map<?, ?>) entry;
final Object model = entryMap.get("model");
if (model instanceof CodegenModel) {
return (CodegenModel) model;
}
}
}
}
}
return null;
}
private void processParentPropertiesInChildModel(final CodegenModel parent, final CodegenModel child) {
final Map<String, CodegenProperty> childPropertiesByName = new HashMap<>(child.vars.size());
for (final CodegenProperty property : child.vars) {
childPropertiesByName.put(property.name, property);
}
CodegenProperty previousParentVar = null;
for (final CodegenProperty property : parent.vars) {
final CodegenProperty duplicatedByParent = childPropertiesByName.get(property.name);
if (duplicatedByParent != null) {
log.info(String.format("Property: '%s' in '%s' model is inherited from '%s'" ,
property.name, child.classname, parent.classname));
duplicatedByParent.isInherited = true;
final CodegenProperty parentVar = duplicatedByParent.clone();
parentVar.hasMore = false;
child.parentVars.add(parentVar);
if (previousParentVar != null) {
previousParentVar.hasMore = true;
}
previousParentVar = parentVar;
}
}
}
@Override
public void postProcessModelProperty(final CodegenModel model, final CodegenProperty property) {
super.postProcessModelProperty(model, property);
if (!isNullOrEmpty(model.parent)) {
parentModels.add(model.parent);
if (!childrenByParent.containsEntry(model.parent, model)) {
childrenByParent.put(model.parent, model);
}
}
}
@Override
public String toEnumVarName(final String name, final String datatype) {
final String enumName = camelize(
sanitizeName(name)
.replaceFirst("^_", "")
.replaceFirst("_$", "")
.replaceAll("-", "_"));
final String result;
if (enumName.matches("\\d.*")) {
result = "_" + enumName;
} else {
result = enumName;
}
log.info(String.format("toEnumVarName('%s', %s) = '%s'", name, datatype, enumName));
return result;
}
@Override
public String toApiName(final String name) {
final String apiName;
if (isNullOrEmpty(name)) {
apiName = "Default";
} else {
apiName = capitalize(name);
}
log.info(String.format("toApiName('%s') = '%s'", name, apiName));
return apiName;
}
@Override
public String toApiFilename(final String name) {
return super.toApiFilename(name) + "Module";
}
@Override
public String toModelImport(final String name) {
final String result;
if (modelNameMapping.containsValue(name)) {
final String modelName = modelNameMapping.inverse().get(name);
result = importMapping.containsKey(modelName) ?
importMapping.get(modelName) : super.toModelImport(name);
} else if (importMapping.containsKey(name)) {
result = importMapping.get(name);
} else {
result = null;
}
log.info(String.format("toModelImport('%s') = '%s'", name, result));
return result;
}
@Override
public String toModelName(final String name) {
final String modelName = super.toModelName(name);
final String mappedModelName = modelNameMapping.get(modelName);
return isNullOrEmpty(mappedModelName) ? modelName: mappedModelName;
}
@Override
public void preprocessSwagger(final Swagger swagger) {
additionalProperties.put("packageContext", sanitizeName(swagger.getBasePath()));
additionalProperties.put("baseContext", swagger.getBasePath());
}
@Override
public String toEnumName(final CodegenProperty property) {
return sanitizeName(camelize(property.name)) + "Enum";
}
@Override
public String getSwaggerType(final Property property) {
for (Entry<String, Predicate<Property>> entry : propertyToSwaggerTypeMapping.entrySet()) {
if (entry.getValue().apply(property)) {
return entry.getKey();
}
}
return super.getSwaggerType(property);
}
private static Map<String, Predicate<Property>> createPropertyToSwaggerTypeMapping() {
final ImmutableMap.Builder<String, Predicate<Property>> mapping = ImmutableMap.builder();
mapping.put("time", timeProperty());
return mapping.build();
}
private static Predicate<Property> timeProperty() {
return new Predicate<Property>() {
@Override
public boolean apply(Property property) {
return property instanceof StringProperty && "time".equalsIgnoreCase(property.getFormat());
}
};
}
private static Map<String, String> nodaTimeTypesMappings() {
return ImmutableMap.of(
"time", "LocalTime?",
"date", "ZonedDateTime?",
"datetime", "ZonedDateTime?");
}
private static Set<String> nodaTimePrimitiveTypes() {
return ImmutableSet.of("LocalTime?", "ZonedDateTime?");
}
private class DependencyInfo {
private final String version;
private final String framework;
private DependencyInfo(final String version, final String framework) {
this.version = version;
this.framework = framework;
}
}
}

View File

@ -723,5 +723,15 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
p.example = example;
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
}

View File

@ -373,7 +373,8 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
return underscore("call_" + operationId);
}
return underscore(operationId);
//return underscore(operationId).replaceAll("[^A-Za-z0-9_]", "");
return underscore(sanitizeName(operationId));
}
public void setModuleName(String moduleName) {
@ -403,4 +404,15 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
}
}
@Override
public String escapeQuotationMark(String input) {
return input.replace("'", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
// remove =end, =cut to avoid code injection
return input.replace("=begin", "=_begin").replace("=end", "=_end").replace("=cut", "=_cut").replace("=pod", "=_pod");
}
}

View File

@ -658,8 +658,22 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation op : operationList) {
// for API test method name
// e.g. public function test{{vendorExtensions.x-testOperationId}}()
op.vendorExtensions.put("x-testOperationId", camelize(op.operationId));
}
return objs;
}
@Override
public String escapeQuotationMark(String input) {
// remove ' to avoid code injection
return input.replace("'", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
}

View File

@ -590,5 +590,16 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
p.example = example;
}
@Override
public String escapeQuotationMark(String input) {
// remove ' to avoid code injection
return input.replace("'", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
// remove multiline comment
return input.replace("'''", "'_'_'");
}
}

View File

@ -333,4 +333,15 @@ public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig {
public String toApiName(String type) {
return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1) + "Api";
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
}

View File

@ -317,4 +317,14 @@ public class Rails5ServerCodegen extends DefaultCodegen implements CodegenConfig
return super.postProcessSupportingFileData(objs);
}
@Override
public String escapeQuotationMark(String input) {
// remove ' to avoid code injection
return input.replace("'", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("=end", "=_end").replace("=begin", "=_begin");
}
}

View File

@ -712,4 +712,15 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
//
//return super.shouldOverwrite(filename) && !filename.endsWith("_spec.rb");
}
@Override
public String escapeQuotationMark(String input) {
// remove ' to avoid code injection
return input.replace("'", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("=end", "=_end").replace("=begin", "=_begin");
}
}

View File

@ -336,4 +336,15 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig
return toModelName(name);
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
}

View File

@ -196,4 +196,16 @@ public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConf
}
return toModelName(type);
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
}

View File

@ -200,4 +200,14 @@ public class SilexServerCodegen extends DefaultCodegen implements CodegenConfig
return toModelName(name);
}
@Override
public String escapeQuotationMark(String input) {
// remove ' to avoid code injection
return input.replace("'", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
}

View File

@ -243,4 +243,14 @@ public class SinatraServerCodegen extends DefaultCodegen implements CodegenConfi
return super.postProcessSupportingFileData(objs);
}
@Override
public String escapeQuotationMark(String input) {
// remove ' to avoid code injection
return input.replace("'", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("=end", "=_end").replace("=begin", "=_begin");
}
}

View File

@ -14,12 +14,17 @@ import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.regex.Matcher;
public class SlimFrameworkServerCodegen extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage;
protected String srcBasePath = "lib";
protected String groupId = "io.swagger";
protected String artifactId = "swagger-server";
protected String artifactVersion = "1.0.0";
protected String packagePath = ""; // empty packagePath (top folder)
private String variableNamingConvention = "camelCase";
public SlimFrameworkServerCodegen() {
@ -27,10 +32,10 @@ public class SlimFrameworkServerCodegen extends DefaultCodegen implements Codege
invokerPackage = camelize("SwaggerServer");
String packagePath = "SwaggerServer";
//String packagePath = "SwaggerServer";
modelPackage = packagePath + "\\lib\\Models";
apiPackage = packagePath + "\\lib";
modelPackage = packagePath + "\\Models";
apiPackage = packagePath;
outputFolder = "generated-code" + File.separator + "slim";
modelTemplateFiles.put("model.mustache", ".php");
@ -115,12 +120,12 @@ public class SlimFrameworkServerCodegen extends DefaultCodegen implements Codege
@Override
public String apiFileFolder() {
return (outputFolder + "/" + apiPackage()).replace('/', File.separatorChar);
return (outputFolder + "/" + toPackagePath(apiPackage, srcBasePath));
}
@Override
public String modelFileFolder() {
return (outputFolder + "/" + modelPackage()).replace('/', File.separatorChar);
return (outputFolder + "/" + toPackagePath(modelPackage, srcBasePath));
}
@Override
@ -225,4 +230,48 @@ public class SlimFrameworkServerCodegen extends DefaultCodegen implements Codege
return toModelName(name);
}
public String toPackagePath(String packageName, String basePath) {
packageName = packageName.replace(invokerPackage, ""); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
if (basePath != null && basePath.length() > 0) {
basePath = basePath.replaceAll("[\\\\/]?$", "") + File.separatorChar; // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
}
String regFirstPathSeparator;
if ("/".equals(File.separator)) { // for mac, linux
regFirstPathSeparator = "^/";
} else { // for windows
regFirstPathSeparator = "^\\\\";
}
String regLastPathSeparator;
if ("/".equals(File.separator)) { // for mac, linux
regLastPathSeparator = "/$";
} else { // for windows
regLastPathSeparator = "\\\\$";
}
return (getPackagePath() + File.separatorChar + basePath
// Replace period, backslash, forward slash with file separator in package name
+ packageName.replaceAll("[\\.\\\\/]", Matcher.quoteReplacement(File.separator))
// Trim prefix file separators from package path
.replaceAll(regFirstPathSeparator, ""))
// Trim trailing file separators from the overall path
.replaceAll(regLastPathSeparator+ "$", "");
}
public String getPackagePath() {
return packagePath;
}
@Override
public String escapeQuotationMark(String input) {
// remove ' to avoid code injection
return input.replace("'", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "");
}
}

View File

@ -9,14 +9,19 @@ import org.apache.commons.lang3.BooleanUtils;
import java.io.File;
import java.util.*;
public class SpringBootServerCodegen extends AbstractJavaCodegen {
public class SpringCodegen extends AbstractJavaCodegen {
public static final String DEFAULT_LIBRARY = "spring-boot";
public static final String TITLE = "title";
public static final String CONFIG_PACKAGE = "configPackage";
public static final String BASE_PACKAGE = "basePackage";
public static final String INTERFACE_ONLY = "interfaceOnly";
public static final String SINGLE_CONTENT_TYPES = "singleContentTypes";
public static final String JAVA_8 = "java8";
public static final String ASYNC = "async";
protected String title = "Petstore Server";
public static final String SPRING_MVC_LIBRARY = "spring-mvc";
public static final String SPRING_CLOUD_LIBRARY = "spring-cloud";
protected String title = "swagger-petstore";
protected String configPackage = "io.swagger.configuration";
protected String basePackage = "io.swagger";
protected boolean interfaceOnly = false;
@ -24,20 +29,20 @@ public class SpringBootServerCodegen extends AbstractJavaCodegen {
protected boolean java8 = false;
protected boolean async = false;
public SpringBootServerCodegen() {
public SpringCodegen() {
super();
outputFolder = "generated-code/javaSpringBoot";
outputFolder = "generated-code/javaSpring";
apiTestTemplateFiles.clear(); // TODO: add test template
embeddedTemplateDir = templateDir = "JavaSpringBoot";
embeddedTemplateDir = templateDir = "JavaSpring";
apiPackage = "io.swagger.api";
modelPackage = "io.swagger.model";
invokerPackage = "io.swagger.api";
artifactId = "swagger-springboot-server";
artifactId = "swagger-spring";
additionalProperties.put("title", title);
additionalProperties.put(CONFIG_PACKAGE, configPackage);
additionalProperties.put(BASE_PACKAGE, basePackage);
cliOptions.add(new CliOption(TITLE, "server title name or client service name"));
cliOptions.add(new CliOption(CONFIG_PACKAGE, "configuration package for generated code"));
cliOptions.add(new CliOption(BASE_PACKAGE, "base package for generated code"));
cliOptions.add(CliOption.newBoolean(INTERFACE_ONLY, "Whether to generate only API interface stubs without the server files."));
@ -45,17 +50,16 @@ public class SpringBootServerCodegen extends AbstractJavaCodegen {
cliOptions.add(CliOption.newBoolean(JAVA_8, "use java8 default interface"));
cliOptions.add(CliOption.newBoolean(ASYNC, "use async Callable controllers"));
supportedLibraries.put(DEFAULT_LIBRARY, "Default Spring Boot server stub.");
supportedLibraries.put("j8-async", "Use async servlet feature and Java 8's default interface. Generating interface with service " +
"declaration is useful when using Maven plugin. Just provide a implementation with @Controller to instantiate service." +
"(DEPRECATED: use -Djava8=true,async=true instead)");
supportedLibraries.put(DEFAULT_LIBRARY, "Spring-boot Server application using the SpringFox integration.");
supportedLibraries.put(SPRING_MVC_LIBRARY, "Spring-MVC Server application using the SpringFox integration.");
supportedLibraries.put(SPRING_CLOUD_LIBRARY, "Spring-Cloud-Feign client with Spring-Boot auto-configured settings.");
setLibrary(DEFAULT_LIBRARY);
CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use");
library.setDefault(DEFAULT_LIBRARY);
library.setEnum(supportedLibraries);
library.setDefault(DEFAULT_LIBRARY);
cliOptions.add(library);
}
@Override
@ -65,7 +69,7 @@ public class SpringBootServerCodegen extends AbstractJavaCodegen {
@Override
public String getName() {
return "springboot";
return "spring";
}
@Override
@ -83,6 +87,10 @@ public class SpringBootServerCodegen extends AbstractJavaCodegen {
modelDocTemplateFiles.remove("model_doc.mustache");
apiDocTemplateFiles.remove("api_doc.mustache");
if (additionalProperties.containsKey(TITLE)) {
this.setTitle((String) additionalProperties.get(TITLE));
}
if (additionalProperties.containsKey(CONFIG_PACKAGE)) {
this.setConfigPackage((String) additionalProperties.get(CONFIG_PACKAGE));
}
@ -111,28 +119,49 @@ public class SpringBootServerCodegen extends AbstractJavaCodegen {
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
if (!this.interfaceOnly) {
apiTemplateFiles.put("apiController.mustache", "Controller.java");
supportingFiles.add(new SupportingFile("apiException.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java"));
supportingFiles.add(new SupportingFile("apiOriginFilter.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiOriginFilter.java"));
supportingFiles.add(new SupportingFile("apiResponseMessage.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java"));
supportingFiles.add(new SupportingFile("notFoundException.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java"));
supportingFiles.add(new SupportingFile("swaggerDocumentationConfig.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerDocumentationConfig.java"));
supportingFiles.add(new SupportingFile("homeController.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "HomeController.java"));
supportingFiles.add(new SupportingFile("swagger2SpringBoot.mustache",
(sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator), "Swagger2SpringBoot.java"));
supportingFiles.add(new SupportingFile("application.properties",
("src.main.resources").replace(".", java.io.File.separator), "application.properties"));
}
if (library.equals(DEFAULT_LIBRARY)) {
supportingFiles.add(new SupportingFile("homeController.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "HomeController.java"));
supportingFiles.add(new SupportingFile("swagger2SpringBoot.mustache",
(sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator), "Swagger2SpringBoot.java"));
supportingFiles.add(new SupportingFile("application.mustache",
("src.main.resources").replace(".", java.io.File.separator), "application.properties"));
}
if (library.equals(SPRING_MVC_LIBRARY)) {
supportingFiles.add(new SupportingFile("webApplication.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "WebApplication.java"));
supportingFiles.add(new SupportingFile("webMvcConfiguration.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "WebMvcConfiguration.java"));
supportingFiles.add(new SupportingFile("swaggerUiConfiguration.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerUiConfiguration.java"));
supportingFiles.add(new SupportingFile("application.properties",
("src.main.resources").replace(".", java.io.File.separator), "swagger.properties"));
}
if (library.equals(SPRING_CLOUD_LIBRARY)) {
supportingFiles.add(new SupportingFile("apiKeyRequestInterceptor.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "ApiKeyRequestInterceptor.java"));
supportingFiles.add(new SupportingFile("clientConfiguration.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "ClientConfiguration.java"));
apiTemplateFiles.put("apiClient.mustache", "Client.java");
if (!additionalProperties.containsKey(SINGLE_CONTENT_TYPES)) {
additionalProperties.put(SINGLE_CONTENT_TYPES, "true");
this.setSingleContentTypes(true);
if ("j8-async".equals(getLibrary())) {
setJava8(true);
setAsync(true);
}
} else {
apiTemplateFiles.put("apiController.mustache", "Controller.java");
supportingFiles.add(new SupportingFile("apiException.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java"));
supportingFiles.add(new SupportingFile("apiResponseMessage.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java"));
supportingFiles.add(new SupportingFile("notFoundException.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java"));
supportingFiles.add(new SupportingFile("apiOriginFilter.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiOriginFilter.java"));
supportingFiles.add(new SupportingFile("swaggerDocumentationConfig.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerDocumentationConfig.java"));
}
}
if (this.java8) {
@ -176,6 +205,22 @@ public class SpringBootServerCodegen extends AbstractJavaCodegen {
swagger.setBasePath("");
}
if(!additionalProperties.containsKey(TITLE)) {
// From the title, compute a reasonable name for the package and the API
String title = swagger.getInfo().getTitle();
// Drop any API suffix
if (title != null) {
title = title.trim().replace(" ", "-");
if (title.toUpperCase().endsWith("API")) {
title = title.substring(0, title.length() - 3);
}
this.title = camelize(sanitizeName(title), true);
}
additionalProperties.put(TITLE, this.title);
}
String host = swagger.getHost();
String port = "8080";
if (host != null) {
@ -259,6 +304,19 @@ public class SpringBootServerCodegen extends AbstractJavaCodegen {
return objs;
}
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
if(library.equals(SPRING_CLOUD_LIBRARY)) {
List<CodegenSecurity> authMethods = (List<CodegenSecurity>) objs.get("authMethods");
if (authMethods != null) {
for (CodegenSecurity authMethod : authMethods) {
authMethod.name = camelize(sanitizeName(authMethod.name), true);
}
}
}
return objs;
}
@Override
public String toApiName(String name) {
if (name.length() == 0) {
@ -268,6 +326,10 @@ public class SpringBootServerCodegen extends AbstractJavaCodegen {
return camelize(name) + "Api";
}
public void setTitle(String title) {
this.title = title;
}
public void setConfigPackage(String configPackage) {
this.configPackage = configPackage;
}
@ -286,33 +348,14 @@ public class SpringBootServerCodegen extends AbstractJavaCodegen {
public void setAsync(boolean async) { this.async = async; }
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
// remove the import of "Object" to avoid compilation error
List<Map<String, String>> imports = (List<Map<String, String>>) objs.get("imports");
Iterator<Map<String, String>> iterator = imports.iterator();
while (iterator.hasNext()) {
String _import = iterator.next().get("import");
if (_import.endsWith(".Object")) iterator.remove();
}
List<Object> models = (List<Object>) objs.get("models");
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
for (CodegenProperty var : cm.vars) {
// handle default value for enum, e.g. available => StatusEnum.available
if (var.isEnum && var.defaultValue != null && !"null".equals(var.defaultValue)) {
var.defaultValue = var.datatypeWithEnum + "." + var.defaultValue;
}
}
}
return objs;
}
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
super.postProcessModelProperty(model, property);
if("null".equals(property.example)) {
property.example = null;
}
//Add imports for Jackson
if(!BooleanUtils.toBoolean(model.isEnum)) {
model.imports.add("JsonProperty");
@ -344,4 +387,5 @@ public class SpringBootServerCodegen extends AbstractJavaCodegen {
return objs;
}
}

View File

@ -1,269 +0,0 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Swagger;
import java.io.File;
import java.util.*;
public class SpringMVCServerCodegen extends JavaClientCodegen implements CodegenConfig{
public static final String CONFIG_PACKAGE = "configPackage";
protected String title = "Petstore Server";
protected String configPackage = "";
protected String templateFileName = "api.mustache";
public SpringMVCServerCodegen() {
super();
outputFolder = "generated-code/javaSpringMVC";
modelTemplateFiles.put("model.mustache", ".java");
apiTemplateFiles.put(templateFileName, ".java");
apiTestTemplateFiles.clear(); // TODO: add test template
embeddedTemplateDir = templateDir = "JavaSpringMVC";
apiPackage = "io.swagger.api";
modelPackage = "io.swagger.model";
configPackage = "io.swagger.configuration";
invokerPackage = "io.swagger.api";
artifactId = "swagger-spring-mvc-server";
dateLibrary = "legacy";
additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
additionalProperties.put(CodegenConstants.GROUP_ID, groupId);
additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId);
additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);
additionalProperties.put("title", title);
additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage);
additionalProperties.put(CONFIG_PACKAGE, configPackage);
cliOptions.add(new CliOption(CONFIG_PACKAGE, "configuration package for generated code"));
supportedLibraries.clear();
supportedLibraries.put(DEFAULT_LIBRARY, "Default Spring MVC server stub.");
supportedLibraries.put("j8-async", "Use async servlet feature and Java 8's default interface. Generating interface with service " +
"declaration is useful when using Maven plugin. Just provide a implementation with @Controller to instantiate service.");
}
@Override
public CodegenType getTag() {
return CodegenType.SERVER;
}
@Override
public String getName() {
return "spring-mvc";
}
@Override
public String getHelp() {
return "Generates a Java Spring-MVC Server application using the SpringFox integration.";
}
@Override
public void processOpts() {
super.processOpts();
// clear model and api doc template as this codegen
// does not support auto-generated markdown doc at the moment
modelDocTemplateFiles.remove("model_doc.mustache");
apiDocTemplateFiles.remove("api_doc.mustache");
if (additionalProperties.containsKey(CONFIG_PACKAGE)) {
this.setConfigPackage((String) additionalProperties.get(CONFIG_PACKAGE));
}
supportingFiles.clear();
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("apiException.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java"));
supportingFiles.add(new SupportingFile("apiOriginFilter.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiOriginFilter.java"));
supportingFiles.add(new SupportingFile("apiResponseMessage.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java"));
supportingFiles.add(new SupportingFile("notFoundException.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java"));
supportingFiles.add(new SupportingFile("swaggerConfig.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerConfig.java"));
supportingFiles.add(new SupportingFile("webApplication.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "WebApplication.java"));
supportingFiles.add(new SupportingFile("webMvcConfiguration.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "WebMvcConfiguration.java"));
supportingFiles.add(new SupportingFile("swaggerUiConfiguration.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerUiConfiguration.java"));
supportingFiles.add(new SupportingFile("swagger.properties",
("src.main.resources").replace(".", java.io.File.separator), "swagger.properties"));
}
@Override
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
String basePath = resourcePath;
if (basePath.startsWith("/")) {
basePath = basePath.substring(1);
}
int pos = basePath.indexOf("/");
if (pos > 0) {
basePath = basePath.substring(0, pos);
}
if (basePath == "") {
basePath = "default";
} else {
if (co.path.startsWith("/" + basePath)) {
co.path = co.path.substring(("/" + basePath).length());
}
co.subresourceOperation = !co.path.isEmpty();
}
List<CodegenOperation> opList = operations.get(basePath);
if (opList == null) {
opList = new ArrayList<CodegenOperation>();
operations.put(basePath, opList);
}
opList.add(co);
co.baseName = basePath;
}
@Override
public void preprocessSwagger(Swagger swagger) {
System.out.println("preprocessSwagger");
if ("/".equals(swagger.getBasePath())) {
swagger.setBasePath("");
}
String host = swagger.getHost();
String port = "8080";
if (host != null) {
String[] parts = host.split(":");
if (parts.length > 1) {
port = parts[1];
}
}
this.additionalProperties.put("serverPort", port);
if (swagger != null && swagger.getPaths() != null) {
for (String pathname : swagger.getPaths().keySet()) {
Path path = swagger.getPath(pathname);
if (path.getOperations() != null) {
for (Operation operation : path.getOperations()) {
if (operation.getTags() != null) {
List<Map<String, String>> tags = new ArrayList<Map<String, String>>();
for (String tag : operation.getTags()) {
Map<String, String> value = new HashMap<String, String>();
value.put("tag", tag);
value.put("hasMore", "true");
tags.add(value);
}
if (tags.size() > 0) {
tags.get(tags.size() - 1).remove("hasMore");
}
if (operation.getTags().size() > 0) {
String tag = operation.getTags().get(0);
operation.setTags(Arrays.asList(tag));
}
operation.setVendorExtension("x-tags", tags);
}
}
}
}
}
}
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
if (operations != null) {
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation operation : ops) {
List<CodegenResponse> responses = operation.responses;
if (responses != null) {
for (CodegenResponse resp : responses) {
if ("0".equals(resp.code)) {
resp.code = "200";
}
}
}
if (operation.returnType == null) {
operation.returnType = "Void";
} else if (operation.returnType.startsWith("List")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("List<".length(), end).trim();
operation.returnContainer = "List";
}
} else if (operation.returnType.startsWith("Map")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("Map<".length(), end).split(",")[1].trim();
operation.returnContainer = "Map";
}
} else if (operation.returnType.startsWith("Set")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("Set<".length(), end).trim();
operation.returnContainer = "Set";
}
}
}
}
if("j8-async".equals(getLibrary())) {
apiTemplateFiles.remove(this.templateFileName);
this.templateFileName = "api-j8-async.mustache";
apiTemplateFiles.put(this.templateFileName, ".java");
int originalPomFileIdx = -1;
for (int i = 0; i < supportingFiles.size(); i++) {
if ("pom.xml".equals(supportingFiles.get(i).destinationFilename)) {
originalPomFileIdx = i;
break;
}
}
if (originalPomFileIdx > -1) {
supportingFiles.remove(originalPomFileIdx);
}
supportingFiles.add(new SupportingFile("pom-j8-async.mustache", "", "pom.xml"));
}
return objs;
}
@Override
public String toApiName(String name) {
if (name.length() == 0) {
return "DefaultApi";
}
name = sanitizeName(name);
return camelize(name) + "Api";
}
public void setConfigPackage(String configPackage) {
this.configPackage = configPackage;
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
// remove the import of "Object" to avoid compilation error
List<Map<String, String>> imports = (List<Map<String, String>>) objs.get("imports");
Iterator<Map<String, String>> iterator = imports.iterator();
while (iterator.hasNext()) {
String _import = iterator.next().get("import");
if (_import.endsWith(".Object")) iterator.remove();
}
List<Object> models = (List<Object>) objs.get("models");
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
for (CodegenProperty var : cm.vars) {
// handle default value for enum, e.g. available => StatusEnum.available
if (var.isEnum && var.defaultValue != null && !"null".equals(var.defaultValue)) {
var.defaultValue = var.datatypeWithEnum + "." + var.defaultValue;
}
}
}
return objs;
}
}

View File

@ -325,9 +325,17 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public CodegenProperty fromProperty(String name, Property p) {
CodegenProperty codegenProperty = super.fromProperty(name, p);
// TODO skip array/map of enum for the time being,
// we need to add logic here to handle array/map of enum for any
// dimensions
if (Boolean.TRUE.equals(codegenProperty.isContainer)) {
return codegenProperty;
}
if (codegenProperty.isEnum) {
List<Map<String, String>> swiftEnums = new ArrayList<Map<String, String>>();
List<String> values = (List<String>) codegenProperty.allowableValues.get("values");
for (String value : values) {
Map<String, String> map = new HashMap<String, String>();
map.put("enum", toSwiftyEnumName(value));
@ -542,4 +550,15 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
return postProcessModelsEnum(objs);
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
}

View File

@ -281,4 +281,14 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
return camelize(operationId, true);
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
}

View File

@ -1,3 +1,4 @@
{{>licenseInfo}}
package {{invokerPackage}};
import com.fasterxml.jackson.annotation.*;

View File

@ -1,3 +1,4 @@
{{>licenseInfo}}
package {{package}};
import com.sun.jersey.api.client.GenericType;

View File

@ -1,20 +0,0 @@
/**
* {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}}
*/
public enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} {
{{#allowableValues}}{{#enumVars}}@SerializedName({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}})
{{{name}}}({{{value}}}){{^-last}},
{{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}}
private {{datatype}} value;
{{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}({{datatype}} value) {
this.value = value;
}
@Override
public String toString() {
return String.valueOf(value);
}
}

View File

@ -9,7 +9,12 @@ import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuil
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
{{^java8}}
import com.fasterxml.jackson.datatype.joda.JodaModule;
{{/java8}}
{{#java8}}
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
{{/java8}}
import feign.Feign;
import feign.RequestInterceptor;
@ -24,7 +29,7 @@ public class ApiClient {
public interface Api {}
protected ObjectMapper objectMapper;
private String basePath = "{{basePath}}";
private String basePath = "{{{basePath}}}";
private Map<String, RequestInterceptor> apiAuthorizations;
private Feign.Builder feignBuilder;
@ -131,7 +136,12 @@ public class ApiClient {
objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
{{^java8}}
objectMapper.registerModule(new JodaModule());
{{/java8}}
{{#java8}}
objectMapper.registerModule(new JavaTimeModule());
{{/java8}}
return objectMapper;
}

View File

@ -78,8 +78,8 @@ if(hasProperty('target') && target == 'android') {
apply plugin: 'java'
apply plugin: 'maven'
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
sourceCompatibility = JavaVersion.VERSION_{{^java8}}1_7{{/java8}}{{#java8}}1_8{{/java8}}
targetCompatibility = JavaVersion.VERSION_{{^java8}}1_7{{/java8}}{{#java8}}1_8{{/java8}}
install {
repositories.mavenInstaller {
@ -94,10 +94,9 @@ if(hasProperty('target') && target == 'android') {
}
ext {
swagger_annotations_version = "1.5.8"
jackson_version = "2.7.0"
feign_version = "8.16.0"
jodatime_version = "2.9.3"
swagger_annotations_version = "1.5.9"
jackson_version = "2.7.5"
feign_version = "8.17.0"
junit_version = "4.12"
oltu_version = "1.0.1"
}
@ -110,8 +109,7 @@ dependencies {
compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version"
compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:2.1.5"
compile "joda-time:joda-time:$jodatime_version"
compile "com.fasterxml.jackson.datatype:jackson-datatype-{{^java8}}joda{{/java8}}{{#java8}}jsr310{{/java8}}:$jackson_version"
compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version"
compile "com.brsanthu:migbase64:2.2"
testCompile "junit:junit:$junit_version"

View File

@ -9,15 +9,14 @@ lazy val root = (project in file(".")).
publishArtifact in (Compile, packageDoc) := false,
resolvers += Resolver.mavenLocal,
libraryDependencies ++= Seq(
"io.swagger" % "swagger-annotations" % "1.5.8" % "compile",
"io.swagger" % "swagger-annotations" % "1.5.9" % "compile",
"com.netflix.feign" % "feign-core" % "8.16.0" % "compile",
"com.netflix.feign" % "feign-jackson" % "8.16.0" % "compile",
"com.netflix.feign" % "feign-jackson" % "8.17.0" % "compile",
"com.netflix.feign" % "feign-slf4j" % "8.16.0" % "compile",
"com.fasterxml.jackson.core" % "jackson-core" % "2.7.0" % "compile",
"com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.0" % "compile",
"com.fasterxml.jackson.core" % "jackson-databind" % "2.7.0" % "compile",
"com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.1.5" % "compile",
"joda-time" % "joda-time" % "2.9.3" % "compile",
"com.fasterxml.jackson.core" % "jackson-core" % "2.7.5" % "compile",
"com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.5" % "compile",
"com.fasterxml.jackson.core" % "jackson-databind" % "2.7.5" % "compile",
"com.fasterxml.jackson.datatype" % "jackson-datatype-{{^java8}}joda{{/java8}}{{#java8}}jsr310{{/java8}}" % "2.7.5" % "compile",
"org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile",
"com.brsanthu" % "migbase64" % "2.2" % "compile",
"junit" % "junit" % "4.12" % "test",

View File

@ -95,15 +95,6 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
@ -148,10 +139,9 @@
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<artifactId>jackson-datatype-{{^java8}}joda{{/java8}}{{#java8}}jsr310{{/java8}}</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>org.apache.oltu.oauth2</groupId>
<artifactId>org.apache.oltu.oauth2.client</artifactId>
@ -167,10 +157,12 @@
</dependency>
</dependencies>
<properties>
<swagger-core-version>1.5.8</swagger-core-version>
<feign-version>8.16.0</feign-version>
<jackson-version>2.7.0</jackson-version>
<jodatime-version>2.9.3</jodatime-version>
<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>
<jackson-version>2.7.5</jackson-version>
<junit-version>4.12</junit-version>
<maven-plugin-version>1.0.0</maven-plugin-version>
<oltu-version>1.0.1</oltu-version>

View File

@ -51,7 +51,7 @@ import {{invokerPackage}}.auth.OAuth;
{{>generatedAnnotation}}
public class ApiClient {
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private String basePath = "{{basePath}}";
private String basePath = "{{{basePath}}}";
private boolean debugging = false;
private int connectionTimeout = 0;

View File

@ -101,7 +101,7 @@ public class ApiClient {
*/
public static final String LENIENT_DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
private String basePath = "{{basePath}}";
private String basePath = "{{{basePath}}}";
private boolean lenientOnJson = false;
private boolean debugging = false;
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
@ -169,7 +169,7 @@ public class ApiClient {
/**
* Set base path
*
* @param basePath Base path of the URL (e.g {{basePath}})
* @param basePath Base path of the URL (e.g {{{basePath}}}
* @return An instance of OkHttpClient
*/
public ApiClient setBasePath(String basePath) {
@ -790,6 +790,7 @@ public class ApiClient {
* @throws ApiException If fail to deserialize response body, i.e. cannot read response body
* or the Content-Type of the response is not supported.
*/
@SuppressWarnings("unchecked")
public <T> T deserialize(Response response, Type returnType) throws ApiException {
if (response == null || returnType == null) {
return null;
@ -984,6 +985,7 @@ public class ApiClient {
* @param returnType Return type
* @param callback ApiCallback
*/
@SuppressWarnings("unchecked")
public <T> void executeAsync(Call call, final Type returnType, final ApiCallback<T> callback) {
call.enqueue(new Callback() {
@Override

View File

@ -21,10 +21,17 @@ import java.io.StringReader;
import java.lang.reflect.Type;
import java.util.Date;
{{^java8}}
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
{{/java8}}
{{#java8}}
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
{{/java8}}
public class JSON {
private ApiClient apiClient;
@ -39,7 +46,12 @@ public class JSON {
this.apiClient = apiClient;
gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new DateAdapter(apiClient))
{{^java8}}
.registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter())
{{/java8}}
{{#java8}}
.registerTypeAdapter(OffsetDateTime.class, new OffsetDateTimeTypeAdapter())
{{/java8}}
.registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter())
.create();
}
@ -80,6 +92,7 @@ public class JSON {
* @param returnType The type to deserialize inot
* @return The deserialized Java object
*/
@SuppressWarnings("unchecked")
public <T> T deserialize(String body, Type returnType) {
try {
if (apiClient.isLenientOnJson()) {
@ -154,6 +167,7 @@ class DateAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
}
}
{{^java8}}
/**
* Gson TypeAdapter for Joda DateTime type
*/
@ -211,4 +225,67 @@ class LocalDateTypeAdapter extends TypeAdapter<LocalDate> {
}
}
}
{{/java8}}
{{#java8}}
/**
* Gson TypeAdapter for jsr310 OffsetDateTime type
*/
class OffsetDateTimeTypeAdapter extends TypeAdapter<OffsetDateTime> {
private final DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
@Override
public void write(JsonWriter out, OffsetDateTime date) throws IOException {
if (date == null) {
out.nullValue();
} else {
out.value(formatter.format(date));
}
}
@Override
public OffsetDateTime read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
if (date.endsWith("+0000")) {
date = date.substring(0, date.length()-5) + "Z";
}
return OffsetDateTime.parse(date, formatter);
}
}
}
/**
* Gson TypeAdapter for jsr310 LocalDate type
*/
class LocalDateTypeAdapter extends TypeAdapter<LocalDate> {
private final DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE;
@Override
public void write(JsonWriter out, LocalDate date) throws IOException {
if (date == null) {
out.nullValue();
} else {
out.value(formatter.format(date));
}
}
@Override
public LocalDate read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
return LocalDate.parse(date, formatter);
}
}
}
{{/java8}}

View File

@ -78,8 +78,8 @@ if(hasProperty('target') && target == 'android') {
apply plugin: 'java'
apply plugin: 'maven'
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
sourceCompatibility = JavaVersion.VERSION_{{^java8}}1_7{{/java8}}{{#java8}}1_8{{/java8}}
targetCompatibility = JavaVersion.VERSION_{{^java8}}1_7{{/java8}}{{#java8}}1_8{{/java8}}
install {
repositories.mavenInstaller {
@ -98,6 +98,8 @@ dependencies {
compile 'com.squareup.okhttp:okhttp:2.7.5'
compile 'com.squareup.okhttp:logging-interceptor:2.7.5'
compile 'com.google.code.gson:gson:2.6.2'
{{^java8}}
compile 'joda-time:joda-time:2.9.3'
{{/java8}}
testCompile 'junit:junit:4.12'
}

View File

@ -13,7 +13,9 @@ lazy val root = (project in file(".")).
"com.squareup.okhttp" % "okhttp" % "2.7.5",
"com.squareup.okhttp" % "logging-interceptor" % "2.7.5",
"com.google.code.gson" % "gson" % "2.6.2",
{{^java8}}
"joda-time" % "joda-time" % "2.9.3" % "compile",
{{/java8}}
"junit" % "junit" % "4.12" % "test",
"com.novocode" % "junit-interface" % "0.10" % "test"
)

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