Merge pull request #2 from swagger-api/master

Merge from swagger-api
This commit is contained in:
Yonas Kolb 2016-04-11 11:49:57 +10:00
commit 01c38f4a22
903 changed files with 55536 additions and 22130 deletions

116
.gitignore vendored
View File

@ -13,33 +13,6 @@ generated-sources/*
generated-code/* generated-code/*
*.swp *.swp
*.swo *.swo
*.csproj.user
/target
/generated-files
/nbactions.xml
*.pyc
__pycache__
samples/server-generator/scalatra/output
samples/server-generator/node/output/node_modules
samples/server-generator/scalatra/target
samples/server-generator/scalatra/output/.history
samples/client/petstore/qt5cpp/PetStore/moc_*
samples/client/petstore/qt5cpp/PetStore/*.o
samples/client/petstore/objc/PetstoreClient.xcworkspace/xcuserdata
samples/client/petstore/qt5cpp/build-*
samples/client/petstore/qt5cpp/PetStore/PetStore
samples/client/petstore/qt5cpp/PetStore/Makefile
samples/client/petstore/java/hello.txt
samples/client/petstore/android/default/hello.txt
samples/client/petstore/objc/SwaggerClientTests/Build
samples/client/petstore/objc/SwaggerClientTests/Pods
samples/client/petstore/objc/SwaggerClientTests/SwaggerClient.xcworkspace
samples/client/petstore/objc/SwaggerClientTests/Podfile.lock
samples/server/petstore/nodejs/node_modules
samples/client/petstore/csharp/SwaggerClientTest/.vs
samples/client/petstore/csharp/SwaggerClientTest/obj
samples/client/petstore/csharp/SwaggerClientTest/bin
target target
.idea .idea
.lib .lib
@ -50,24 +23,6 @@ packages/
.packages .packages
.vagrant/ .vagrant/
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/
samples/client/petstore/perl/deep_module_test/
samples/client/petstore/python/.projectile
samples/client/petstore/python/.venv/
samples/client/petstore/python/dev-requirements.txt.log
samples/client/petstore/objc/SwaggerClientTests/SwaggerClient.xcodeproj/xcuserdata
samples/client/petstore/swift/SwaggerClientTests/SwaggerClient.xcodeproj/xcuserdata
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
.settings .settings
*.mustache~ *.mustache~
@ -76,10 +31,79 @@ samples/client/petstore/swift/SwaggerClientTests/Pods/Pods.xcodeproj/xcshareddat
*.xml~ *.xml~
*.t~ *.t~
/target
/generated-files
/nbactions.xml
# scalatra
samples/server-generator/scalatra/output
samples/server-generator/scalatra/target
samples/server-generator/scalatra/output/.history
# nodejs
samples/server-generator/node/output/node_modules
samples/server/petstore/nodejs/node_modules
samples/server/petstore/nodejs-server/node_modules
# qt5 cpp
samples/client/petstore/qt5cpp/PetStore/moc_*
samples/client/petstore/qt5cpp/PetStore/*.o
samples/client/petstore/qt5cpp/build-*
samples/client/petstore/qt5cpp/PetStore/PetStore
samples/client/petstore/qt5cpp/PetStore/Makefile
#Java/Android
**/.gradle/
samples/client/petstore/java/hello.txt
samples/client/petstore/android/default/hello.txt
samples/client/petstore/android/volley/.gradle/
samples/client/petstore/android/volley/build/
samples/client/petstore/java/jersey2/.gradle/
samples/client/petstore/java/jersey2/build/
samples/client/petstore/java/okhttp-gson/.gradle/
samples/client/petstore/java/okhttp-gson/build/
#PHP
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/
# Perl
samples/client/petstore/perl/deep_module_test/
# Objc
samples/client/petstore/objc/PetstoreClient.xcworkspace/xcuserdata
samples/client/petstore/objc/SwaggerClientTests/SwaggerClient.xcodeproj/xcuserdata
samples/client/petstore/objc/SwaggerClientTests/Build
samples/client/petstore/objc/SwaggerClientTests/Pods
samples/client/petstore/objc/SwaggerClientTests/SwaggerClient.xcworkspace
samples/client/petstore/objc/SwaggerClientTests/Podfile.lock
# Swift
samples/client/petstore/swift/SwaggerClientTests/SwaggerClient.xcodeproj/xcuserdata
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
# C#
*.csproj.user
samples/client/petstore/csharp/SwaggerClientTest/.vs
samples/client/petstore/csharp/SwaggerClientTest/obj
samples/client/petstore/csharp/SwaggerClientTest/bin
samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/vendor/
samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/ samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/
samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/ samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/
**/.gradle/ samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/nuget.exe
samples/client/petstore/csharp/SwaggerClientTest/TestResult.xml
samples/client/petstore/csharp/SwaggerClientTest/nuget.exe
samples/client/petstore/csharp/SwaggerClientTest/testrunner/
# Python
*.pyc
__pycache__
samples/client/petstore/python/dev-requirements.txt.log samples/client/petstore/python/dev-requirements.txt.log
samples/client/petstore/python/swagger_client.egg-info/SOURCES.txt samples/client/petstore/python/swagger_client.egg-info/SOURCES.txt
samples/client/petstore/python/.coverage samples/client/petstore/python/.coverage
samples/client/petstore/python/.projectile
samples/client/petstore/python/.venv/

View File

@ -13,6 +13,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. - 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. - 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
## How to contribute ## How to contribute
@ -31,8 +32,10 @@ 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: Code change should conform to the programming style guide of the respective langauages:
- C#: https://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx - C#: https://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx
- Java: https://google.github.io/styleguide/javaguide.html - Java: https://google.github.io/styleguide/javaguide.html
- JavaScript - https://github.com/airbnb/javascript/tree/master/es5 - JavaScript: https://github.com/airbnb/javascript/tree/master/es5
- Go: https://github.com/golang/go/wiki/CodeReviewComments
- ObjC: https://github.com/NYTimes/objective-c-style-guide - ObjC: https://github.com/NYTimes/objective-c-style-guide
- Perl: http://perldoc.perl.org/perlstyle.html
- PHP: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md - PHP: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md
- Python: https://www.python.org/dev/peps/pep-0008/ - Python: https://www.python.org/dev/peps/pep-0008/
- Ruby: https://github.com/bbatsov/ruby-style-guide - Ruby: https://github.com/bbatsov/ruby-style-guide

View File

@ -46,11 +46,13 @@ Check out [Swagger-Spec](https://github.com/OAI/OpenAPI-Specification) for addit
- [Scala Scalatra](#scala-scalatra) - [Scala Scalatra](#scala-scalatra)
- [Java JAX-RS (Java JAX-RS (Jersey v1.18)](#java-jax-rs-jersey-v118) - [Java JAX-RS (Java JAX-RS (Jersey v1.18)](#java-jax-rs-jersey-v118)
- [Java JAX-RS (Apache CXF 2 / 3)](#java-jax-rs-apache-cxf-2--3) - [Java JAX-RS (Apache CXF 2 / 3)](#java-jax-rs-apache-cxf-2--3)
- [Java JAX-RS (Resteasy)](#java-jax-rs-resteasy)
- [Java Spring MVC](#java-spring-mvc) - [Java Spring MVC](#java-spring-mvc)
- [Haskell Servant](#haskell-servant) - [Haskell Servant](#haskell-servant)
- [ASP.NET 5 Web API](#aspnet-5-web-api) - [ASP.NET 5 Web API](#aspnet-5-web-api)
- [To build the codegen library](#to-build-the-codegen-library) - [To build the codegen library](#to-build-the-codegen-library)
- [Workflow Integration](#workflow-integration) - [Workflow Integration](#workflow-integration)
- [Github Integration](#github-integration)
- [Online Generators](#online-generators) - [Online Generators](#online-generators)
- [Guidelines for Contribution](https://github.com/swagger-api/swagger-codegen/wiki/Guidelines-for-Contribution) - [Guidelines for Contribution](https://github.com/swagger-api/swagger-codegen/wiki/Guidelines-for-Contribution)
- [Companies/Projects using Swagger Codegen](#companiesprojects-using-swagger-codegen) - [Companies/Projects using Swagger Codegen](#companiesprojects-using-swagger-codegen)
@ -62,8 +64,8 @@ The OpenAPI Specification has undergone 3 revisions since initial creation in 20
Swagger Codegen Version | Release Date | OpenAPI Spec compatibility | Notes Swagger Codegen Version | Release Date | OpenAPI Spec compatibility | Notes
-------------------------- | ------------ | -------------------------- | ----- -------------------------- | ------------ | -------------------------- | -----
2.1.6-SNAPSHOT | | 1.0, 1.1, 1.2, 2.0 | [master](https://github.com/swagger-api/swagger-codegen) 2.1.7-SNAPSHOT | | 1.0, 1.1, 1.2, 2.0 | [master](https://github.com/swagger-api/swagger-codegen)
2.1.5 (**current stable**) | 2015-01-06 | 1.0, 1.1, 1.2, 2.0 | [tag v2.1.5](https://github.com/swagger-api/swagger-codegen/tree/v2.1.5) 2.1.6 (**current stable**) | 2016-04-06 | 1.0, 1.1, 1.2, 2.0 | [tag v2.1.6](https://github.com/swagger-api/swagger-codegen/tree/v2.1.6)
2.0.17 | 2014-08-22 | 1.1, 1.2 | [tag v2.0.17](https://github.com/swagger-api/swagger-codegen/tree/v2.0.17) 2.0.17 | 2014-08-22 | 1.1, 1.2 | [tag v2.0.17](https://github.com/swagger-api/swagger-codegen/tree/v2.0.17)
1.0.4 | 2012-04-12 | 1.0, 1.1 | [tag v1.0.4](https://github.com/swagger-api/swagger-codegen/tree/swagger-codegen_2.9.1-1.1) 1.0.4 | 2012-04-12 | 1.0, 1.1 | [tag v1.0.4](https://github.com/swagger-api/swagger-codegen/tree/swagger-codegen_2.9.1-1.1)
@ -72,7 +74,7 @@ Swagger Codegen Version | Release Date | OpenAPI Spec compatibility | Notes
If you're looking for the latest stable version, you can grab it directly from maven central (you'll need java 7 runtime at a minimum): If you're looking for the latest stable version, you can grab it directly from maven central (you'll need java 7 runtime at a minimum):
``` ```
wget http://repo1.maven.org/maven2/io/swagger/swagger-codegen-cli/2.1.5/swagger-codegen-cli-2.1.5.jar -O swagger-codegen-cli.jar wget http://repo1.maven.org/maven2/io/swagger/swagger-codegen-cli/2.1.6/swagger-codegen-cli-2.1.6.jar -O swagger-codegen-cli.jar
java -jar swagger-codegen-cli.jar help java -jar swagger-codegen-cli.jar help
``` ```
@ -86,7 +88,7 @@ To build from source, you need the following installed and available in your $PA
* [Java 7 or 8](http://java.oracle.com) * [Java 7 or 8](http://java.oracle.com)
* [Apache maven 3.0.3 or greater](http://maven.apache.org/) * [Apache maven 3.3.3 or greater](http://maven.apache.org/)
#### OS X Users #### OS X Users
Don't forget to install Java 7 or 8. You probably have 1.6. Don't forget to install Java 7 or 8. You probably have 1.6.
@ -386,6 +388,7 @@ JavaCXFServerCodegen.java
JavaClientCodegen.java JavaClientCodegen.java
JavaInflectorServerCodegen.java JavaInflectorServerCodegen.java
JavaJerseyServerCodegen.java JavaJerseyServerCodegen.java
JavaResteasyServerCodegen.java
JavascriptClientCodegen.java JavascriptClientCodegen.java
NodeJSServerCodegen.java NodeJSServerCodegen.java
ObjcClientCodegen.java ObjcClientCodegen.java
@ -644,6 +647,14 @@ You must register this class into your JAX-RS configuration file:
This is no longer necessary if you are using CXF >=v3.x This is no longer necessary if you are using CXF >=v3.x
### Java JAX-RS (Resteasy)
```
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
-i http://petstore.swagger.io/v2/swagger.json \
-l jaxrs-resteasy \
-o samples/server/petstore/jaxrs-resteasy
```
### Java Spring MVC ### Java Spring MVC
@ -686,6 +697,26 @@ Note! The templates are included in the library generated. If you want to modi
You can use the [swagger-codegen-maven-plugin](modules/swagger-codegen-maven-plugin/README.md) for integrating with your workflow, and generating any codegen target. You can use the [swagger-codegen-maven-plugin](modules/swagger-codegen-maven-plugin/README.md) for integrating with your workflow, and generating any codegen target.
## GitHub Integration
To push the auto-generated SDK to GitHub, we provide `git_push.sh` to streamline the process. For example:
1) Create a new repository in GitHub (Ref: https://help.github.com/articles/creating-a-new-repository/)
2) Generate the SDK
```
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
-i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l perl \
--git-user-id "wing328" \
--git-repo-id "petstore-perl" \
--release-note "Github integration demo" \
-o /var/tmp/perl/petstore
```
3) Push the SDK to GitHub
```
cd /var/tmp/perl/petstore
/bin/sh ./git_push.sh
```
## Online generators ## Online generators
@ -708,13 +739,18 @@ Here are some companies/projects using Swagger Codegen in production. To add you
- [Activehours](https://www.activehours.com/) - [Activehours](https://www.activehours.com/)
- [Acunetix](https://www.acunetix.com/) - [Acunetix](https://www.acunetix.com/)
- [Atlassian](https://www.atlassian.com/) - [Atlassian](https://www.atlassian.com/)
- [beemo](http://www.beemo.eu)
- [CloudBoost](https://www.CloudBoost.io/) - [CloudBoost](https://www.CloudBoost.io/)
- [Cupix](http://www.cupix.com) - [Cupix](http://www.cupix.com)
- [DocuSign](https://www.docusign.com) - [DocuSign](https://www.docusign.com)
- [Ergon](http://www.ergon.ch/) - [Ergon](http://www.ergon.ch/)
- [eureka](http://eure.jp/)
- [everystory.us](http://everystory.us) - [everystory.us](http://everystory.us)
- [Expected Behavior](http://www.expectedbehavior.com/) - [Expected Behavior](http://www.expectedbehavior.com/)
- [FH Münster - University of Applied Sciences](http://www.fh-muenster.de)
- [LANDR Audio](https://www.landr.com/)
- [LiveAgent](https://www.ladesk.com/) - [LiveAgent](https://www.ladesk.com/)
- [Kuary](https://kuary.com/)
- [nViso](http://www.nviso.ch/) - [nViso](http://www.nviso.ch/)
- [Okiok](https://www.okiok.com) - [Okiok](https://www.okiok.com)
- [OSDN](https://osdn.jp) - [OSDN](https://osdn.jp)

View File

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

View File

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

View File

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

View File

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

View File

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

31
bin/jersey2-petstore-server.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/JavaJaxRS -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l jaxrs -o samples/server/petstore/jersey2 --library=jersey2 -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. # if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l nodejs -o samples/server/petstore/nodejs" ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l nodejs-server -o samples/server/petstore/nodejs"
java $JAVA_OPTS -Dservice -jar $executable $ags java $JAVA_OPTS -Dservice -jar $executable $ags

View File

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

View File

@ -3,7 +3,7 @@
<parent> <parent>
<groupId>io.swagger</groupId> <groupId>io.swagger</groupId>
<artifactId>swagger-codegen-project</artifactId> <artifactId>swagger-codegen-project</artifactId>
<version>2.1.6-SNAPSHOT</version> <version>2.1.6</version>
<relativePath>../..</relativePath> <relativePath>../..</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -106,6 +106,18 @@ public class Generate implements Runnable {
@Option(name = {"--library"}, title = "library", description = CodegenConstants.LIBRARY_DESC) @Option(name = {"--library"}, title = "library", description = CodegenConstants.LIBRARY_DESC)
private String library; private String library;
@Option(name = {"--git-user-id"}, title = "git user id", description = CodegenConstants.GIT_USER_ID_DESC)
private String gitUserId;
@Option(name = {"--git-repo-id"}, title = "git repo id", description = CodegenConstants.GIT_REPO_ID_DESC)
private String gitRepoId;
@Option(name = {"--release-note"}, title = "release note", description = CodegenConstants.RELEASE_NOTE_DESC)
private String releaseNote;
@Option(name = {"--http-user-agent"}, title = "http user agent", description = CodegenConstants.HTTP_USER_AGENT_DESC)
private String httpUserAgent;
@Override @Override
public void run() { public void run() {
@ -183,6 +195,22 @@ public class Generate implements Runnable {
configurator.setLibrary(library); configurator.setLibrary(library);
} }
if (isNotEmpty(gitUserId)) {
configurator.setGitUserId(gitUserId);
}
if (isNotEmpty(gitRepoId)) {
configurator.setGitRepoId(gitRepoId);
}
if (isNotEmpty(releaseNote)) {
configurator.setReleaseNote(releaseNote);
}
if (isNotEmpty(httpUserAgent)) {
configurator.setHttpUserAgent(httpUserAgent);
}
applySystemPropertiesKvp(systemProperties, configurator); applySystemPropertiesKvp(systemProperties, configurator);
applyInstantiationTypesKvp(instantiationTypes, configurator); applyInstantiationTypesKvp(instantiationTypes, configurator);
applyImportMappingsKvp(importMappings, configurator); applyImportMappingsKvp(importMappings, configurator);

View File

@ -6,7 +6,7 @@
<parent> <parent>
<groupId>io.swagger</groupId> <groupId>io.swagger</groupId>
<artifactId>swagger-codegen-project</artifactId> <artifactId>swagger-codegen-project</artifactId>
<version>2.1.6-SNAPSHOT</version> <version>2.1.6</version>
<relativePath>../..</relativePath> <relativePath>../..</relativePath>
</parent> </parent>
<artifactId>swagger-codegen-maven-plugin</artifactId> <artifactId>swagger-codegen-maven-plugin</artifactId>

View File

@ -3,7 +3,7 @@
<parent> <parent>
<groupId>io.swagger</groupId> <groupId>io.swagger</groupId>
<artifactId>swagger-codegen-project</artifactId> <artifactId>swagger-codegen-project</artifactId>
<version>2.1.6-SNAPSHOT</version> <version>2.1.6</version>
<relativePath>../..</relativePath> <relativePath>../..</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -69,6 +69,7 @@ public abstract class AbstractGenerator {
* *
* @param config Codegen config * @param config Codegen config
* @param templateFile Template file * @param templateFile Template file
* @return String Full template file path
*/ */
public String getFullTemplateFile(CodegenConfig config, String templateFile) { public String getFullTemplateFile(CodegenConfig config, String templateFile) {
String library = config.getLibrary(); String library = config.getLibrary();

View File

@ -29,6 +29,8 @@ public interface CodegenConfig {
String apiTestFileFolder(); String apiTestFileFolder();
String apiDocFileFolder();
String fileSuffix(); String fileSuffix();
String outputFolder(); String outputFolder();
@ -41,6 +43,8 @@ public interface CodegenConfig {
String modelTestFileFolder(); String modelTestFileFolder();
String modelDocFileFolder();
String modelPackage(); String modelPackage();
String toApiName(String name); String toApiName(String name);
@ -99,6 +103,10 @@ public interface CodegenConfig {
Map<String, String> modelTestTemplateFiles(); Map<String, String> modelTestTemplateFiles();
Map<String, String> apiDocTemplateFiles();
Map<String, String> modelDocTemplateFiles();
Set<String> languageSpecificPrimitives(); Set<String> languageSpecificPrimitives();
void preprocessSwagger(Swagger swagger); void preprocessSwagger(Swagger swagger);
@ -115,6 +123,10 @@ public interface CodegenConfig {
String toModelTestFilename(String name); String toModelTestFilename(String name);
String toApiDocFilename(String name);
String toModelDocFilename(String name);
String toModelImport(String name); String toModelImport(String name);
String toApiImport(String name); String toApiImport(String name);
@ -137,6 +149,8 @@ public interface CodegenConfig {
String apiTestFilename(String templateName, String tag); String apiTestFilename(String templateName, String tag);
String apiDocFilename(String templateName, String tag);
boolean shouldOverwrite(String filename); boolean shouldOverwrite(String filename);
boolean isSkipOverwrite(); boolean isSkipOverwrite();
@ -153,4 +167,21 @@ public interface CodegenConfig {
* @return libray template * @return libray template
*/ */
String getLibrary(); String getLibrary();
void setGitUserId(String gitUserId);
String getGitUserId();
void setGitRepoId(String gitRepoId);
String getGitRepoId();
void setReleaseNote(String releaseNote);
String getReleaseNote();
void setHttpUserAgent(String httpUserAgent);
String getHttpUserAgent();
} }

View File

@ -91,4 +91,16 @@ public class CodegenConstants {
public static final String OPTIONAL_EMIT_DEFAULT_VALUES = "optionalEmitDefaultValues"; public static final String OPTIONAL_EMIT_DEFAULT_VALUES = "optionalEmitDefaultValues";
public static final String OPTIONAL_EMIT_DEFAULT_VALUES_DESC = "Set DataMember's EmitDefaultValue, default false."; public static final String OPTIONAL_EMIT_DEFAULT_VALUES_DESC = "Set DataMember's EmitDefaultValue, default false.";
public static final String GIT_USER_ID = "gitUserId";
public static final String GIT_USER_ID_DESC = "Git user ID, e.g. swagger-api.";
public static final String GIT_REPO_ID = "gitRepoId";
public static final String GIT_REPO_ID_DESC = "Git repo ID, e.g. swagger-codegen.";
public static final String RELEASE_NOTE = "releaseNote";
public static final String RELEASE_NOTE_DESC = "Release note, default to 'Minor update'.";
public static final String HTTP_USER_AGENT = "httpUserAgent";
public static final String HTTP_USER_AGENT_DESC = "HTTP user agent, e.g. codegen_csharp_api_client, default to 'Swagger-Codegen/{packageVersion}}/{language}'";
} }

View File

@ -6,20 +6,35 @@ import java.util.*;
public class CodegenModel { public class CodegenModel {
public String parent, parentSchema; public String parent, parentSchema;
public List<String> interfaces;
// References to parent and interface CodegenModels. Only set when code generator supports inheritance.
public CodegenModel parentModel;
public List<CodegenModel> interfaceModels;
public String name, classname, description, classVarName, modelJson, dataType; public String name, classname, description, classVarName, modelJson, dataType;
public String classFilename; // store the class file name, mainly used for import public String classFilename; // store the class file name, mainly used for import
public String unescapedDescription; public String unescapedDescription;
public String discriminator; public String discriminator;
public String defaultValue; public String defaultValue;
public List<CodegenProperty> vars = new ArrayList<CodegenProperty>(); public List<CodegenProperty> vars = new ArrayList<CodegenProperty>();
public List<CodegenProperty> allVars;
public List<String> allowableValues; public List<String> allowableValues;
// list of all required parameters // Sorted sets of required parameters.
public Set<String> mandatory = new HashSet<String>(); public Set<String> mandatory = new TreeSet<String>();
public Set<String> allMandatory;
public Set<String> imports = new TreeSet<String>(); public Set<String> imports = new TreeSet<String>();
public Boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum; public Boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum;
public ExternalDocs externalDocs; public ExternalDocs externalDocs;
public Map<String, Object> vendorExtensions; public Map<String, Object> vendorExtensions;
{
// By default these are the same collections. Where the code generator supports inheritance, composed models
// store the complete closure of owned and inherited properties in allVars and allMandatory.
allVars = vars;
allMandatory = mandatory;
}
} }

View File

@ -15,7 +15,7 @@ public class CodegenOperation {
isListContainer, isMultipart, hasMore = Boolean.TRUE, isListContainer, isMultipart, hasMore = Boolean.TRUE,
isResponseBinary = Boolean.FALSE, hasReference = Boolean.FALSE; isResponseBinary = Boolean.FALSE, hasReference = Boolean.FALSE;
public String path, operationId, returnType, httpMethod, returnBaseType, public String path, operationId, returnType, httpMethod, returnBaseType,
returnContainer, summary, notes, baseName, defaultResponse; returnContainer, summary, notes, baseName, defaultResponse, discriminator;
public List<Map<String, String>> consumes, produces; public List<Map<String, String>> consumes, produces;
public CodegenParameter bodyParam; public CodegenParameter bodyParam;
public List<CodegenParameter> allParams = new ArrayList<CodegenParameter>(); public List<CodegenParameter> allParams = new ArrayList<CodegenParameter>();
@ -32,6 +32,7 @@ public class CodegenOperation {
public ExternalDocs externalDocs; public ExternalDocs externalDocs;
public Map<String, Object> vendorExtensions; public Map<String, Object> vendorExtensions;
public String nickname; // legacy support public String nickname; // legacy support
public String operationIdLowerCase; // for mardown documentation
/** /**
* Check if there's at least one parameter * Check if there's at least one parameter

View File

@ -8,8 +8,9 @@ import java.util.List;
public class CodegenParameter { public class CodegenParameter {
public Boolean isFormParam, isQueryParam, isPathParam, isHeaderParam, public Boolean isFormParam, isQueryParam, isPathParam, isHeaderParam,
isCookieParam, isBodyParam, hasMore, isContainer, isCookieParam, isBodyParam, hasMore, isContainer,
secondaryParam, isCollectionFormatMulti; secondaryParam, isCollectionFormatMulti, isPrimitiveType;
public String baseName, paramName, dataType, datatypeWithEnum, collectionFormat, description, baseType, defaultValue; public String baseName, paramName, dataType, datatypeWithEnum, collectionFormat, description, baseType, defaultValue;
public String example; // example value (x-example)
public String jsonSchema; public String jsonSchema;
public Boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, isBoolean, isDate, isDateTime; public Boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, isBoolean, isDate, isDateTime;
public Boolean isListContainer, isMapContainer; public Boolean isListContainer, isMapContainer;
@ -107,6 +108,7 @@ public class CodegenParameter {
output.multipleOf = this.multipleOf; output.multipleOf = this.multipleOf;
output.jsonSchema = this.jsonSchema; output.jsonSchema = this.jsonSchema;
output.defaultValue = this.defaultValue; output.defaultValue = this.defaultValue;
output.example = this.example;
output.isEnum = this.isEnum; output.isEnum = this.isEnum;
if (this._enum != null) { if (this._enum != null) {
output._enum = new ArrayList<String>(this._enum); output._enum = new ArrayList<String>(this._enum);

View File

@ -32,6 +32,7 @@ public class CodegenProperty {
public Boolean exclusiveMinimum; public Boolean exclusiveMinimum;
public Boolean exclusiveMaximum; public Boolean exclusiveMaximum;
public Boolean hasMore, required, secondaryParam; public Boolean hasMore, required, secondaryParam;
public Boolean hasMoreNonReadOnly; // for model constructor, true if next properyt is not readonly
public Boolean isPrimitiveType, isContainer, isNotContainer; public Boolean isPrimitiveType, isContainer, isNotContainer;
public Boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, isBoolean, isDate, isDateTime; public Boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, isBoolean, isDate, isDateTime;
public Boolean isListContainer, isMapContainer; public Boolean isListContainer, isMapContainer;
@ -63,6 +64,7 @@ public class CodegenProperty {
result = prime * result + ((exclusiveMinimum == null) ? 0 : exclusiveMinimum.hashCode()); result = prime * result + ((exclusiveMinimum == null) ? 0 : exclusiveMinimum.hashCode());
result = prime * result + ((getter == null) ? 0 : getter.hashCode()); result = prime * result + ((getter == null) ? 0 : getter.hashCode());
result = prime * result + ((hasMore == null) ? 0 : hasMore.hashCode()); result = prime * result + ((hasMore == null) ? 0 : hasMore.hashCode());
result = prime * result + ((hasMoreNonReadOnly == null) ? 0 : hasMoreNonReadOnly.hashCode());
result = prime * result + ((isContainer == null) ? 0 : isContainer.hashCode()); result = prime * result + ((isContainer == null) ? 0 : isContainer.hashCode());
result = prime * result + (isEnum ? 1231 : 1237); result = prime * result + (isEnum ? 1231 : 1237);
result = prime * result + ((isNotContainer == null) ? 0 : isNotContainer.hashCode()); result = prime * result + ((isNotContainer == null) ? 0 : isNotContainer.hashCode());

View File

@ -2,52 +2,22 @@ package io.swagger.codegen;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import io.swagger.codegen.examples.ExampleGenerator; import io.swagger.codegen.examples.ExampleGenerator;
import io.swagger.models.ArrayModel; import io.swagger.models.*;
import io.swagger.models.ComposedModel; import io.swagger.models.auth.*;
import io.swagger.models.Model; import io.swagger.models.parameters.*;
import io.swagger.models.ModelImpl;
import io.swagger.models.Operation;
import io.swagger.models.RefModel;
import io.swagger.models.Response;
import io.swagger.models.Swagger;
import io.swagger.models.auth.ApiKeyAuthDefinition;
import io.swagger.models.auth.BasicAuthDefinition;
import io.swagger.models.auth.In;
import io.swagger.models.auth.OAuth2Definition;
import io.swagger.models.auth.SecuritySchemeDefinition;
import io.swagger.models.parameters.BodyParameter;
import io.swagger.models.parameters.CookieParameter;
import io.swagger.models.parameters.FormParameter;
import io.swagger.models.parameters.HeaderParameter;
import io.swagger.models.parameters.Parameter;
import io.swagger.models.parameters.PathParameter;
import io.swagger.models.parameters.QueryParameter;
import io.swagger.models.parameters.SerializableParameter;
import io.swagger.models.properties.*; import io.swagger.models.properties.*;
import io.swagger.models.properties.PropertyBuilder.PropertyId; import io.swagger.models.properties.PropertyBuilder.PropertyId;
import io.swagger.util.Json; import io.swagger.util.Json;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.io.File; import java.io.File;
import java.util.ArrayList; import java.util.*;
import java.util.Arrays; import java.util.Map.Entry;
import java.util.Collection;
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.Set;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@ -69,6 +39,8 @@ public class DefaultCodegen {
protected Map<String, String> modelTemplateFiles = new HashMap<String, String>(); protected Map<String, String> modelTemplateFiles = new HashMap<String, String>();
protected Map<String, String> apiTestTemplateFiles = new HashMap<String, String>(); protected Map<String, String> apiTestTemplateFiles = new HashMap<String, String>();
protected Map<String, String> modelTestTemplateFiles = new HashMap<String, String>(); protected Map<String, String> modelTestTemplateFiles = new HashMap<String, String>();
protected Map<String, String> apiDocTemplateFiles = new HashMap<String, String>();
protected Map<String, String> modelDocTemplateFiles = new HashMap<String, String>();
protected String templateDir; protected String templateDir;
protected String embeddedTemplateDir; protected String embeddedTemplateDir;
protected Map<String, Object> additionalProperties = new HashMap<String, Object>(); protected Map<String, Object> additionalProperties = new HashMap<String, Object>();
@ -81,6 +53,8 @@ public class DefaultCodegen {
protected String library; protected String library;
protected Boolean sortParamsByRequiredFlag = true; protected Boolean sortParamsByRequiredFlag = true;
protected Boolean ensureUniqueParams = true; protected Boolean ensureUniqueParams = true;
protected String gitUserId, gitRepoId, releaseNote;
protected String httpUserAgent;
public List<CliOption> cliOptions() { public List<CliOption> cliOptions() {
return cliOptions; return cliOptions;
@ -116,11 +90,40 @@ public class DefaultCodegen {
if(additionalProperties.containsKey(CodegenConstants.MODEL_NAME_SUFFIX)){ if(additionalProperties.containsKey(CodegenConstants.MODEL_NAME_SUFFIX)){
this.setModelNameSuffix((String) additionalProperties.get(CodegenConstants.MODEL_NAME_SUFFIX)); this.setModelNameSuffix((String) additionalProperties.get(CodegenConstants.MODEL_NAME_SUFFIX));
} }
} }
// override with any special post-processing for all models // override with any special post-processing for all models
@SuppressWarnings("static-method") @SuppressWarnings({ "static-method", "unchecked" })
public Map<String, Object> postProcessAllModels(Map<String, Object> objs) { public Map<String, Object> postProcessAllModels(Map<String, Object> objs) {
if (supportsInheritance) {
// Index all CodegenModels by name.
Map<String, CodegenModel> allModels = new HashMap<String, CodegenModel>();
for (Entry<String, Object> entry : objs.entrySet()) {
String modelName = entry.getKey();
Map<String, Object> inner = (Map<String, Object>) entry.getValue();
List<Map<String, Object>> models = (List<Map<String, Object>>) inner.get("models");
for (Map<String, Object> mo : models) {
CodegenModel cm = (CodegenModel) mo.get("model");
allModels.put(modelName, cm);
}
}
// Fix up all parent and interface CodegenModel references.
for (CodegenModel cm : allModels.values()) {
if (cm.parent != null) {
cm.parentModel = allModels.get(cm.parent);
}
if (cm.interfaces != null && !cm.interfaces.isEmpty()) {
cm.interfaceModels = new ArrayList<CodegenModel>(cm.interfaces.size());
for (String intf : cm.interfaces) {
CodegenModel intfModel = allModels.get(intf);
if (intfModel != null) {
cm.interfaceModels.add(intfModel);
}
}
}
}
}
return objs; return objs;
} }
@ -167,11 +170,7 @@ public class DefaultCodegen {
@SuppressWarnings("static-method") @SuppressWarnings("static-method")
public String escapeText(String input) { public String escapeText(String input) {
if (input != null) { if (input != null) {
input = input.trim(); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. return StringEscapeUtils.escapeJava(input).replace("\\/", "/");
String output = input.replaceAll("\n", "\\\\n");
output = output.replace("\r", "\\r");
output = output.replace("\"", "\\\"");
return output;
} }
return input; return input;
} }
@ -228,6 +227,14 @@ public class DefaultCodegen {
} }
} }
public Map<String, String> apiDocTemplateFiles() {
return apiDocTemplateFiles;
}
public Map<String, String> modelDocTemplateFiles() {
return modelDocTemplateFiles;
}
public Map<String, String> apiTestTemplateFiles() { public Map<String, String> apiTestTemplateFiles() {
return apiTestTemplateFiles; return apiTestTemplateFiles;
} }
@ -260,6 +267,14 @@ public class DefaultCodegen {
return outputFolder + "/" + testPackage().replace('.', '/'); return outputFolder + "/" + testPackage().replace('.', '/');
} }
public String apiDocFileFolder() {
return outputFolder;
}
public String modelDocFileFolder() {
return outputFolder;
}
public Map<String, Object> additionalProperties() { public Map<String, Object> additionalProperties() {
return additionalProperties; return additionalProperties;
} }
@ -322,6 +337,16 @@ public class DefaultCodegen {
return toApiName(name); return toApiName(name);
} }
/**
* Return the file name of the Api Documentation
*
* @param name the file name of the Api
* @return the file name of the Api
*/
public String toApiDocFilename(String name) {
return toApiName(name);
}
/** /**
* Return the file name of the Api Test * Return the file name of the Api Test
* *
@ -362,6 +387,16 @@ public class DefaultCodegen {
return initialCaps(name) + "Test"; return initialCaps(name) + "Test";
} }
/**
* Return the capitalized file name of the model documentation
*
* @param name the model name
* @return the file name of the model
*/
public String toModelDocFilename(String name) {
return initialCaps(name);
}
/** /**
* Return the operation ID (method name) * Return the operation ID (method name)
* *
@ -614,13 +649,21 @@ public class DefaultCodegen {
} }
} }
/**
* Return the example value of the parameter.
*
* @param p Swagger property object
*/
public void setParameterExampleValue(CodegenParameter p) {
}
/** /**
* Return the example value of the property * Return the example value of the property
* *
* @param p Swagger property object * @param p Swagger property object
* @return string presentation of the example value of the property * @return string presentation of the example value of the property
*/ */
@SuppressWarnings("static-method")
public String toExampleValue(Property p) { public String toExampleValue(Property p) {
if(p.getExample() != null) { if(p.getExample() != null) {
return p.getExample().toString(); return p.getExample().toString();
@ -896,8 +939,18 @@ public class DefaultCodegen {
// TODO // TODO
} else if (model instanceof ComposedModel) { } else if (model instanceof ComposedModel) {
final ComposedModel composed = (ComposedModel) model; final ComposedModel composed = (ComposedModel) model;
Map<String, Property> properties = new HashMap<String, Property>(); Map<String, Property> properties = new LinkedHashMap<String, Property>();
List<String> required = new ArrayList<String>(); List<String> required = new ArrayList<String>();
Map<String, Property> allProperties;
List<String> allRequired;
if (supportsInheritance) {
allProperties = new LinkedHashMap<String, Property>();
allRequired = new ArrayList<String>();
m.allVars = new ArrayList<CodegenProperty>();
} else {
allProperties = null;
allRequired = null;
}
// parent model // parent model
final RefModel parent = (RefModel) composed.getParent(); final RefModel parent = (RefModel) composed.getParent();
if (parent != null) { if (parent != null) {
@ -905,31 +958,29 @@ public class DefaultCodegen {
m.parentSchema = parentRef; m.parentSchema = parentRef;
m.parent = toModelName(parent.getSimpleRef()); m.parent = toModelName(parent.getSimpleRef());
addImport(m, m.parent); addImport(m, m.parent);
if (!supportsInheritance && allDefinitions != null) { if (allDefinitions != null) {
final Model parentModel = allDefinitions.get(m.parentSchema); final Model parentModel = allDefinitions.get(m.parentSchema);
if (parentModel instanceof ModelImpl) { if (supportsInheritance) {
final ModelImpl _parent = (ModelImpl) parentModel; addProperties(allProperties, allRequired, parentModel, allDefinitions);
if (_parent.getProperties() != null) { } else {
properties.putAll(_parent.getProperties()); addProperties(properties, required, parentModel, allDefinitions);
}
if (_parent.getRequired() != null) {
required.addAll(_parent.getRequired());
}
} }
} }
} }
// interfaces (intermediate models) // interfaces (intermediate models)
if (allDefinitions != null && composed.getInterfaces() != null) { if (composed.getInterfaces() != null) {
if (m.interfaces == null)
m.interfaces = new ArrayList<String>();
for (RefModel _interface : composed.getInterfaces()) { for (RefModel _interface : composed.getInterfaces()) {
final String interfaceRef = toModelName(_interface.getSimpleRef()); final String interfaceRef = toModelName(_interface.getSimpleRef());
final Model interfaceModel = allDefinitions.get(interfaceRef); m.interfaces.add(interfaceRef);
if (interfaceModel instanceof ModelImpl) { addImport(m, interfaceRef);
final ModelImpl _interfaceModel = (ModelImpl) interfaceModel; if (allDefinitions != null) {
if (_interfaceModel.getProperties() != null) { final Model interfaceModel = allDefinitions.get(interfaceRef);
properties.putAll(_interfaceModel.getProperties()); if (supportsInheritance) {
} addProperties(allProperties, allRequired, interfaceModel, allDefinitions);
if (_interfaceModel.getRequired() != null) { } else {
required.addAll(_interfaceModel.getRequired()); addProperties(properties, required, interfaceModel, allDefinitions);
} }
} }
} }
@ -941,15 +992,12 @@ public class DefaultCodegen {
child = allDefinitions.get(childRef); child = allDefinitions.get(childRef);
} }
if (child != null && child instanceof ModelImpl) { if (child != null && child instanceof ModelImpl) {
final ModelImpl _child = (ModelImpl) child; addProperties(properties, required, child, allDefinitions);
if (_child.getProperties() != null) { if (supportsInheritance) {
properties.putAll(_child.getProperties()); addProperties(allProperties, allRequired, child, allDefinitions);
}
if (_child.getRequired() != null) {
required.addAll(_child.getRequired());
} }
} }
addVars(m, properties, required); addVars(m, properties, required, allProperties, allRequired);
} else { } else {
ModelImpl impl = (ModelImpl) model; ModelImpl impl = (ModelImpl) model;
if(impl.getEnum() != null && impl.getEnum().size() > 0) { if(impl.getEnum() != null && impl.getEnum().size() > 0) {
@ -965,7 +1013,7 @@ public class DefaultCodegen {
addVars(m, impl.getProperties(), impl.getRequired()); addVars(m, impl.getProperties(), impl.getRequired());
} }
if(m.vars != null) { if (m.vars != null) {
for(CodegenProperty prop : m.vars) { for(CodegenProperty prop : m.vars) {
postProcessModelProperty(m, prop); postProcessModelProperty(m, prop);
} }
@ -973,6 +1021,28 @@ public class DefaultCodegen {
return m; return m;
} }
protected void addProperties(Map<String, Property> properties, List<String> required, Model model,
Map<String, Model> allDefinitions) {
if (model instanceof ModelImpl) {
ModelImpl mi = (ModelImpl) model;
if (mi.getProperties() != null) {
properties.putAll(mi.getProperties());
}
if (mi.getRequired() != null) {
required.addAll(mi.getRequired());
}
} else if (model instanceof RefModel) {
String interfaceRef = toModelName(((RefModel) model).getSimpleRef());
Model interfaceModel = allDefinitions.get(interfaceRef);
addProperties(properties, required, interfaceModel, allDefinitions);
} else if (model instanceof ComposedModel) {
for (Model component :((ComposedModel) model).getAllOf()) {
addProperties(properties, required, component, allDefinitions);
}
}
}
/** /**
* Camelize the method name of the getter and setter * Camelize the method name of the getter and setter
* *
@ -1214,6 +1284,7 @@ public class DefaultCodegen {
property.containerType = "map"; property.containerType = "map";
MapProperty ap = (MapProperty) p; MapProperty ap = (MapProperty) p;
CodegenProperty cp = fromProperty("inner", ap.getAdditionalProperties()); CodegenProperty cp = fromProperty("inner", ap.getAdditionalProperties());
property.items = cp;
property.baseType = getSwaggerType(p); property.baseType = getSwaggerType(p);
if (!languageSpecificPrimitives.contains(cp.baseType)) { if (!languageSpecificPrimitives.contains(cp.baseType)) {
@ -1402,6 +1473,16 @@ public class DefaultCodegen {
op.defaultResponse = toDefaultValue(responseProperty); op.defaultResponse = toDefaultValue(responseProperty);
op.returnType = cm.datatype; op.returnType = cm.datatype;
op.hasReference = definitions != null && definitions.containsKey(op.returnBaseType); op.hasReference = definitions != null && definitions.containsKey(op.returnBaseType);
// lookup discriminator
if (definitions != null) {
Model m = definitions.get(op.returnBaseType);
if (m != null) {
CodegenModel cmod = fromModel(op.returnBaseType, m, definitions);
op.discriminator = cmod.discriminator;
}
}
if (cm.isContainer != null) { if (cm.isContainer != null) {
op.returnContainer = cm.containerType; op.returnContainer = cm.containerType;
if ("map".equals(cm.containerType)) { if ("map".equals(cm.containerType)) {
@ -1452,6 +1533,14 @@ public class DefaultCodegen {
} }
} }
} }
// set isPrimitiveType and baseType for allParams
/*if (languageSpecificPrimitives.contains(p.baseType)) {
p.isPrimitiveType = true;
p.baseType = getSwaggerType(p);
}*/
allParams.add(p); allParams.add(p);
if (param instanceof QueryParameter) { if (param instanceof QueryParameter) {
p.isQueryParam = new Boolean(true); p.isQueryParam = new Boolean(true);
@ -1518,7 +1607,6 @@ public class DefaultCodegen {
// legacy support // legacy support
op.nickname = op.operationId; op.nickname = op.operationId;
if (op.allParams.size() > 0) { if (op.allParams.size() > 0) {
op.hasParams = true; op.hasParams = true;
} }
@ -1723,7 +1811,9 @@ public class DefaultCodegen {
prop.setRequired(bp.getRequired()); prop.setRequired(bp.getRequired());
CodegenProperty cp = fromProperty("property", prop); CodegenProperty cp = fromProperty("property", prop);
if (cp != null) { if (cp != null) {
p.baseType = cp.baseType;
p.dataType = cp.datatype; p.dataType = cp.datatype;
p.isPrimitiveType = cp.isPrimitiveType;
p.isBinary = cp.datatype.toLowerCase().startsWith("byte"); p.isBinary = cp.datatype.toLowerCase().startsWith("byte");
} }
@ -1743,6 +1833,8 @@ public class DefaultCodegen {
} }
imports.add(cp.baseType); imports.add(cp.baseType);
p.dataType = cp.datatype; p.dataType = cp.datatype;
p.baseType = cp.complexType;
p.isPrimitiveType = cp.isPrimitiveType;
p.isContainer = true; p.isContainer = true;
p.isListContainer = true; p.isListContainer = true;
@ -1763,11 +1855,47 @@ public class DefaultCodegen {
name = getTypeDeclaration(name); name = getTypeDeclaration(name);
} }
p.dataType = name; p.dataType = name;
p.baseType = name;
} }
} }
p.paramName = toParamName(bp.getName()); p.paramName = toParamName(bp.getName());
} }
// set the example value
// if not specified in x-example, generate a default value
if (p.vendorExtensions.containsKey("x-example")) {
p.example = (String) p.vendorExtensions.get("x-example");
} else if (Boolean.TRUE.equals(p.isString)) {
p.example = p.paramName + "_example";
} else if (Boolean.TRUE.equals(p.isBoolean)) {
p.example = new String("true");
} else if (Boolean.TRUE.equals(p.isLong)) {
p.example = new String("789");
} else if (Boolean.TRUE.equals(p.isInteger)) {
p.example = new String("56");
} else if (Boolean.TRUE.equals(p.isFloat)) {
p.example = new String("3.4");
} else if (Boolean.TRUE.equals(p.isDouble)) {
p.example = new String("1.2");
} else if (Boolean.TRUE.equals(p.isBinary)) {
p.example = new String("BINARY_DATA_HERE");
} else if (Boolean.TRUE.equals(p.isByteArray)) {
p.example = new String("B");
} else if (Boolean.TRUE.equals(p.isDate)) {
p.example = new String("2013-10-20");
} else if (Boolean.TRUE.equals(p.isDateTime)) {
p.example = new String("2013-10-20T19:20:30+01:00");
} else if (param instanceof FormParameter &&
("file".equalsIgnoreCase(((FormParameter) param).getType()) ||
"file".equals(p.baseType))) {
p.isFile = true;
p.example = new String("/path/to/file.txt");
}
// set the parameter excample value
// should be overridden by lang codegen
setParameterExampleValue(p);
postProcessParameter(p); postProcessParameter(p);
return p; return p;
} }
@ -1978,6 +2106,7 @@ public class DefaultCodegen {
LOGGER.warn("generated unique operationId `" + uniqueName + "`"); LOGGER.warn("generated unique operationId `" + uniqueName + "`");
} }
co.operationId = uniqueName; co.operationId = uniqueName;
co.operationIdLowerCase = uniqueName.toLowerCase();
opList.add(co); opList.add(co);
co.baseName = tag; co.baseName = tag;
} }
@ -2060,45 +2189,74 @@ public class DefaultCodegen {
} }
} }
private void addVars(CodegenModel m, Map<String, Property> properties, Collection<String> required) { private void addVars(CodegenModel m, Map<String, Property> properties, List<String> required) {
if (properties != null && properties.size() > 0) { addVars(m, properties, required, null, null);
}
private void addVars(CodegenModel m, Map<String, Property> properties, List<String> required,
Map<String, Property> allProperties, List<String> allRequired) {
if (properties != null && !properties.isEmpty()) {
m.hasVars = true; m.hasVars = true;
m.hasEnums = false; m.hasEnums = false;
final int totalCount = properties.size();
final Set<String> mandatory = required == null ? Collections.<String>emptySet() : new HashSet<String>(required);
int count = 0;
for (Map.Entry<String, Property> entry : properties.entrySet()) {
final String key = entry.getKey();
final Property prop = entry.getValue();
if (prop == null) {
LOGGER.warn("null property for " + key);
} else {
final CodegenProperty cp = fromProperty(key, prop);
cp.required = mandatory.contains(key) ? true : null;
if (cp.isEnum) {
m.hasEnums = true;
}
count += 1;
if (count != totalCount) {
cp.hasMore = true;
}
if (cp.isContainer != null) {
addImport(m, typeMapping.get("array"));
}
addImport(m, cp.baseType);
addImport(m, cp.complexType);
m.vars.add(cp);
}
}
m.mandatory = mandatory;
Set<String> mandatory = required == null ? Collections.<String> emptySet()
: new TreeSet<String>(required);
addVars(m, m.vars, properties, mandatory);
m.allMandatory = m.mandatory = mandatory;
} else { } else {
m.emptyVars = true; m.emptyVars = true;
m.hasVars = false; m.hasVars = false;
m.hasEnums = false; m.hasEnums = false;
} }
if (allProperties != null) {
Set<String> allMandatory = allRequired == null ? Collections.<String> emptySet()
: new TreeSet<String>(allRequired);
addVars(m, m.allVars, allProperties, allMandatory);
m.allMandatory = allMandatory;
}
}
private void addVars(CodegenModel m, List<CodegenProperty> vars, Map<String, Property> properties, Set<String> mandatory) {
// convert set to list so that we can access the next entry in the loop
List<Map.Entry<String, Property>> propertyList = new ArrayList<Map.Entry<String, Property>>(properties.entrySet());
final int totalCount = propertyList.size();
for (int i = 0; i < totalCount; i++) {
Map.Entry<String, Property> entry = propertyList.get(i);
final String key = entry.getKey();
final Property prop = entry.getValue();
if (prop == null) {
LOGGER.warn("null property for " + key);
} else {
final CodegenProperty cp = fromProperty(key, prop);
cp.required = mandatory.contains(key) ? true : null;
if (cp.isEnum) {
// FIXME: if supporting inheritance, when called a second time for allProperties it is possible for
// m.hasEnums to be set incorrectly if allProperties has enumerations but properties does not.
m.hasEnums = true;
}
if (i+1 != totalCount) {
cp.hasMore = true;
// check the next entry to see if it's read only
if (!Boolean.TRUE.equals(propertyList.get(i+1).getValue().getReadOnly())) {
cp.hasMoreNonReadOnly = true; // next entry is not ready only
}
}
if (cp.isContainer != null) {
addImport(m, typeMapping.get("array"));
}
addImport(m, cp.baseType);
addImport(m, cp.complexType);
vars.add(cp);
}
}
} }
/** /**
@ -2196,6 +2354,19 @@ public class DefaultCodegen {
return apiFileFolder() + '/' + toApiFilename(tag) + suffix; return apiFileFolder() + '/' + toApiFilename(tag) + suffix;
} }
/**
* Return the full path and API documentation file
*
* @param templateName template name
* @param tag tag
*
* @return the API documentation file name with full path
*/
public String apiDocFilename(String templateName, String tag) {
String suffix = apiDocTemplateFiles().get(templateName);
return apiDocFileFolder() + '/' + toApiDocFilename(tag) + suffix;
}
/** /**
* Return the full path and API test file * Return the full path and API test file
* *
@ -2230,6 +2401,11 @@ public class DefaultCodegen {
return supportedLibraries; return supportedLibraries;
} }
/**
* Set library template (sub-template).
*
* @param library Library template
*/
public void setLibrary(String library) { public void setLibrary(String library) {
if (library != null && !supportedLibraries.containsKey(library)) if (library != null && !supportedLibraries.containsKey(library))
throw new RuntimeException("unknown library: " + library); throw new RuntimeException("unknown library: " + library);
@ -2245,6 +2421,78 @@ public class DefaultCodegen {
return library; return library;
} }
/**
* Set Git user ID.
*
* @param gitUserId Git user ID
*/
public void setGitUserId(String gitUserId) {
this.gitUserId = gitUserId;
}
/**
* Git user ID
*
* @return Git user ID
*/
public String getGitUserId() {
return gitUserId;
}
/**
* Set Git repo ID.
*
* @param gitRepoId Git repo ID
*/
public void setGitRepoId(String gitRepoId) {
this.gitRepoId = gitRepoId;
}
/**
* Git repo ID
*
* @return Git repo ID
*/
public String getGitRepoId() {
return gitRepoId;
}
/**
* Set release note.
*
* @param releaseNote Release note
*/
public void setReleaseNote(String releaseNote) {
this.releaseNote = releaseNote;
}
/**
* Release note
*
* @return Release note
*/
public String getReleaseNote() {
return releaseNote;
}
/**
* Set HTTP user agent.
*
* @param httpUserAgent HTTP user agent
*/
public void setHttpUserAgent(String httpUserAgent) {
this.httpUserAgent = httpUserAgent;
}
/**
* HTTP user agent
*
* @return HTTP user agent
*/
public String getHttpUserAgent() {
return httpUserAgent;
}
@SuppressWarnings("static-method") @SuppressWarnings("static-method")
protected CliOption buildLibraryCliOption(Map<String, String> supportedLibraries) { protected CliOption buildLibraryCliOption(Map<String, String> supportedLibraries) {
StringBuilder sb = new StringBuilder("library template (sub-template) to use:"); StringBuilder sb = new StringBuilder("library template (sub-template) to use:");
@ -2361,24 +2609,34 @@ public class DefaultCodegen {
if (Boolean.TRUE.equals(property.isString)) { if (Boolean.TRUE.equals(property.isString)) {
parameter.isString = true; parameter.isString = true;
parameter.isPrimitiveType = true;
} else if (Boolean.TRUE.equals(property.isBoolean)) { } else if (Boolean.TRUE.equals(property.isBoolean)) {
parameter.isBoolean = true; parameter.isBoolean = true;
parameter.isPrimitiveType = true;
} else if (Boolean.TRUE.equals(property.isLong)) { } else if (Boolean.TRUE.equals(property.isLong)) {
parameter.isLong = true; parameter.isLong = true;
parameter.isPrimitiveType = true;
} else if (Boolean.TRUE.equals(property.isInteger)) { } else if (Boolean.TRUE.equals(property.isInteger)) {
parameter.isInteger = true; parameter.isInteger = true;
parameter.isPrimitiveType = true;
} else if (Boolean.TRUE.equals(property.isDouble)) { } else if (Boolean.TRUE.equals(property.isDouble)) {
parameter.isDouble = true; parameter.isDouble = true;
parameter.isPrimitiveType = true;
} else if (Boolean.TRUE.equals(property.isFloat)) { } else if (Boolean.TRUE.equals(property.isFloat)) {
parameter.isFloat = true; parameter.isFloat = true;
parameter.isPrimitiveType = true;
} else if (Boolean.TRUE.equals(property.isByteArray)) { } else if (Boolean.TRUE.equals(property.isByteArray)) {
parameter.isByteArray = true; parameter.isByteArray = true;
parameter.isPrimitiveType = true;
} else if (Boolean.TRUE.equals(property.isBinary)) { } else if (Boolean.TRUE.equals(property.isBinary)) {
parameter.isByteArray = true; parameter.isByteArray = true;
parameter.isPrimitiveType = true;
} else if (Boolean.TRUE.equals(property.isDate)) { } else if (Boolean.TRUE.equals(property.isDate)) {
parameter.isDate = true; parameter.isDate = true;
parameter.isPrimitiveType = true;
} else if (Boolean.TRUE.equals(property.isDateTime)) { } else if (Boolean.TRUE.equals(property.isDateTime)) {
parameter.isDateTime = true; parameter.isDateTime = true;
parameter.isPrimitiveType = true;
} else { } else {
LOGGER.debug("Property type is not primitive: " + property.datatype); LOGGER.debug("Property type is not primitive: " + property.datatype);
} }

View File

@ -8,6 +8,7 @@ import io.swagger.models.auth.SecuritySchemeDefinition;
import io.swagger.models.parameters.Parameter; import io.swagger.models.parameters.Parameter;
import io.swagger.util.Json; import io.swagger.util.Json;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -167,26 +168,63 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
List<Object> allModels = new ArrayList<Object>(); List<Object> allModels = new ArrayList<Object>();
// models // models
Map<String, Model> definitions = swagger.getDefinitions(); final Map<String, Model> definitions = swagger.getDefinitions();
if (definitions != null) { if (definitions != null) {
List<String> sortedModelKeys = sortModelsByInheritance(definitions); Set<String> modelKeys = definitions.keySet();
if(generateModels) { if(generateModels) {
if(modelsToGenerate != null && modelsToGenerate.size() > 0) { if(modelsToGenerate != null && modelsToGenerate.size() > 0) {
List<String> updatedKeys = new ArrayList<String>(); Set<String> updatedKeys = new HashSet<String>();
for(String m : sortedModelKeys) { for(String m : modelKeys) {
if(modelsToGenerate.contains(m)) { if(modelsToGenerate.contains(m)) {
updatedKeys.add(m); updatedKeys.add(m);
} }
} }
sortedModelKeys = updatedKeys; modelKeys = updatedKeys;
} }
// store all processed models // store all processed models
Map<String,Object> allProcessedModels = new HashMap<String, Object>(); Map<String,Object> allProcessedModels = new TreeMap<String, Object>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
Model model1 = definitions.get(o1);
Model model2 = definitions.get(o2);
int model1InheritanceDepth = getInheritanceDepth(model1);
int model2InheritanceDepth = getInheritanceDepth(model2);
if (model1InheritanceDepth == model2InheritanceDepth) {
return ObjectUtils.compare(config.toModelName(o1), config.toModelName(o2));
} else if (model1InheritanceDepth > model2InheritanceDepth) {
return 1;
} else {
return -1;
}
}
private int getInheritanceDepth(Model model) {
int inheritanceDepth = 0;
Model parent = getParent(model);
while (parent != null) {
inheritanceDepth++;
parent = getParent(parent);
}
return inheritanceDepth;
}
private Model getParent(Model model) {
if (model instanceof ComposedModel) {
return definitions.get(((ComposedModel) model).getParent().getReference());
}
return null;
}
});
// process models only // process models only
for (String name : sortedModelKeys) { for (String name : modelKeys) {
try { try {
//don't generate models that have an import mapping //don't generate models that have an import mapping
if(config.importMapping().containsKey(name)) { if(config.importMapping().containsKey(name)) {
@ -197,6 +235,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
Map<String, Model> modelMap = new HashMap<String, Model>(); Map<String, Model> modelMap = new HashMap<String, Model>();
modelMap.put(name, model); modelMap.put(name, model);
Map<String, Object> models = processModels(config, modelMap, definitions); Map<String, Object> models = processModels(config, modelMap, definitions);
models.put("classname", config.toModelName(name));
models.putAll(config.additionalProperties()); models.putAll(config.additionalProperties());
allProcessedModels.put(name, models); allProcessedModels.put(name, models);
@ -263,6 +302,28 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
writeToFile(filename, tmpl.execute(models)); writeToFile(filename, tmpl.execute(models));
files.add(new File(filename)); files.add(new File(filename));
} }
// to generate model documentation files
for (String templateName : config.modelDocTemplateFiles().keySet()) {
String suffix = config.modelDocTemplateFiles().get(templateName);
String filename = config.modelDocFileFolder() + File.separator + config.toModelDocFilename(name) + suffix;
if (!config.shouldOverwrite(filename)) {
continue;
}
String templateFile = getFullTemplateFile(config, templateName);
String template = readTemplate(templateFile);
Template tmpl = Mustache.compiler()
.withLoader(new Mustache.TemplateLoader() {
@Override
public Reader getTemplate(String name) {
return getTemplateReader(getFullTemplateFile(config, name + ".mustache"));
}
})
.defaultValue("")
.compile(template);
writeToFile(filename, tmpl.execute(models));
files.add(new File(filename));
}
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException("Could not generate model '" + name + "'", e); throw new RuntimeException("Could not generate model '" + name + "'", e);
} }
@ -289,6 +350,12 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
for (String tag : paths.keySet()) { for (String tag : paths.keySet()) {
try { try {
List<CodegenOperation> ops = paths.get(tag); List<CodegenOperation> ops = paths.get(tag);
Collections.sort(ops, new Comparator<CodegenOperation>() {
@Override
public int compare(CodegenOperation one, CodegenOperation another) {
return ObjectUtils.compare(one.operationId, another.operationId);
}
});
Map<String, Object> operation = processOperations(config, tag, ops); Map<String, Object> operation = processOperations(config, tag, ops);
operation.put("basePath", basePath); operation.put("basePath", basePath);
@ -368,11 +435,35 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
files.add(new File(filename)); files.add(new File(filename));
} }
// to generate api documentation files
for (String templateName : config.apiDocTemplateFiles().keySet()) {
String filename = config.apiDocFilename(templateName, tag);
if (!config.shouldOverwrite(filename) && new File(filename).exists()) {
continue;
}
String templateFile = getFullTemplateFile(config, templateName);
String template = readTemplate(templateFile);
Template tmpl = Mustache.compiler()
.withLoader(new Mustache.TemplateLoader() {
@Override
public Reader getTemplate(String name) {
return getTemplateReader(getFullTemplateFile(config, name + ".mustache"));
}
})
.defaultValue("")
.compile(template);
writeToFile(filename, tmpl.execute(operation));
files.add(new File(filename));
}
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException("Could not generate api file for '" + tag + "'", e); throw new RuntimeException("Could not generate api file for '" + tag + "'", e);
} }
} }
} }
if (System.getProperty("debugOperations") != null) { if (System.getProperty("debugOperations") != null) {
LOGGER.info("############ Operation info ############"); LOGGER.info("############ Operation info ############");
Json.prettyPrint(allOperations); Json.prettyPrint(allOperations);
@ -513,54 +604,8 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
} }
} }
private static List<String> sortModelsByInheritance(final Map<String, Model> definitions) {
List<String> sortedModelKeys = new ArrayList<String>(definitions.keySet());
Comparator<String> cmp = new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
Model model1 = definitions.get(o1);
Model model2 = definitions.get(o2);
int model1InheritanceDepth = getInheritanceDepth(model1);
int model2InheritanceDepth = getInheritanceDepth(model2);
if (model1InheritanceDepth == model2InheritanceDepth) {
return 0;
} else if (model1InheritanceDepth > model2InheritanceDepth) {
return 1;
} else {
return -1;
}
}
private int getInheritanceDepth(Model model) {
int inheritanceDepth = 0;
Model parent = getParent(model);
while (parent != null) {
inheritanceDepth++;
parent = getParent(parent);
}
return inheritanceDepth;
}
private Model getParent(Model model) {
if (model instanceof ComposedModel) {
return definitions.get(((ComposedModel) model).getParent().getReference());
}
return null;
}
};
Collections.sort(sortedModelKeys, cmp);
return sortedModelKeys;
}
public Map<String, List<CodegenOperation>> processPaths(Map<String, Path> paths) { public Map<String, List<CodegenOperation>> processPaths(Map<String, Path> paths) {
Map<String, List<CodegenOperation>> ops = new HashMap<String, List<CodegenOperation>>(); Map<String, List<CodegenOperation>> ops = new TreeMap<String, List<CodegenOperation>>();
for (String resourcePath : paths.keySet()) { for (String resourcePath : paths.keySet()) {
Path path = paths.get(resourcePath); Path path = paths.get(resourcePath);

View File

@ -60,6 +60,10 @@ public class CodegenConfigurator {
private Map<String, String> additionalProperties = new HashMap<String, String>(); private Map<String, String> additionalProperties = new HashMap<String, String>();
private Map<String, String> importMappings = new HashMap<String, String>(); private Map<String, String> importMappings = new HashMap<String, String>();
private Set<String> languageSpecificPrimitives = new HashSet<String>(); private Set<String> languageSpecificPrimitives = new HashSet<String>();
private String gitUserId="YOUR_GIT_USR_ID";
private String gitRepoId="YOUR_GIT_REPO_ID";
private String releaseNote="Minor update";
private String httpUserAgent;
private final Map<String, String> dynamicProperties = new HashMap<String, String>(); //the map that holds the JsonAnySetter/JsonAnyGetter values private final Map<String, String> dynamicProperties = new HashMap<String, String>(); //the map that holds the JsonAnySetter/JsonAnyGetter values
@ -295,6 +299,42 @@ public class CodegenConfigurator {
return this; return this;
} }
public String getGitUserId() {
return gitUserId;
}
public CodegenConfigurator setGitUserId(String gitUserId) {
this.gitUserId = gitUserId;
return this;
}
public String getGitRepoId() {
return gitRepoId;
}
public CodegenConfigurator setGitRepoId(String gitRepoId) {
this.gitRepoId = gitRepoId;
return this;
}
public String getReleaseNote() {
return releaseNote;
}
public CodegenConfigurator setReleaseNote(String releaseNote) {
this.releaseNote = releaseNote;
return this;
}
public String getHttpUserAgent() {
return httpUserAgent;
}
public CodegenConfigurator setHttpUserAgent(String httpUserAgent) {
this.httpUserAgent= httpUserAgent;
return this;
}
public ClientOptInput toClientOptInput() { public ClientOptInput toClientOptInput() {
Validate.notEmpty(lang, "language must be specified"); Validate.notEmpty(lang, "language must be specified");
@ -322,6 +362,10 @@ public class CodegenConfigurator {
checkAndSetAdditionalProperty(templateDir, toAbsolutePathStr(templateDir), CodegenConstants.TEMPLATE_DIR); checkAndSetAdditionalProperty(templateDir, toAbsolutePathStr(templateDir), CodegenConstants.TEMPLATE_DIR);
checkAndSetAdditionalProperty(modelNamePrefix, CodegenConstants.MODEL_NAME_PREFIX); checkAndSetAdditionalProperty(modelNamePrefix, CodegenConstants.MODEL_NAME_PREFIX);
checkAndSetAdditionalProperty(modelNameSuffix, CodegenConstants.MODEL_NAME_SUFFIX); checkAndSetAdditionalProperty(modelNameSuffix, CodegenConstants.MODEL_NAME_SUFFIX);
checkAndSetAdditionalProperty(gitUserId, CodegenConstants.GIT_USER_ID);
checkAndSetAdditionalProperty(gitRepoId, CodegenConstants.GIT_REPO_ID);
checkAndSetAdditionalProperty(releaseNote, CodegenConstants.RELEASE_NOTE);
checkAndSetAdditionalProperty(httpUserAgent, CodegenConstants.HTTP_USER_AGENT);
handleDynamicProperties(config); handleDynamicProperties(config);

View File

@ -101,6 +101,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
typeMapping = new HashMap<String, String>(); typeMapping = new HashMap<String, String>();
typeMapping.put("string", "string"); typeMapping.put("string", "string");
typeMapping.put("binary", "byte[]"); typeMapping.put("binary", "byte[]");
typeMapping.put("bytearray", "byte[]");
typeMapping.put("boolean", "bool?"); typeMapping.put("boolean", "bool?");
typeMapping.put("integer", "int?"); typeMapping.put("integer", "int?");
typeMapping.put("float", "float?"); typeMapping.put("float", "float?");
@ -435,7 +436,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
} else if (p instanceof FloatProperty) { } else if (p instanceof FloatProperty) {
FloatProperty dp = (FloatProperty) p; FloatProperty dp = (FloatProperty) p;
if (dp.getDefault() != null) { if (dp.getDefault() != null) {
return dp.getDefault().toString(); return String.format("%1$sF", dp.getDefault());
} }
} else if (p instanceof IntegerProperty) { } else if (p instanceof IntegerProperty) {
IntegerProperty dp = (IntegerProperty) p; IntegerProperty dp = (IntegerProperty) p;
@ -500,6 +501,12 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
name = "model_" + name; // e.g. return => ModelReturn (after camelize) name = "model_" + name; // e.g. return => ModelReturn (after camelize)
} }
// model name starts with number
if (name.matches("^\\d.*")) {
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name));
name = "model_" + name; // e.g. 200Response => Model200Response (after camelize)
}
// camelize the model name // camelize the model name
// phone_number => PhoneNumber // phone_number => PhoneNumber
return camelize(name); return camelize(name);

View File

@ -1,6 +1,7 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.CodegenOperation; import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenResponse; import io.swagger.codegen.CodegenResponse;
import io.swagger.codegen.CodegenType; import io.swagger.codegen.CodegenType;
import io.swagger.models.Operation; import io.swagger.models.Operation;
@ -95,6 +96,25 @@ public abstract class AbstractJavaJAXRSServerCodegen extends JavaClientCodegen
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation"); List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
for ( CodegenOperation operation : ops ) { for ( CodegenOperation operation : ops ) {
boolean isMultipartPost = false;
List<Map<String, String>> consumes = operation.consumes;
if(consumes != null) {
for(Map<String, String> consume : consumes) {
String mt = consume.get("mediaType");
if(mt != null) {
if(mt.startsWith("multipart/form-data")) {
isMultipartPost = true;
}
}
}
}
for(CodegenParameter parameter : operation.allParams) {
if(isMultipartPost) {
parameter.vendorExtensions.put("x-multipart", "true");
}
}
List<CodegenResponse> responses = operation.responses; List<CodegenResponse> responses = operation.responses;
if ( responses != null ) { if ( responses != null ) {
for ( CodegenResponse resp : responses ) { for ( CodegenResponse resp : responses ) {

View File

@ -139,6 +139,13 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
return modelName; return modelName;
} }
// model name starts with number
if (name.matches("^\\d.*")) {
String modelName = camelize("model_" + name); // e.g. 200Response => Model200Response (after camelize)
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName);
return modelName;
}
// camelize the model name // camelize the model name
// phone_number => PhoneNumber // phone_number => PhoneNumber
return camelize(name); return camelize(name);

View File

@ -157,6 +157,9 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
@Override @Override
public String toVarName(String name) { public String toVarName(String name) {
// sanitize name
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// replace - with _ e.g. created-at => created_at // replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
@ -205,6 +208,13 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
return modelName; return modelName;
} }
// model name starts with number
if (name.matches("^\\d.*")) {
String modelName = "Model" + name; // e.g. 200Response => Model200Response (after camelize)
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName);
return modelName;
}
return name; return name;
} }
@ -302,6 +312,8 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
(sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "ApiException.java")); (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "ApiException.java"));
supportingFiles.add(new SupportingFile("Pair.mustache", supportingFiles.add(new SupportingFile("Pair.mustache",
(sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "Pair.java")); (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "Pair.java"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
} }
private void addSupportingFilesForVolley() { private void addSupportingFilesForVolley() {

View File

@ -34,6 +34,7 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
private static final Logger LOGGER = LoggerFactory.getLogger(CSharpClientCodegen.class); private static final Logger LOGGER = LoggerFactory.getLogger(CSharpClientCodegen.class);
private static final String NET45 = "v4.5"; private static final String NET45 = "v4.5";
private static final String NET35 = "v3.5"; private static final String NET35 = "v3.5";
private static final String DATA_TYPE_WITH_ENUM_EXTENSION = "plainDatatypeWithEnum";
protected String packageGuid = "{" + java.util.UUID.randomUUID().toString().toUpperCase() + "}"; protected String packageGuid = "{" + java.util.UUID.randomUUID().toString().toUpperCase() + "}";
protected String packageTitle = "Swagger Library"; protected String packageTitle = "Swagger Library";
@ -209,6 +210,9 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
supportingFiles.add(new SupportingFile("compile-mono.sh.mustache", "", "compile-mono.sh")); supportingFiles.add(new SupportingFile("compile-mono.sh.mustache", "", "compile-mono.sh"));
supportingFiles.add(new SupportingFile("packages.config.mustache", "vendor" + java.io.File.separator, "packages.config")); supportingFiles.add(new SupportingFile("packages.config.mustache", "vendor" + java.io.File.separator, "packages.config"));
supportingFiles.add(new SupportingFile("README.md", "", "README.md")); supportingFiles.add(new SupportingFile("README.md", "", "README.md"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
if (optionalAssemblyInfoFlag) { if (optionalAssemblyInfoFlag) {
supportingFiles.add(new SupportingFile("AssemblyInfo.mustache", packageFolder + File.separator + "Properties", "AssemblyInfo.cs")); supportingFiles.add(new SupportingFile("AssemblyInfo.mustache", packageFolder + File.separator + "Properties", "AssemblyInfo.cs"));
@ -285,7 +289,9 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
} }
@Override @Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) { public Map<String, Object> postProcessModels(Map<String, Object> objMap) {
Map<String, Object> objs = super.postProcessModels(objMap);
List<Object> models = (List<Object>) objs.get("models"); List<Object> models = (List<Object>) objs.get("models");
for (Object _mo : models) { for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo; Map<String, Object> mo = (Map<String, Object>) _mo;
@ -328,23 +334,27 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
} }
allowableValues.put("enumVars", enumVars); allowableValues.put("enumVars", enumVars);
// handle default value for enum, e.g. available => StatusEnum.AVAILABLE // handle default value for enum, e.g. available => StatusEnum.AVAILABLE
// HACK: strip ? from enum
if (var.datatypeWithEnum != null) {
var.vendorExtensions.put(DATA_TYPE_WITH_ENUM_EXTENSION, var.datatypeWithEnum.substring(0, var.datatypeWithEnum.length() - 1));
}
if (var.defaultValue != null) { if (var.defaultValue != null) {
String enumName = null; String enumName = null;
for (Map<String, String> enumVar : enumVars) { for (Map<String, String> enumVar : enumVars) {
if (var.defaultValue.equals(enumVar.get("value"))) {
if (var.defaultValue.replace("\"", "").equals(enumVar.get("value"))) {
enumName = enumVar.get("name"); enumName = enumVar.get("name");
break; break;
} }
} }
if (enumName != null) { if (enumName != null && var.vendorExtensions.containsKey(DATA_TYPE_WITH_ENUM_EXTENSION)) {
var.defaultValue = var.datatypeWithEnum + "." + enumName; var.defaultValue = var.vendorExtensions.get(DATA_TYPE_WITH_ENUM_EXTENSION) + "." + enumName;
} }
} }
// HACK: strip ? from enum
if (var.datatypeWithEnum != null) {
var.vendorExtensions.put("plainDatatypeWithEnum", var.datatypeWithEnum.substring(0, var.datatypeWithEnum.length() - 1));
}
} }
} }

View File

@ -143,6 +143,8 @@ public class ClojureClientCodegen extends DefaultCodegen implements CodegenConfi
final String baseNamespaceFolder = sourceFolder + File.separator + namespaceToFolder(baseNamespace); final String baseNamespaceFolder = sourceFolder + File.separator + namespaceToFolder(baseNamespace);
supportingFiles.add(new SupportingFile("project.mustache", "", "project.clj")); supportingFiles.add(new SupportingFile("project.mustache", "", "project.clj"));
supportingFiles.add(new SupportingFile("core.mustache", baseNamespaceFolder, "core.clj")); supportingFiles.add(new SupportingFile("core.mustache", baseNamespaceFolder, "core.clj"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
} }
@Override @Override

View File

@ -52,9 +52,8 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
Arrays.asList( Arrays.asList(
"String", "String",
"bool", "bool",
"num",
"int", "int",
"float") "double")
); );
instantiationTypes.put("array", "List"); instantiationTypes.put("array", "List");
instantiationTypes.put("map", "Map"); instantiationTypes.put("map", "Map");
@ -66,11 +65,11 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
typeMapping.put("boolean", "bool"); typeMapping.put("boolean", "bool");
typeMapping.put("string", "String"); typeMapping.put("string", "String");
typeMapping.put("int", "int"); typeMapping.put("int", "int");
typeMapping.put("float", "num"); typeMapping.put("float", "double");
typeMapping.put("long", "int"); typeMapping.put("long", "int");
typeMapping.put("short", "int"); typeMapping.put("short", "int");
typeMapping.put("char", "String"); typeMapping.put("char", "String");
typeMapping.put("double", "num"); typeMapping.put("double", "double");
typeMapping.put("object", "Object"); typeMapping.put("object", "Object");
typeMapping.put("integer", "int"); typeMapping.put("integer", "int");
typeMapping.put("Date", "DateTime"); typeMapping.put("Date", "DateTime");
@ -150,6 +149,9 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("auth/http_basic_auth.mustache", authFolder, "http_basic_auth.dart")); supportingFiles.add(new SupportingFile("auth/http_basic_auth.mustache", authFolder, "http_basic_auth.dart"));
supportingFiles.add(new SupportingFile("auth/api_key_auth.mustache", authFolder, "api_key_auth.dart")); supportingFiles.add(new SupportingFile("auth/api_key_auth.mustache", authFolder, "api_key_auth.dart"));
supportingFiles.add(new SupportingFile("auth/oauth.mustache", authFolder, "oauth.dart")); supportingFiles.add(new SupportingFile("auth/oauth.mustache", authFolder, "oauth.dart"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
} }

View File

@ -153,6 +153,8 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig
+ File.separator + "lib" + File.separator + "ext", "flexunit-cilistener-4.1.0_RC2-28-3.5.0.12683.swc")); + File.separator + "lib" + File.separator + "ext", "flexunit-cilistener-4.1.0_RC2-28-3.5.0.12683.swc"));
supportingFiles.add(new SupportingFile("flexunit-core-flex-4.0.0.2-sdk3.5.0.12683.swc", sourceFolder supportingFiles.add(new SupportingFile("flexunit-core-flex-4.0.0.2-sdk3.5.0.12683.swc", sourceFolder
+ File.separator + "lib" + File.separator + "ext", "flexunit-core-flex-4.0.0.2-sdk3.5.0.12683.swc")); + File.separator + "lib" + File.separator + "ext", "flexunit-core-flex-4.0.0.2-sdk3.5.0.12683.swc"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
} }
private static String dropDots(String str) { private static String dropDots(String str) {

View File

@ -129,6 +129,9 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
apiPackage = packageName; apiPackage = packageName;
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
supportingFiles.add(new SupportingFile("configuration.mustache", packageName, "Configuration.go"));
} }
@Override @Override

View File

@ -42,6 +42,8 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
protected Boolean serializableModel = false; protected Boolean serializableModel = false;
protected boolean serializeBigDecimalAsString = false; protected boolean serializeBigDecimalAsString = false;
protected boolean useRxJava = false; protected boolean useRxJava = false;
protected boolean hideGenerationTimestamp = false;
public JavaClientCodegen() { public JavaClientCodegen() {
super(); super();
@ -99,6 +101,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
.SERIALIZE_BIG_DECIMAL_AS_STRING_DESC)); .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"));
cliOptions.add(CliOption.newBoolean(USE_RX_JAVA, "Whether to use the RxJava adapter with the retrofit2 library.")); cliOptions.add(CliOption.newBoolean(USE_RX_JAVA, "Whether to use the RxJava adapter with the retrofit2 library."));
cliOptions.add(new CliOption("hideGenerationTimestamp", "hides the timestamp when files were generated"));
supportedLibraries.put(DEFAULT_LIBRARY, "HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2"); supportedLibraries.put(DEFAULT_LIBRARY, "HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2");
supportedLibraries.put("feign", "HTTP client: Netflix Feign 8.1.1"); supportedLibraries.put("feign", "HTTP client: Netflix Feign 8.1.1");
@ -301,6 +304,10 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
importMapping.put("LocalDate", "java.time.LocalDate"); importMapping.put("LocalDate", "java.time.LocalDate");
importMapping.put("LocalDateTime", "java.time.LocalDateTime"); importMapping.put("LocalDateTime", "java.time.LocalDateTime");
} }
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
} }
private boolean usesAnyRetrofitLibrary() { private boolean usesAnyRetrofitLibrary() {
@ -393,6 +400,13 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
return modelName; return modelName;
} }
// model name starts with number
if (name.matches("^\\d.*")) {
final String modelName = "Model" + camelizedName; // e.g. 200Response => Model200Response (after camelize)
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName);
return modelName;
}
return camelizedName; return camelizedName;
} }
@ -525,7 +539,9 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override @Override
public CodegenModel fromModel(String name, Model model, Map<String, Model> allDefinitions) { public CodegenModel fromModel(String name, Model model, Map<String, Model> allDefinitions) {
CodegenModel codegenModel = super.fromModel(name, model, allDefinitions); CodegenModel codegenModel = super.fromModel(name, model, allDefinitions);
if(codegenModel.description != null) {
codegenModel.imports.add("ApiModel");
}
if (allDefinitions != null && codegenModel != null && codegenModel.parentSchema != null && codegenModel.hasEnums) { if (allDefinitions != null && codegenModel != null && codegenModel.parentSchema != null && codegenModel.hasEnums) {
final Model parentModel = allDefinitions.get(codegenModel.parentSchema); final Model parentModel = allDefinitions.get(codegenModel.parentSchema);
final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel); final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel);
@ -584,6 +600,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
for (Object _mo : models) { for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo; Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model"); CodegenModel cm = (CodegenModel) mo.get("model");
for (CodegenProperty var : cm.vars) { for (CodegenProperty var : cm.vars) {
Map<String, Object> allowableValues = var.allowableValues; Map<String, Object> allowableValues = var.allowableValues;

View File

@ -83,21 +83,6 @@ public class JavaInflectorServerCodegen extends JavaClientCodegen {
(sourceFolder + '/' + invokerPackage).replace(".", "/"), "StringUtil.java")); (sourceFolder + '/' + invokerPackage).replace(".", "/"), "StringUtil.java"));
} }
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getTypeDeclaration(inner);
}
return super.getTypeDeclaration(p);
}
@Override @Override
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) { public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
String basePath = resourcePath; String basePath = resourcePath;

View File

@ -6,11 +6,8 @@ import io.swagger.models.Operation;
import java.io.File; import java.io.File;
import java.util.*; import java.util.*;
public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen {
{ public JavaJerseyServerCodegen() {
public JavaJerseyServerCodegen()
{
super(); super();
sourceFolder = "src/gen/java"; sourceFolder = "src/gen/java";
@ -43,6 +40,7 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen
Map<String, String> supportedLibraries = new LinkedHashMap<String, String>(); Map<String, String> supportedLibraries = new LinkedHashMap<String, String>();
supportedLibraries.put(DEFAULT_LIBRARY, "Jersey core 1.18.1"); supportedLibraries.put(DEFAULT_LIBRARY, "Jersey core 1.18.1");
supportedLibraries.put("jersey2", "Jersey core 2.x");
library.setEnum(supportedLibraries); library.setEnum(supportedLibraries);
cliOptions.add(library); cliOptions.add(library);
@ -85,6 +83,9 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen
supportingFiles.add(new SupportingFile("ApiOriginFilter.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiOriginFilter.java")); supportingFiles.add(new SupportingFile("ApiOriginFilter.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiOriginFilter.java"));
supportingFiles.add(new SupportingFile("ApiResponseMessage.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiResponseMessage.java")); supportingFiles.add(new SupportingFile("ApiResponseMessage.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiResponseMessage.java"));
supportingFiles.add(new SupportingFile("NotFoundException.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "NotFoundException.java")); supportingFiles.add(new SupportingFile("NotFoundException.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "NotFoundException.java"));
supportingFiles.add(new SupportingFile("jacksonJsonProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JacksonJsonProvider.java"));
writeOptional(outputFolder, new SupportingFile("bootstrap.mustache", (implFolder + '/' + apiPackage).replace(".", "/"), "Bootstrap.java"));
writeOptional(outputFolder, new SupportingFile("web.mustache", ("src/main/webapp/WEB-INF"), "web.xml")); writeOptional(outputFolder, new SupportingFile("web.mustache", ("src/main/webapp/WEB-INF"), "web.xml"));
supportingFiles.add(new SupportingFile("StringUtil.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "StringUtil.java")); supportingFiles.add(new SupportingFile("StringUtil.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "StringUtil.java"));
@ -92,6 +93,24 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen
setDateLibrary(additionalProperties.get("dateLibrary").toString()); setDateLibrary(additionalProperties.get("dateLibrary").toString());
additionalProperties.put(dateLibrary, "true"); additionalProperties.put(dateLibrary, "true");
} }
if(DEFAULT_LIBRARY.equals(library) || library == null) {
if(templateDir.startsWith(JAXRS_TEMPLATE_DIRECTORY_NAME)) {
// set to the default location
templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "jersey1_18";
}
else {
templateDir += File.separator + "jersey1_18";
}
}
if("jersey2".equals(library)) {
if(templateDir.startsWith(JAXRS_TEMPLATE_DIRECTORY_NAME)) {
// set to the default location
templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "jersey2";
}
else {
templateDir += File.separator + "jersey2";
}
}
if ( "joda".equals(dateLibrary) ) { if ( "joda".equals(dateLibrary) ) {
supportingFiles.add(new SupportingFile("JodaDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaDateTimeProvider.java")); supportingFiles.add(new SupportingFile("JodaDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaDateTimeProvider.java"));
@ -129,4 +148,8 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen
opList.add(co); opList.add(co);
co.baseName = basePath; co.baseName = basePath;
} }
public void hideGenerationTimestamp(boolean hideGenerationTimestamp) {
this.hideGenerationTimestamp = hideGenerationTimestamp;
}
} }

View File

@ -47,23 +47,29 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
@SuppressWarnings("hiding") @SuppressWarnings("hiding")
private static final Logger LOGGER = LoggerFactory.getLogger(JavascriptClientCodegen.class); private static final Logger LOGGER = LoggerFactory.getLogger(JavascriptClientCodegen.class);
private static final String PROJECT_NAME = "projectName"; public static final String PROJECT_NAME = "projectName";
private static final String MODULE_NAME = "moduleName"; public static final String MODULE_NAME = "moduleName";
private static final String PROJECT_DESCRIPTION = "projectDescription"; public static final String PROJECT_DESCRIPTION = "projectDescription";
private static final String PROJECT_VERSION = "projectVersion"; public static final String PROJECT_VERSION = "projectVersion";
private static final String PROJECT_LICENSE_NAME = "projectLicenseName"; public static final String PROJECT_LICENSE_NAME = "projectLicenseName";
private static final String USE_PROMISES = "usePromises"; public static final String USE_PROMISES = "usePromises";
private static final String OMIT_MODEL_METHODS = "omitModelMethods"; public static final String USE_INHERITANCE = "useInheritance";
public static final String EMIT_MODEL_METHODS = "emitModelMethods";
public static final String EMIT_JS_DOC = "emitJSDoc";
protected String projectName; protected String projectName;
protected String moduleName; protected String moduleName;
protected String projectDescription; protected String projectDescription;
protected String projectVersion; protected String projectVersion;
protected String projectLicenseName;
protected String sourceFolder = "src"; protected String sourceFolder = "src";
protected String localVariablePrefix = ""; protected String localVariablePrefix = "";
protected boolean usePromises = false; protected boolean usePromises;
protected boolean omitModelMethods = false; protected boolean emitModelMethods;
protected boolean emitJSDoc = true;
protected String apiDocPath = "docs/";
protected String modelDocPath = "docs/";
public JavascriptClientCodegen() { public JavascriptClientCodegen() {
super(); super();
@ -73,6 +79,8 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
templateDir = "Javascript"; templateDir = "Javascript";
apiPackage = "api"; apiPackage = "api";
modelPackage = "model"; modelPackage = "model";
modelDocTemplateFiles.put("model_doc.mustache", ".md");
apiDocTemplateFiles.put("api_doc.mustache", ".md");
// reference: http://www.w3schools.com/js/js_reserved.asp // reference: http://www.w3schools.com/js/js_reserved.asp
setReservedWordsLowerCase( setReservedWordsLowerCase(
@ -101,8 +109,36 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
); );
defaultIncludes = new HashSet<String>(languageSpecificPrimitives); defaultIncludes = new HashSet<String>(languageSpecificPrimitives);
instantiationTypes.put("array", "Array");
instantiationTypes.put("list", "Array");
instantiationTypes.put("map", "Object");
typeMapping.clear();
typeMapping.put("array", "Array");
typeMapping.put("map", "Object");
typeMapping.put("List", "Array");
typeMapping.put("boolean", "Boolean");
typeMapping.put("string", "String");
typeMapping.put("int", "Integer"); // Huh? What is JS Integer?
typeMapping.put("float", "Number");
typeMapping.put("number", "Number");
typeMapping.put("DateTime", "Date"); // Should this be dateTime?
typeMapping.put("Date", "Date"); // Should this be date?
typeMapping.put("long", "Integer");
typeMapping.put("short", "Integer");
typeMapping.put("char", "String");
typeMapping.put("double", "Number");
typeMapping.put("object", "Object");
typeMapping.put("integer", "Integer");
// binary not supported in JavaScript client right now, using String as a workaround
typeMapping.put("ByteArray", "String"); // I don't see ByteArray defined in the Swagger docs.
typeMapping.put("binary", "String");
importMapping.clear();
cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC).defaultValue("src")); cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC).defaultValue("src"));
cliOptions.add(new CliOption(CodegenConstants.LOCAL_VARIABLE_PREFIX, CodegenConstants.LOCAL_VARIABLE_PREFIX_DESC)); cliOptions.add(new CliOption(CodegenConstants.LOCAL_VARIABLE_PREFIX, CodegenConstants.LOCAL_VARIABLE_PREFIX_DESC));
cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC));
cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC));
cliOptions.add(new CliOption(PROJECT_NAME, cliOptions.add(new CliOption(PROJECT_NAME,
"name of the project (Default: generated from info.title or \"swagger-js-client\")")); "name of the project (Default: generated from info.title or \"swagger-js-client\")"));
cliOptions.add(new CliOption(MODULE_NAME, cliOptions.add(new CliOption(MODULE_NAME,
@ -116,9 +152,15 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
cliOptions.add(new CliOption(USE_PROMISES, cliOptions.add(new CliOption(USE_PROMISES,
"use Promises as return values from the client API, instead of superagent callbacks") "use Promises as return values from the client API, instead of superagent callbacks")
.defaultValue(Boolean.FALSE.toString())); .defaultValue(Boolean.FALSE.toString()));
cliOptions.add(new CliOption(OMIT_MODEL_METHODS, cliOptions.add(new CliOption(EMIT_MODEL_METHODS,
"omits generation of getters and setters for model classes") "generate getters and setters for model properties")
.defaultValue(Boolean.FALSE.toString())); .defaultValue(Boolean.FALSE.toString()));
cliOptions.add(new CliOption(EMIT_JS_DOC,
"generate JSDoc comments")
.defaultValue(Boolean.TRUE.toString()));
cliOptions.add(new CliOption(USE_INHERITANCE,
"use JavaScript prototype chains & delegation for inheritance")
.defaultValue(Boolean.TRUE.toString()));
} }
@Override @Override
@ -140,59 +182,47 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
public void processOpts() { public void processOpts() {
super.processOpts(); super.processOpts();
typeMapping = new HashMap<String, String>(); if (additionalProperties.containsKey(PROJECT_NAME)) {
typeMapping.put("array", "Array"); setProjectName(((String) additionalProperties.get(PROJECT_NAME)));
typeMapping.put("List", "Array"); }
typeMapping.put("map", "Object"); if (additionalProperties.containsKey(MODULE_NAME)) {
typeMapping.put("object", "Object"); setModuleName(((String) additionalProperties.get(MODULE_NAME)));
typeMapping.put("boolean", "Boolean"); }
typeMapping.put("char", "String"); if (additionalProperties.containsKey(PROJECT_DESCRIPTION)) {
typeMapping.put("string", "String"); setProjectDescription(((String) additionalProperties.get(PROJECT_DESCRIPTION)));
typeMapping.put("short", "Integer"); }
typeMapping.put("int", "Integer"); if (additionalProperties.containsKey(PROJECT_VERSION)) {
typeMapping.put("integer", "Integer"); setProjectVersion(((String) additionalProperties.get(PROJECT_VERSION)));
typeMapping.put("long", "Integer"); }
typeMapping.put("float", "Number"); if (additionalProperties.containsKey(PROJECT_LICENSE_NAME)) {
typeMapping.put("double", "Number"); setProjectLicenseName(((String) additionalProperties.get(PROJECT_LICENSE_NAME)));
typeMapping.put("number", "Number"); }
typeMapping.put("DateTime", "Date"); if (additionalProperties.containsKey(CodegenConstants.LOCAL_VARIABLE_PREFIX)) {
typeMapping.put("Date", "Date"); setLocalVariablePrefix((String) additionalProperties.get(CodegenConstants.LOCAL_VARIABLE_PREFIX));
typeMapping.put("file", "File"); }
// binary not supported in JavaScript client right now, using String as a workaround if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) {
typeMapping.put("binary", "String"); setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER));
}
importMapping.clear(); if (additionalProperties.containsKey(USE_PROMISES)) {
setUsePromises(Boolean.parseBoolean((String)additionalProperties.get(USE_PROMISES)));
}
if (additionalProperties.containsKey(USE_INHERITANCE)) {
setUseInheritance(Boolean.parseBoolean((String)additionalProperties.get(USE_INHERITANCE)));
} else {
supportsInheritance = true;
}
if (additionalProperties.containsKey(EMIT_MODEL_METHODS)) {
setEmitModelMethods(Boolean.parseBoolean((String)additionalProperties.get(EMIT_MODEL_METHODS)));
}
if (additionalProperties.containsKey(EMIT_JS_DOC)) {
setEmitJSDoc(Boolean.parseBoolean((String)additionalProperties.get(EMIT_JS_DOC)));
}
} }
@Override @Override
public void preprocessSwagger(Swagger swagger) { public void preprocessSwagger(Swagger swagger) {
super.preprocessSwagger(swagger); super.preprocessSwagger(swagger);
if (additionalProperties.containsKey(PROJECT_NAME)) {
projectName = ((String) additionalProperties.get(PROJECT_NAME));
}
if (additionalProperties.containsKey(MODULE_NAME)) {
moduleName = ((String) additionalProperties.get(MODULE_NAME));
}
if (additionalProperties.containsKey(PROJECT_DESCRIPTION)) {
projectDescription = ((String) additionalProperties.get(PROJECT_DESCRIPTION));
}
if (additionalProperties.containsKey(PROJECT_VERSION)) {
projectVersion = ((String) additionalProperties.get(PROJECT_VERSION));
}
if (additionalProperties.containsKey(CodegenConstants.LOCAL_VARIABLE_PREFIX)) {
localVariablePrefix = (String) additionalProperties.get(CodegenConstants.LOCAL_VARIABLE_PREFIX);
}
if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) {
sourceFolder = (String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER);
}
if (additionalProperties.containsKey(USE_PROMISES)) {
usePromises = Boolean.parseBoolean((String)additionalProperties.get(USE_PROMISES));
}
if (additionalProperties.containsKey(OMIT_MODEL_METHODS)) {
omitModelMethods = Boolean.parseBoolean((String)additionalProperties.get(OMIT_MODEL_METHODS));
}
if (swagger.getInfo() != null) { if (swagger.getInfo() != null) {
Info info = swagger.getInfo(); Info info = swagger.getInfo();
if (StringUtils.isBlank(projectName) && info.getTitle() != null) { if (StringUtils.isBlank(projectName) && info.getTitle() != null) {
@ -207,9 +237,10 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
// when projectDescription is not specified, use info.description // when projectDescription is not specified, use info.description
projectDescription = info.getDescription(); projectDescription = info.getDescription();
} }
if (info.getLicense() != null) { if (additionalProperties.get(PROJECT_LICENSE_NAME) == null) {
License license = info.getLicense(); // when projectLicense is not specified, use info.license
if (additionalProperties.get(PROJECT_LICENSE_NAME) == null) { if (info.getLicense() != null) {
License license = info.getLicense();
additionalProperties.put(PROJECT_LICENSE_NAME, license.getName()); additionalProperties.put(PROJECT_LICENSE_NAME, license.getName());
} }
} }
@ -233,14 +264,24 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
additionalProperties.put(MODULE_NAME, moduleName); additionalProperties.put(MODULE_NAME, moduleName);
additionalProperties.put(PROJECT_DESCRIPTION, escapeText(projectDescription)); additionalProperties.put(PROJECT_DESCRIPTION, escapeText(projectDescription));
additionalProperties.put(PROJECT_VERSION, projectVersion); additionalProperties.put(PROJECT_VERSION, projectVersion);
additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage);
additionalProperties.put(CodegenConstants.LOCAL_VARIABLE_PREFIX, localVariablePrefix); additionalProperties.put(CodegenConstants.LOCAL_VARIABLE_PREFIX, localVariablePrefix);
additionalProperties.put(CodegenConstants.MODEL_PACKAGE, modelPackage);
additionalProperties.put(CodegenConstants.SOURCE_FOLDER, sourceFolder); additionalProperties.put(CodegenConstants.SOURCE_FOLDER, sourceFolder);
additionalProperties.put(USE_PROMISES, usePromises); additionalProperties.put(USE_PROMISES, usePromises);
additionalProperties.put(OMIT_MODEL_METHODS, omitModelMethods); additionalProperties.put(USE_INHERITANCE, supportsInheritance);
additionalProperties.put(EMIT_MODEL_METHODS, emitModelMethods);
additionalProperties.put(EMIT_JS_DOC, emitJSDoc);
// make api and model doc path available in mustache template
additionalProperties.put("apiDocPath", apiDocPath);
additionalProperties.put("modelDocPath", modelDocPath);
supportingFiles.add(new SupportingFile("package.mustache", "", "package.json")); supportingFiles.add(new SupportingFile("package.mustache", "", "package.json"));
supportingFiles.add(new SupportingFile("index.mustache", sourceFolder, "index.js")); supportingFiles.add(new SupportingFile("index.mustache", sourceFolder, "index.js"));
supportingFiles.add(new SupportingFile("ApiClient.mustache", sourceFolder, "ApiClient.js")); supportingFiles.add(new SupportingFile("ApiClient.mustache", sourceFolder, "ApiClient.js"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
} }
@Override @Override
@ -250,12 +291,76 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
@Override @Override
public String apiFileFolder() { public String apiFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); return outputFolder + '/' + sourceFolder + '/' + apiPackage().replace('.', '/');
} }
@Override @Override
public String modelFileFolder() { public String modelFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); return outputFolder + '/' + sourceFolder + '/' + modelPackage().replace('.', '/');
}
public void setSourceFolder(String sourceFolder) {
this.sourceFolder = sourceFolder;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public void setLocalVariablePrefix(String localVariablePrefix) {
this.localVariablePrefix = localVariablePrefix;
}
public void setModuleName(String moduleName) {
this.moduleName = moduleName;
}
public void setProjectDescription(String projectDescription) {
this.projectDescription = projectDescription;
}
public void setProjectVersion(String projectVersion) {
this.projectVersion = projectVersion;
}
public void setProjectLicenseName(String projectLicenseName) {
this.projectLicenseName = projectLicenseName;
}
public void setUsePromises(boolean usePromises) {
this.usePromises = usePromises;
}
public void setUseInheritance(boolean useInheritance) {
this.supportsInheritance = useInheritance;
}
public void setEmitModelMethods(boolean emitModelMethods) {
this.emitModelMethods = emitModelMethods;
}
public void setEmitJSDoc(boolean emitJSDoc) {
this.emitJSDoc = emitJSDoc;
}
@Override
public String apiDocFileFolder() {
return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar);
}
@Override
public String modelDocFileFolder() {
return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar);
}
@Override
public String toApiDocFilename(String name) {
return toApiName(name);
}
@Override
public String toModelDocFilename(String name) {
return toModelName(name);
} }
@Override @Override
@ -313,6 +418,13 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
return modelName; return modelName;
} }
// model name starts with number
if (name.matches("^\\d.*")) {
String modelName = "Model" + name; // e.g. 200Response => Model200Response (after camelize)
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName);
return modelName;
}
return name; return name;
} }
@ -397,6 +509,84 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
} }
} }
@Override
public void setParameterExampleValue(CodegenParameter p) {
String example;
if (p.defaultValue == null) {
example = p.example;
} else {
example = p.defaultValue;
}
String type = p.baseType;
if (type == null) {
type = p.dataType;
}
typeMapping.put("array", "Array");
typeMapping.put("List", "Array");
typeMapping.put("map", "Object");
typeMapping.put("object", "Object");
typeMapping.put("boolean", "Boolean");
typeMapping.put("char", "String");
typeMapping.put("string", "String");
typeMapping.put("short", "Integer");
typeMapping.put("int", "Integer");
typeMapping.put("integer", "Integer");
typeMapping.put("long", "Integer");
typeMapping.put("float", "Number");
typeMapping.put("double", "Number");
typeMapping.put("number", "Number");
typeMapping.put("DateTime", "Date");
typeMapping.put("Date", "Date");
typeMapping.put("file", "File");
// binary not supported in JavaScript client right now, using String as a workaround
typeMapping.put("binary", "String");
if ("String".equals(type)) {
if (example == null) {
example = p.paramName + "_example";
}
example = "\"" + escapeText(example) + "\"";
} else if ("Integer".equals(type)) {
if (example == null) {
example = "56";
}
} else if ("Number".equals(type)) {
if (example == null) {
example = "3.4";
}
} else if ("Boolean".equals(type)) {
if (example == null) {
example = "true";
}
} else if ("File".equals(type)) {
if (example == null) {
example = "/path/to/file";
}
example = "\"" + escapeText(example) + "\"";
} else if ("Date".equals(type)) {
if (example == null) {
example = "2013-10-20T19:20:30+01:00";
}
example = "new Date(\"" + escapeText(example) + "\")";
} else if (!languageSpecificPrimitives.contains(type)) {
// type is a model class, e.g. User
example = "new " + moduleName + "." + type + "()";
}
if (example == null) {
example = "null";
} else if (Boolean.TRUE.equals(p.isListContainer)) {
example = "[" + example + "]";
} else if (Boolean.TRUE.equals(p.isMapContainer)) {
example = "{key: " + example + "}";
}
p.example = example;
}
/** /**
* Normalize type by wrapping primitive types with single quotes. * Normalize type by wrapping primitive types with single quotes.
* *
@ -450,6 +640,32 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
if (op.returnType != null) { if (op.returnType != null) {
op.returnType = normalizeType(op.returnType); op.returnType = normalizeType(op.returnType);
} }
// Set vendor-extension to be used in template:
// x-codegen-hasMoreRequired
// x-codegen-hasMoreOptional
// x-codegen-hasRequiredParams
CodegenParameter lastRequired = null;
CodegenParameter lastOptional = null;
for (CodegenParameter p : op.allParams) {
if (p.required != null && p.required) {
lastRequired = p;
} else {
lastOptional = p;
}
}
for (CodegenParameter p : op.allParams) {
if (p == lastRequired) {
p.vendorExtensions.put("x-codegen-hasMoreRequired", false);
} else if (p == lastOptional) {
p.vendorExtensions.put("x-codegen-hasMoreOptional", false);
} else {
p.vendorExtensions.put("x-codegen-hasMoreRequired", true);
p.vendorExtensions.put("x-codegen-hasMoreOptional", true);
}
}
op.vendorExtensions.put("x-codegen-hasRequiredParams", lastRequired != null);
return op; return op;
} }
@ -466,6 +682,92 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
return codegenModel; return codegenModel;
} }
private String trimBrackets(String s) {
if (s != null) {
int beginIdx = s.charAt(0) == '[' ? 1 : 0;
int endIdx = s.length();
if (s.charAt(endIdx - 1) == ']')
endIdx--;
return s.substring(beginIdx, endIdx);
}
return null;
}
private String getModelledType(String dataType) {
return "module:" + (StringUtils.isEmpty(modelPackage) ? "" : (modelPackage + "/")) + dataType;
}
private String getJSDocTypeWithBraces(CodegenModel cm, CodegenProperty cp) {
return "{" + getJSDocType(cm, cp) + "}";
}
private String getJSDocType(CodegenModel cm, CodegenProperty cp) {
if (Boolean.TRUE.equals(cp.isContainer)) {
if (cp.containerType.equals("array"))
return "Array.<" + getJSDocType(cm, cp.items) + ">";
else if (cp.containerType.equals("map"))
return "Object.<String, " + getJSDocType(cm, cp.items) + ">";
}
String dataType = trimBrackets(cp.datatypeWithEnum);
if (cp.isEnum) {
dataType = cm.classname + '.' + dataType;
}
if (isModelledType(cp))
dataType = getModelledType(dataType);
return dataType;
}
private boolean isModelledType(CodegenProperty cp) {
// N.B. enums count as modelled types, file is not modelled (SuperAgent uses some 3rd party library).
return cp.isEnum || !languageSpecificPrimitives.contains(cp.baseType == null ? cp.datatype : cp.baseType);
}
private String getJSDocTypeWithBraces(CodegenParameter cp) {
return "{" + getJSDocType(cp) + "}";
}
private String getJSDocType(CodegenParameter cp) {
String dataType = trimBrackets(cp.dataType);
if (isModelledType(cp))
dataType = getModelledType(dataType);
if (Boolean.TRUE.equals(cp.isListContainer)) {
return "Array.<" + dataType + ">";
} else if (Boolean.TRUE.equals(cp.isMapContainer)) {
return "Object.<String, " + dataType + ">";
}
return dataType;
}
private boolean isModelledType(CodegenParameter cp) {
// N.B. enums count as modelled types, file is not modelled (SuperAgent uses some 3rd party library).
return cp.isEnum || !languageSpecificPrimitives.contains(cp.baseType == null ? cp.dataType : cp.baseType);
}
private String getJSDocTypeWithBraces(CodegenOperation co) {
String jsDocType = getJSDocType(co);
return jsDocType == null ? null : "{" + jsDocType + "}";
}
private String getJSDocType(CodegenOperation co) {
String returnType = trimBrackets(co.returnType);
if (returnType != null) {
if (isModelledType(co))
returnType = getModelledType(returnType);
if (Boolean.TRUE.equals(co.isListContainer)) {
return "Array.<" + returnType + ">";
} else if (Boolean.TRUE.equals(co.isMapContainer)) {
return "Object.<String, " + returnType + ">";
}
}
return returnType;
}
private boolean isModelledType(CodegenOperation co) {
// This seems to be the only way to tell whether an operation return type is modelled.
return !Boolean.TRUE.equals(co.returnTypeIsPrimitive);
}
@SuppressWarnings("unchecked")
@Override @Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) { public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
// Generate and store argument list string of each operation into // Generate and store argument list string of each operation into
@ -474,7 +776,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
if (operations != null) { if (operations != null) {
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation"); List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation operation : ops) { for (CodegenOperation operation : ops) {
List<String> argList = new ArrayList(); List<String> argList = new ArrayList<String>();
boolean hasOptionalParams = false; boolean hasOptionalParams = false;
for (CodegenParameter p : operation.allParams) { for (CodegenParameter p : operation.allParams) {
if (p.required != null && p.required) { if (p.required != null && p.required) {
@ -490,20 +792,46 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
argList.add("callback"); argList.add("callback");
} }
operation.vendorExtensions.put("x-codegen-argList", StringUtils.join(argList, ", ")); operation.vendorExtensions.put("x-codegen-argList", StringUtils.join(argList, ", "));
// Store JSDoc type specification into vendor-extension: x-jsdoc-type.
for (CodegenParameter cp : operation.allParams) {
String jsdocType = getJSDocTypeWithBraces(cp);
cp.vendorExtensions.put("x-jsdoc-type", jsdocType);
}
String jsdocType = getJSDocTypeWithBraces(operation);
operation.vendorExtensions.put("x-jsdoc-type", jsdocType);
} }
} }
return objs; return objs;
} }
@SuppressWarnings("unchecked")
@Override @Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) { public Map<String, Object> postProcessModels(Map<String, Object> objs) {
List<Object> models = (List<Object>) objs.get("models"); List<Object> models = (List<Object>) objs.get("models");
for (Object _mo : models) { for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo; Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model"); CodegenModel cm = (CodegenModel) mo.get("model");
// 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;
cm.vendorExtensions.put("x-required", required);
cm.vendorExtensions.put("x-all-required", allRequired);
for (CodegenProperty var : cm.vars) { for (CodegenProperty var : cm.vars) {
Map<String, Object> allowableValues = var.allowableValues; Map<String, Object> allowableValues = var.allowableValues;
// Add JSDoc @type value for this property.
String jsDocType = getJSDocTypeWithBraces(cm, var);
var.vendorExtensions.put("x-jsdoc-type", jsDocType);
if (Boolean.TRUE.equals(var.required)) {
required.add(var.name);
}
// handle ArrayProperty // handle ArrayProperty
if (var.items != null) { if (var.items != null) {
allowableValues = var.items.allowableValues; allowableValues = var.items.allowableValues;
@ -538,6 +866,15 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
} }
allowableValues.put("enumVars", enumVars); allowableValues.put("enumVars", enumVars);
} }
if (supportsInheritance) {
for (CodegenProperty var : cm.allVars) {
if (Boolean.TRUE.equals(var.required)) {
allRequired.add(var.name);
}
}
}
// set vendor-extension: x-codegen-hasMoreRequired // set vendor-extension: x-codegen-hasMoreRequired
CodegenProperty lastRequired = null; CodegenProperty lastRequired = null;
for (CodegenProperty var : cm.vars) { for (CodegenProperty var : cm.vars) {

View File

@ -123,7 +123,7 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
*/ */
@Override @Override
public String getName() { public String getName() {
return "nodejs"; return "nodejs-server";
} }
/** /**
@ -278,7 +278,9 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
if(operation.getOperationId() == null) { if(operation.getOperationId() == null) {
operation.setOperationId(getOrGenerateOperationId(operation, pathname, method.toString())); operation.setOperationId(getOrGenerateOperationId(operation, pathname, method.toString()));
} }
operation.getVendorExtensions().put("x-swagger-router-controller", toApiName(tag)); if(operation.getVendorExtensions().get("x-swagger-router-controller") == null) {
operation.getVendorExtensions().put("x-swagger-router-controller", sanitizeTag(tag));
}
} }
} }
} }

View File

@ -4,6 +4,7 @@ import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenOperation; import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType; import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.DefaultCodegen;
@ -36,6 +37,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String license = "MIT"; protected String license = "MIT";
protected String gitRepoURL = "https://github.com/swagger-api/swagger-codegen"; protected String gitRepoURL = "https://github.com/swagger-api/swagger-codegen";
protected String[] specialWords = {"new", "copy"}; protected String[] specialWords = {"new", "copy"};
protected String apiDocPath = "docs/";
protected String modelDocPath = "docs/";
public ObjcClientCodegen() { public ObjcClientCodegen() {
super(); super();
@ -46,6 +49,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
apiTemplateFiles.put("api-header.mustache", ".h"); apiTemplateFiles.put("api-header.mustache", ".h");
apiTemplateFiles.put("api-body.mustache", ".m"); apiTemplateFiles.put("api-body.mustache", ".m");
embeddedTemplateDir = templateDir = "objc"; embeddedTemplateDir = templateDir = "objc";
modelDocTemplateFiles.put("model_doc.mustache", ".md");
apiDocTemplateFiles.put("api_doc.mustache", ".md");
defaultIncludes.clear(); defaultIncludes.clear();
defaultIncludes.add("bool"); defaultIncludes.add("bool");
@ -90,7 +95,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
//TODO binary should be mapped to byte array //TODO binary should be mapped to byte array
// mapped to String as a workaround // mapped to String as a workaround
typeMapping.put("binary", "NSString"); typeMapping.put("binary", "NSString");
typeMapping.put("ByteArray", "NSString");
// ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm // ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm
setReservedWordsLowerCase( setReservedWordsLowerCase(
@ -199,6 +204,10 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
additionalProperties.put(GIT_REPO_URL, gitRepoURL); additionalProperties.put(GIT_REPO_URL, gitRepoURL);
additionalProperties.put(LICENSE, license); additionalProperties.put(LICENSE, license);
// make api and model doc path available in mustache template
additionalProperties.put("apiDocPath", apiDocPath);
additionalProperties.put("modelDocPath", modelDocPath);
String swaggerFolder = podName; String swaggerFolder = podName;
modelPackage = swaggerFolder; modelPackage = swaggerFolder;
@ -220,6 +229,10 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("Configuration-header.mustache", swaggerFolder, classPrefix + "Configuration.h")); supportingFiles.add(new SupportingFile("Configuration-header.mustache", swaggerFolder, classPrefix + "Configuration.h"));
supportingFiles.add(new SupportingFile("podspec.mustache", "", podName + ".podspec")); supportingFiles.add(new SupportingFile("podspec.mustache", "", podName + ".podspec"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
} }
@Override @Override
@ -320,6 +333,14 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
type = "model_" + type; // e.g. return => ModelReturn (after camelize) type = "model_" + type; // e.g. return => ModelReturn (after camelize)
} }
// model name starts with number
/* no need for the fix below as objc model starts with prefix (e.g. SWG)
if (type.matches("^\\d.*")) {
LOGGER.warn(type + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + type));
type = "model_" + type; // e.g. 200Response => Model200Response (after camelize)
}
*/
return toModelNameWithoutReservedWordCheck(type); return toModelNameWithoutReservedWordCheck(type);
} }
@ -376,6 +397,26 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
return name; return name;
} }
@Override
public String apiDocFileFolder() {
return (outputFolder + "/" + apiDocPath).replace("/", File.separator);
}
@Override
public String modelDocFileFolder() {
return (outputFolder + "/" + modelDocPath).replace("/", File.separator);
}
@Override
public String toModelDocFilename(String name) {
return toModelName(name);
}
@Override
public String toApiDocFilename(String name) {
return toApiName(name);
}
@Override @Override
public String apiFileFolder() { public String apiFileFolder() {
return outputFolder + File.separatorChar + apiPackage(); return outputFolder + File.separatorChar + apiPackage();
@ -550,4 +591,75 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
return null; return null;
} }
@Override
public void setParameterExampleValue(CodegenParameter p) {
String example;
if (p.defaultValue == null) {
example = p.example;
} else {
example = p.defaultValue;
}
String type = p.baseType;
if (type == null) {
type = p.dataType;
}
if ("NSString*".equalsIgnoreCase(type)) {
if (example == null) {
example = p.paramName + "_example";
}
example = "@\"" + escapeText(example) + "\"";
} else if ("NSNumber*".equals(type)) {
if (example == null) {
example = "56";
}
example = "@" + example;
/* OBJC uses NSNumber to represent both int, long, double and float
} else if ("Float".equalsIgnoreCase(type) || "Double".equalsIgnoreCase(type)) {
if (example == null) {
example = "3.4";
} */
} else if ("BOOLEAN".equalsIgnoreCase(type) || "bool".equalsIgnoreCase(type)) {
if (example == null) {
example = "True";
}
} else if ("NSURL*".equalsIgnoreCase(type)) {
if (example == null) {
example = "/path/to/file";
}
//[NSURL fileURLWithPath:@"path/to/file"]
example = "[NSURL fileURLWithPath:@\"" + escapeText(example) + "\"]";
/*} else if ("NSDate".equalsIgnoreCase(type)) {
if (example == null) {
example = "2013-10-20";
}
example = "'" + escapeText(example) + "'";*/
} else if ("NSDate*".equalsIgnoreCase(type)) {
if (example == null) {
example = "2013-10-20T19:20:30+01:00";
}
example = "@\"" + escapeText(example) + "\"";
} else if (!languageSpecificPrimitives.contains(type)) {
// type is a model class, e.g. User
type = type.replace("*", "");
// e.g. [[SWGPet alloc] init
example = "[[" + type + " alloc] init]";
} else {
LOGGER.warn("Type " + type + " not handled properly in setParameterExampleValue");
}
if (example == null) {
example = "NULL";
} else if (Boolean.TRUE.equals(p.isListContainer)) {
example = "@[" + example + "]";
} else if (Boolean.TRUE.equals(p.isMapContainer)) {
example = "@{@\"key\" : " + example + "}";
}
p.example = example;
}
} }

View File

@ -1,6 +1,7 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenType; import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile; import io.swagger.codegen.SupportingFile;
@ -9,6 +10,17 @@ import io.swagger.codegen.CliOption;
import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property; import io.swagger.models.properties.Property;
import io.swagger.models.properties.StringProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.FloatProperty;
import io.swagger.models.properties.DoubleProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.BinaryProperty;
import io.swagger.models.properties.ByteArrayProperty;
import io.swagger.models.properties.DateTimeProperty;
import io.swagger.models.properties.DateProperty;
import java.io.File; import java.io.File;
import java.util.Arrays; import java.util.Arrays;
@ -23,6 +35,8 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String moduleName = "WWW::SwaggerClient"; protected String moduleName = "WWW::SwaggerClient";
protected String modulePathPart = moduleName.replaceAll("::", Matcher.quoteReplacement(File.separator)); protected String modulePathPart = moduleName.replaceAll("::", Matcher.quoteReplacement(File.separator));
protected String moduleVersion = "1.0.0"; protected String moduleVersion = "1.0.0";
protected String apiDocPath = "docs/";
protected String modelDocPath = "docs/";
protected static int emptyFunctionNameCounter = 0; protected static int emptyFunctionNameCounter = 0;
@ -34,6 +48,8 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
apiTemplateFiles.put("api.mustache", ".pm"); apiTemplateFiles.put("api.mustache", ".pm");
modelTestTemplateFiles.put("object_test.mustache", ".t"); modelTestTemplateFiles.put("object_test.mustache", ".t");
apiTestTemplateFiles.put("api_test.mustache", ".t"); apiTestTemplateFiles.put("api_test.mustache", ".t");
modelDocTemplateFiles.put("object_doc.mustache", ".md");
apiDocTemplateFiles.put("api_doc.mustache", ".md");
embeddedTemplateDir = templateDir = "perl"; embeddedTemplateDir = templateDir = "perl";
@ -108,6 +124,10 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
additionalProperties.put(MODULE_NAME, moduleName); additionalProperties.put(MODULE_NAME, moduleName);
} }
// make api and model doc path available in mustache template
additionalProperties.put("apiDocPath", apiDocPath);
additionalProperties.put("modelDocPath", modelDocPath);
supportingFiles.add(new SupportingFile("ApiClient.mustache", ("lib/" + modulePathPart).replace('/', File.separatorChar), "ApiClient.pm")); supportingFiles.add(new SupportingFile("ApiClient.mustache", ("lib/" + modulePathPart).replace('/', File.separatorChar), "ApiClient.pm"));
supportingFiles.add(new SupportingFile("Configuration.mustache", ("lib/" + modulePathPart).replace('/', File.separatorChar), "Configuration.pm")); supportingFiles.add(new SupportingFile("Configuration.mustache", ("lib/" + modulePathPart).replace('/', File.separatorChar), "Configuration.pm"));
supportingFiles.add(new SupportingFile("ApiFactory.mustache", ("lib/" + modulePathPart).replace('/', File.separatorChar), "ApiFactory.pm")); supportingFiles.add(new SupportingFile("ApiFactory.mustache", ("lib/" + modulePathPart).replace('/', File.separatorChar), "ApiFactory.pm"));
@ -115,6 +135,8 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("AutoDoc.mustache", ("lib/" + modulePathPart + "/Role").replace('/', File.separatorChar), "AutoDoc.pm")); supportingFiles.add(new SupportingFile("AutoDoc.mustache", ("lib/" + modulePathPart + "/Role").replace('/', File.separatorChar), "AutoDoc.pm"));
supportingFiles.add(new SupportingFile("autodoc.script.mustache", "bin", "autodoc")); supportingFiles.add(new SupportingFile("autodoc.script.mustache", "bin", "autodoc"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
} }
@Override @Override
@ -147,7 +169,6 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
return (outputFolder + "/lib/" + modulePathPart + modelPackage()).replace('/', File.separatorChar); return (outputFolder + "/lib/" + modulePathPart + modelPackage()).replace('/', File.separatorChar);
} }
@Override @Override
public String apiTestFileFolder() { public String apiTestFileFolder() {
return (outputFolder + "/t").replace('/', File.separatorChar); return (outputFolder + "/t").replace('/', File.separatorChar);
@ -158,6 +179,16 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
return (outputFolder + "/t").replace('/', File.separatorChar); return (outputFolder + "/t").replace('/', File.separatorChar);
} }
@Override
public String apiDocFileFolder() {
return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar);
}
@Override
public String modelDocFileFolder() {
return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar);
}
@Override @Override
public String getTypeDeclaration(Property p) { public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) { if (p instanceof ArrayProperty) {
@ -192,7 +223,43 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override @Override
public String toDefaultValue(Property p) { public String toDefaultValue(Property p) {
return "null"; if (p instanceof StringProperty) {
StringProperty dp = (StringProperty) p;
if (dp.getDefault() != null) {
return "'" + dp.getDefault().toString() + "'";
}
} else if (p instanceof BooleanProperty) {
BooleanProperty dp = (BooleanProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof DateProperty) {
// TODO
} else if (p instanceof DateTimeProperty) {
// TODO
} else if (p instanceof DoubleProperty) {
DoubleProperty dp = (DoubleProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof FloatProperty) {
FloatProperty dp = (FloatProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof IntegerProperty) {
IntegerProperty dp = (IntegerProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof LongProperty) {
LongProperty dp = (LongProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
}
return null;
} }
@ -226,6 +293,12 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
name = "model_" + name; name = "model_" + name;
} }
// model name starts with number
if (name.matches("^\\d.*")) {
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name));
name = "model_" + name; // e.g. 200Response => Model200Response (after camelize)
}
// add prefix/suffic to model name // add prefix/suffic to model name
if (!StringUtils.isEmpty(modelNamePrefix)) { if (!StringUtils.isEmpty(modelNamePrefix)) {
name = modelNamePrefix + "_" + name; name = modelNamePrefix + "_" + name;
@ -251,11 +324,21 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
return toModelFilename(name) + "Test"; return toModelFilename(name) + "Test";
} }
@Override
public String toModelDocFilename(String name) {
return toModelFilename(name);
}
@Override @Override
public String toApiTestFilename(String name) { public String toApiTestFilename(String name) {
return toApiFilename(name) + "Test"; return toApiFilename(name) + "Test";
} }
@Override
public String toApiDocFilename(String name) {
return toApiFilename(name);
}
@Override @Override
public String toApiFilename(String name) { public String toApiFilename(String name) {
// replace - with _ e.g. created-at => created_at // replace - with _ e.g. created-at => created_at
@ -303,4 +386,20 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
public void setModuleVersion(String moduleVersion) { public void setModuleVersion(String moduleVersion) {
this.moduleVersion = moduleVersion; this.moduleVersion = moduleVersion;
} }
@Override
public void setParameterExampleValue(CodegenParameter p) {
if (Boolean.TRUE.equals(p.isString) || Boolean.TRUE.equals(p.isBinary) ||
Boolean.TRUE.equals(p.isByteArray) || Boolean.TRUE.equals(p.isFile)) {
p.example = "'" + p.example + "'";
} else if (Boolean.TRUE.equals(p.isBoolean)) {
if (Boolean.parseBoolean(p.example))
p.example = new String("1");
else
p.example = new String("0");
} else if (Boolean.TRUE.equals(p.isDateTime) || Boolean.TRUE.equals(p.isDate)) {
p.example = "DateTime->from_epoch(epoch => str2time('" + p.example + "'))";
}
}
} }

View File

@ -3,6 +3,7 @@ package io.swagger.codegen.languages;
import io.swagger.codegen.CliOption; import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenType; import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile; import io.swagger.codegen.SupportingFile;
@ -35,10 +36,13 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String artifactVersion = "1.0.0"; protected String artifactVersion = "1.0.0";
protected String srcBasePath = "lib"; protected String srcBasePath = "lib";
protected String variableNamingConvention= "snake_case"; protected String variableNamingConvention= "snake_case";
protected String apiDocPath = "docs/";
protected String modelDocPath = "docs/";
public PhpClientCodegen() { public PhpClientCodegen() {
super(); super();
supportsInheritance = true;
outputFolder = "generated-code" + File.separator + "php"; outputFolder = "generated-code" + File.separator + "php";
modelTemplateFiles.put("model.mustache", ".php"); modelTemplateFiles.put("model.mustache", ".php");
apiTemplateFiles.put("api.mustache", ".php"); apiTemplateFiles.put("api.mustache", ".php");
@ -49,6 +53,9 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
modelPackage = invokerPackage + "\\Model"; modelPackage = invokerPackage + "\\Model";
testPackage = invokerPackage + "\\Tests"; testPackage = invokerPackage + "\\Tests";
modelDocTemplateFiles.put("model_doc.mustache", ".md");
apiDocTemplateFiles.put("api_doc.mustache", ".md");
setReservedWordsLowerCase( setReservedWordsLowerCase(
Arrays.asList( Arrays.asList(
// local variables used in api methods (endpoints) // local variables used in api methods (endpoints)
@ -89,6 +96,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
typeMapping = new HashMap<String, String>(); typeMapping = new HashMap<String, String>();
typeMapping.put("integer", "int"); typeMapping.put("integer", "int");
typeMapping.put("long", "int"); typeMapping.put("long", "int");
typeMapping.put("number", "float");
typeMapping.put("float", "float"); typeMapping.put("float", "float");
typeMapping.put("double", "double"); typeMapping.put("double", "double");
typeMapping.put("string", "string"); typeMapping.put("string", "string");
@ -110,8 +118,8 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, "The main namespace to use for all classes. e.g. Yay\\Pets")); cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, "The main namespace to use for all classes. e.g. Yay\\Pets"));
cliOptions.add(new CliOption(PACKAGE_PATH, "The main package name for classes. e.g. GeneratedPetstore")); cliOptions.add(new CliOption(PACKAGE_PATH, "The main package name for classes. e.g. GeneratedPetstore"));
cliOptions.add(new CliOption(SRC_BASE_PATH, "The directory under packagePath to serve as source root.")); cliOptions.add(new CliOption(SRC_BASE_PATH, "The directory under packagePath to serve as source root."));
cliOptions.add(new CliOption(COMPOSER_VENDOR_NAME, "The vendor name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. yaypets")); cliOptions.add(new CliOption(COMPOSER_VENDOR_NAME, "The vendor name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. yaypets. IMPORTANT NOTE (2016/03): composerVendorName will be deprecated and replaced by gitUserId in the next swagger-codegen release"));
cliOptions.add(new CliOption(COMPOSER_PROJECT_NAME, "The project name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. petstore-client")); cliOptions.add(new CliOption(COMPOSER_PROJECT_NAME, "The project name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. petstore-client. IMPORTANT NOTE (2016/03): composerProjectName will be deprecated and replaced by gitRepoId in the next swagger-codegen release"));
cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, "The version to use in the composer package version field. e.g. 1.2.3")); cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, "The version to use in the composer package version field. e.g. 1.2.3"));
} }
@ -217,6 +225,10 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
additionalProperties.put("escapedInvokerPackage", invokerPackage.replace("\\", "\\\\")); additionalProperties.put("escapedInvokerPackage", invokerPackage.replace("\\", "\\\\"));
// make api and model doc path available in mustache template
additionalProperties.put("apiDocPath", apiDocPath);
additionalProperties.put("modelDocPath", modelDocPath);
supportingFiles.add(new SupportingFile("configuration.mustache", toPackagePath(invokerPackage, srcBasePath), "Configuration.php")); supportingFiles.add(new SupportingFile("configuration.mustache", toPackagePath(invokerPackage, srcBasePath), "Configuration.php"));
supportingFiles.add(new SupportingFile("ApiClient.mustache", toPackagePath(invokerPackage, srcBasePath), "ApiClient.php")); supportingFiles.add(new SupportingFile("ApiClient.mustache", toPackagePath(invokerPackage, srcBasePath), "ApiClient.php"));
supportingFiles.add(new SupportingFile("ApiException.mustache", toPackagePath(invokerPackage, srcBasePath), "ApiException.php")); supportingFiles.add(new SupportingFile("ApiException.mustache", toPackagePath(invokerPackage, srcBasePath), "ApiException.php"));
@ -225,6 +237,8 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("autoload.mustache", getPackagePath(), "autoload.php")); supportingFiles.add(new SupportingFile("autoload.mustache", getPackagePath(), "autoload.php"));
supportingFiles.add(new SupportingFile("README.mustache", getPackagePath(), "README.md")); supportingFiles.add(new SupportingFile("README.mustache", getPackagePath(), "README.md"));
supportingFiles.add(new SupportingFile(".travis.yml", getPackagePath(), ".travis.yml")); supportingFiles.add(new SupportingFile(".travis.yml", getPackagePath(), ".travis.yml"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", getPackagePath(), "git_push.sh"));
} }
@Override @Override
@ -252,6 +266,28 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
return (outputFolder + "/" + toPackagePath(testPackage, srcBasePath)); return (outputFolder + "/" + toPackagePath(testPackage, srcBasePath));
} }
@Override
public String apiDocFileFolder() {
//return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar);
return (outputFolder + "/" + getPackagePath() + "/" + apiDocPath);
}
@Override
public String modelDocFileFolder() {
//return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar);
return (outputFolder + "/" + getPackagePath() + "/" + modelDocPath);
}
@Override
public String toModelDocFilename(String name) {
return toModelName(name);
}
@Override
public String toApiDocFilename(String name) {
return toApiName(name);
}
@Override @Override
public String getTypeDeclaration(Property p) { public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) { if (p instanceof ArrayProperty) {
@ -373,6 +409,12 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
name = "model_" + name; // e.g. return => ModelReturn (after camelize) name = "model_" + name; // e.g. return => ModelReturn (after camelize)
} }
// model name starts with number
if (name.matches("^\\d.*")) {
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name));
name = "model_" + name; // e.g. 200Response => Model200Response (after camelize)
}
// add prefix and/or suffic only if name does not start wth \ (e.g. \DateTime) // add prefix and/or suffic only if name does not start wth \ (e.g. \DateTime)
if (!name.matches("^\\\\.*")) { if (!name.matches("^\\\\.*")) {
name = modelNamePrefix + name + modelNameSuffix; name = modelNamePrefix + name + modelNameSuffix;
@ -458,4 +500,69 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
return null; return null;
} }
@Override
public void setParameterExampleValue(CodegenParameter p) {
String example;
if (p.defaultValue == null) {
example = p.example;
} else {
example = p.defaultValue;
}
String type = p.baseType;
if (type == null) {
type = p.dataType;
}
if ("String".equalsIgnoreCase(type)) {
if (example == null) {
example = p.paramName + "_example";
}
example = "\"" + escapeText(example) + "\"";
} else if ("Integer".equals(type) || "int".equals(type)) {
if (example == null) {
example = "56";
}
} else if ("Float".equalsIgnoreCase(type) || "Double".equalsIgnoreCase(type)) {
if (example == null) {
example = "3.4";
}
} else if ("BOOLEAN".equalsIgnoreCase(type) || "bool".equalsIgnoreCase(type)) {
if (example == null) {
example = "True";
}
} else if ("\\SplFileObject".equalsIgnoreCase(type)) {
if (example == null) {
example = "/path/to/file";
}
example = "\"" + escapeText(example) + "\"";
} else if ("Date".equalsIgnoreCase(type)) {
if (example == null) {
example = "2013-10-20";
}
example = "new \\DateTime(\"" + escapeText(example) + "\")";
} else if ("DateTime".equalsIgnoreCase(type)) {
if (example == null) {
example = "2013-10-20T19:20:30+01:00";
}
example = "new \\DateTime(\"" + escapeText(example) + "\")";
} else if (!languageSpecificPrimitives.contains(type)) {
// type is a model class, e.g. User
example = "new " + type + "()";
} else {
LOGGER.warn("Type " + type + " not handled properly in setParameterExampleValue");
}
if (example == null) {
example = "NULL";
} else if (Boolean.TRUE.equals(p.isListContainer)) {
example = "array(" + example + ")";
} else if (Boolean.TRUE.equals(p.isMapContainer)) {
example = "array('key' => " + example + ")";
}
p.example = example;
}
} }

View File

@ -3,6 +3,7 @@ package io.swagger.codegen.languages;
import io.swagger.codegen.CliOption; import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenType; import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile; import io.swagger.codegen.SupportingFile;
@ -17,6 +18,8 @@ import org.apache.commons.lang.StringUtils;
public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig { public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String packageName; protected String packageName;
protected String packageVersion; protected String packageVersion;
protected String apiDocPath = "docs/";
protected String modelDocPath = "docs/";
public PythonClientCodegen() { public PythonClientCodegen() {
super(); super();
@ -28,6 +31,9 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
apiTemplateFiles.put("api.mustache", ".py"); apiTemplateFiles.put("api.mustache", ".py");
embeddedTemplateDir = templateDir = "python"; embeddedTemplateDir = templateDir = "python";
modelDocTemplateFiles.put("model_doc.mustache", ".md");
apiDocTemplateFiles.put("api_doc.mustache", ".md");
languageSpecificPrimitives.clear(); languageSpecificPrimitives.clear();
languageSpecificPrimitives.add("int"); languageSpecificPrimitives.add("int");
languageSpecificPrimitives.add("float"); languageSpecificPrimitives.add("float");
@ -36,6 +42,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
languageSpecificPrimitives.add("str"); languageSpecificPrimitives.add("str");
languageSpecificPrimitives.add("datetime"); languageSpecificPrimitives.add("datetime");
languageSpecificPrimitives.add("date"); languageSpecificPrimitives.add("date");
languageSpecificPrimitives.add("object");
typeMapping.clear(); typeMapping.clear();
typeMapping.put("integer", "int"); typeMapping.put("integer", "int");
@ -97,6 +104,10 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName);
additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion); additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion);
// make api and model doc path available in mustache template
additionalProperties.put("apiDocPath", apiDocPath);
additionalProperties.put("modelDocPath", modelDocPath);
String swaggerFolder = packageName; String swaggerFolder = packageName;
modelPackage = swaggerFolder + File.separatorChar + "models"; modelPackage = swaggerFolder + File.separatorChar + "models";
@ -110,6 +121,8 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
supportingFiles.add(new SupportingFile("__init__package.mustache", swaggerFolder, "__init__.py")); supportingFiles.add(new SupportingFile("__init__package.mustache", swaggerFolder, "__init__.py"));
supportingFiles.add(new SupportingFile("__init__model.mustache", modelPackage, "__init__.py")); supportingFiles.add(new SupportingFile("__init__model.mustache", modelPackage, "__init__.py"));
supportingFiles.add(new SupportingFile("__init__api.mustache", apiPackage, "__init__.py")); supportingFiles.add(new SupportingFile("__init__api.mustache", apiPackage, "__init__.py"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
} }
private static String dropDots(String str) { private static String dropDots(String str) {
@ -136,6 +149,27 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
return "_" + name; return "_" + name;
} }
@Override
public String apiDocFileFolder() {
return (outputFolder + "/" + apiDocPath);
}
@Override
public String modelDocFileFolder() {
return (outputFolder + "/" + modelDocPath);
}
@Override
public String toModelDocFilename(String name) {
return toModelName(name);
}
@Override
public String toApiDocFilename(String name) {
return toApiName(name);
}
@Override @Override
public String apiFileFolder() { public String apiFileFolder() {
return outputFolder + File.separatorChar + apiPackage().replace('.', File.separatorChar); return outputFolder + File.separatorChar + apiPackage().replace('.', File.separatorChar);
@ -222,6 +256,12 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
name = "model_" + name; // e.g. return => ModelReturn (after camelize) name = "model_" + name; // e.g. return => ModelReturn (after camelize)
} }
// model name starts with number
if (name.matches("^\\d.*")) {
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name));
name = "model_" + name; // e.g. 200Response => Model200Response (after camelize)
}
if (!StringUtils.isEmpty(modelNamePrefix)) { if (!StringUtils.isEmpty(modelNamePrefix)) {
name = modelNamePrefix + "_" + name; name = modelNamePrefix + "_" + name;
} }
@ -247,6 +287,12 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
name = "model_" + name; // e.g. return => ModelReturn (after camelize) name = "model_" + name; // e.g. return => ModelReturn (after camelize)
} }
// model name starts with number
if (name.matches("^\\d.*")) {
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + underscore("model_" + name));
name = "model_" + name; // e.g. 200Response => Model200Response (after camelize)
}
if (!StringUtils.isEmpty(modelNamePrefix)) { if (!StringUtils.isEmpty(modelNamePrefix)) {
name = modelNamePrefix + "_" + name; name = modelNamePrefix + "_" + name;
} }
@ -374,4 +420,70 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
return null; return null;
} }
@Override
public void setParameterExampleValue(CodegenParameter p) {
String example;
if (p.defaultValue == null) {
example = p.example;
} else {
example = p.defaultValue;
}
String type = p.baseType;
if (type == null) {
type = p.dataType;
}
if ("String".equalsIgnoreCase(type) || "str".equalsIgnoreCase(type)) {
if (example == null) {
example = p.paramName + "_example";
}
example = "'" + escapeText(example) + "'";
} else if ("Integer".equals(type) || "int".equals(type)) {
if (example == null) {
example = "56";
}
} else if ("Float".equalsIgnoreCase(type) || "Double".equalsIgnoreCase(type)) {
if (example == null) {
example = "3.4";
}
} else if ("BOOLEAN".equalsIgnoreCase(type) || "bool".equalsIgnoreCase(type)) {
if (example == null) {
example = "True";
}
} else if ("file".equalsIgnoreCase(type)) {
if (example == null) {
example = "/path/to/file";
}
example = "'" + escapeText(example) + "'";
} else if ("Date".equalsIgnoreCase(type)) {
if (example == null) {
example = "2013-10-20";
}
example = "'" + escapeText(example) + "'";
} else if ("DateTime".equalsIgnoreCase(type)) {
if (example == null) {
example = "2013-10-20T19:20:30+01:00";
}
example = "'" + escapeText(example) + "'";
} else if (!languageSpecificPrimitives.contains(type)) {
// type is a model class, e.g. User
example = this.packageName + "." + type + "()";
} else {
LOGGER.warn("Type " + type + " not handled properly in setParameterExampleValue");
}
if (example == null) {
example = "NULL";
} else if (Boolean.TRUE.equals(p.isListContainer)) {
example = "[" + example + "]";
} else if (Boolean.TRUE.equals(p.isMapContainer)) {
example = "{'key': " + example + "}";
}
p.example = example;
}
} }

View File

@ -3,15 +3,21 @@ package io.swagger.codegen.languages;
import io.swagger.codegen.CliOption; import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenType; import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile; import io.swagger.codegen.SupportingFile;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Swagger;
import io.swagger.models.properties.*; import io.swagger.models.properties.*;
import java.io.File; import java.io.File;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -40,6 +46,8 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String gemDescription = "This gem maps to a swagger API"; protected String gemDescription = "This gem maps to a swagger API";
protected String gemAuthor = ""; protected String gemAuthor = "";
protected String gemAuthorEmail = ""; protected String gemAuthorEmail = "";
protected String apiDocPath = "docs/";
protected String modelDocPath = "docs/";
protected static int emptyMethodNameCounter = 0; protected static int emptyMethodNameCounter = 0;
@ -50,6 +58,8 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
outputFolder = "generated-code" + File.separator + "ruby"; outputFolder = "generated-code" + File.separator + "ruby";
modelTemplateFiles.put("model.mustache", ".rb"); modelTemplateFiles.put("model.mustache", ".rb");
apiTemplateFiles.put("api.mustache", ".rb"); apiTemplateFiles.put("api.mustache", ".rb");
modelDocTemplateFiles.put("model_doc.mustache", ".md");
apiDocTemplateFiles.put("api_doc.mustache", ".md");
embeddedTemplateDir = templateDir = "ruby"; embeddedTemplateDir = templateDir = "ruby";
modelTestTemplateFiles.put("model_test.mustache", ".rb"); modelTestTemplateFiles.put("model_test.mustache", ".rb");
@ -194,6 +204,9 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
setGemAuthorEmail((String) additionalProperties.get(GEM_AUTHOR_EMAIL)); setGemAuthorEmail((String) additionalProperties.get(GEM_AUTHOR_EMAIL));
} }
// make api and model doc path available in mustache template
additionalProperties.put("apiDocPath", apiDocPath);
additionalProperties.put("modelDocPath", modelDocPath);
// use constant model/api package (folder path) // use constant model/api package (folder path)
setModelPackage("models"); setModelPackage("models");
@ -206,8 +219,40 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("api_error.mustache", gemFolder, "api_error.rb")); supportingFiles.add(new SupportingFile("api_error.mustache", gemFolder, "api_error.rb"));
supportingFiles.add(new SupportingFile("configuration.mustache", gemFolder, "configuration.rb")); supportingFiles.add(new SupportingFile("configuration.mustache", gemFolder, "configuration.rb"));
supportingFiles.add(new SupportingFile("version.mustache", gemFolder, "version.rb")); supportingFiles.add(new SupportingFile("version.mustache", gemFolder, "version.rb"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
} }
@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);
// Set vendor-extension to be used in template:
// x-codegen-hasMoreRequired
// x-codegen-hasMoreOptional
// x-codegen-hasRequiredParams
CodegenParameter lastRequired = null;
CodegenParameter lastOptional = null;
for (CodegenParameter p : op.allParams) {
if (p.required != null && p.required) {
lastRequired = p;
} else {
lastOptional = p;
}
}
for (CodegenParameter p : op.allParams) {
if (p == lastRequired) {
p.vendorExtensions.put("x-codegen-hasMoreRequired", false);
} else if (p == lastOptional) {
p.vendorExtensions.put("x-codegen-hasMoreOptional", false);
} else {
p.vendorExtensions.put("x-codegen-hasMoreRequired", true);
p.vendorExtensions.put("x-codegen-hasMoreOptional", true);
}
}
op.vendorExtensions.put("x-codegen-hasRequiredParams", lastRequired != null);
return op;
}
@Override @Override
public CodegenType getTag() { public CodegenType getTag() {
@ -271,6 +316,16 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
return outputFolder + File.separator + specFolder + File.separator + modelPackage.replace("/", File.separator); return outputFolder + File.separator + specFolder + File.separator + modelPackage.replace("/", File.separator);
} }
@Override
public String apiDocFileFolder() {
return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar);
}
@Override
public String modelDocFileFolder() {
return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar);
}
@Override @Override
public String getTypeDeclaration(Property p) { public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) { if (p instanceof ArrayProperty) {
@ -386,6 +441,12 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
return modelName; return modelName;
} }
// model name starts with number
if (name.matches("^\\d.*")) {
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name));
name = "model_" + name; // e.g. 200Response => Model200Response (after camelize)
}
// camelize the model name // camelize the model name
// phone_number => PhoneNumber // phone_number => PhoneNumber
return camelize(name); return camelize(name);
@ -409,11 +470,22 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
return filename; return filename;
} }
// model name starts with number
if (name.matches("^\\d.*")) {
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + underscore("model_" + name));
name = "model_" + name; // e.g. 200Response => model_200_response
}
// underscore the model file name // underscore the model file name
// PhoneNumber.rb => phone_number.rb // PhoneNumber.rb => phone_number.rb
return underscore(name); return underscore(name);
} }
@Override
public String toModelDocFilename(String name) {
return toModelName(name);
}
@Override @Override
public String toApiFilename(String name) { public String toApiFilename(String name) {
// replace - with _ e.g. created-at => created_at // replace - with _ e.g. created-at => created_at
@ -423,6 +495,11 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
return underscore(name) + "_api"; return underscore(name) + "_api";
} }
@Override
public String toApiDocFilename(String name) {
return toApiName(name);
}
@Override @Override
public String toApiTestFilename(String name) { public String toApiTestFilename(String name) {
return toApiFilename(name) + "_spec"; return toApiFilename(name) + "_spec";
@ -466,6 +543,69 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
return gemName + "/" + apiPackage() + "/" + toApiFilename(name); return gemName + "/" + apiPackage() + "/" + toApiFilename(name);
} }
@Override
public void setParameterExampleValue(CodegenParameter p) {
String example;
if (p.defaultValue == null) {
example = p.example;
} else {
example = p.defaultValue;
}
String type = p.baseType;
if (type == null) {
type = p.dataType;
}
if ("String".equals(type)) {
if (example == null) {
example = p.paramName + "_example";
}
example = "\"" + escapeText(example) + "\"";
} else if ("Integer".equals(type)) {
if (example == null) {
example = "56";
}
} else if ("Float".equals(type)) {
if (example == null) {
example = "3.4";
}
} else if ("BOOLEAN".equals(type)) {
if (example == null) {
example = "true";
}
} else if ("File".equals(type)) {
if (example == null) {
example = "/path/to/file";
}
example = "File.new(\"" + escapeText(example) + "\")";
} else if ("Date".equals(type)) {
if (example == null) {
example = "2013-10-20";
}
example = "Date.parse(\"" + escapeText(example) + "\")";
} else if ("DateTime".equals(type)) {
if (example == null) {
example = "2013-10-20T19:20:30+01:00";
}
example = "DateTime.parse(\"" + escapeText(example) + "\")";
} else if (!languageSpecificPrimitives.contains(type)) {
// type is a model class, e.g. User
example = moduleName + "::" + type + ".new";
}
if (example == null) {
example = "nil";
} else if (Boolean.TRUE.equals(p.isListContainer)) {
example = "[" + example + "]";
} else if (Boolean.TRUE.equals(p.isMapContainer)) {
example = "{'key' => " + example + "}";
}
p.example = example;
}
public void setGemName(String gemName) { public void setGemName(String gemName) {
this.gemName = gemName; this.gemName = gemName;
} }

View File

@ -72,6 +72,8 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("apiInvoker.mustache", supportingFiles.add(new SupportingFile("apiInvoker.mustache",
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.scala")); (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.scala"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
importMapping.remove("List"); importMapping.remove("List");
importMapping.remove("Set"); importMapping.remove("Set");
@ -110,6 +112,7 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig
"Long", "Long",
"Float", "Float",
"Object", "Object",
"Any",
"List", "List",
"Map") "Map")
); );
@ -255,4 +258,67 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig
return objs; return objs;
} }
@Override
public String toVarName(String name) {
// sanitize name
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
if("_".equals(name)) {
name = "_u";
}
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$")) {
return name;
}
// camelize (lower first character) the variable name
// pet_id => petId
name = camelize(name, true);
// for reserved word or word starting with number, append _
if (isReservedWord(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
}
return name;
}
@Override
public String toParamName(String name) {
// should be the same as variable name
return toVarName(name);
}
@Override
public String toModelName(final String name) {
final String sanitizedName = sanitizeName(modelNamePrefix + name + modelNameSuffix);
// camelize the model name
// phone_number => PhoneNumber
final String camelizedName = camelize(sanitizedName);
// model name cannot use reserved keyword, e.g. return
if (isReservedWord(camelizedName)) {
final String modelName = "Model" + camelizedName;
LOGGER.warn(camelizedName + " (reserved word) cannot be used as model name. Renamed to " + modelName);
return modelName;
}
// model name starts with number
if (name.matches("^\\d.*")) {
final String modelName = "Model" + camelizedName; // e.g. 200Response => Model200Response (after camelize)
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName);
return modelName;
}
return camelizedName;
}
@Override
public String toModelFilename(String name) {
// should be the same as the model name
return toModelName(name);
}
} }

View File

@ -74,6 +74,8 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
languageSpecificPrimitives = new HashSet<String>( languageSpecificPrimitives = new HashSet<String>(
Arrays.asList( Arrays.asList(
"Int", "Int",
"Int32",
"Int64",
"Float", "Float",
"Double", "Double",
"Bool", "Bool",
@ -115,10 +117,10 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
typeMapping.put("string", "String"); typeMapping.put("string", "String");
typeMapping.put("char", "Character"); typeMapping.put("char", "Character");
typeMapping.put("short", "Int"); typeMapping.put("short", "Int");
typeMapping.put("int", "Int"); typeMapping.put("int", "Int32");
typeMapping.put("long", "Int"); typeMapping.put("long", "Int64");
typeMapping.put("integer", "Int"); typeMapping.put("integer", "Int32");
typeMapping.put("Integer", "Int"); typeMapping.put("Integer", "Int32");
typeMapping.put("float", "Float"); typeMapping.put("float", "Float");
typeMapping.put("number", "Double"); typeMapping.put("number", "Double");
typeMapping.put("double", "Double"); typeMapping.put("double", "Double");
@ -195,6 +197,9 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("Extensions.mustache", sourceFolder, "Extensions.swift")); supportingFiles.add(new SupportingFile("Extensions.mustache", sourceFolder, "Extensions.swift"));
supportingFiles.add(new SupportingFile("Models.mustache", sourceFolder, "Models.swift")); supportingFiles.add(new SupportingFile("Models.mustache", sourceFolder, "Models.swift"));
supportingFiles.add(new SupportingFile("APIs.mustache", sourceFolder, "APIs.swift")); supportingFiles.add(new SupportingFile("APIs.mustache", sourceFolder, "APIs.swift"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
} }
@Override @Override
@ -268,6 +273,13 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
return modelName; return modelName;
} }
// model name starts with number
if (name.matches("^\\d.*")) {
String modelName = "Model" + name; // e.g. 200Response => Model200Response (after camelize)
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName);
return modelName;
}
return name; return name;
} }

View File

@ -19,6 +19,10 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
public void processOpts() { public void processOpts() {
super.processOpts(); super.processOpts();
supportingFiles.add(new SupportingFile("api.d.mustache", apiPackage().replace('.', File.separatorChar), "api.d.ts")); supportingFiles.add(new SupportingFile("api.d.mustache", apiPackage().replace('.', File.separatorChar), "api.d.ts"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
//supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
} }
public TypeScriptAngularClientCodegen() { public TypeScriptAngularClientCodegen() {

View File

@ -18,6 +18,8 @@ public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen
public void processOpts() { public void processOpts() {
super.processOpts(); super.processOpts();
supportingFiles.add(new SupportingFile("api.mustache", null, "api.ts")); supportingFiles.add(new SupportingFile("api.mustache", null, "api.ts"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
//supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
} }
public TypeScriptNodeClientCodegen() { public TypeScriptNodeClientCodegen() {

View File

@ -71,7 +71,7 @@ public class ApiClient {
dateFormat = ApiClient.buildDefaultDateFormat(); dateFormat = ApiClient.buildDefaultDateFormat();
// Set default User-Agent. // Set default User-Agent.
setUserAgent("Java-Swagger"); setUserAgent("{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{artifactVersion}}}/java{{/httpUserAgent}}");
// Setup authentications (key: authentication name, value: authentication). // Setup authentications (key: authentication name, value: authentication).
authentications = new HashMap<String, Authentication>();{{#authMethods}}{{#isBasic}} authentications = new HashMap<String, Authentication>();{{#authMethods}}{{#isBasic}}

View File

@ -42,7 +42,7 @@ public class {{classname}} {
/** /**
* {{summary}} * {{summary}}
* {{notes}}{{#allParams}} * {{notes}}{{#allParams}}
* @param {{paramName}} {{description}}{{/allParams}}{{#returnType}} * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}{{#returnType}}
* @return {{{returnType}}}{{/returnType}} * @return {{{returnType}}}{{/returnType}}
* @throws ApiException if fails to make API call * @throws ApiException if fails to make API call
*/ */

View File

@ -1 +1 @@
@javax.annotation.Generated(value = "{{generatorClass}}", date = "{{generatedDate}}") {{^hideGenerationTimestamp}}@javax.annotation.Generated(value = "{{generatorClass}}", date = "{{generatedDate}}"){{/hideGenerationTimestamp}}

View File

@ -0,0 +1,52 @@
#!/bin/sh
# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/
#
# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update"
git_user_id=$1
git_repo_id=$2
release_note=$3
if [ "$git_user_id" = "" ]; then
git_user_id="{{{gitUserId}}}"
echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id"
fi
if [ "$git_repo_id" = "" ]; then
git_repo_id="{{{gitRepoId}}}"
echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
fi
if [ "$release_note" = "" ]; then
release_note="{{{releaseNote}}}"
echo "[INFO] No command line input provided. Set \$release_note to $release_note"
fi
# Initialize the local directory as a Git repository
git init
# Adds the files in the local repository and stages them for commit.
git add .
# Commits the tracked changes and prepares them to be pushed to a remote repository.
git commit -m "$release_note"
# Sets the new remote
git_remote=`git remote`
if [ "$git_remote" = "" ]; then # git remote not defined
if [ "$GIT_TOKEN" = "" ]; then
echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment."
git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git
else
git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git
fi
fi
git pull origin master
# Pushes (Forces) the changes in the local repository up to the remote repository
echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git"
git push origin master 2>&1 | grep -v 'To https'

View File

@ -0,0 +1,12 @@
*.class
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.ear
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*

View File

@ -20,7 +20,7 @@ public interface {{classname}} extends ApiClient.Api {
/** /**
* {{summary}} * {{summary}}
* {{notes}} * {{notes}}
{{#allParams}} * @param {{paramName}} {{description}} {{#allParams}} * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}
{{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
*/ */
@RequestLine("{{httpMethod}} {{{path}}}{{#hasQueryParams}}?{{/hasQueryParams}}{{#queryParams}}{{baseName}}={{=<% %>=}}{<%paramName%>}<%={{ }}=%>{{#hasMore}}&{{/hasMore}}{{/queryParams}}") @RequestLine("{{httpMethod}} {{{path}}}{{#hasQueryParams}}?{{/hasQueryParams}}{{#queryParams}}{{baseName}}={{=<% %>=}}{<%paramName%>}<%={{ }}=%>{{#hasMore}}&{{/hasMore}}{{/queryParams}}")

View File

@ -110,7 +110,7 @@
<dependency> <dependency>
<groupId>io.swagger</groupId> <groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId> <artifactId>swagger-annotations</artifactId>
<version>${swagger-annotations-version}</version> <version>${swagger-core-version}</version>
</dependency> </dependency>
<!-- HTTP client: Netflix Feign --> <!-- HTTP client: Netflix Feign -->
@ -179,7 +179,7 @@
</dependency> </dependency>
</dependencies> </dependencies>
<properties> <properties>
<swagger-annotations-version>1.5.0</swagger-annotations-version> <swagger-core-version>1.5.8</swagger-core-version>
<feign-version>8.1.1</feign-version> <feign-version>8.1.1</feign-version>
<jackson-version>2.6.3</jackson-version> <jackson-version>2.6.3</jackson-version>
<jodatime-version>2.5</jodatime-version> <jodatime-version>2.5</jodatime-version>

View File

@ -80,7 +80,7 @@ public class ApiClient {
this.json.setDateFormat((DateFormat) dateFormat.clone()); this.json.setDateFormat((DateFormat) dateFormat.clone());
// Set default User-Agent. // Set default User-Agent.
setUserAgent("Java-Swagger"); setUserAgent("{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{artifactVersion}}}/java{{/httpUserAgent}}");
// Setup authentications (key: authentication name, value: authentication). // Setup authentications (key: authentication name, value: authentication).
authentications = new HashMap<String, Authentication>();{{#authMethods}}{{#isBasic}} authentications = new HashMap<String, Authentication>();{{#authMethods}}{{#isBasic}}

View File

@ -42,7 +42,7 @@ public class {{classname}} {
/** /**
* {{summary}} * {{summary}}
* {{notes}}{{#allParams}} * {{notes}}{{#allParams}}
* @param {{paramName}} {{description}}{{/allParams}}{{#returnType}} * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}{{#returnType}}
* @return {{{returnType}}}{{/returnType}} * @return {{{returnType}}}{{/returnType}}
* @throws ApiException if fails to make API call * @throws ApiException if fails to make API call
*/ */

View File

@ -131,7 +131,7 @@
<dependency> <dependency>
<groupId>io.swagger</groupId> <groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId> <artifactId>swagger-annotations</artifactId>
<version>${swagger-annotations-version}</version> <version>${swagger-core-version}</version>
</dependency> </dependency>
<!-- HTTP client: jersey-client --> <!-- HTTP client: jersey-client -->
@ -194,7 +194,7 @@
</dependency> </dependency>
</dependencies> </dependencies>
<properties> <properties>
<swagger-annotations-version>1.5.0</swagger-annotations-version> <swagger-core-version>1.5.8</swagger-core-version>
<jersey-version>2.22</jersey-version> <jersey-version>2.22</jersey-version>
<jackson-version>2.4.2</jackson-version> <jackson-version>2.4.2</jackson-version>
<jodatime-version>2.3</jodatime-version> <jodatime-version>2.3</jodatime-version>

View File

@ -141,7 +141,7 @@ public class ApiClient {
this.lenientDatetimeFormat = true; this.lenientDatetimeFormat = true;
// Set default User-Agent. // Set default User-Agent.
setUserAgent("Java-Swagger"); setUserAgent("{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{artifactVersion}}}/java{{/httpUserAgent}}");
// Setup authentications (key: authentication name, value: authentication). // Setup authentications (key: authentication name, value: authentication).
authentications = new HashMap<String, Authentication>();{{#authMethods}}{{#isBasic}} authentications = new HashMap<String, Authentication>();{{#authMethods}}{{#isBasic}}

View File

@ -106,7 +106,7 @@ public class {{classname}} {
/** /**
* {{summary}} * {{summary}}
* {{notes}}{{#allParams}} * {{notes}}{{#allParams}}
* @param {{paramName}} {{description}}{{/allParams}}{{#returnType}} * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}{{#returnType}}
* @return {{{returnType}}}{{/returnType}} * @return {{{returnType}}}{{/returnType}}
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/ */
@ -118,7 +118,7 @@ public class {{classname}} {
/** /**
* {{summary}} * {{summary}}
* {{notes}}{{#allParams}} * {{notes}}{{#allParams}}
* @param {{paramName}} {{description}}{{/allParams}} * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
* @return ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> * @return ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/ */
@ -131,7 +131,7 @@ public class {{classname}} {
/** /**
* {{summary}} (asynchronously) * {{summary}} (asynchronously)
* {{notes}}{{#allParams}} * {{notes}}{{#allParams}}
* @param {{paramName}} {{description}}{{/allParams}} * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
* @param callback The callback to be executed when the API call finishes * @param callback The callback to be executed when the API call finishes
* @return The request call * @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object * @throws ApiException If fail to process the API call, e.g. serializing the request body object

View File

@ -13,7 +13,7 @@ import com.google.gson.annotations.SerializedName;
/** /**
* {{description}} * {{description}}
**/{{/description}} **/{{/description}}
@ApiModel(description = "{{{description}}}") {{#description}}@ApiModel(description = "{{{description}}}"){{/description}}
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} {
{{#vars}}{{#isEnum}} {{#vars}}{{#isEnum}}

View File

@ -132,7 +132,7 @@
<dependency> <dependency>
<groupId>io.swagger</groupId> <groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId> <artifactId>swagger-annotations</artifactId>
<version>${swagger-annotations-version}</version> <version>${swagger-core-version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.squareup.okhttp</groupId> <groupId>com.squareup.okhttp</groupId>
@ -159,7 +159,7 @@
</dependency> </dependency>
</dependencies> </dependencies>
<properties> <properties>
<swagger-annotations-version>1.5.0</swagger-annotations-version> <swagger-core-version>1.5.8</swagger-core-version>
<okhttp-version>2.7.2</okhttp-version> <okhttp-version>2.7.2</okhttp-version>
<gson-version>2.3.1</gson-version> <gson-version>2.3.1</gson-version>
<maven-plugin-version>1.0.0</maven-plugin-version> <maven-plugin-version>1.0.0</maven-plugin-version>

View File

@ -23,7 +23,7 @@ public interface {{classname}} {
* {{summary}} * {{summary}}
* Sync method * Sync method
* {{notes}} * {{notes}}
{{#allParams}} * @param {{paramName}} {{description}} {{#allParams}} * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}
{{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
*/ */
{{#formParams}}{{#-first}} {{#formParams}}{{#-first}}
@ -36,7 +36,7 @@ public interface {{classname}} {
/** /**
* {{summary}} * {{summary}}
* Async method * Async method
{{#allParams}} * @param {{paramName}} {{description}} {{#allParams}} * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}
{{/allParams}} * @param cb callback method {{/allParams}} * @param cb callback method
* @return void * @return void
*/ */

View File

@ -13,7 +13,7 @@ import com.google.gson.annotations.SerializedName;
/** /**
* {{description}} * {{description}}
**/{{/description}} **/{{/description}}
@ApiModel(description = "{{{description}}}") {{#description}}@ApiModel(description = "{{{description}}}"){{/description}}
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} {
{{#vars}}{{#isEnum}} {{#vars}}{{#isEnum}}

View File

@ -110,7 +110,7 @@
<dependency> <dependency>
<groupId>io.swagger</groupId> <groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId> <artifactId>swagger-annotations</artifactId>
<version>${swagger-annotations-version}</version> <version>${swagger-core-version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.squareup.retrofit</groupId> <groupId>com.squareup.retrofit</groupId>
@ -137,7 +137,7 @@
</dependency> </dependency>
</dependencies> </dependencies>
<properties> <properties>
<swagger-annotations-version>1.5.0</swagger-annotations-version> <swagger-core-version>1.5.8</swagger-core-version>
<retrofit-version>1.9.0</retrofit-version> <retrofit-version>1.9.0</retrofit-version>
<okhttp-version>2.4.0</okhttp-version> <okhttp-version>2.4.0</okhttp-version>
<oltu-version>1.0.0</oltu-version> <oltu-version>1.0.0</oltu-version>

View File

@ -12,8 +12,9 @@ import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuil
import retrofit2.Converter; import retrofit2.Converter;
import retrofit2.Retrofit; import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
{{#useRxJava}}import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;{{/useRxJava}} {{#useRxJava}}import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;{{/useRxJava}}
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -120,6 +121,7 @@ public class ApiClient {
.baseUrl(baseUrl) .baseUrl(baseUrl)
.client(okClient) .client(okClient)
{{#useRxJava}}.addCallAdapterFactory(RxJavaCallAdapterFactory.create()){{/useRxJava}} {{#useRxJava}}.addCallAdapterFactory(RxJavaCallAdapterFactory.create()){{/useRxJava}}
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonCustomConverterFactory.create(gson)); .addConverterFactory(GsonCustomConverterFactory.create(gson));
} }

View File

@ -24,7 +24,7 @@ public interface {{classname}} {
/** /**
* {{summary}} * {{summary}}
* {{notes}} * {{notes}}
{{#allParams}} * @param {{paramName}} {{description}} {{#allParams}} * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}
{{/allParams}} * @return Call<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{/allParams}} * @return Call<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}>
*/ */
{{#formParams}}{{#-first}} {{#formParams}}{{#-first}}

View File

@ -46,6 +46,10 @@ if(hasProperty('target') && target == 'android') {
} }
} }
} }
dependencies {
provided 'javax.annotation:jsr250-api:1.0'
}
} }
afterEvaluate { afterEvaluate {
@ -103,6 +107,7 @@ ext {
dependencies { dependencies {
compile "com.squareup.retrofit2:retrofit:$retrofit_version" compile "com.squareup.retrofit2:retrofit:$retrofit_version"
compile "com.squareup.retrofit2:converter-scalars:$retrofit_version"
compile "com.squareup.retrofit2:converter-gson:$retrofit_version" compile "com.squareup.retrofit2:converter-gson:$retrofit_version"
{{#useRxJava}} {{#useRxJava}}
compile "com.squareup.retrofit2:adapter-rxjava:$retrofit_version" compile "com.squareup.retrofit2:adapter-rxjava:$retrofit_version"

View File

@ -13,7 +13,7 @@ import com.google.gson.annotations.SerializedName;
/** /**
* {{description}} * {{description}}
**/{{/description}} **/{{/description}}
@ApiModel(description = "{{{description}}}") {{#description}}@ApiModel(description = "{{{description}}}"){{/description}}
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} {
{{#vars}}{{#isEnum}} {{#vars}}{{#isEnum}}

View File

@ -111,45 +111,38 @@
<dependency> <dependency>
<groupId>io.swagger</groupId> <groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId> <artifactId>swagger-annotations</artifactId>
<version>${swagger-annotations-version}</version> <version>${swagger-core-version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.squareup.retrofit2</groupId> <groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId> <artifactId>retrofit</artifactId>
<version>${retrofit-version}</version> <version>${retrofit-version}</version>
</dependency> </dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-scalars</artifactId>
<version>${retrofit-version}</version>
</dependency>
<dependency> <dependency>
<groupId>com.squareup.retrofit2</groupId> <groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-gson</artifactId> <artifactId>converter-gson</artifactId>
<version>${retrofit-version}</version> <version>${retrofit-version}</version>
</dependency> </dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson-version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.apache.oltu.oauth2</groupId> <groupId>org.apache.oltu.oauth2</groupId>
<artifactId>org.apache.oltu.oauth2.client</artifactId> <artifactId>org.apache.oltu.oauth2.client</artifactId>
<version>${oltu-version}</version> <version>${oltu-version}</version>
</dependency>{{#useRxJava}}
<dependency>
<groupId>io.reactivex</groupId>
<artifactId>rxjava</artifactId>
<version>${rxjava-version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.squareup.okhttp3</groupId> <groupId>com.squareup.retrofit2</groupId>
<artifactId>okhttp</artifactId> <artifactId>adapter-rxjava</artifactId>
<version>${okhttp-version}</version> <version>${retrofit-version}</version>
</dependency> </dependency>{{/useRxJava}}
{{#useRxJava}}
<dependency>
<groupId>io.reactivex</groupId>
<artifactId>rxjava</artifactId>
<version>${rxjava-version}</version>
</dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>adapter-rxjava</artifactId>
<version>${retrofit-version}</version>
</dependency>
{{/useRxJava}}
<!-- test dependencies --> <!-- test dependencies -->
<dependency> <dependency>
@ -160,11 +153,9 @@
</dependency> </dependency>
</dependencies> </dependencies>
<properties> <properties>
<swagger-annotations-version>1.5.0</swagger-annotations-version> <swagger-core-version>1.5.8</swagger-core-version>
<retrofit-version>2.0.0-beta4</retrofit-version> <retrofit-version>2.0.0-beta4</retrofit-version>{{#useRxJava}}
{{#useRxJava}}<rxjava-version>1.0.16</rxjava-version>{{/useRxJava}} <rxjava-version>1.0.16</rxjava-version>{{/useRxJava}}
<okhttp-version>3.0.1</okhttp-version>
<gson-version>2.4</gson-version>
<oltu-version>1.0.0</oltu-version> <oltu-version>1.0.0</oltu-version>
<maven-plugin-version>1.0.0</maven-plugin-version> <maven-plugin-version>1.0.0</maven-plugin-version>
<junit-version>4.12</junit-version> <junit-version>4.12</junit-version>

View File

@ -64,6 +64,7 @@
<plugin> <plugin>
<groupId>org.codehaus.mojo</groupId> <groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId> <artifactId>build-helper-maven-plugin</artifactId>
<version>1.10</version>
<executions> <executions>
<execution> <execution>
<id>add_sources</id> <id>add_sources</id>
@ -169,7 +170,8 @@
</dependency> </dependency>
</dependencies> </dependencies>
<properties> <properties>
<swagger-annotations-version>1.5.4</swagger-annotations-version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<swagger-annotations-version>1.5.8</swagger-annotations-version>
<jersey-version>1.18</jersey-version> <jersey-version>1.18</jersey-version>
<jackson-version>2.4.2</jackson-version> <jackson-version>2.4.2</jackson-version>
<jodatime-version>2.3</jodatime-version> <jodatime-version>2.3</jodatime-version>

View File

@ -2,8 +2,11 @@ controllerPackage: {{invokerPackage}}
modelPackage: {{modelPackage}} modelPackage: {{modelPackage}}
swaggerUrl: ./src/main/swagger/swagger.yaml swaggerUrl: ./src/main/swagger/swagger.yaml
modelMappings: modelMappings:
# to enable explicit mappings, use this syntax:
DefinitionFromSwaggerSpecification: fully.qualified.path.to.Model
{{#models}}{{#model}}{{classname}} : {{modelPackage}}.{{classname}}{{/model}} {{#models}}{{#model}}{{classname}} : {{modelPackage}}.{{classname}}{{/model}}
{{/models}} {{/models}}
entityProcessors: entityProcessors:
- json - json
- xml - xml

View File

@ -19,6 +19,25 @@
<directory>target</directory> <directory>target</directory>
<finalName>${project.artifactId}-${project.version}</finalName> <finalName>${project.artifactId}-${project.version}</finalName>
<plugins> <plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.10</version>
<executions>
<execution>
<id>add-source</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>src/gen/java</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
<plugin> <plugin>
<artifactId>maven-dependency-plugin</artifactId> <artifactId>maven-dependency-plugin</artifactId>
<executions> <executions>
@ -78,12 +97,21 @@
<dependency> <dependency>
<groupId>io.swagger</groupId> <groupId>io.swagger</groupId>
<artifactId>swagger-inflector</artifactId> <artifactId>swagger-inflector</artifactId>
<version>1.0.2</version> <version>${swagger-inflector-version}</version>
</dependency> </dependency>
</dependencies> </dependencies>
<repositories>
<repository>
<id>sonatype-snapshots</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<properties> <properties>
<maven-plugin-version>1.0.0</maven-plugin-version> <maven-plugin-version>1.0.0</maven-plugin-version>
<swagger-core-version>1.5.7</swagger-core-version> <swagger-inflector-version>1.0.4</swagger-inflector-version>
<jetty-version>9.2.9.v20150224</jetty-version> <jetty-version>9.2.9.v20150224</jetty-version>
<logback-version>1.0.1</logback-version> <logback-version>1.0.1</logback-version>
<junit-version>4.8.2</junit-version> <junit-version>4.8.2</junit-version>

View File

@ -6,6 +6,8 @@ package {{package}};
import javax.ws.rs.*; import javax.ws.rs.*;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import org.apache.cxf.jaxrs.ext.multipart.*;
@Path("/") @Path("/")
public interface {{classname}} { public interface {{classname}} {
{{#operations}} {{#operations}}

View File

@ -46,10 +46,10 @@ public class {{classname}} {
{{/hasMore}}{{/authMethods}} {{/hasMore}}{{/authMethods}}
}{{/hasAuthMethods}}, tags={ {{#vendorExtensions.x-tags}}"{{tag}}"{{#hasMore}}, {{/hasMore}}{{/vendorExtensions.x-tags}} }) }{{/hasAuthMethods}}, tags={ {{#vendorExtensions.x-tags}}"{{tag}}"{{#hasMore}}, {{/hasMore}}{{/vendorExtensions.x-tags}} })
@io.swagger.annotations.ApiResponses(value = { {{#responses}} @io.swagger.annotations.ApiResponses(value = { {{#responses}}
@io.swagger.annotations.ApiResponse(code = {{{code}}}, message = "{{{message}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}){{#hasMore}}, @io.swagger.annotations.ApiResponse(code = {{{code}}}, message = "{{{message}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}){{#hasMore}},{{/hasMore}}{{/responses}} })
{{/hasMore}}{{/responses}} }) public Response {{nickname}}(
{{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}},
public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}},{{/allParams}}@Context SecurityContext securityContext) {{/allParams}}@Context SecurityContext securityContext)
throws NotFoundException { throws NotFoundException {
return delegate.{{nickname}}({{#allParams}}{{#isFile}}inputStream, fileDetail{{/isFile}}{{^isFile}}{{paramName}}{{/isFile}},{{/allParams}}securityContext); return delegate.{{nickname}}({{#allParams}}{{#isFile}}inputStream, fileDetail{{/isFile}}{{^isFile}}{{paramName}}{{/isFile}},{{/allParams}}securityContext);
} }

View File

@ -0,0 +1,31 @@
package {{apiPackage}};
import io.swagger.jaxrs.config.SwaggerContextService;
import io.swagger.models.*;
import io.swagger.models.auth.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
public class Bootstrap extends HttpServlet {
@Override
public void init(ServletConfig config) throws ServletException {
Info info = new Info()
.title("{{title}}")
.description("{{{appDescription}}}")
.termsOfService("{{termsOfService}}")
.contact(new Contact()
.email("{{infoEmail}}"))
.license(new License()
.name("{{licenseInfo}}")
.url("{{licenseUrl}}"));
ServletContext context = config.getServletContext();
Swagger swagger = new Swagger().info(info);
new SwaggerContextService().withServletConfig(config).updateSwagger(swagger);
}
}

View File

@ -1,2 +1,2 @@
{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@FormParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}} @FormDataParam("file") InputStream inputStream, {{#isFormParam}}{{#notFile}}{{^vendorExtensions.x-multipart}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}){{/vendorExtensions.x-multipart}}{{#vendorExtensions.x-multipart}}@FormDataParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{^vendorExtensions.x-multipart}}@FormParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{/notFile}}{{#isFile}}@FormDataParam("file") InputStream inputStream,
@FormDataParam("file") FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}} @FormDataParam("file") FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}}

View File

@ -1 +1 @@
@javax.annotation.Generated(value = "{{generatorClass}}", date = "{{generatedDate}}") {{^hideGenerationTimestamp}}@javax.annotation.Generated(value = "{{generatorClass}}", date = "{{generatedDate}}"){{/hideGenerationTimestamp}}

View File

@ -0,0 +1,19 @@
package {{apiPackage}};
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
import io.swagger.util.Json;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.Provider;
@Provider
@Produces({MediaType.APPLICATION_JSON})
public class JacksonJsonProvider extends JacksonJaxbJsonProvider {
private static ObjectMapper commonMapper = Json.mapper();
public JacksonJsonProvider() {
super.setMapper(commonMapper);
}
}

View File

@ -168,7 +168,7 @@
</repository> </repository>
</repositories> </repositories>
<properties> <properties>
<swagger-core-version>1.5.7</swagger-core-version> <swagger-core-version>1.5.8</swagger-core-version>
<jetty-version>9.2.9.v20150224</jetty-version> <jetty-version>9.2.9.v20150224</jetty-version>
<jersey-version>1.18.1</jersey-version> <jersey-version>1.18.1</jersey-version>
<slf4j-version>1.6.3</slf4j-version> <slf4j-version>1.6.3</slf4j-version>

View File

@ -0,0 +1,10 @@
package {{apiPackage}};
{{>generatedAnnotation}}
public class ApiException extends Exception{
private int code;
public ApiException (int code, String msg) {
super(msg);
this.code = code;
}
}

View File

@ -0,0 +1,22 @@
package {{apiPackage}};
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
{{>generatedAnnotation}}
public class ApiOriginFilter implements javax.servlet.Filter {
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
res.addHeader("Access-Control-Allow-Origin", "*");
res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
res.addHeader("Access-Control-Allow-Headers", "Content-Type");
chain.doFilter(request, response);
}
public void destroy() {}
public void init(FilterConfig filterConfig) throws ServletException {}
}

View File

@ -0,0 +1,69 @@
package {{apiPackage}};
import javax.xml.bind.annotation.XmlTransient;
@javax.xml.bind.annotation.XmlRootElement
{{>generatedAnnotation}}
public class ApiResponseMessage {
public static final int ERROR = 1;
public static final int WARNING = 2;
public static final int INFO = 3;
public static final int OK = 4;
public static final int TOO_BUSY = 5;
int code;
String type;
String message;
public ApiResponseMessage(){}
public ApiResponseMessage(int code, String message){
this.code = code;
switch(code){
case ERROR:
setType("error");
break;
case WARNING:
setType("warning");
break;
case INFO:
setType("info");
break;
case OK:
setType("ok");
break;
case TOO_BUSY:
setType("too busy");
break;
default:
setType("unknown");
break;
}
this.message = message;
}
@XmlTransient
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

View File

@ -0,0 +1,44 @@
package {{apiPackage}};
import com.sun.jersey.core.spi.component.ComponentContext;
import com.sun.jersey.spi.inject.Injectable;
import com.sun.jersey.spi.inject.PerRequestTypeInjectableProvider;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Provider;
import org.joda.time.DateTime;
import java.util.List;
@Provider
public class JodaDateTimeProvider extends PerRequestTypeInjectableProvider<QueryParam, DateTime> {
private final UriInfo uriInfo;
public JodaDateTimeProvider(@Context UriInfo uriInfo) {
super(DateTime.class);
this.uriInfo = uriInfo;
}
@Override
public Injectable<DateTime> getInjectable(final ComponentContext cc, final QueryParam a) {
return new Injectable<DateTime>() {
@Override
public DateTime getValue() {
final List<String> values = uriInfo.getQueryParameters().get(a.value());
if (values == null || values.isEmpty())
return null;
if (values.size() > 1) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).
entity(a.value() + " cannot contain multiple values").build());
}
return DateTime.parse(values.get(0));
}
};
}
}

View File

@ -0,0 +1,44 @@
package {{apiPackage}};
import com.sun.jersey.core.spi.component.ComponentContext;
import com.sun.jersey.spi.inject.Injectable;
import com.sun.jersey.spi.inject.PerRequestTypeInjectableProvider;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Provider;
import org.joda.time.LocalDate;
import java.util.List;
@Provider
public class JodaLocalDateProvider extends PerRequestTypeInjectableProvider<QueryParam, LocalDate> {
private final UriInfo uriInfo;
public JodaLocalDateProvider(@Context UriInfo uriInfo) {
super(LocalDate.class);
this.uriInfo = uriInfo;
}
@Override
public Injectable<LocalDate> getInjectable(final ComponentContext cc, final QueryParam a) {
return new Injectable<LocalDate>() {
@Override
public LocalDate getValue() {
final List<String> values = uriInfo.getQueryParameters().get(a.value());
if (values == null || values.isEmpty())
return null;
if (values.size() > 1) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).
entity(a.value() + " cannot contain multiple values").build());
}
return LocalDate.parse(values.get(0));
}
};
}
}

View File

@ -0,0 +1,44 @@
package {{apiPackage}};
import com.sun.jersey.core.spi.component.ComponentContext;
import com.sun.jersey.spi.inject.Injectable;
import com.sun.jersey.spi.inject.PerRequestTypeInjectableProvider;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Provider;
import java.time.LocalDate;
import java.util.List;
@Provider
public class LocalDateProvider extends PerRequestTypeInjectableProvider<QueryParam, LocalDate> {
private final UriInfo uriInfo;
public LocalDateProvider(@Context UriInfo uriInfo) {
super(LocalDate.class);
this.uriInfo = uriInfo;
}
@Override
public Injectable<LocalDate> getInjectable(final ComponentContext cc, final QueryParam a) {
return new Injectable<LocalDate>() {
@Override
public LocalDate getValue() {
final List<String> values = uriInfo.getQueryParameters().get(a.value());
if (values == null || values.isEmpty())
return null;
if (values.size() > 1) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).
entity(a.value() + " cannot contain multiple values").build());
}
return LocalDate.parse(values.get(0));
}
};
}
}

View File

@ -0,0 +1,44 @@
package {{apiPackage}};
import com.sun.jersey.core.spi.component.ComponentContext;
import com.sun.jersey.spi.inject.Injectable;
import com.sun.jersey.spi.inject.PerRequestTypeInjectableProvider;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Provider;
import java.time.LocalDateTime;
import java.util.List;
@Provider
public class LocalDateTimeProvider extends PerRequestTypeInjectableProvider<QueryParam, LocalDateTime> {
private final UriInfo uriInfo;
public LocalDateTimeProvider(@Context UriInfo uriInfo) {
super(LocalDateTime.class);
this.uriInfo = uriInfo;
}
@Override
public Injectable<LocalDateTime> getInjectable(final ComponentContext cc, final QueryParam a) {
return new Injectable<LocalDateTime>() {
@Override
public LocalDateTime getValue() {
final List<String> values = uriInfo.getQueryParameters().get(a.value());
if (values == null || values.isEmpty())
return null;
if (values.size() > 1) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).
entity(a.value() + " cannot contain multiple values").build());
}
return LocalDateTime.parse(values.get(0));
}
};
}
}

View File

@ -0,0 +1,10 @@
package {{apiPackage}};
{{>generatedAnnotation}}
public class NotFoundException extends ApiException {
private int code;
public NotFoundException (int code, String msg) {
super(code, msg);
this.code = code;
}
}

View File

@ -0,0 +1,23 @@
# Swagger Jersey 2 generated server
## Overview
This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the
[OpenAPI-Spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This
is an example of building a swagger-enabled JAX-RS server.
This example uses the [JAX-RS](https://jax-rs-spec.java.net/) framework.
To run the server, please execute the following:
```
mvn clean package jetty:run
```
You can then view the swagger listing here:
```
http://localhost:{{serverPort}}{{contextPath}}/swagger.json
```
Note that if you have configured the `host` to be something other than localhost, the calls through
swagger-ui will be directed to that host and not localhost!

View File

@ -0,0 +1,42 @@
package {{invokerPackage}};
{{>generatedAnnotation}}
public class StringUtil {
/**
* Check if the given array contains the given value (with case-insensitive comparison).
*
* @param array The array
* @param value The value to search
* @return true if the array contains the value
*/
public static boolean containsIgnoreCase(String[] array, String value) {
for (String str : array) {
if (value == null && str == null) return true;
if (value != null && value.equalsIgnoreCase(str)) return true;
}
return false;
}
/**
* Join an array of strings with the given separator.
* <p>
* Note: This might be replaced by utility method from commons-lang or guava someday
* if one of those libraries is added as dependency.
* </p>
*
* @param array The array of strings
* @param separator The separator
* @return the resulting string
*/
public static String join(String[] array, String separator) {
int len = array.length;
if (len == 0) return "";
StringBuilder out = new StringBuilder();
out.append(array[0]);
for (int i = 1; i < len; i++) {
out.append(separator).append(array[i]);
}
return out.toString();
}
}

View File

@ -0,0 +1 @@
{{#allowableValues}}allowableValues="{{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}{{^values}}range=[{{#min}}{{.}}{{/min}}{{^min}}-infinity{{/min}}, {{#max}}{{.}}{{/max}}{{^max}}infinity{{/max}}]{{/values}}"{{/allowableValues}}

View File

@ -0,0 +1,55 @@
package {{package}};
import {{modelPackage}}.*;
import {{package}}.{{classname}}Service;
import {{package}}.factories.{{classname}}ServiceFactory;
import io.swagger.annotations.ApiParam;
{{#imports}}import {{import}};
{{/imports}}
import java.util.List;
import {{package}}.NotFoundException;
import java.io.InputStream;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.*;
@Path("/{{baseName}}")
{{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}}
{{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}}
@io.swagger.annotations.Api(description = "the {{baseName}} API")
{{>generatedAnnotation}}
{{#operations}}
public class {{classname}} {
private final {{classname}}Service delegate = {{classname}}ServiceFactory.get{{classname}}();
{{#operation}}
@{{httpMethod}}
{{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}}
{{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}}
{{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}}
@io.swagger.annotations.ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}{{#hasAuthMethods}}, authorizations = {
{{#authMethods}}@io.swagger.annotations.Authorization(value = "{{name}}"{{#isOAuth}}, scopes = {
{{#scopes}}@io.swagger.annotations.AuthorizationScope(scope = "{{scope}}", description = "{{description}}"){{#hasMore}},
{{/hasMore}}{{/scopes}}
}{{/isOAuth}}){{#hasMore}},
{{/hasMore}}{{/authMethods}}
}{{/hasAuthMethods}}, tags={ {{#vendorExtensions.x-tags}}"{{tag}}",{{/vendorExtensions.x-tags}} })
@io.swagger.annotations.ApiResponses(value = { {{#responses}}
@io.swagger.annotations.ApiResponse(code = {{{code}}}, message = "{{{message}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}){{#hasMore}},
{{/hasMore}}{{/responses}} })
public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}},{{/allParams}}@Context SecurityContext securityContext)
throws NotFoundException {
return delegate.{{nickname}}({{#allParams}}{{#isFile}}inputStream, fileDetail{{/isFile}}{{^isFile}}{{paramName}}{{/isFile}},{{/allParams}}securityContext);
}
{{/operation}}
}
{{/operations}}

View File

@ -0,0 +1,26 @@
package {{package}};
import {{package}}.*;
import {{modelPackage}}.*;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
{{#imports}}import {{import}};
{{/imports}}
import java.util.List;
import {{package}}.NotFoundException;
import java.io.InputStream;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
{{>generatedAnnotation}}
{{#operations}}
public abstract class {{classname}}Service {
{{#operation}}
public abstract Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}},{{/allParams}}SecurityContext securityContext) throws NotFoundException;
{{/operation}}
}
{{/operations}}

View File

@ -0,0 +1,13 @@
package {{package}}.factories;
import {{package}}.{{classname}}Service;
import {{package}}.impl.{{classname}}ServiceImpl;
{{>generatedAnnotation}}
public class {{classname}}ServiceFactory {
private final static {{classname}}Service service = new {{classname}}ServiceImpl();
public static {{classname}}Service get{{classname}}() {
return service;
}
}

View File

@ -0,0 +1,30 @@
package {{package}}.impl;
import {{package}}.*;
import {{modelPackage}}.*;
{{#imports}}import {{import}};
{{/imports}}
import java.util.List;
import {{package}}.NotFoundException;
import java.io.InputStream;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
{{>generatedAnnotation}}
{{#operations}}
public class {{classname}}ServiceImpl extends {{classname}}Service {
{{#operation}}
@Override
public Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}, {{/allParams}}SecurityContext securityContext) throws NotFoundException {
// do some magic!
return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build();
}
{{/operation}}
}
{{/operations}}

View File

@ -0,0 +1 @@
{{#isBodyParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{{dataType}}} {{paramName}}{{/isBodyParam}}

View File

@ -0,0 +1,31 @@
package {{apiPackage}};
import io.swagger.jaxrs.config.SwaggerContextService;
import io.swagger.models.*;
import io.swagger.models.auth.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
public class Bootstrap extends HttpServlet {
@Override
public void init(ServletConfig config) throws ServletException {
Info info = new Info()
.title("{{title}}")
.description("{{{appDescription}}}")
.termsOfService("{{termsOfService}}")
.contact(new Contact()
.email("{{infoEmail}}"))
.license(new License()
.name("{{licenseInfo}}")
.url("{{licenseUrl}}"));
ServletContext context = config.getServletContext();
Swagger swagger = new Swagger().info(info);
new SwaggerContextService().withServletConfig(config).updateSwagger(swagger);
}
}

View File

@ -0,0 +1,17 @@
public enum {{{datatypeWithEnum}}} {
{{#allowableValues}}{{#enumVars}}{{{name}}}("{{{value}}}"){{^-last}},
{{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}}
private String value;
{{{datatypeWithEnum}}}(String value) {
this.value = value;
}
@Override
@JsonValue
public String toString() {
return value;
}
}

View File

@ -0,0 +1,3 @@
public enum {{classname}} {
{{#allowableValues}}{{.}}{{^-last}}, {{/-last}}{{/allowableValues}}
}

View File

@ -0,0 +1,3 @@
{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}){{#vendorExtensions.x-multipart}}@FormDataParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{^vendorExtensions.x-multipart}}@FormParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{/notFile}}{{#isFile}}
@FormDataParam("file") InputStream inputStream,
@FormDataParam("file") FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}}

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