sync from origin master

This commit is contained in:
abcsun 2016-06-13 10:25:03 +08:00
commit bffb0fb4d8
2034 changed files with 78304 additions and 34362 deletions

46
.github/ISSUE_TEMPLATE.md vendored Normal file
View File

@ -0,0 +1,46 @@
<!--
Please follow the issue template below for bug reports and feature requests.
Also please indicate in the issue title which language/library is concerned. Eg: [JAVA] Bug generating foo with bar
-->
##### Description
<!-- describe what is the issue and why this is a problem for you. -->
##### Swagger-codegen version
<!-- which version of swagger-codegen are you using, is it a regression? -->
##### Swagger declaration file content or url
<!-- if it is a bug, a json or yaml that produces it.
If you post the code inline, please wrap it with
```yaml
(here your code)
```
(for YAML code) or
```json
(here your code)
```
(for JSON code), so it becomes more readable. If it is longer than about ten lines,
please create a Gist (https://gist.github.com) or upload it somewhere else and
link it here.
-->
##### Command line used for generation
<!-- including the language, libraries and various options -->
##### Steps to reproduce
<!-- unambiguous set of steps to reproduce the bug.-->
##### Related issues
<!-- has a similar issue been reported before? -->
##### Suggest a Fix
<!-- if you can't fix the bug yourself, perhaps you can point to what might be
causing the problem (line of code or commit) -->

22
.gitignore vendored
View File

@ -41,6 +41,7 @@ samples/server-generator/scalatra/target
samples/server-generator/scalatra/output/.history
# nodejs
**/node_modules/
samples/server-generator/node/output/node_modules
samples/server/petstore/nodejs/node_modules
samples/server/petstore/nodejs-server/node_modules
@ -62,6 +63,12 @@ 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/
samples/client/petstore/java/feign/build/
samples/client/petstore/java/retrofit/build/
samples/client/petstore/java/retrofit2/build/
samples/client/petstore/java/retrofit2rx/build/
samples/client/petstore/java/default/build/
samples/client/petstore/scala/build/
#PHP
samples/client/petstore/php/SwaggerClient-php/composer.lock
@ -88,6 +95,7 @@ samples/client/petstore/swift/SwaggerClientTests/Pods/Pods.xcodeproj/xcshareddat
# C#
*.csproj.user
samples/client/petstore/csharp/SwaggerClient/IO.Swagger.userprefs
samples/client/petstore/csharp/SwaggerClientTest/.vs
samples/client/petstore/csharp/SwaggerClientTest/obj
samples/client/petstore/csharp/SwaggerClientTest/bin
@ -104,6 +112,7 @@ samples/client/petstore/csharp/SwaggerClient/bin
samples/client/petstore/csharp/SwaggerClient/obj/Debug/
samples/client/petstore/csharp/SwaggerClient/bin/Debug/
samples/client/petstore/csharp/SwaggerClient/packages
samples/client/petstore/csharp/SwaggerClient/TestResult.xml
# Python
*.pyc
@ -116,13 +125,8 @@ samples/client/petstore/python/.venv/
# ts
samples/client/petstore/typescript-node/npm/node_modules
samples/client/petstore/typescript-fetch/with-package-metadata/node_modules
samples/client/petstore/typescript-fetch/with-package-metadata/dist
samples/client/petstore/typescript-fetch/with-package-metadata/typings
samples/client/petstore/typescript-fetch/default/node_modules
samples/client/petstore/typescript-fetch/default/dist
samples/client/petstore/typescript-fetch/default/typings
samples/client/petstore/typescript-fetch/default-es6/node_modules
samples/client/petstore/typescript-fetch/default-es6/dist
samples/client/petstore/typescript-fetch/default-es6/typings
samples/client/petstore/typescript-node/**/typings
samples/client/petstore/typescript-angular/**/typings
samples/client/petstore/typescript-fetch/**/dist/
samples/client/petstore/typescript-fetch/**/typings

View File

@ -10,6 +10,8 @@ services:
before_install:
# required when sudo: required for the Ruby petstore tests
- gem install bundler
- npm install -g typescript
- sudo pip install virtualenv
install:

View File

@ -2,12 +2,10 @@
## Before submitting an issue
- If you're not using the latest master to generate API clients or server stubs, please give it another try by pulling the latest master as the issue may have already been addressed. Ref: [Getting Started](https://github.com/swagger-api/swagger-codegen#getting-started)
- Search the [open issue](https://github.com/swagger-api/swagger-codegen/issues) and [closed issue](https://github.com/swagger-api/swagger-codegen/issues?q=is%3Aissue+is%3Aclosed) to ensure no one else has reported something similar before.
- The issue should contain details on how to repeat the issue, e.g.
- the OpenAPI Spec for reproducing the issue (:bulb: use [Gist](https://gist.github.com) to share). If the OpenAPI Spec cannot be shared publicly, it will be hard for the community to help
- version of Swagger Codegen
- language (`-l` in the command line, e.g. java, csharp, php)
- You can also make a suggestion or ask a question by opening an "issue"
- File an [issue ticket](https://github.com/swagger-api/swagger-codegen/issues/new) by providing all the required information.
- You can also make a suggestion or ask a question by opening an "issue".
## Before submitting a PR
@ -42,11 +40,14 @@ Code change should conform to the programming style guide of the respective lang
- Swift: https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html
- TypeScript: https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines
For other languages, feel free to suggest.
You may find the current code base not 100% conform to the coding style and we welcome contributions to fix those.
For [Vendor Extensions](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#vendorExtensions), please follow the naming convention below:
- For general vendor extension, use lower case and hyphen. e.g. `x-is-unique`, `x-content-type`
- For language-specified vendor extension, put it in the form of `x-{lang}-{extension-name}`. e.g. `x-objc-operation-id`, `x-java-feign-retry-limit`
### Testing
To add test cases (optional) covering the change in the code generator, please refer to [modules/swagger-codegen/src/test/java/io/swagger/codegen](https://github.com/swagger-api/swagger-codegen/tree/master/modules/swagger-codegen/src/test/java/io/swagger/codegen)

View File

@ -69,7 +69,7 @@ The OpenAPI Specification has undergone 3 revisions since initial creation in 20
Swagger Codegen Version | Release Date | OpenAPI Spec compatibility | Notes
-------------------------- | ------------ | -------------------------- | -----
2.1.7-SNAPSHOT | | 1.0, 1.1, 1.2, 2.0 | [master](https://github.com/swagger-api/swagger-codegen)
2.2.0-SNAPSHOT | | 1.0, 1.1, 1.2, 2.0 | [master](https://github.com/swagger-api/swagger-codegen)
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)
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)
@ -386,8 +386,66 @@ To control the specific files being generated, you can pass a CSV list of what y
-Dmodels=User -DsupportingFiles=StringUtil.java
```
To control generation of docs and tests for api and models, pass false to the option. For api, these options are `-DapiTest=false` and `-DapiDocs=false`. For models, `-DmodelTest=false` and `-DmodelDocs=false`.
These options default to true and don't limit the generation of the feature options listed above (like `-Dapi`):
```
# generate only models (with tests and documentation)
java -Dmodels {opts}
# generate only models (with tests but no documentation)
java -Dmodels -DmodelDocs=false {opts}
# generate only User and Pet models (no tests and no documentation)
java -Dmodels=User,Pet -DmodelTests=false {opts}
# generate only apis (without tests)
java -Dapis -DapiTests=false {opts}
# generate only apis (modelTests option is ignored)
java -Dapis -DmodelTests=false {opts}
```
When using selective generation, _only_ the templates needed for the specific generation will be used.
### Ignore file format
Swagger codegen supports a `.swagger-codegen-ignore` file, similar to `.gitignore` or `.dockerignore` you're probably already familiar with.
The ignore file allows for better control over overwriting existing files than the `--skip-overwrite` flag. With the ignore file, you can specify individual files or directories can be ignored. This can be useful, for example if you only want a subset of the generated code.
Examples:
```
# Swagger Codegen Ignore
# Lines beginning with a # are comments
# This should match build.sh located anywhere.
build.sh
# Matches build.sh in the root
/build.sh
# Exclude all recursively
docs/**
# Explicitly allow files excluded by other rules
!docs/UserApi.md
# Recursively exclude directories named Api
# You can't negate files below this directory.
src/**/Api/
# When this file is nested under /Api (excluded above),
# this rule is ignored because parent directory is excluded by previous rule.
!src/**/PetApiTests.cs
# Exclude a single, nested file explicitly
src/IO.Swagger.Test/Model/AnimalFarmTests.cs
```
The `.swagger-codegen-ignore` file must exist in the root of the output directory.
### Customizing the generator
There are different aspects of customizing the code generator beyond just creating or modifying templates. Each language has a supporting configuration file to handle different type mappings, etc:
@ -608,7 +666,7 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
```
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
-i http://petstore.swagger.io/v2/swagger.json \
-l silex \
-l silex-PHP \
-o samples/server/petstore/silex
```
@ -789,20 +847,25 @@ Here are some companies/projects using Swagger Codegen in production. To add you
- [Activehours](https://www.activehours.com/)
- [Acunetix](https://www.acunetix.com/)
- [Atlassian](https://www.atlassian.com/)
- [Avenida Compras S.A.](https://www.avenida.com.ar)
- [beemo](http://www.beemo.eu)
- [bitly](https://bitly.com)
- [Cachet Financial](http://www.cachetfinancial.com/)
- [CloudBoost](https://www.CloudBoost.io/)
- [Cupix](http://www.cupix.com)
- [DBBest Technologies](https://www.dbbest.com)
- [DocuSign](https://www.docusign.com)
- [Ergon](http://www.ergon.ch/)
- [eureka](http://eure.jp/)
- [everystory.us](http://everystory.us)
- [Expected Behavior](http://www.expectedbehavior.com/)
- [FH Münster - University of Applied Sciences](http://www.fh-muenster.de)
- [GraphHopper](https://graphhopper.com/)
- [IMS Health](http://www.imshealth.com/en/solution-areas/technology-and-applications)
- [Interactive Intelligence](http://developer.mypurecloud.com/)
- [LANDR Audio](https://www.landr.com/)
- [LiveAgent](https://www.ladesk.com/)
- [Kabuku](http://www.kabuku.co.jp/en)
- [Kuary](https://kuary.com/)
- [nViso](http://www.nviso.ch/)
- [Okiok](https://www.okiok.com)
@ -813,12 +876,15 @@ Here are some companies/projects using Swagger Codegen in production. To add you
- [PostAffiliatePro](https://www.postaffiliatepro.com/)
- [Reload! A/S](https://reload.dk/)
- [REstore](https://www.restore.eu)
- [Revault Sàrl](http://revault.ch)
- [Royal Bank of Canada (RBC)](http://www.rbc.com/canada.html)
- [SCOOP Software GmbH](http://www.scoop-software.de)
- [SmartRecruiters](https://www.smartrecruiters.com/)
- [StyleRecipe](http://stylerecipe.co.jp)
- [Svenska Spel AB](https://www.svenskaspel.se/)
- [ThoughtWorks](https://www.thoughtworks.com)
- [uShip](https://www.uship.com/)
- [WEXO A/S](https://www.wexo.dk/)
- [Zalando](https://tech.zalando.com)
- [ZEEF.com](https://zeef.com/)
@ -836,13 +902,13 @@ Swaagger Codegen core team members are contributors who have been making signfic
| Dart | |
| Groovy | |
| Go | @guohuang (2016/05/01) @neilotoole (2016/05/01) |
| Java | @cbornet (2016/05/01) @xhh (2016/05/01) |
| Java | @cbornet (2016/05/01) @xhh (2016/05/01) @epaul (2016/06/04) |
| NodeJS/Javascript | @xhh (2016/05/01) |
| ObjC | @mateuszmackowiak (2016/05/09) |
| Perl | @wing328 (2016/05/01) |
| PHP | @arnested (2016/05/01) |
| Python | @scottrw93 (2016/05/01) |
| Ruby | @wing328 (2016/05/01) |
| Ruby | @wing328 (2016/05/01) @zlx (2016/05/22) |
| Scala | |
| Swift | @jaz-ah (2016/05/01) @Edubits (2016/05/01) |
| TypeScript (Node) | @Vrolijkx (2016/05/01) |
@ -894,6 +960,7 @@ Here is a list of template creators:
* JAX-RS CXF: @hiveship
* PHP Lumen: @abcsum
* PHP Slim: @jfastnacht
* Ruby on Rails 5: @zlx
## How to join the core team

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/android -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l android -Dlibrary=httpclient -o samples/client/petstore/android/httpclient"
java $JAVA_OPTS -jar $executable $ags

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

31
bin/rails5-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/rails5 -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l rails5 -o samples/server/petstore/rails5"
java $JAVA_OPTS -jar $executable $ags

31
bin/spring-stubs.sh Executable file
View File

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

View File

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

View File

@ -0,0 +1,7 @@
{
"podSummary": "PetstoreClient",
"podHomepage": "https://github.com/swagger-api/swagger-codegen",
"podAuthors": "",
"projectName": "PetstoreClient",
"responseAs": "PromiseKit"
}

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/swift -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l swift -c ./bin/swift-petstore-promisekit.json -o samples/client/petstore/swift/promisekit"
java $JAVA_OPTS -jar $executable $ags

View File

@ -1,4 +1,6 @@
{
"projectName": "PetstoreClient",
"responseAs": "PromiseKit"
"podSummary": "PetstoreClient",
"podHomepage": "https://github.com/swagger-api/swagger-codegen",
"podAuthors": "",
"projectName": "PetstoreClient"
}

View File

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

View File

@ -1,5 +1,5 @@
#!/bin/sh
./bin/typescript-fetch-petstore-target-es6.sh
./bin/typescript-fetch-petstore-target-with-package-metadata.sh
./bin/typescript-fetch-petstore-with-npm-version.sh
./bin/typescript-fetch-petstore.sh

View File

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

View File

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

View File

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

View File

@ -0,0 +1,10 @@
set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar
If Not Exist %executable% (
mvn clean package
)
set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -t modules\swagger-codegen\src\main\resources\java -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l java -o samples\client\petstore\java --library=okhttp-gson -DdateLibrary=joda,hideGenerationTimestamp=true
java %JAVA_OPTS% -jar %executable% %ags%

View File

@ -5,6 +5,6 @@ If Not Exist %executable% (
)
set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -t modules\swagger-codegen\src\main\resources\java -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l java -o samples\client\petstore\java
set ags=generate -t modules\swagger-codegen\src\main\resources\java -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l java -o samples\client\petstore\java -DdateLibrary=joda,hideGenerationTimestamp=true
java %JAVA_OPTS% -jar %executable% %ags%

View File

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

View File

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

View File

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

View File

@ -48,6 +48,44 @@ mvn clean compile
- `configOptions` - a map of language-specific parameters (see below)
- `configHelp` - dumps the configuration help for the specified library (generates no sources)
### Custom Generator
Specifying a custom generator is a bit different. It doesn't support the classpath:/ syntax, but it does support the fully qualified name of the package. You can also specify your custom templates, which also get pulled in. Notice the dependency on a project, in the plugin scope. That would be your generator/template jar.
```xml
<plugin>
<groupId>io.swagger</groupId>
<artifactId>swagger-codegen-maven-plugin</artifactId>
<version>${swagger-codegen-maven-plugin-version}</version>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<inputSpec>src/main/resources/yaml/yamlfilename.yaml</inputSpec>
<!-- language file, like e.g. JavaJaxRSCodegen shipped with swagger -->
<language>com.my.package.for.GeneratorLanguage</language>
<templateDirectory>myTemplateDir</templateDirectory>
<output>${project.build.directory}/generated-sources</output>
<apiPackage>${default.package}.handler</apiPackage>
<modelPackage>${default.package}.model</modelPackage>
<invokerPackage>${default.package}.handler</invokerPackage>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>com.my.generator</groupId>
<artifactId>customgenerator</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</plugin>
```
### Sample configuration
- Please see [an example configuration](examples) for using the plugin
- Please see [an example configuration](examples) for using the plugin

View File

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

View File

@ -163,8 +163,6 @@ public class CodeGenMojo extends AbstractMojo {
@Override
public void execute() throws MojoExecutionException {
Swagger swagger = new SwaggerParser().read(inputSpec);
//attempt to read from config file
CodegenConfigurator configurator = CodegenConfigurator.fromFile(configurationFile);

View File

@ -1 +1,2 @@
/.settings/
/test-output/

View File

@ -3,7 +3,7 @@
<parent>
<groupId>io.swagger</groupId>
<artifactId>swagger-codegen-project</artifactId>
<version>2.1.6</version>
<version>2.2.0-SNAPSHOT</version>
<relativePath>../..</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
@ -199,6 +199,9 @@
</plugin>
</plugins>
</reporting>
<properties>
<diffutils-version>1.2.1</diffutils-version>
</properties>
<dependencies>
<dependency>
<groupId>io.swagger</groupId>
@ -279,6 +282,13 @@
<!-- <version>${jmockit-version}</version> -->
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.googlecode.java-diff-utils</groupId>
<artifactId>diffutils</artifactId>
<version>${diffutils-version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>

View File

@ -72,33 +72,35 @@ public abstract class AbstractGenerator {
* @return String Full template file path
*/
public String getFullTemplateFile(CodegenConfig config, String templateFile) {
String library = config.getLibrary();
if (library != null && !"".equals(library)) {
String libTemplateFile = config.templateDir() + File.separator +
"libraries" + File.separator + library + File.separator +
templateFile;
if (new File(libTemplateFile).exists()) {
return libTemplateFile;
}
libTemplateFile = config.embeddedTemplateDir() + File.separator +
"libraries" + File.separator + library + File.separator +
templateFile;
if (embeddedTemplateExists(libTemplateFile)) {
// Fall back to the template file embedded/packaged in the JAR file...
return libTemplateFile;
}
}
String template = config.templateDir() + File.separator + templateFile;
if (new File(template).exists()) {
return template;
} else {
String library = config.getLibrary();
if (library != null && !"".equals(library)) {
String libTemplateFile = config.embeddedTemplateDir() + File.separator +
"libraries" + File.separator + library + File.separator +
templateFile;
if (embeddedTemplateExists(libTemplateFile)) {
// Fall back to the template file embedded/packaged in the JAR file...
return libTemplateFile;
}
}
// Fall back to the template file embedded/packaged in the JAR file...
return config.embeddedTemplateDir() + File.separator + templateFile;
}
}
public String readResourceContents(String resourceFilePath) {
StringBuilder sb = new StringBuilder();
Scanner scanner = new Scanner(this.getClass().getResourceAsStream(getCPResourcePath(resourceFilePath)), "UTF-8");
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
sb.append(line).append('\n');
}
return sb.toString();
}
public boolean embeddedTemplateExists(String name) {
return this.getClass().getClassLoader().getResource(getCPResourcePath(name)) != null;
}

View File

@ -1,10 +1,10 @@
package io.swagger.codegen;
import io.swagger.codegen.auth.AuthMethod;
import java.util.HashMap;
import java.util.Map;
import io.swagger.codegen.auth.AuthMethod;
public class ClientOpts {
protected String uri;
protected String target;

View File

@ -184,4 +184,5 @@ public interface CodegenConfig {
String getHttpUserAgent();
String getCommonTemplateDir();
}

View File

@ -105,4 +105,14 @@ public class CodegenConstants {
public static final String SUPPORTS_ES6 = "supportsES6";
public static final String SUPPORTS_ES6_DESC = "Generate code that conforms to ES6.";
public static final String EXCLUDE_TESTS = "excludeTests";
public static final String EXCLUDE_TESTS_DESC = "Specifies that no tests are to be generated.";
public static final String GENERATE_API_TESTS = "generateApiTests";
public static final String GENERATE_API_TESTS_DESC = "Specifies that api tests are to be generated.";
public static final String GENERATE_MODEL_TESTS = "generateModelTests";
public static final String GENERATE_MODEL_TESTS_DESC = "Specifies that model tests are to be generated.";
}

View File

@ -1,7 +1,13 @@
package io.swagger.codegen;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import io.swagger.models.ExternalDocs;
import java.util.*;
public class CodegenModel {
public String parent, parentSchema;
@ -19,6 +25,8 @@ public class CodegenModel {
public List<CodegenProperty> vars = new ArrayList<CodegenProperty>();
public List<CodegenProperty> requiredVars = new ArrayList<CodegenProperty>(); // a list of required properties
public List<CodegenProperty> optionalVars = new ArrayList<CodegenProperty>(); // a list of optional properties
public List<CodegenProperty> readOnlyVars = new ArrayList<CodegenProperty>(); // a list of read-only properties
public List<CodegenProperty> readWriteVars = new ArrayList<CodegenProperty>(); // a list of properties for read, write
public List<CodegenProperty> allVars;
public Map<String, Object> allowableValues;
@ -27,11 +35,14 @@ public class CodegenModel {
public Set<String> allMandatory;
public Set<String> imports = new TreeSet<String>();
public Boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum;
public Boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum, hasRequired;
public ExternalDocs externalDocs;
public Map<String, Object> vendorExtensions;
//The type of the value from additional properties. Used in map like objects.
public String additionalPropertiesType;
{
// 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.

View File

@ -7,13 +7,16 @@ import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Arrays;
public class CodegenOperation {
public final List<CodegenProperty> responseHeaders = new ArrayList<CodegenProperty>();
public Boolean hasAuthMethods, hasConsumes, hasProduces, hasParams, hasOptionalParams,
returnTypeIsPrimitive, returnSimpleType, subresourceOperation, isMapContainer,
isListContainer, isMultipart, hasMore = Boolean.TRUE,
isResponseBinary = Boolean.FALSE, hasReference = Boolean.FALSE;
isResponseBinary = Boolean.FALSE, hasReference = Boolean.FALSE,
isRestfulIndex, isRestfulShow, isRestfulCreate, isRestfulUpdate, isRestfulDestroy,
isRestful;
public String path, operationId, returnType, httpMethod, returnBaseType,
returnContainer, summary, unescapedNotes, notes, baseName, defaultResponse, discriminator;
public List<Map<String, String>> consumes, produces;
@ -88,6 +91,81 @@ public class CodegenOperation {
return nonempty(formParams);
}
/**
* Check if act as Restful index method
*
* @return true if act as Restful index method, false otherwise
*/
public boolean isRestfulIndex() {
return "GET".equals(httpMethod) && "".equals(pathWithoutBaseName());
}
/**
* Check if act as Restful show method
*
* @return true if act as Restful show method, false otherwise
*/
public boolean isRestfulShow() {
return "GET".equals(httpMethod) && isMemberPath();
}
/**
* Check if act as Restful create method
*
* @return true if act as Restful create method, false otherwise
*/
public boolean isRestfulCreate() {
return "POST".equals(httpMethod) && "".equals(pathWithoutBaseName());
}
/**
* Check if act as Restful update method
*
* @return true if act as Restful update method, false otherwise
*/
public boolean isRestfulUpdate() {
return Arrays.asList("PUT", "PATCH").contains(httpMethod) && isMemberPath();
}
/**
* Check if act as Restful destroy method
*
* @return true if act as Restful destroy method, false otherwise
*/
public boolean isRestfulDestroy() {
return "DELETE".equals(httpMethod) && isMemberPath();
}
/**
* Check if Restful-style
*
* @return true if Restful-style, false otherwise
*/
public boolean isRestful() {
return isRestfulIndex() || isRestfulShow() || isRestfulCreate() || isRestfulUpdate() || isRestfulDestroy();
}
/**
* Get the substring except baseName from path
*
* @return the substring
*/
private String pathWithoutBaseName() {
return baseName != null ? path.replace("/" + baseName.toLowerCase(), "") : path;
}
/**
* Check if the path match format /xxx/:id
*
* @return true if path act as member
*/
private boolean isMemberPath() {
if (pathParams.size() != 1) return false;
String id = pathParams.get(0).baseName;
return ("/{" + id + "}").equals(pathWithoutBaseName());
}
@Override
public String toString() {
return String.format("%s(%s)", baseName, path);

View File

@ -2,25 +2,76 @@ package io.swagger.codegen;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import io.swagger.codegen.examples.ExampleGenerator;
import io.swagger.models.*;
import io.swagger.models.auth.*;
import io.swagger.models.parameters.*;
import io.swagger.models.properties.*;
import io.swagger.models.properties.PropertyBuilder.PropertyId;
import io.swagger.util.Json;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.File;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
import io.swagger.codegen.examples.ExampleGenerator;
import io.swagger.models.ArrayModel;
import io.swagger.models.ComposedModel;
import io.swagger.models.Model;
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.AbstractNumericProperty;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BaseIntegerProperty;
import io.swagger.models.properties.BinaryProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.ByteArrayProperty;
import io.swagger.models.properties.DateProperty;
import io.swagger.models.properties.DateTimeProperty;
import io.swagger.models.properties.DecimalProperty;
import io.swagger.models.properties.DoubleProperty;
import io.swagger.models.properties.FloatProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.PropertyBuilder;
import io.swagger.models.properties.PropertyBuilder.PropertyId;
import io.swagger.models.properties.RefProperty;
import io.swagger.models.properties.StringProperty;
import io.swagger.models.properties.UUIDProperty;
import io.swagger.util.Json;
public class DefaultCodegen {
protected static final Logger LOGGER = LoggerFactory.getLogger(DefaultCodegen.class);
@ -43,6 +94,7 @@ public class DefaultCodegen {
protected Map<String, String> modelDocTemplateFiles = new HashMap<String, String>();
protected String templateDir;
protected String embeddedTemplateDir;
protected String commonTemplateDir = "_common";
protected Map<String, Object> additionalProperties = new HashMap<String, Object>();
protected Map<String, Object> vendorExtensions = new HashMap<String, Object>();
protected List<SupportingFile> supportingFiles = new ArrayList<SupportingFile>();
@ -390,6 +442,14 @@ public class DefaultCodegen {
}
}
public String getCommonTemplateDir() {
return this.commonTemplateDir;
}
public void setCommonTemplateDir(String commonTemplateDir) {
this.commonTemplateDir = commonTemplateDir;
}
public Map<String, String> apiDocTemplateFiles() {
return apiDocTemplateFiles;
}
@ -732,6 +792,12 @@ public class DefaultCodegen {
importMapping.put("LocalDate", "org.joda.time.*");
importMapping.put("LocalTime", "org.joda.time.*");
// we've used the .swagger-codegen-ignore approach as
// suppportingFiles can be cleared by code generator that extends
// the default codegen, leaving the commented code below for
// future reference
//supportingFiles.add(new GlobalSupportingFile("LICENSE", "LICENSE"));
cliOptions.add(CliOption.newBoolean(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG,
CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC).defaultValue(Boolean.TRUE.toString()));
cliOptions.add(CliOption.newBoolean(CodegenConstants.ENSURE_UNIQUE_PARAMS, CodegenConstants
@ -1207,8 +1273,7 @@ public class DefaultCodegen {
m.dataType = getSwaggerType(p);
}
if (impl.getAdditionalProperties() != null) {
MapProperty mapProperty = new MapProperty(impl.getAdditionalProperties());
addParentContainer(m, name, mapProperty);
addAdditionPropertiesToCodeGenModel(m, impl);
}
addVars(m, impl.getProperties(), impl.getRequired());
}
@ -1221,8 +1286,12 @@ public class DefaultCodegen {
return m;
}
protected void addProperties(Map<String, Property> properties, List<String> required, Model model,
Map<String, Model> allDefinitions) {
protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, ModelImpl swaggerModel) {
MapProperty mapProperty = new MapProperty(swaggerModel.getAdditionalProperties());
addParentContainer(codegenModel, codegenModel.name, mapProperty);
}
protected void addProperties(Map<String, Property> properties, List<String> required, Model model, Map<String, Model> allDefinitions) {
if (model instanceof ModelImpl) {
ModelImpl mi = (ModelImpl) model;
@ -1847,6 +1916,14 @@ public class DefaultCodegen {
}
op.externalDocs = operation.getExternalDocs();
// set Restful Flag
op.isRestfulShow = op.isRestfulShow();
op.isRestfulIndex = op.isRestfulIndex();
op.isRestfulCreate = op.isRestfulCreate();
op.isRestfulUpdate = op.isRestfulUpdate();
op.isRestfulDestroy = op.isRestfulDestroy();
op.isRestful = op.isRestful();
return op;
}
@ -1887,7 +1964,7 @@ public class DefaultCodegen {
}
}
r.dataType = cm.datatype;
r.isBinary = cm.datatype.toLowerCase().startsWith("byte");
r.isBinary = isDataTypeBinary(cm.datatype);
if (cm.isContainer != null) {
r.simpleType = false;
r.containerType = cm.containerType;
@ -2056,7 +2133,7 @@ public class DefaultCodegen {
p.baseType = cp.baseType;
p.dataType = cp.datatype;
p.isPrimitiveType = cp.isPrimitiveType;
p.isBinary = cp.datatype.toLowerCase().startsWith("byte");
p.isBinary = isDataTypeBinary(cp.datatype);
}
// set boolean flag (e.g. isString)
@ -2153,7 +2230,7 @@ public class DefaultCodegen {
p.isCookieParam = true;
} else if (param instanceof BodyParameter) {
p.isBodyParam = true;
p.isBinary = p.dataType.toLowerCase().startsWith("byte");
p.isBinary = isDataTypeBinary(p.dataType);
} else if (param instanceof FormParameter) {
if ("file".equalsIgnoreCase(((FormParameter) param).getType())) {
p.isFile = true;
@ -2169,6 +2246,10 @@ public class DefaultCodegen {
return p;
}
public boolean isDataTypeBinary(String dataType) {
return dataType.toLowerCase().startsWith("byte");
}
/**
* Convert map of Swagger SecuritySchemeDefinition objects to a list of Codegen Security objects
*
@ -2452,7 +2533,7 @@ public class DefaultCodegen {
}
}
private void addImport(CodegenModel m, String type) {
protected void addImport(CodegenModel m, String type) {
if (type != null && needToImport(type)) {
m.imports.add(type);
}
@ -2465,6 +2546,7 @@ public class DefaultCodegen {
private void addVars(CodegenModel m, Map<String, Property> properties, List<String> required,
Map<String, Property> allProperties, List<String> allRequired) {
m.hasRequired = false;
if (properties != null && !properties.isEmpty()) {
m.hasVars = true;
m.hasEnums = false;
@ -2503,6 +2585,7 @@ public class DefaultCodegen {
} else {
final CodegenProperty cp = fromProperty(key, prop);
cp.required = mandatory.contains(key) ? true : null;
m.hasRequired = Boolean.TRUE.equals(m.hasRequired) || Boolean.TRUE.equals(cp.required);
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.
@ -2525,11 +2608,19 @@ public class DefaultCodegen {
addImport(m, cp.complexType);
vars.add(cp);
if (Boolean.TRUE.equals(cp.required)) { // if required, add to the list "requiredVars"
// if required, add to the list "requiredVars"
if (Boolean.TRUE.equals(cp.required)) {
m.requiredVars.add(cp);
} else { // else add to the list "optionalVars" for optional property
m.optionalVars.add(cp);
}
// if readonly, add to readOnlyVars (list of properties)
if (Boolean.TRUE.equals(cp.isReadOnly)) {
m.readOnlyVars.add(cp);
} else { // else add to readWriteVars (list of properties)
m.readWriteVars.add(cp);
}
}
}
}

View File

@ -2,6 +2,7 @@ package io.swagger.codegen;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;
import io.swagger.codegen.ignore.CodegenIgnoreProcessor;
import io.swagger.models.*;
import io.swagger.models.auth.OAuth2Definition;
import io.swagger.models.auth.SecuritySchemeDefinition;
@ -24,6 +25,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
protected CodegenConfig config;
protected ClientOptInput opts;
protected Swagger swagger;
protected CodegenIgnoreProcessor ignoreProcessor;
@Override
public Generator opts(ClientOptInput opts) {
@ -31,8 +33,11 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
this.swagger = opts.getSwagger();
this.config = opts.getConfig();
this.config.additionalProperties().putAll(opts.getOpts().getProperties());
ignoreProcessor = new CodegenIgnoreProcessor(this.config.getOutputDir());
return this;
}
@ -41,6 +46,10 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
Boolean generateApis = null;
Boolean generateModels = null;
Boolean generateSupportingFiles = null;
Boolean generateApiTests = null;
Boolean generateApiDocumentation = null;
Boolean generateModelTests = null;
Boolean generateModelDocumentation = null;
Set<String> modelsToGenerate = null;
Set<String> apisToGenerate = null;
@ -68,6 +77,18 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
supportingFilesToGenerate = new HashSet<String>(Arrays.asList(supportingFiles.split(",")));
}
}
if(System.getProperty("modelTests") != null) {
generateModelTests = Boolean.valueOf(System.getProperty("modelTests"));
}
if(System.getProperty("modelDocs") != null) {
generateModelDocumentation = Boolean.valueOf(System.getProperty("modelDocs"));
}
if(System.getProperty("apiTests") != null) {
generateApiTests = Boolean.valueOf(System.getProperty("apiTests"));
}
if(System.getProperty("apiDocs") != null) {
generateApiDocumentation = Boolean.valueOf(System.getProperty("apiDocs"));
}
if(generateApis == null && generateModels == null && generateSupportingFiles == null) {
// no specifics are set, generate everything
@ -85,6 +106,28 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
}
}
// model/api tests and documentation options rely on parent generate options (api or model) and no other options.
// They default to true in all scenarios and can only be marked false explicitly
if (generateModelTests == null) {
generateModelTests = true;
}
if (generateModelDocumentation == null) {
generateModelDocumentation = true;
}
if (generateApiTests == null) {
generateApiTests = true;
}
if (generateApiDocumentation == null) {
generateApiDocumentation = true;
}
// Additional properties added for tests to exclude references in project related files
config.additionalProperties().put(CodegenConstants.GENERATE_API_TESTS, generateApiTests);
config.additionalProperties().put(CodegenConstants.GENERATE_MODEL_TESTS, generateModelTests);
if(Boolean.FALSE.equals(generateApiTests) && Boolean.FALSE.equals(generateModelTests)) {
config.additionalProperties().put(CodegenConstants.EXCLUDE_TESTS, Boolean.TRUE);
}
if (swagger == null || config == null) {
throw new RuntimeException("missing swagger input or config!");
}
@ -159,7 +202,6 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
String basePath = hostBuilder.toString();
String basePathWithoutHost = swagger.getBasePath();
// resolve inline models
InlineModelResolver inlineModelResolver = new InlineModelResolver();
inlineModelResolver.flatten(swagger);
@ -267,66 +309,46 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
LOGGER.info("Skipped overwriting " + 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));
File written = processTemplateToFile(models, templateName, filename);
if(written != null) {
files.add(written);
}
}
// to generate model test files
for (String templateName : config.modelTestTemplateFiles().keySet()) {
String suffix = config.modelTestTemplateFiles().get(templateName);
String filename = config.modelTestFileFolder() + File.separator + config.toModelTestFilename(name) + suffix;
// do not overwrite test file that already exists
if (new File(filename).exists()) {
LOGGER.info("File exists. Skipped overwriting " + filename);
continue;
if(generateModelTests) {
// to generate model test files
for (String templateName : config.modelTestTemplateFiles().keySet()) {
String suffix = config.modelTestTemplateFiles().get(templateName);
String filename = config.modelTestFileFolder() + File.separator + config.toModelTestFilename(name) + suffix;
// do not overwrite test file that already exists
if (new File(filename).exists()) {
LOGGER.info("File exists. Skipped overwriting " + filename);
continue;
}
File written = processTemplateToFile(models, templateName, filename);
if (written != null) {
files.add(written);
}
}
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));
}
// 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)) {
LOGGER.info("Skipped overwriting " + filename);
continue;
if(generateModelDocumentation) {
// 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)) {
LOGGER.info("Skipped overwriting " + filename);
continue;
}
File written = processTemplateToFile(models, templateName, filename);
if (written != null) {
files.add(written);
}
}
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) {
throw new RuntimeException("Could not generate model '" + name + "'", e);
@ -401,68 +423,44 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
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));
File written = processTemplateToFile(operation, templateName, filename);
if(written != null) {
files.add(written);
}
}
// to generate api test files
for (String templateName : config.apiTestTemplateFiles().keySet()) {
String filename = config.apiTestFilename(templateName, tag);
// do not overwrite test file that already exists
if (new File(filename).exists()) {
LOGGER.info("File exists. Skipped overwriting " + 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);
if(generateApiTests) {
// to generate api test files
for (String templateName : config.apiTestTemplateFiles().keySet()) {
String filename = config.apiTestFilename(templateName, tag);
// do not overwrite test file that already exists
if (new File(filename).exists()) {
LOGGER.info("File exists. Skipped overwriting " + filename);
continue;
}
writeToFile(filename, tmpl.execute(operation));
files.add(new File(filename));
File written = processTemplateToFile(operation, templateName, filename);
if (written != null) {
files.add(written);
}
}
}
// 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()) {
LOGGER.info("Skipped overwriting " + filename);
continue;
if(generateApiDocumentation) {
// 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()) {
LOGGER.info("Skipped overwriting " + filename);
continue;
}
File written = processTemplateToFile(operation, templateName, filename);
if (written != null) {
files.add(written);
}
}
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) {
@ -488,6 +486,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
}
bundle.put("swagger", this.swagger);
bundle.put("basePath", basePath);
bundle.put("basePathWithoutHost",basePathWithoutHost);
bundle.put("scheme", scheme);
bundle.put("contextPath", contextPath);
bundle.put("apiInfo", apis);
@ -531,9 +530,12 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
LOGGER.info("Skipped overwriting " + outputFilename);
continue;
}
String templateFile = getFullTemplateFile(config, support.templateFile);
String templateFile;
if( support instanceof GlobalSupportingFile) {
templateFile = config.getCommonTemplateDir() + File.separator + support.templateFile;
} else {
templateFile = getFullTemplateFile(config, support.templateFile);
}
boolean shouldGenerate = true;
if(supportingFilesToGenerate != null && supportingFilesToGenerate.size() > 0) {
if(supportingFilesToGenerate.contains(support.destinationFilename)) {
@ -544,53 +546,108 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
}
}
if(shouldGenerate) {
if (templateFile.endsWith("mustache")) {
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);
if(ignoreProcessor.allowsFile(new File(outputFilename))) {
if (templateFile.endsWith("mustache")) {
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(outputFilename, tmpl.execute(bundle));
files.add(new File(outputFilename));
} else {
InputStream in = null;
try {
in = new FileInputStream(templateFile);
} catch (Exception e) {
// continue
}
if (in == null) {
in = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(templateFile));
}
File outputFile = new File(outputFilename);
OutputStream out = new FileOutputStream(outputFile, false);
if (in != null) {
LOGGER.info("writing file " + outputFile);
IOUtils.copy(in, out);
writeToFile(outputFilename, tmpl.execute(bundle));
files.add(new File(outputFilename));
} else {
if (in == null) {
LOGGER.error("can't open " + templateFile + " for input");
InputStream in = null;
try {
in = new FileInputStream(templateFile);
} catch (Exception e) {
// continue
}
if (in == null) {
in = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(templateFile));
}
File outputFile = new File(outputFilename);
OutputStream out = new FileOutputStream(outputFile, false);
if (in != null) {
LOGGER.info("writing file " + outputFile);
IOUtils.copy(in, out);
} else {
if (in == null) {
LOGGER.error("can't open " + templateFile + " for input");
}
}
files.add(outputFile);
}
files.add(outputFile);
} else {
LOGGER.info("Skipped generation of " + outputFilename + " due to rule in .swagger-codegen-ignore");
}
}
} catch (Exception e) {
throw new RuntimeException("Could not generate supporting file '" + support + "'", e);
}
}
// Consider .swagger-codegen-ignore a supporting file
// Output .swagger-codegen-ignore if it doesn't exist and wasn't explicitly created by a generator
final String swaggerCodegenIgnore = ".swagger-codegen-ignore";
String ignoreFileNameTarget = config.outputFolder() + File.separator + swaggerCodegenIgnore;
File ignoreFile = new File(ignoreFileNameTarget);
if(!ignoreFile.exists()) {
String ignoreFileNameSource = File.separator + config.getCommonTemplateDir() + File.separator + swaggerCodegenIgnore;
String ignoreFileContents = readResourceContents(ignoreFileNameSource);
try {
writeToFile(ignoreFileNameTarget, ignoreFileContents);
} catch (IOException e) {
throw new RuntimeException("Could not generate supporting file '" + swaggerCodegenIgnore + "'", e);
}
files.add(ignoreFile);
}
// Add default LICENSE (Apache-2.0) for all generators
final String apache2License = "LICENSE";
String licenseFileNameTarget = config.outputFolder() + File.separator + apache2License;
File licenseFile = new File(licenseFileNameTarget);
String licenseFileNameSource = File.separator + config.getCommonTemplateDir() + File.separator + apache2License;
String licenseFileContents = readResourceContents(licenseFileNameSource);
try {
writeToFile(licenseFileNameTarget, licenseFileContents);
} catch (IOException e) {
throw new RuntimeException("Could not generate LICENSE file '" + apache2License + "'", e);
}
files.add(licenseFile);
}
config.processSwagger(swagger);
return files;
}
private File processTemplateToFile(Map<String, Object> templateData, String templateName, String outputFilename) throws IOException {
if(ignoreProcessor.allowsFile(new File(outputFilename.replaceAll("//", "/")))) {
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(outputFilename, tmpl.execute(templateData));
return new File(outputFilename);
}
LOGGER.info("Skipped generation of " + outputFilename + " due to rule in .swagger-codegen-ignore");
return null;
}
private static void processMimeTypes(List<String> mimeTypeList, Map<String, Object> operation, String source) {
if (mimeTypeList != null && mimeTypeList.size() > 0) {
List<Map<String, String>> c = new ArrayList<Map<String, String>>();

View File

@ -0,0 +1,12 @@
package io.swagger.codegen;
public class GlobalSupportingFile extends SupportingFile {
GlobalSupportingFile(String templateFile, String folder, String destinationFilename) {
super(templateFile, folder, destinationFilename);
}
GlobalSupportingFile(String templateFile, String destinationFilename) {
super(templateFile, destinationFilename);
}
}

View File

@ -50,7 +50,7 @@ public class InlineModelResolver {
if (obj.getType() == null || "object".equals(obj.getType())) {
if (obj.getProperties() != null && obj.getProperties().size() > 0) {
flattenProperties(obj.getProperties(), pathname);
String modelName = uniqueName(bp.getName());
String modelName = resolveModelName( obj.getTitle(), bp.getName());
bp.setSchema(new RefModel(modelName));
addGenerated(modelName, model);
swagger.addDefinition(modelName, model);
@ -65,7 +65,7 @@ public class InlineModelResolver {
ObjectProperty op = (ObjectProperty) inner;
if (op.getProperties() != null && op.getProperties().size() > 0) {
flattenProperties(op.getProperties(), pathname);
String modelName = uniqueName(bp.getName());
String modelName = resolveModelName( op.getTitle(), bp.getName());
Model innerModel = modelFromProperty(op, modelName);
String existing = matchGenerated(innerModel);
if (existing != null) {
@ -91,7 +91,7 @@ public class InlineModelResolver {
if (property instanceof ObjectProperty) {
ObjectProperty op = (ObjectProperty) property;
if (op.getProperties() != null && op.getProperties().size() > 0) {
String modelName = uniqueName("inline_response_" + key);
String modelName = resolveModelName( op.getTitle(),"inline_response_" + key);
Model model = modelFromProperty(op, modelName);
String existing = matchGenerated(model);
if (existing != null) {
@ -108,18 +108,18 @@ public class InlineModelResolver {
if(inner instanceof ObjectProperty) {
ObjectProperty op = (ObjectProperty) inner;
if (op.getProperties() != null && op.getProperties().size() > 0) {
flattenProperties(op.getProperties(), pathname);
String modelName = uniqueName("inline_response_" + key);
Model innerModel = modelFromProperty(op, modelName);
String existing = matchGenerated(innerModel);
if (existing != null) {
ap.setItems(new RefProperty(existing));
} else {
if (op.getProperties() != null && op.getProperties().size() > 0) {
flattenProperties(op.getProperties(), pathname);
String modelName = resolveModelName( op.getTitle(),"inline_response_" + key);
Model innerModel = modelFromProperty(op, modelName);
String existing = matchGenerated(innerModel);
if (existing != null) {
ap.setItems(new RefProperty(existing));
} else {
ap.setItems(new RefProperty(modelName));
addGenerated(modelName, innerModel);
swagger.addDefinition(modelName, innerModel);
}
}
}
}
} else if (property instanceof MapProperty) {
@ -129,18 +129,18 @@ public class InlineModelResolver {
if(innerProperty instanceof ObjectProperty) {
ObjectProperty op = (ObjectProperty) innerProperty;
if (op.getProperties() != null && op.getProperties().size() > 0) {
flattenProperties(op.getProperties(), pathname);
String modelName = uniqueName("inline_response_" + key);
Model innerModel = modelFromProperty(op, modelName);
String existing = matchGenerated(innerModel);
if (existing != null) {
mp.setAdditionalProperties(new RefProperty(existing));
} else {
mp.setAdditionalProperties(new RefProperty(modelName));
addGenerated(modelName, innerModel);
swagger.addDefinition(modelName, innerModel);
}
}
flattenProperties(op.getProperties(), pathname);
String modelName = resolveModelName( op.getTitle(),"inline_response_" + key);
Model innerModel = modelFromProperty(op, modelName);
String existing = matchGenerated(innerModel);
if (existing != null) {
mp.setAdditionalProperties(new RefProperty(existing));
} else {
mp.setAdditionalProperties(new RefProperty(modelName));
addGenerated(modelName, innerModel);
swagger.addDefinition(modelName, innerModel);
}
}
}
}
}
@ -184,6 +184,15 @@ public class InlineModelResolver {
}
}
private String resolveModelName(String title, String key ) {
if (title == null) {
return uniqueName(key);
}
else {
return uniqueName(title);
}
}
public String matchGenerated(Model model) {
if (this.skipMatches) {
return null;

View File

@ -5,6 +5,10 @@ public class SupportingFile {
public String folder;
public String destinationFilename;
public SupportingFile(String templateFile, String destinationFilename) {
this(templateFile, "", destinationFilename);
}
public SupportingFile(String templateFile, String folder, String destinationFilename) {
this.templateFile = templateFile;
this.folder = folder;
@ -44,4 +48,6 @@ public class SupportingFile {
result = 31 * result + (destinationFilename != null ? destinationFilename.hashCode() : 0);
return result;
}
}
}

View File

@ -0,0 +1,134 @@
package io.swagger.codegen.ignore;
import com.google.common.collect.ImmutableList;
import io.swagger.codegen.ignore.rules.DirectoryRule;
import io.swagger.codegen.ignore.rules.Rule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class CodegenIgnoreProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(CodegenIgnoreProcessor.class);
private final String outputPath;
private List<Rule> exclusionRules = new ArrayList<>();
private List<Rule> inclusionRules = new ArrayList<>();
public CodegenIgnoreProcessor(String outputPath) {
this.outputPath = outputPath;
final File directory = new File(outputPath);
if(directory.exists() && directory.isDirectory()){
final File codegenIgnore = new File(directory, ".swagger-codegen-ignore");
if(codegenIgnore.exists() && codegenIgnore.isFile()){
try {
loadCodegenRules(codegenIgnore);
} catch (IOException e) {
LOGGER.error("Could not process .swagger-codegen-ignore.", e.getMessage());
}
} else {
// log info message
LOGGER.info("No .swagger-codegen-ignore file found.");
}
}
}
void loadCodegenRules(File codegenIgnore) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(codegenIgnore))) {
String line;
// NOTE: Comments that start with a : (e.g. //:) are pulled from git documentation for .gitignore
// see: https://github.com/git/git/blob/90f7b16b3adc78d4bbabbd426fb69aa78c714f71/Documentation/gitignore.txt
while ((line = reader.readLine()) != null) {
if(
//: A blank line matches no files, so it can serve as a separator for readability.
line.length() == 0
) continue;
Rule rule = Rule.create(line);
// rule could be null here if it's a COMMENT, for example
if(rule != null) {
if (Boolean.TRUE.equals(rule.getNegated())) {
inclusionRules.add(rule);
} else {
exclusionRules.add(rule);
}
}
}
}
}
public boolean allowsFile(File targetFile) {
File file = new File(new File(this.outputPath).toURI().relativize(targetFile.toURI()).getPath());
Boolean directoryExcluded = false;
Boolean exclude = false;
if(exclusionRules.size() == 0 && inclusionRules.size() == 0) {
return true;
}
// NOTE: We *must* process all exclusion rules
for (int i = 0; i < exclusionRules.size(); i++) {
Rule current = exclusionRules.get(i);
Rule.Operation op = current.evaluate(file.getPath());
switch (op){
case EXCLUDE:
exclude = true;
// Include rule can't override rules that exclude a file by some parent directory.
if(current instanceof DirectoryRule) {
directoryExcluded = true;
}
break;
case INCLUDE:
// This won't happen here.
break;
case NOOP:
break;
case EXCLUDE_AND_TERMINATE:
i = exclusionRules.size();
break;
}
}
if(exclude) {
// Only need to process inclusion rules if we've been excluded
for (int i = 0; exclude && i < inclusionRules.size(); i++) {
Rule current = inclusionRules.get(i);
Rule.Operation op = current.evaluate(file.getPath());
// At this point exclude=true means the file should be ignored.
// op == INCLUDE means we have to flip that flag.
if(op.equals(Rule.Operation.INCLUDE)) {
if(current instanceof DirectoryRule && directoryExcluded) {
// e.g
// baz/
// !foo/bar/baz/
// NOTE: Possibly surprising side effect:
// foo/bar/baz/
// !bar/
exclude = false;
} else if (!directoryExcluded) {
// e.g.
// **/*.log
// !ISSUE_1234.log
exclude = false;
}
}
}
}
return Boolean.FALSE.equals(exclude);
}
public List<Rule> getInclusionRules() {
return ImmutableList.copyOf(inclusionRules);
}
public List<Rule> getExclusionRules() {
return ImmutableList.copyOf(exclusionRules);
}
}

View File

@ -0,0 +1,27 @@
package io.swagger.codegen.ignore.rules;
import java.nio.file.*;
import java.util.List;
public class DirectoryRule extends FileRule {
private PathMatcher directoryMatcher = null;
private PathMatcher contentsMatcher = null;
DirectoryRule(List<Part> syntax, String definition) {
super(syntax, definition);
String pattern = this.getPattern();
StringBuilder sb = new StringBuilder();
sb.append("glob:");
sb.append(pattern);
if(!pattern.endsWith("/")) sb.append("/");
directoryMatcher = FileSystems.getDefault().getPathMatcher(sb.toString());
sb.append("**");
contentsMatcher = FileSystems.getDefault().getPathMatcher(sb.toString());
}
@Override
public Boolean matches(String relativePath) {
return contentsMatcher.matches(FileSystems.getDefault().getPath(relativePath)) || directoryMatcher.matches(FileSystems.getDefault().getPath(relativePath));
}
}

View File

@ -0,0 +1,20 @@
package io.swagger.codegen.ignore.rules;
import java.util.List;
/**
* An ignore rule which matches everything.
*/
public class EverythingRule extends Rule {
EverythingRule(List<Part> syntax, String definition) {
super(syntax, definition);
}
@Override
public Boolean matches(String relativePath) {
return true;
}
@Override
protected Operation getExcludeOperation(){ return Operation.EXCLUDE_AND_TERMINATE; }
}

View File

@ -0,0 +1,20 @@
package io.swagger.codegen.ignore.rules;
import java.nio.file.FileSystems;
import java.nio.file.PathMatcher;
import java.util.List;
public class FileRule extends Rule {
private PathMatcher matcher = null;
FileRule(List<Part> syntax, String definition) {
super(syntax, definition);
matcher = FileSystems.getDefault().getPathMatcher("glob:"+this.getPattern());
}
@Override
public Boolean matches(String relativePath) {
return matcher.matches(FileSystems.getDefault().getPath(relativePath));
}
}

View File

@ -0,0 +1,141 @@
package io.swagger.codegen.ignore.rules;
import java.util.ArrayList;
import java.util.List;
public class IgnoreLineParser {
enum Token {
MATCH_ALL("**"),
MATCH_ANY("*"),
ESCAPED_EXCLAMATION("\\!"),
ESCAPED_SPACE("\\ "),
PATH_DELIM("/"),
NEGATE("!"),
TEXT(null),
DIRECTORY_MARKER("/"),
ROOTED_MARKER("/"),
COMMENT(null);
private String pattern;
Token(String pattern) {
this.pattern = pattern;
}
public String getPattern() {
return pattern;
}
}
// NOTE: Comments that start with a : (e.g. //:) are pulled from git documentation for .gitignore
// see: https://github.com/git/git/blob/90f7b16b3adc78d4bbabbd426fb69aa78c714f71/Documentation/gitignore.txt
static List<Part> parse(String text) throws ParserException {
List<Part> parts = new ArrayList<>();
StringBuilder sb = new StringBuilder();
String current = null;
String next = null;
char[] characters = text.toCharArray();
for (int i = 0, totalLength = characters.length; i < totalLength; i++) {
char character = characters[i];
current = String.valueOf(character);
next = i < totalLength - 1 ? String.valueOf(characters[i + 1]) : null;
if (i == 0) {
if ("#".equals(current)) {
//: A line starting with # serves as a comment.
parts.add(new Part(Token.COMMENT, text));
i = totalLength; // rather than early return
continue;
} else if ("!".equals(current)) {
if (i == totalLength - 1) {
throw new ParserException("Negation with no negated pattern.");
} else {
parts.add(new Part(Token.NEGATE));
continue;
}
} else if ("\\".equals(current) && "#".equals(next)) {
//: Put a backslash ("`\`") in front of the first hash for patterns
//: that begin with a hash.
// NOTE: Just push forward and drop the escape character. Falls through to TEXT token.
current = next;
next = null;
i++;
}
}
if (Token.MATCH_ANY.pattern.equals(current)) {
if (Token.MATCH_ANY.pattern.equals(next)) {
// peek ahead for invalid pattern. Slightly inefficient, but acceptable.
if ((i+2 < totalLength - 1) &&
String.valueOf(characters[i+2]).equals(Token.MATCH_ANY.pattern)) {
// It doesn't matter where we are in the pattern, *** is invalid.
throw new ParserException("The pattern *** is invalid.");
}
parts.add(new Part(Token.MATCH_ALL));
i++;
continue;
} else {
if (sb.length() > 0) {
// A MATCH_ANY may commonly follow a filename or some other character. Dump that to results before the MATCH_ANY.
parts.add(new Part(Token.TEXT, sb.toString()));
sb.delete(0, sb.length());
}
parts.add(new Part(Token.MATCH_ANY));
continue;
}
}
if (i == 0 && Token.ROOTED_MARKER.pattern.equals(current)) {
parts.add(new Part(Token.ROOTED_MARKER));
continue;
}
if ("\\".equals(current) && " ".equals(next)) {
parts.add(new Part(Token.ESCAPED_SPACE));
i++;
continue;
} else if ("\\".equals(current) && "!".equals(next)) {
parts.add(new Part(Token.ESCAPED_EXCLAMATION));
i++;
continue;
}
if (Token.PATH_DELIM.pattern.equals(current)) {
if (i != totalLength - 1) {
if (sb.length() > 0) {
parts.add(new Part(Token.TEXT, sb.toString()));
sb.delete(0, sb.length());
}
parts.add(new Part(Token.PATH_DELIM));
if(Token.PATH_DELIM.pattern.equals(next)) {
// ignore doubled path delims. NOTE: doesn't do full lookahead, so /// will result in //
i++;
}
continue;
} else if (i == totalLength - 1) {
parts.add(new Part(Token.TEXT, sb.toString()));
sb.delete(0, sb.length());
parts.add(new Part(Token.DIRECTORY_MARKER));
continue;
}
}
sb.append(current);
}
if (sb.length() > 0) {
// NOTE: All spaces escaped spaces are a special token, ESCAPED_SPACE
//: Trailing spaces are ignored unless they are quoted with backslash ("`\`")
parts.add(new Part(Token.TEXT, sb.toString().trim()));
}
return parts;
}
}

View File

@ -0,0 +1,26 @@
package io.swagger.codegen.ignore.rules;
import java.util.List;
public class InvalidRule extends Rule {
private final String reason;
InvalidRule(List<Part> syntax, String definition, String reason) {
super(syntax, definition);
this.reason = reason;
}
@Override
public Boolean matches(String relativePath) {
return null;
}
@Override
public Operation evaluate(String relativePath) {
return Operation.NOOP;
}
public String getReason() {
return reason;
}
}

View File

@ -0,0 +1,15 @@
package io.swagger.codegen.ignore.rules;
public class ParserException extends Exception {
/**
* Constructs a new exception with the specified detail message. The
* cause is not initialized, and may subsequently be initialized by
* a call to {@link #initCause}.
*
* @param message the detail message. The detail message is saved for
* later retrieval by the {@link #getMessage()} method.
*/
public ParserException(String message) {
super(message);
}
}

View File

@ -0,0 +1,24 @@
package io.swagger.codegen.ignore.rules;
class Part {
private final IgnoreLineParser.Token token;
private final String value;
public Part(IgnoreLineParser.Token token, String value) {
this.token = token;
this.value = value;
}
public Part(IgnoreLineParser.Token token) {
this.token = token;
this.value = token.getPattern();
}
public IgnoreLineParser.Token getToken() {
return token;
}
public String getValue() {
return value;
}
}

View File

@ -0,0 +1,58 @@
package io.swagger.codegen.ignore.rules;
import java.util.List;
import java.util.regex.Pattern;
/**
* A special case rule which matches files only if they're located
* in the same directory as the .swagger-codegen-ignore file.
*/
public class RootedFileRule extends Rule {
private String definedFilename = null;
private String definedExtension = null;
RootedFileRule(List<Part> syntax, String definition) {
super(syntax, definition);
int separatorIndex = definition.lastIndexOf(".");
definedFilename = getFilenamePart(definition, separatorIndex);
definedExtension = getExtensionPart(definition, separatorIndex);
}
private String getFilenamePart(final String input, int stopIndex){
return input.substring('/' == input.charAt(0) ? 1 : 0, stopIndex > 0 ? stopIndex : input.length());
}
private String getExtensionPart(final String input, int stopIndex) {
return input.substring(stopIndex > 0 ? stopIndex+1: input.length(), input.length());
}
@Override
public Boolean matches(String relativePath) {
// NOTE: Windows-style separator isn't supported, so File.pathSeparator would be incorrect here.
// NOTE: lastIndexOf rather than contains because /file.txt is acceptable while path/file.txt is not.
// relativePath will be passed by CodegenIgnoreProcessor and is relative to .codegen-ignore.
boolean isSingleFile = relativePath.lastIndexOf("/") <= 0;
if(isSingleFile) {
int separatorIndex = relativePath.lastIndexOf(".");
final String filename = getFilenamePart(relativePath, separatorIndex);
final String extension = getExtensionPart(relativePath, separatorIndex);
boolean extensionMatches = definedExtension.equals(extension) || definedExtension.equals(IgnoreLineParser.Token.MATCH_ANY.getPattern());
if(extensionMatches && definedFilename.contains(IgnoreLineParser.Token.MATCH_ANY.getPattern())) {
// TODO: Evaluate any other escape requirements here.
Pattern regex = Pattern.compile(
definedFilename
.replaceAll(Pattern.quote("."), "\\\\Q.\\\\E")
.replaceAll(Pattern.quote("*"), ".*?") // non-greedy match on 0+ any character
);
return regex.matcher(filename).matches();
}
return extensionMatches && definedFilename.equals(filename);
}
return false;
}
}

View File

@ -0,0 +1,175 @@
package io.swagger.codegen.ignore.rules;
import java.util.List;
public abstract class Rule {
public enum Operation {EXCLUDE, INCLUDE, NOOP, EXCLUDE_AND_TERMINATE}
// The original rule
private final String definition;
private final List<Part> syntax;
Rule(List<Part> syntax, String definition) {
this.syntax = syntax;
this.definition = definition;
}
public abstract Boolean matches(String relativePath);
public String getDefinition() {
return this.definition;
}
protected String getPattern() {
if(syntax == null) return this.definition;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < syntax.size(); i++) {
Part current = syntax.get(i);
switch(current.getToken()){
case MATCH_ALL:
case MATCH_ANY:
case ESCAPED_EXCLAMATION:
case ESCAPED_SPACE:
case PATH_DELIM:
case TEXT:
case DIRECTORY_MARKER:
sb.append(current.getValue());
break;
case NEGATE:
case ROOTED_MARKER:
case COMMENT:
break;
}
}
return sb.toString();
}
/**
* Whether or not the rule should be negated. !foo means foo should be removed from previous matches.
* Example: **\/*.bak excludes all backup. Adding !/test.bak will include test.bak in the project root.
* <p>
* NOTE: It is not possible to re-include a file if a parent directory of that file is excluded.
*/
public Boolean getNegated() {
return this.syntax != null && this.syntax.size() > 0 && this.syntax.get(0).getToken() == IgnoreLineParser.Token.NEGATE;
}
public Operation evaluate(String relativePath) {
if (Boolean.TRUE.equals(matches(relativePath))) {
if(Boolean.TRUE.equals(this.getNegated())) {
return this.getIncludeOperation();
}
return this.getExcludeOperation();
}
return Operation.NOOP;
}
protected Operation getIncludeOperation(){ return Operation.INCLUDE; }
protected Operation getExcludeOperation(){ return Operation.EXCLUDE; }
public static Rule create(String definition) {
// NOTE: Comments that start with a : (e.g. //:) are pulled from git documentation for .gitignore
// see: https://github.com/git/git/blob/90f7b16b3adc78d4bbabbd426fb69aa78c714f71/Documentation/gitignore.txt
Rule rule = null;
if (definition.equals(".")) {
return new InvalidRule(null, definition, "Pattern '.' is invalid.");
} else if (definition.equals("!.")) {
return new InvalidRule(null, definition, "Pattern '!.' is invalid.");
} else if (definition.startsWith("..")) {
return new InvalidRule(null, definition, "Pattern '..' is invalid.");
}
try {
List<Part> result = IgnoreLineParser.parse(definition);
Boolean directoryOnly = null;
if (result.size() == 0) {
return rule;
} else if (result.size() == 1) {
// single-character filename only
Part part = result.get(0);
if (IgnoreLineParser.Token.MATCH_ANY.equals(part.getToken())) {
rule = new RootedFileRule(result, definition);
} else {
rule = new FileRule(result, definition);
}
} else {
IgnoreLineParser.Token head = result.get(0).getToken();
//: An optional prefix "`!`" which negates the pattern; any
//: matching file excluded by a previous pattern will become
//: included again. It is not possible to re-include a file if a parent
//: directory of that file is excluded. Git doesn't list excluded
//: directories for performance reasons, so any patterns on contained
//: files have no effect, no matter where they are defined.
//: Put a backslash ("`\`") in front of the first "`!`" for patterns
//: that begin with a literal "`!`", for example, "`\!important!.txt`".
// see this.getNegated();
//: If the pattern ends with a slash, it is removed for the
//: purpose of the following description, but it would only find
//: a match with a directory. In other words, `foo/` will match a
//: directory `foo` and paths underneath it, but will not match a
//: regular file or a symbolic link `foo` (this is consistent
//: with the way how pathspec works in general in Git).
directoryOnly = IgnoreLineParser.Token.DIRECTORY_MARKER.equals(result.get(result.size() - 1).getToken());
if (directoryOnly) {
rule = new DirectoryRule(result, definition);
} else if (IgnoreLineParser.Token.PATH_DELIM.equals(head)) {
//: A leading slash matches the beginning of the pathname.
//: For example, "/{asterisk}.c" matches "cat-file.c" but not
//: "mozilla-sha1/sha1.c".
rule = new RootedFileRule(result, definition);
} else {
// case 1
//: If the pattern does not contain a slash '/', Git treats it as
//: a shell glob pattern and checks for a match against the
//: pathname relative to the location of the `.gitignore` file
//: (relative to the toplevel of the work tree if not from a
//: `.gitignore` file).
// case 2
//: Otherwise, Git treats the pattern as a shell glob suitable
//: for consumption by fnmatch(3) with the FNM_PATHNAME flag:
//: wildcards in the pattern will not match a / in the pathname.
//: For example, "Documentation/{asterisk}.html" matches
//: "Documentation/git.html" but not "Documentation/ppc/ppc.html"
//: or "tools/perf/Documentation/perf.html".
// case 3
//: Two consecutive asterisks ("`**`") in patterns matched against
//: full pathname may have special meaning:
//:
//: - A leading "`**`" followed by a slash means match in all
//: directories. For example, "`**/foo`" matches file or directory
//: "`foo`" anywhere, the same as pattern "`foo`". "`**/foo/bar`"
//: matches file or directory "`bar`" anywhere that is directly
//: under directory "`foo`".
//:
//: - A trailing "`/**`" matches everything inside. For example,
//: "`abc/**`" matches all files inside directory "`abc`", relative
//: to the location of the `.gitignore` file, with infinite depth.
//:
//: - A slash followed by two consecutive asterisks then a slash
//: matches zero or more directories. For example, "`a/**/b`"
//: matches "`a/b`", "`a/x/b`", "`a/x/y/b`" and so on.
//:
//: - Other consecutive asterisks are considered invalid.
rule = new FileRule(result, definition);
}
}
} catch (ParserException e) {
e.printStackTrace();
return new InvalidRule(null, definition, e.getMessage());
}
return rule;
}
}

View File

@ -77,6 +77,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
"string",
"bool?",
"double?",
"decimal?",
"int?",
"long?",
"float?",
@ -112,7 +113,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
typeMapping.put("float", "float?");
typeMapping.put("long", "long?");
typeMapping.put("double", "double?");
typeMapping.put("number", "double?");
typeMapping.put("number", "decimal?");
typeMapping.put("datetime", "DateTime?");
typeMapping.put("date", "DateTime?");
typeMapping.put("file", "System.IO.Stream");

View File

@ -8,10 +8,12 @@ import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Swagger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
public abstract class AbstractJavaJAXRSServerCodegen extends JavaClientCodegen
{
public abstract class AbstractJavaJAXRSServerCodegen extends JavaClientCodegen {
/**
* Name of the sub-directory in "src/main/resource" where to find the
* Mustache template for the JAX-RS Codegen.
@ -19,10 +21,13 @@ public abstract class AbstractJavaJAXRSServerCodegen extends JavaClientCodegen
protected static final String JAXRS_TEMPLATE_DIRECTORY_NAME = "JavaJaxRS";
protected String implFolder = "src/main/java";
protected String title = "Swagger Server";
static Logger LOGGER = LoggerFactory.getLogger(AbstractJavaJAXRSServerCodegen.class);
public AbstractJavaJAXRSServerCodegen()
{
super();
dateLibrary = "legacy";
apiTestTemplateFiles.clear(); // TODO: add test template
}
@Override
@ -198,4 +203,5 @@ public abstract class AbstractJavaJAXRSServerCodegen extends JavaClientCodegen
public boolean shouldOverwrite(String filename) {
return super.shouldOverwrite(filename) && !filename.endsWith("ServiceImpl.java") && !filename.endsWith("ServiceFactory.java");
}
}

View File

@ -1,62 +1,73 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.properties.*;
import java.util.*;
import java.io.File;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.FileProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String modelPropertyNaming= "camelCase";
protected Boolean supportsES6 = true;
public AbstractTypeScriptClientCodegen() {
super();
supportsInheritance = true;
setReservedWordsLowerCase(Arrays.asList(
// local variable names used in API methods (endpoints)
"varLocalPath", "queryParameters", "headerParams", "formParams", "useFormData", "varLocalDeferred",
"requestOptions",
// Typescript reserved words
"abstract", "await", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "debugger", "default", "delete", "do", "double", "else", "enum", "export", "extends", "false", "final", "finally", "float", "for", "function", "goto", "if", "implements", "import", "in", "instanceof", "int", "interface", "let", "long", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "super", "switch", "synchronized", "this", "throw", "transient", "true", "try", "typeof", "var", "void", "volatile", "while", "with", "yield"));
public AbstractTypeScriptClientCodegen() {
super();
supportsInheritance = true;
setReservedWordsLowerCase(Arrays.asList(
// local variable names used in API methods (endpoints)
"varLocalPath", "queryParameters", "headerParams", "formParams", "useFormData", "varLocalDeferred",
"requestOptions",
// Typescript reserved words
"abstract", "await", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "debugger", "default", "delete", "do", "double", "else", "enum", "export", "extends", "false", "final", "finally", "float", "for", "function", "goto", "if", "implements", "import", "in", "instanceof", "int", "interface", "let", "long", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "super", "switch", "synchronized", "this", "throw", "transient", "true", "try", "typeof", "var", "void", "volatile", "while", "with", "yield"));
languageSpecificPrimitives = new HashSet<String>(Arrays.asList(
"string",
"String",
"boolean",
"Boolean",
"Double",
"Integer",
"Long",
"Float",
"Object",
languageSpecificPrimitives = new HashSet<String>(Arrays.asList(
"string",
"String",
"boolean",
"Boolean",
"Double",
"Integer",
"Long",
"Float",
"Object",
"Array",
"Date",
"number",
"any"
));
instantiationTypes.put("array", "Array");
));
instantiationTypes.put("array", "Array");
typeMapping = new HashMap<String, String>();
typeMapping.put("Array", "Array");
typeMapping.put("array", "Array");
typeMapping.put("List", "Array");
typeMapping.put("boolean", "boolean");
typeMapping.put("string", "string");
typeMapping.put("int", "number");
typeMapping.put("float", "number");
typeMapping.put("number", "number");
typeMapping.put("long", "number");
typeMapping.put("short", "number");
typeMapping.put("char", "string");
typeMapping.put("double", "number");
typeMapping.put("object", "any");
typeMapping.put("integer", "number");
typeMapping.put("Map", "any");
typeMapping.put("DateTime", "Date");
typeMapping = new HashMap<String, String>();
typeMapping.put("Array", "Array");
typeMapping.put("array", "Array");
typeMapping.put("List", "Array");
typeMapping.put("boolean", "boolean");
typeMapping.put("string", "string");
typeMapping.put("int", "number");
typeMapping.put("float", "number");
typeMapping.put("number", "number");
typeMapping.put("long", "number");
typeMapping.put("short", "number");
typeMapping.put("char", "string");
typeMapping.put("double", "number");
typeMapping.put("object", "any");
typeMapping.put("integer", "number");
typeMapping.put("Map", "any");
typeMapping.put("DateTime", "Date");
//TODO binary should be mapped to byte array
// mapped to String as a workaround
typeMapping.put("binary", "string");
@ -66,7 +77,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
cliOptions.add(new CliOption(CodegenConstants.MODEL_PROPERTY_NAMING, CodegenConstants.MODEL_PROPERTY_NAMING_DESC).defaultValue("camelCase"));
cliOptions.add(new CliOption(CodegenConstants.SUPPORTS_ES6, CodegenConstants.SUPPORTS_ES6_DESC).defaultValue("false"));
}
}
@Override
public void processOpts() {
@ -104,24 +115,24 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
}
@Override
public String toParamName(String name) {
// 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'.
public String toParamName(String name) {
// 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'.
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$"))
return name;
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$"))
return name;
// camelize the variable name
// pet_id => petId
name = camelize(name, true);
// camelize 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);
// for reserved word or word starting with number, append _
if (isReservedWord(name) || name.matches("^\\d.*"))
name = escapeReservedWord(name);
return name;
}
return name;
}
@Override
public String toVarName(String name) {
@ -130,70 +141,70 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
}
@Override
public String toModelName(String name) {
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
public String toModelName(String name) {
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
if (!StringUtils.isEmpty(modelNamePrefix)) {
name = modelNamePrefix + "_" + name;
if (!StringUtils.isEmpty(modelNamePrefix)) {
name = modelNamePrefix + "_" + name;
}
if (!StringUtils.isEmpty(modelNameSuffix)) {
name = name + "_" + modelNameSuffix;
}
// model name cannot use reserved keyword, e.g. return
if (isReservedWord(name)) {
String modelName = camelize("model_" + name);
LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + 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
// phone_number => PhoneNumber
return camelize(name);
}
if (!StringUtils.isEmpty(modelNameSuffix)) {
name = name + "_" + modelNameSuffix;
@Override
public String toModelFilename(String name) {
// should be the same as the model name
return toModelName(name);
}
@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 "{ [key: string]: "+ getTypeDeclaration(inner) + "; }";
} else if (p instanceof FileProperty) {
return "any";
}
return super.getTypeDeclaration(p);
}
// model name cannot use reserved keyword, e.g. return
if (isReservedWord(name)) {
String modelName = camelize("model_" + name);
LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + 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
// phone_number => PhoneNumber
return camelize(name);
}
@Override
public String toModelFilename(String name) {
// should be the same as the model name
return toModelName(name);
}
@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 "{ [key: string]: "+ getTypeDeclaration(inner) + "; }";
} else if (p instanceof FileProperty) {
return "any";
}
return super.getTypeDeclaration(p);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type))
return type;
} else
type = swaggerType;
return toModelName(type);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type))
return type;
} else
type = swaggerType;
return toModelName(type);
}
@Override
public String toOperationId(String operationId) {
@ -217,8 +228,8 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
this.modelPropertyNaming = naming;
} else {
throw new IllegalArgumentException("Invalid model property naming '" +
naming + "'. Must be 'original', 'camelCase', " +
"'PascalCase' or 'snake_case'");
naming + "'. Must be 'original', 'camelCase', " +
"'PascalCase' or 'snake_case'");
}
}
@ -232,9 +243,9 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
case camelCase: return camelize(name, true);
case PascalCase: return camelize(name);
case snake_case: return underscore(name);
default: throw new IllegalArgumentException("Invalid model property naming '" +
name + "'. Must be 'original', 'camelCase', " +
"'PascalCase' or 'snake_case'");
default: throw new IllegalArgumentException("Invalid model property naming '" +
name + "'. Must be 'original', 'camelCase', " +
"'PascalCase' or 'snake_case'");
}
}

View File

@ -33,6 +33,7 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
// requestPackage and authPackage are used by the "volley" template/library
protected String requestPackage = "io.swagger.client.request";
protected String authPackage = "io.swagger.client.auth";
protected String gradleWrapperPackage = "gradle.wrapper";
protected String apiDocPath = "docs/";
protected String modelDocPath = "docs/";
@ -89,8 +90,8 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
cliOptions.add(CliOption.newBoolean(USE_ANDROID_MAVEN_GRADLE_PLUGIN, "A flag to toggle android-maven gradle plugin.")
.defaultValue(Boolean.TRUE.toString()));
supportedLibraries.put("<default>", "HTTP client: Apache HttpClient 4.3.6. JSON processing: Gson 2.3.1");
supportedLibraries.put("volley", "HTTP client: Volley 1.0.19");
supportedLibraries.put("volley", "HTTP client: Volley 1.0.19 (default)");
supportedLibraries.put("httpclient", "HTTP client: Apache HttpClient 4.3.6. JSON processing: Gson 2.3.1. IMPORTANT: Android client using HttpClient is not actively maintained and will be depecreated in the next major release.");
CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use");
library.setEnum(supportedLibraries);
cliOptions.add(library);
@ -382,23 +383,26 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
additionalProperties.put( "modelDocPath", modelDocPath );
if (StringUtils.isEmpty(getLibrary())) {
modelDocTemplateFiles.put( "model_doc.mustache", ".md" );
apiDocTemplateFiles.put( "api_doc.mustache", ".md" );
//supportingFiles.add(new SupportingFile("api_doc.mustache", apiDocPath, "api.md"));
//supportingFiles.add(new SupportingFile("model_doc.mustache", modelDocPath, "model.md"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
addSupportingFilesForDefault();
} else if ("volley".equals(getLibrary())) {
modelDocTemplateFiles.put( "model_doc.mustache", ".md" );
apiDocTemplateFiles.put( "api_doc.mustache", ".md" );
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
//supportingFiles.add(new SupportingFile("api_doc.mustache", apiDocPath, "api.md"));
//supportingFiles.add(new SupportingFile("model_doc.mustache", modelDocPath, "model.md"));
addSupportingFilesForVolley();
setLibrary("volley"); // set volley as the default library
}
// determine which file (mustache) to add based on library
if ("volley".equals(getLibrary())) {
addSupportingFilesForVolley();
} else if ("httpclient".equals(getLibrary())) {
addSupportingFilesForHttpClient();
} else {
throw new IllegalArgumentException("Invalid 'library' option specified: '" + getLibrary() + "'. Must be 'httpclient' or 'volley' (default)");
}
}
private void addSupportingFilesForDefault() {
private void addSupportingFilesForHttpClient() {
// documentation files
modelDocTemplateFiles.put( "model_doc.mustache", ".md" );
apiDocTemplateFiles.put( "api_doc.mustache", ".md" );
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle"));
supportingFiles.add(new SupportingFile("build.mustache", "", "build.gradle"));
@ -415,9 +419,25 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
(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"));
// gradle wrapper files
supportingFiles.add(new SupportingFile( "gradlew.mustache", "", "gradlew" ));
supportingFiles.add(new SupportingFile( "gradlew.bat.mustache", "", "gradlew.bat" ));
supportingFiles.add(new SupportingFile( "gradle-wrapper.properties.mustache",
gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.properties" ));
supportingFiles.add(new SupportingFile( "gradle-wrapper.jar",
gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.jar" ));
}
private void addSupportingFilesForVolley() {
// documentation files
modelDocTemplateFiles.put( "model_doc.mustache", ".md" );
apiDocTemplateFiles.put( "api_doc.mustache", ".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("pom.mustache", "", "pom.xml"));
// supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle"));
supportingFiles.add(new SupportingFile("build.mustache", "", "build.gradle"));
@ -446,6 +466,14 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
(sourceFolder + File.separator + authPackage).replace(".", File.separator), "HttpBasicAuth.java"));
supportingFiles.add(new SupportingFile("auth/authentication.mustache",
(sourceFolder + File.separator + authPackage).replace(".", File.separator), "Authentication.java"));
// gradle wrapper files
supportingFiles.add(new SupportingFile( "gradlew.mustache", "", "gradlew" ));
supportingFiles.add(new SupportingFile( "gradlew.bat.mustache", "", "gradlew.bat" ));
supportingFiles.add(new SupportingFile( "gradle-wrapper.properties.mustache",
gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.properties" ));
supportingFiles.add(new SupportingFile( "gradle-wrapper.jar",
gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.jar" ));
}
public Boolean getUseAndroidMavenGradlePlugin() {

View File

@ -137,6 +137,11 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
@Override
public void processOpts() {
super.processOpts();
Boolean excludeTests = false;
if(additionalProperties.containsKey(CodegenConstants.EXCLUDE_TESTS)) {
excludeTests = Boolean.valueOf(additionalProperties.get(CodegenConstants.EXCLUDE_TESTS).toString());
}
apiPackage = "Api";
modelPackage = "Model";
@ -218,6 +223,8 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
binRelativePath += "vendor";
additionalProperties.put("binRelativePath", binRelativePath);
supportingFiles.add(new SupportingFile("IApiAccessor.mustache",
clientPackageDir, "IApiAccessor.cs"));
supportingFiles.add(new SupportingFile("Configuration.mustache",
clientPackageDir, "Configuration.cs"));
supportingFiles.add(new SupportingFile("ApiClient.mustache",
@ -226,17 +233,29 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
clientPackageDir, "ApiException.cs"));
supportingFiles.add(new SupportingFile("ApiResponse.mustache",
clientPackageDir, "ApiResponse.cs"));
supportingFiles.add(new SupportingFile("ExceptionFactory.mustache",
clientPackageDir, "ExceptionFactory.cs"));
supportingFiles.add(new SupportingFile("compile.mustache", "", "build.bat"));
supportingFiles.add(new SupportingFile("compile-mono.sh.mustache", "", "build.sh"));
// shell script to run the nunit test
supportingFiles.add(new SupportingFile("mono_nunit_test.mustache", "", "mono_nunit_test.sh"));
// copy package.config to nuget's standard location for project-level installs
supportingFiles.add(new SupportingFile("packages.config.mustache", packageFolder + File.separator, "packages.config"));
supportingFiles.add(new SupportingFile("packages_test.config.mustache", testPackageFolder + File.separator, "packages.config"));
// .travis.yml for travis-ci.org CI
supportingFiles.add(new SupportingFile("travis.mustache", "", ".travis.yml"));
if(Boolean.FALSE.equals(excludeTests)) {
supportingFiles.add(new SupportingFile("packages_test.config.mustache", testPackageFolder + File.separator, "packages.config"));
}
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"));
// apache v2 license
// UPDATE (20160612) no longer needed as the Apache v2 LICENSE is added globally
//supportingFiles.add(new SupportingFile("LICENSE", "", "LICENSE"));
if (optionalAssemblyInfoFlag) {
supportingFiles.add(new SupportingFile("AssemblyInfo.mustache", packageFolder + File.separator + "Properties", "AssemblyInfo.cs"));
@ -245,11 +264,9 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
supportingFiles.add(new SupportingFile("Solution.mustache", "", packageName + ".sln"));
supportingFiles.add(new SupportingFile("Project.mustache", packageFolder, packageName + ".csproj"));
// TODO: Check if test project output is enabled, partially related to #2506. Should have options for:
// 1) No test project
// 2) No model tests
// 3) No api tests
supportingFiles.add(new SupportingFile("TestProject.mustache", testPackageFolder, testPackageName + ".csproj"));
if(Boolean.FALSE.equals(excludeTests)) {
supportingFiles.add(new SupportingFile("TestProject.mustache", testPackageFolder, testPackageName + ".csproj"));
}
}
additionalProperties.put("apiDocPath", apiDocPath);

View File

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

View File

@ -19,6 +19,7 @@ public class GroovyClientCodegen extends JavaClientCodegen {
outputFolder = "generated-code/groovy";
modelTemplateFiles.put("model.mustache", ".groovy");
apiTemplateFiles.put(templateFileName, ".groovy");
apiTestTemplateFiles.clear(); // TODO: add test template
embeddedTemplateDir = templateDir = "Groovy";
apiPackage = "io.swagger.api";
@ -26,6 +27,7 @@ public class GroovyClientCodegen extends JavaClientCodegen {
configPackage = "io.swagger.configuration";
invokerPackage = "io.swagger.api";
artifactId = "swagger-spring-mvc-server";
dateLibrary = "legacy";
additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
additionalProperties.put(CodegenConstants.GROUP_ID, groupId);

View File

@ -7,10 +7,8 @@ import io.swagger.models.properties.*;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Swagger;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import java.util.*;
import java.io.File;
public class HaskellServantCodegen extends DefaultCodegen implements CodegenConfig {
@ -432,7 +430,7 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
case "pipes": return "(QueryList 'PipeSeparated (" + type + "))";
case "multi": return "(QueryList 'MultiParamArray (" + type + "))";
default:
throw new NotImplementedException();
throw new UnsupportedOperationException();
}
}

View File

@ -30,13 +30,16 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
public static final String RETROFIT_1 = "retrofit";
public static final String RETROFIT_2 = "retrofit2";
protected String dateLibrary = "default";
protected String dateLibrary = "joda";
protected String invokerPackage = "io.swagger.client";
protected String groupId = "io.swagger";
protected String artifactId = "swagger-java-client";
protected String artifactVersion = "1.0.0";
protected String projectFolder = "src" + File.separator + "main";
protected String projectTestFolder = "src" + File.separator + "test";
protected String sourceFolder = projectFolder + File.separator + "java";
protected String testFolder = projectTestFolder + File.separator + "java";
protected String gradleWrapperPackage = "gradle.wrapper";
protected String localVariablePrefix = "";
protected boolean fullJavaUtil;
protected String javaUtilPrefix = "";
@ -52,6 +55,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
outputFolder = "generated-code" + File.separator + "java";
modelTemplateFiles.put("model.mustache", ".java");
apiTemplateFiles.put("api.mustache", ".java");
apiTestTemplateFiles.put("api_test.mustache", ".java");
embeddedTemplateDir = templateDir = "Java";
apiPackage = "io.swagger.client.api";
modelPackage = "io.swagger.client.model";
@ -107,12 +111,12 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
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("feign", "HTTP client: Netflix Feign 8.1.1");
supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.6");
supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1");
supportedLibraries.put(RETROFIT_1, "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)");
supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 2.5.0. JSON processing: Gson 2.4 (Retrofit 2.0.1). Enable the RxJava adapter using '-DuseRxJava=true'. (RxJava 1.1.2)");
supportedLibraries.put(DEFAULT_LIBRARY, "HTTP client: Jersey client 1.19.1. JSON processing: Jackson 2.7.0");
supportedLibraries.put("feign", "HTTP client: Netflix Feign 8.16.0. JSON processing: Jackson 2.7.0");
supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.22.2. JSON processing: Jackson 2.7.0");
supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.6.2");
supportedLibraries.put(RETROFIT_1, "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)");
supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 3.2.0. JSON processing: Gson 2.6.1 (Retrofit 2.0.2). Enable the RxJava adapter using '-DuseRxJava=true'. (RxJava 1.1.3)");
CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use");
library.setDefault(DEFAULT_LIBRARY);
@ -124,6 +128,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
Map<String, String> dateOptions = new HashMap<String, String>();
dateOptions.put("java8", "Java 8 native");
dateOptions.put("joda", "Joda");
dateOptions.put("legacy", "Legacy java.util.Date");
dateLibrary.setEnum(dateOptions);
cliOptions.add(dateLibrary);
@ -257,12 +262,22 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
writeOptional(outputFolder, new SupportingFile("settings.gradle.mustache", "", "settings.gradle"));
writeOptional(outputFolder, new SupportingFile("gradle.properties.mustache", "", "gradle.properties"));
writeOptional(outputFolder, new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml"));
writeOptional(outputFolder, new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java"));
supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java"));
supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java"));
final String authFolder = (sourceFolder + '/' + invokerPackage + ".auth").replace(".", "/");
if ("feign".equals(getLibrary())) {
supportingFiles.add(new SupportingFile("FormAwareEncoder.mustache", invokerFolder, "FormAwareEncoder.java"));
//gradleWrapper files
supportingFiles.add( new SupportingFile( "gradlew.mustache", "", "gradlew") );
supportingFiles.add( new SupportingFile( "gradlew.bat.mustache", "", "gradlew.bat") );
supportingFiles.add( new SupportingFile( "gradle-wrapper.properties.mustache",
gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.properties") );
supportingFiles.add( new SupportingFile( "gradle-wrapper.jar",
gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.jar") );
// "build.sbt" is for development with SBT
supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt"));
}
supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java"));
supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java"));
@ -281,6 +296,14 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
// generate markdown docs
modelDocTemplateFiles.put("model_doc.mustache", ".md");
apiDocTemplateFiles.put("api_doc.mustache", ".md");
//gradleWrapper files
supportingFiles.add( new SupportingFile( "gradlew.mustache", "", "gradlew") );
supportingFiles.add( new SupportingFile( "gradlew.bat.mustache", "", "gradlew.bat") );
supportingFiles.add( new SupportingFile( "gradle-wrapper.properties.mustache",
gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.properties") );
supportingFiles.add( new SupportingFile( "gradle-wrapper.jar",
gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.jar") );
} else if ("okhttp-gson".equals(getLibrary())) {
// generate markdown docs
modelDocTemplateFiles.put("model_doc.mustache", ".md");
@ -293,14 +316,49 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("ProgressResponseBody.mustache", invokerFolder, "ProgressResponseBody.java"));
// "build.sbt" is for development with SBT
supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt"));
//gradleWrapper files
supportingFiles.add( new SupportingFile( "gradlew.mustache", "", "gradlew") );
supportingFiles.add( new SupportingFile( "gradlew.bat.mustache", "", "gradlew.bat") );
supportingFiles.add( new SupportingFile( "gradle-wrapper.properties.mustache",
gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.properties") );
supportingFiles.add( new SupportingFile( "gradle-wrapper.jar",
gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.jar") );
} else if (usesAnyRetrofitLibrary()) {
supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java"));
supportingFiles.add(new SupportingFile("CollectionFormats.mustache", invokerFolder, "CollectionFormats.java"));
//gradleWrapper files
supportingFiles.add( new SupportingFile( "gradlew.mustache", "", "gradlew") );
supportingFiles.add( new SupportingFile( "gradlew.bat.mustache", "", "gradlew.bat") );
supportingFiles.add( new SupportingFile( "gradle-wrapper.properties.mustache",
gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.properties") );
supportingFiles.add( new SupportingFile( "gradle-wrapper.jar",
gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.jar") );
// "build.sbt" is for development with SBT
supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt"));
//generate markdown docs for retrofit2
if ( usesRetrofit2Library() ){
modelDocTemplateFiles.put("model_doc.mustache", ".md");
apiDocTemplateFiles.put("api_doc.mustache", ".md");
}
} else if("jersey2".equals(getLibrary())) {
// generate markdown docs
modelDocTemplateFiles.put("model_doc.mustache", ".md");
apiDocTemplateFiles.put("api_doc.mustache", ".md");
supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java"));
//gradleWrapper files
supportingFiles.add( new SupportingFile( "gradlew.mustache", "", "gradlew") );
supportingFiles.add( new SupportingFile( "gradlew.bat.mustache", "", "gradlew.bat") );
supportingFiles.add( new SupportingFile( "gradle-wrapper.properties.mustache",
gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.properties") );
supportingFiles.add( new SupportingFile( "gradle-wrapper.jar",
gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.jar") );
// "build.sbt" is for development with SBT
supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt"));
}
if(additionalProperties.containsKey(DATE_LIBRARY)) {
@ -366,6 +424,11 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', '/');
}
@Override
public String apiTestFileFolder() {
return outputFolder + "/" + testFolder + "/" + apiPackage().replace('.', '/');
}
@Override
public String modelFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', '/');
@ -391,6 +454,11 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
return toModelName(name);
}
@Override
public String toApiTestFilename(String name) {
return toApiName(name) + "Test";
}
@Override
public String toVarName(String name) {
// sanitize name

View File

@ -25,9 +25,11 @@ public class JavaInflectorServerCodegen extends JavaClientCodegen {
sourceFolder = "src/gen/java";
modelTemplateFiles.put("model.mustache", ".java");
apiTemplateFiles.put("api.mustache", ".java");
apiTestTemplateFiles.clear(); // TODO: add test template
embeddedTemplateDir = templateDir = "JavaInflector";
invokerPackage = "io.swagger.handler";
artifactId = "swagger-inflector-server";
dateLibrary = "legacy";
apiPackage = System.getProperty("swagger.codegen.inflector.apipackage", "io.swagger.handler");
modelPackage = System.getProperty("swagger.codegen.inflector.modelpackage", "io.swagger.model");

View File

@ -6,6 +6,8 @@ import io.swagger.models.Operation;
import java.io.File;
import java.util.*;
import org.apache.commons.lang3.StringUtils;
public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen {
public JavaJerseyServerCodegen() {
super();
@ -26,7 +28,7 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen {
additionalProperties.put("title", title);
embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "jersey1_18";
embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME;
for ( int i = 0; i < cliOptions.size(); i++ ) {
if ( CodegenConstants.LIBRARY.equals(cliOptions.get(i).getOpt()) ) {
@ -36,13 +38,11 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen {
}
CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use");
library.setDefault(DEFAULT_LIBRARY);
Map<String, String> supportedLibraries = new LinkedHashMap<String, String>();
supportedLibraries.put(DEFAULT_LIBRARY, "Jersey core 1.18.1");
supportedLibraries.put("jersey2", "Jersey core 2.x");
supportedLibraries.put("jersey1", "Jersey core 1.x");
supportedLibraries.put("jersey2", "Jersey core 2.x (default)");
library.setEnum(supportedLibraries);
library.setDefault("jersey1");
cliOptions.add(library);
cliOptions.add(new CliOption(CodegenConstants.IMPL_FOLDER, CodegenConstants.IMPL_FOLDER_DESC));
@ -73,16 +73,35 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen {
public void processOpts() {
super.processOpts();
// set jersey2 as default
if (StringUtils.isEmpty(library)) {
setLibrary("jersey2");
}
supportingFiles.clear();
// clear model and api doc template as this codegen
// does not support auto-generated markdown doc at the moment
modelDocTemplateFiles.remove("model_doc.mustache");
apiDocTemplateFiles.remove("api_doc.mustache");
if ( additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER) ) {
if ( additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER)) {
implFolder = (String) additionalProperties.get(CodegenConstants.IMPL_FOLDER);
}
supportingFiles.clear();
if (additionalProperties.containsKey("dateLibrary")) {
setDateLibrary(additionalProperties.get("dateLibrary").toString());
additionalProperties.put(dateLibrary, "true");
}
if ("joda".equals(dateLibrary)) {
supportingFiles.add(new SupportingFile("JodaDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaDateTimeProvider.java"));
supportingFiles.add(new SupportingFile("JodaLocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaLocalDateProvider.java"));
} else if ( "java8".equals(dateLibrary) ) {
supportingFiles.add(new SupportingFile("LocalDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateTimeProvider.java"));
supportingFiles.add(new SupportingFile("LocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateProvider.java"));
}
writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml"));
writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("ApiException.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiException.java"));
@ -91,40 +110,8 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen {
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"));
supportingFiles.add(new SupportingFile("StringUtil.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "StringUtil.java"));
if ( additionalProperties.containsKey("dateLibrary") ) {
setDateLibrary(additionalProperties.get("dateLibrary").toString());
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) ) {
supportingFiles.add(new SupportingFile("JodaDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaDateTimeProvider.java"));
supportingFiles.add(new SupportingFile("JodaLocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaLocalDateProvider.java"));
} else if ( "java8".equals(dateLibrary) ) {
supportingFiles.add(new SupportingFile("LocalDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateTimeProvider.java"));
supportingFiles.add(new SupportingFile("LocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateProvider.java"));
}
}
@Override

View File

@ -31,8 +31,10 @@ public class JavaResteasyServerCodegen extends JavaClientCodegen implements Code
apiTemplateFiles.put("apiService.mustache", ".java");
apiTemplateFiles.put("apiServiceImpl.mustache", ".java");
apiTemplateFiles.put("apiServiceFactory.mustache", ".java");
apiTestTemplateFiles.clear(); // TODO: add test template
apiPackage = "io.swagger.api";
modelPackage = "io.swagger.model";
dateLibrary = "legacy";
additionalProperties.put("title", title);

View File

@ -1,14 +1,7 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.codegen.*;
import io.swagger.models.Model;
import io.swagger.models.properties.*;
import java.io.File;
@ -26,10 +19,10 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
public static final String POD_NAME = "podName";
public static final String AUTHOR_NAME = "authorName";
public static final String AUTHOR_EMAIL = "authorEmail";
public static final String GIT_REPO_URL = "gitRepoURL";
public static final String LICENSE = "license";
public static final String BinaryDataType = "ObjcClientCodegenBinaryData";
public static final String GIT_REPO_URL = "gitRepoURL";
public static final String DEFAULT_LICENSE = "Apache License, Version 2.0";
public static final String CORE_DATA = "coreData";
protected Set<String> foundationClasses = new HashSet<String>();
protected String podName = "SwaggerClient";
@ -37,11 +30,16 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String classPrefix = "SWG";
protected String authorName = "Swagger";
protected String authorEmail = "apiteam@swagger.io";
protected String license = "MIT";
protected String license = DEFAULT_LICENSE;
protected String gitRepoURL = "https://github.com/swagger-api/swagger-codegen";
protected String[] specialWords = {"new", "copy"};
protected String apiDocPath = "docs/";
protected String modelDocPath = "docs/";
protected String modelFilesPath = "Model/";
protected String coreFilesPath = "Core/";
protected String apiFilesPath = "Api/";
protected boolean generateCoreData = false;
protected Set<String> advancedMapingTypes = new HashSet<String>();
@ -70,8 +68,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
defaultIncludes.add("NSDictionary");
defaultIncludes.add("NSMutableArray");
defaultIncludes.add("NSMutableDictionary");
defaultIncludes.add(BinaryDataType);
defaultIncludes.add("NSManagedObject");
defaultIncludes.add("NSData");
advancedMapingTypes.add("NSDictionary");
advancedMapingTypes.add("NSArray");
@ -88,6 +86,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
languageSpecificPrimitives.add("NSString");
languageSpecificPrimitives.add("NSObject");
languageSpecificPrimitives.add("NSDate");
languageSpecificPrimitives.add("NSData");
languageSpecificPrimitives.add("NSURL");
languageSpecificPrimitives.add("bool");
languageSpecificPrimitives.add("BOOL");
@ -109,8 +108,9 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
typeMapping.put("List", "NSArray");
typeMapping.put("object", "NSObject");
typeMapping.put("file", "NSURL");
typeMapping.put("binary", BinaryDataType);
typeMapping.put("ByteArray", BinaryDataType);
typeMapping.put("binary", "NSData");
typeMapping.put("ByteArray", "NSData");
typeMapping.put("byte", "NSData");
// ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm
setReservedWordsLowerCase(
@ -143,6 +143,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
"NSObject",
"NSString",
"NSDate",
"NSData",
"NSURL",
"NSDictionary")
);
@ -151,6 +152,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
instantiationTypes.put("map", "NSMutableDictionary");
cliOptions.clear();
cliOptions.add(new CliOption(CORE_DATA, "Should generate core data models").defaultValue("false"));
cliOptions.add(new CliOption(CLASS_PREFIX, "prefix for generated classes (convention: Abbreviation of pod name e.g. `HN` for `HackerNews`).`")
.defaultValue("SWG"));
cliOptions.add(new CliOption(POD_NAME, "cocoapods package name (convention: CameCase).")
@ -161,7 +163,6 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
cliOptions.add(new CliOption(AUTHOR_EMAIL, "Email to use in the podspec file.").defaultValue("apiteam@swagger.io"));
cliOptions.add(new CliOption(GIT_REPO_URL, "URL for the git repo where this podspec should point to.")
.defaultValue("https://github.com/swagger-api/swagger-codegen"));
cliOptions.add(new CliOption(LICENSE, "License to use in the podspec file.").defaultValue("MIT"));
}
@Override
@ -191,6 +192,12 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
setPodVersion((String) additionalProperties.get(CodegenConstants.POD_VERSION));
}
if (additionalProperties.containsKey(CORE_DATA)) {
Object coreData = additionalProperties.get(CORE_DATA);
if(((String)coreData).equalsIgnoreCase("true")) {
generateCoreData = true;
}
}
if (additionalProperties.containsKey(CLASS_PREFIX)) {
setClassPrefix((String) additionalProperties.get(CLASS_PREFIX));
}
@ -207,8 +214,11 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
setGitRepoURL((String) additionalProperties.get(GIT_REPO_URL));
}
if (additionalProperties.containsKey(LICENSE)) {
setLicense((String) additionalProperties.get(LICENSE));
if(generateCoreData) {
modelTemplateFiles.put("NSManagedObject-header.mustache", "ManagedObject.h");
modelTemplateFiles.put("NSManagedObject-body.mustache", "ManagedObject.m");
modelTemplateFiles.put("NSManagedObjectBuilder-header.mustache", "ManagedObjectBuilder.h");
modelTemplateFiles.put("NSManagedObjectBuilder-body.mustache", "ManagedObjectBuilder.m");
}
additionalProperties.put(POD_NAME, podName);
@ -222,36 +232,41 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
// make api and model doc path available in mustache template
additionalProperties.put("apiDocPath", apiDocPath);
additionalProperties.put("modelDocPath", modelDocPath);
additionalProperties.put("useCoreData", generateCoreData);
String swaggerFolder = podName;
modelPackage = podName;
apiPackage = podName;
modelPackage = swaggerFolder;
apiPackage = swaggerFolder;
supportingFiles.add(new SupportingFile("Object-header.mustache", swaggerFolder, classPrefix + "Object.h"));
supportingFiles.add(new SupportingFile("Object-body.mustache", swaggerFolder, classPrefix + "Object.m"));
supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", swaggerFolder, classPrefix + "QueryParamCollection.h"));
supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", swaggerFolder, classPrefix + "QueryParamCollection.m"));
supportingFiles.add(new SupportingFile("ApiClient-header.mustache", swaggerFolder, classPrefix + "ApiClient.h"));
supportingFiles.add(new SupportingFile("ApiClient-body.mustache", swaggerFolder, classPrefix + "ApiClient.m"));
supportingFiles.add(new SupportingFile("JSONResponseSerializer-header.mustache", swaggerFolder, classPrefix + "JSONResponseSerializer.h"));
supportingFiles.add(new SupportingFile("JSONResponseSerializer-body.mustache", swaggerFolder, classPrefix + "JSONResponseSerializer.m"));
supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", swaggerFolder, classPrefix + "JSONRequestSerializer.m"));
supportingFiles.add(new SupportingFile("JSONRequestSerializer-header.mustache", swaggerFolder, classPrefix + "JSONRequestSerializer.h"));
supportingFiles.add(new SupportingFile("ResponseDeserializer-body.mustache", swaggerFolder, classPrefix + "ResponseDeserializer.m"));
supportingFiles.add(new SupportingFile("ResponseDeserializer-header.mustache", swaggerFolder, classPrefix + "ResponseDeserializer.h"));
supportingFiles.add(new SupportingFile("Sanitizer-body.mustache", swaggerFolder, classPrefix + "Sanitizer.m"));
supportingFiles.add(new SupportingFile("Sanitizer-header.mustache", swaggerFolder, classPrefix + "Sanitizer.h"));
supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.m", swaggerFolder, "JSONValueTransformer+ISO8601.m"));
supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.h", swaggerFolder, "JSONValueTransformer+ISO8601.h"));
supportingFiles.add(new SupportingFile("Configuration-body.mustache", swaggerFolder, classPrefix + "Configuration.m"));
supportingFiles.add(new SupportingFile("Configuration-header.mustache", swaggerFolder, classPrefix + "Configuration.h"));
supportingFiles.add(new SupportingFile("Object-header.mustache", coreFileFolder(), classPrefix + "Object.h"));
supportingFiles.add(new SupportingFile("Object-body.mustache", coreFileFolder(), classPrefix + "Object.m"));
supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.h"));
supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.m"));
supportingFiles.add(new SupportingFile("ApiClient-header.mustache", coreFileFolder(), classPrefix + "ApiClient.h"));
supportingFiles.add(new SupportingFile("ApiClient-body.mustache", coreFileFolder(), classPrefix + "ApiClient.m"));
supportingFiles.add(new SupportingFile("JSONResponseSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.h"));
supportingFiles.add(new SupportingFile("JSONResponseSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.m"));
supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.m"));
supportingFiles.add(new SupportingFile("JSONRequestSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.h"));
supportingFiles.add(new SupportingFile("ResponseDeserializer-body.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.m"));
supportingFiles.add(new SupportingFile("ResponseDeserializer-header.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.h"));
supportingFiles.add(new SupportingFile("Sanitizer-body.mustache", coreFileFolder(), classPrefix + "Sanitizer.m"));
supportingFiles.add(new SupportingFile("Sanitizer-header.mustache", coreFileFolder(), classPrefix + "Sanitizer.h"));
supportingFiles.add(new SupportingFile("Logger-body.mustache", coreFileFolder(), classPrefix + "Logger.m"));
supportingFiles.add(new SupportingFile("Logger-header.mustache", coreFileFolder(), classPrefix + "Logger.h"));
supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-body.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.m"));
supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-header.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.h"));
supportingFiles.add(new SupportingFile("Configuration-body.mustache", coreFileFolder(), classPrefix + "Configuration.m"));
supportingFiles.add(new SupportingFile("Configuration-header.mustache", coreFileFolder(), classPrefix + "Configuration.h"));
supportingFiles.add(new SupportingFile("api-protocol.mustache", coreFileFolder(), classPrefix + "Api.h"));
supportingFiles.add(new SupportingFile("podspec.mustache", "", podName + ".podspec"));
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"));
if(generateCoreData) {
supportingFiles.add(new SupportingFile("xccurrentversion.mustache", (modelPackage() + "/" + modelFilesPath + "/").replace("/", File.separator) + classPrefix + "Model.xcdatamodeld", ".xccurrentversion"));
supportingFiles.add(new SupportingFile("Model.xcdatamodel.mustache",(modelPackage() + "/" + modelFilesPath + "/").replace("/", File.separator) + classPrefix + "Model.xcdatamodeld" + File.separator + classPrefix + "Model.xcdatamodel", "contents"));
}
}
@Override
@ -289,8 +304,81 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
return toModelNameWithoutReservedWordCheck(type);
}
public CodegenProperty coreDatafromProperty(String name, Property p) {
CodegenProperty property = fromProperty(name, p);
if(!generateCoreData) {
return property;
}
property.baseType = getTypeCoreDataDeclaration(p);
return property;
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
String innerTypeDeclaration = getTypeDeclaration(inner);
if (innerTypeDeclaration.endsWith("*")) {
innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1);
}
// In this condition, type of property p is array of primitive,
// return container type with pointer, e.g. `NSArray*<NSString*>*'
if (languageSpecificPrimitives.contains(innerTypeDeclaration)) {
return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*";
}
// In this condition, type of property p is array of model,
// return container type combine inner type with pointer, e.g. `NSArray<SWGTag>*'
else {
for (String sd : advancedMapingTypes) {
if(innerTypeDeclaration.startsWith(sd)) {
return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*";
}
}
return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*";
}
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
String innerTypeDeclaration = getTypeDeclaration(inner);
if (innerTypeDeclaration.endsWith("*")) {
innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1);
}
if (languageSpecificPrimitives.contains(innerTypeDeclaration)) {
return getSwaggerType(p) + "<NSString*, " + innerTypeDeclaration + "*>*";
} else {
for (String s : advancedMapingTypes) {
if(innerTypeDeclaration.startsWith(s)) {
return getSwaggerType(p) + "<NSString*, " + innerTypeDeclaration + "*>*";
}
}
return getSwaggerType(p) + "<NSString*, " + innerTypeDeclaration + ">*";
}
} else {
String swaggerType = getSwaggerType(p);
// In this condition, type of p is objective-c primitive type, e.g. `NSSNumber',
// return type of p with pointer, e.g. `NSNumber*'
if (languageSpecificPrimitives.contains(swaggerType) &&
foundationClasses.contains(swaggerType)) {
return swaggerType + "*";
}
// In this condition, type of p is c primitive type, e.g. `bool',
// return type of p, e.g. `bool'
else if (languageSpecificPrimitives.contains(swaggerType)) {
return swaggerType;
}
// In this condition, type of p is objective-c object type, e.g. `SWGPet',
// return type of p with pointer, e.g. `SWGPet*'
else {
return swaggerType + "*";
}
}
}
public String getTypeCoreDataDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
@ -300,10 +388,6 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
if (innerTypeDeclaration.endsWith("*")) {
innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1);
}
if(innerTypeDeclaration.equalsIgnoreCase(BinaryDataType)) {
return "NSData*";
}
// In this codition, type of property p is array of primitive,
// return container type with pointer, e.g. `NSArray*<NSString*>*'
if (languageSpecificPrimitives.contains(innerTypeDeclaration)) {
@ -324,7 +408,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
Property inner = mp.getAdditionalProperties();
String innerTypeDeclaration = getTypeDeclaration(inner);
if (innerTypeDeclaration.endsWith("*")) {
innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1);
}
@ -360,6 +444,11 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
}
}
@Override
public boolean isDataTypeBinary(String dataType) {
return dataType.toLowerCase().startsWith("nsdata");
}
@Override
public String toModelName(String type) {
// model name cannot use reserved keyword
@ -454,12 +543,16 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String apiFileFolder() {
return outputFolder + File.separatorChar + apiPackage();
return (outputFolder + "/"+ apiPackage() + "/" + apiFilesPath).replace("/", File.separator);
}
@Override
public String modelFileFolder() {
return outputFolder + File.separatorChar + modelPackage();
return (outputFolder + "/"+ modelPackage() + "/" + modelFilesPath).replace("/", File.separator);
}
public String coreFileFolder() {
return (apiPackage() + "/" + coreFilesPath).replace("/", File.separator);
}
@Override
@ -576,6 +669,12 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
return objs;
}
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property){
super.postProcessModelProperty(model,property);
property.vendorExtensions.put("x-uppercaseName", camelize(property.name));
}
/**
* Return the default value of the property
*

View File

@ -3,6 +3,7 @@ package io.swagger.codegen.languages;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
@ -13,6 +14,7 @@ import io.swagger.models.properties.*;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.HashSet;
import java.util.regex.Matcher;
@ -32,10 +34,10 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
public static final String COMPOSER_VENDOR_NAME = "composerVendorName";
public static final String COMPOSER_PROJECT_NAME = "composerProjectName";
protected String invokerPackage = "Swagger\\Client";
protected String composerVendorName = "swagger";
protected String composerProjectName = "swagger-client";
protected String composerVendorName = null;
protected String composerProjectName = null;
protected String packagePath = "SwaggerClient-php";
protected String artifactVersion = "1.0.0";
protected String artifactVersion = null;
protected String srcBasePath = "lib";
protected String testBasePath = "test";
protected String docsBasePath = "docs";
@ -126,7 +128,9 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
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(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(CodegenConstants.GIT_USER_ID, CodegenConstants.GIT_USER_ID_DESC));
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.GIT_REPO_ID, CodegenConstants.GIT_REPO_ID_DESC));
cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, "The version to use in the composer package version field. e.g. 1.2.3"));
}
@ -163,6 +167,15 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
.replaceAll(regLastPathSeparator+ "$", "");
}
@Override
public String escapeText(String input) {
if (input != null) {
// Trim the string to avoid leading and trailing spaces.
return super.escapeText(input).trim();
}
return input;
}
@Override
public CodegenType getTag() {
return CodegenType.CLIENT;
@ -214,12 +227,24 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
additionalProperties.put(COMPOSER_PROJECT_NAME, composerProjectName);
}
if (additionalProperties.containsKey(CodegenConstants.GIT_USER_ID)) {
this.setGitUserId((String) additionalProperties.get(CodegenConstants.GIT_USER_ID));
} else {
additionalProperties.put(CodegenConstants.GIT_USER_ID, gitUserId);
}
if (additionalProperties.containsKey(COMPOSER_VENDOR_NAME)) {
this.setComposerVendorName((String) additionalProperties.get(COMPOSER_VENDOR_NAME));
} else {
additionalProperties.put(COMPOSER_VENDOR_NAME, composerVendorName);
}
if (additionalProperties.containsKey(CodegenConstants.GIT_REPO_ID)) {
this.setGitRepoId((String) additionalProperties.get(CodegenConstants.GIT_REPO_ID));
} else {
additionalProperties.put(CodegenConstants.GIT_REPO_ID, gitRepoId);
}
if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_VERSION)) {
this.setArtifactVersion((String) additionalProperties.get(CodegenConstants.ARTIFACT_VERSION));
} else {
@ -248,7 +273,8 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("README.mustache", getPackagePath(), "README.md"));
supportingFiles.add(new SupportingFile(".travis.yml", getPackagePath(), ".travis.yml"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", getPackagePath(), "git_push.sh"));
// apache v2 license
supportingFiles.add(new SupportingFile("LICENSE", getPackagePath(), "LICENSE"));
}
@Override
@ -626,4 +652,14 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
// process enum in models
return postProcessModelsEnum(objs);
}
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation op : operationList) {
op.vendorExtensions.put("x-testOperationId", camelize(op.operationId));
}
return objs;
}
}

View File

@ -15,7 +15,6 @@ import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
@ -116,6 +115,11 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
@Override
public void processOpts() {
super.processOpts();
Boolean excludeTests = false;
if(additionalProperties.containsKey(CodegenConstants.EXCLUDE_TESTS)) {
excludeTests = Boolean.valueOf(additionalProperties.get(CodegenConstants.EXCLUDE_TESTS).toString());
}
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) {
setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME));
@ -144,14 +148,23 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
apiPackage = swaggerFolder + File.separatorChar + "apis";
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("LICENSE", "", "LICENSE"));
supportingFiles.add(new SupportingFile("setup.mustache", "", "setup.py"));
supportingFiles.add(new SupportingFile("tox.mustache", "", "tox.ini"));
supportingFiles.add(new SupportingFile("test-requirements.mustache", "", "test-requirements.txt"));
supportingFiles.add(new SupportingFile("requirements.mustache", "", "requirements.txt"));
supportingFiles.add(new SupportingFile("api_client.mustache", swaggerFolder, "api_client.py"));
supportingFiles.add(new SupportingFile("rest.mustache", swaggerFolder, "rest.py"));
supportingFiles.add(new SupportingFile("configuration.mustache", swaggerFolder, "configuration.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__api.mustache", apiPackage, "__init__.py"));
supportingFiles.add(new SupportingFile("__init__test.mustache", testFolder, "__init__.py"));
if(Boolean.FALSE.equals(excludeTests)) {
supportingFiles.add(new SupportingFile("__init__test.mustache", testFolder, "__init__.py"));
}
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
}

View File

@ -0,0 +1,320 @@
package io.swagger.codegen.languages;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.Swagger;
import io.swagger.util.Yaml;
import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Rails5ServerCodegen extends DefaultCodegen implements CodegenConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(Rails5ServerCodegen.class);
private static final SimpleDateFormat MIGRATE_FILE_NAME_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss");
protected String gemName;
protected String moduleName;
protected String gemVersion = "1.0.0";
protected String appFolder = "app";
protected String channelsFolder = appFolder + File.separator + "channels";
protected String applicationCableFolder = channelsFolder + File.separator + "application_cable";
protected String controllersFolder = appFolder + File.separator + "controllers";
protected String jobsFolder = appFolder + File.separator + "jobs";
protected String mailersFolder = appFolder + File.separator + "mailers";
protected String modelsFolder = appFolder + File.separator + "models";
protected String viewsFolder = appFolder + File.separator + "views";
protected String layoutsFolder = viewsFolder + File.separator + "layouts";
protected String binFolder = "bin";
protected String configFolder = "config";
protected String environmentsFolder = configFolder + File.separator + "config";
protected String initializersFolder = configFolder + File.separator + "initializers";
protected String localesFolder = configFolder + File.separator + "locales";
protected String dbFolder = "db";
protected String migrateFolder = dbFolder + File.separator + "migrate";
protected String libFolder = "lib";
protected String tasksFolder = libFolder + File.separator + "tasks";
protected String logFolder = "log";
protected String publicFolder = "public";
protected String testFolder = "test";
protected String tmpFolder = "tmp";
protected String cacheFolder = tmpFolder + File.separator + "cache";
protected String pidFolder = tmpFolder + File.separator + "pids";
protected String socketsFolder = tmpFolder + File.separator + "sockets";
protected String vendorFolder = "vendor";
public Rails5ServerCodegen() {
super();
outputFolder = "generated-code" + File.separator + "rails5";
apiPackage = "app/controllers";
apiTemplateFiles.put("controller.mustache", ".rb");
modelPackage = "app/models";
modelTemplateFiles.put("model.mustache", ".rb");
embeddedTemplateDir = templateDir = "rails5";
typeMapping.clear();
languageSpecificPrimitives.clear();
setReservedWordsLowerCase(
Arrays.asList(
"__FILE__", "and", "def", "end", "in", "or", "self", "unless", "__LINE__",
"begin", "defined?", "ensure", "module", "redo", "super", "until", "BEGIN",
"break", "do", "false", "next", "rescue", "then", "when", "END", "case",
"else", "for", "nil", "retry", "true", "while", "alias", "class", "elsif",
"if", "not", "return", "undef", "yield")
);
typeMapping.put("string", "string");
typeMapping.put("char", "string");
typeMapping.put("int", "integer");
typeMapping.put("integer", "integer");
typeMapping.put("long", "integer");
typeMapping.put("short", "integer");
typeMapping.put("float", "float");
typeMapping.put("double", "decimal");
typeMapping.put("number", "float");
typeMapping.put("date", "date");
typeMapping.put("DateTime", "datetime");
typeMapping.put("boolean", "boolean");
typeMapping.put("binary", "string");
typeMapping.put("ByteArray", "string");
typeMapping.put("UUID", "string");
// remove modelPackage and apiPackage added by default
cliOptions.clear();
}
@Override
public void processOpts() {
super.processOpts();
// use constant model/api package (folder path)
//setModelPackage("models");
setApiPackage("app/controllers");
supportingFiles.add(new SupportingFile("Gemfile", "", "Gemfile"));
supportingFiles.add(new SupportingFile("README.md", "", "README.md"));
supportingFiles.add(new SupportingFile("Rakefile", "", "Rakefile"));
supportingFiles.add(new SupportingFile("config.ru", "", "config.ru"));
supportingFiles.add(new SupportingFile("channel.rb", applicationCableFolder, "channel.rb"));
supportingFiles.add(new SupportingFile("connection.rb", applicationCableFolder, "connection.rb"));
supportingFiles.add(new SupportingFile("application_controller.rb", controllersFolder, "application_controller.rb"));
supportingFiles.add(new SupportingFile("application_job.rb", jobsFolder, "application_job.rb"));
supportingFiles.add(new SupportingFile("application_mailer.rb", mailersFolder, "application_mailer.rb"));
supportingFiles.add(new SupportingFile("application_record.rb", modelsFolder, "application_record.rb"));
supportingFiles.add(new SupportingFile("mailer.html.erb", layoutsFolder, "mailer.html.erb"));
supportingFiles.add(new SupportingFile("mailer.text.erb", layoutsFolder, "mailer.text.erb"));
supportingFiles.add(new SupportingFile("bundle", binFolder, "bundle"));
supportingFiles.add(new SupportingFile("rails", binFolder, "rails"));
supportingFiles.add(new SupportingFile("rake", binFolder, "rake"));
supportingFiles.add(new SupportingFile("setup", binFolder, "setup"));
supportingFiles.add(new SupportingFile("update", binFolder, "update"));
supportingFiles.add(new SupportingFile("development.rb", environmentsFolder, "development.rb"));
supportingFiles.add(new SupportingFile("production.rb", environmentsFolder, "production.rb"));
supportingFiles.add(new SupportingFile("active_record_belongs_to_required_by_default.rb", initializersFolder, "active_record_belongs_to_required_by_default.rb"));
supportingFiles.add(new SupportingFile("application_controller_renderer.rb", initializersFolder, "application_controller_renderer.rb"));
supportingFiles.add(new SupportingFile("backtrace_silencers.rb", initializersFolder, "backtrace_silencers.rb"));
supportingFiles.add(new SupportingFile("callback_terminator.rb", initializersFolder, "callback_terminator.rb"));
supportingFiles.add(new SupportingFile("cors.rb", initializersFolder, "cors.rb"));
supportingFiles.add(new SupportingFile("filter_parameter_logging.rb", initializersFolder, "filter_parameter_logging.rb"));
supportingFiles.add(new SupportingFile("inflections.rb", initializersFolder, "inflections.rb"));
supportingFiles.add(new SupportingFile("mime_types.rb", initializersFolder, "mime_types.rb"));
supportingFiles.add(new SupportingFile("ssl_options.rb", initializersFolder, "ssl_options.rb"));
supportingFiles.add(new SupportingFile("to_time_preserves_timezone.rb", initializersFolder, "to_time_preserves_timezone.rb"));
supportingFiles.add(new SupportingFile("en.yml", localesFolder, "en.yml"));
supportingFiles.add(new SupportingFile("application.rb", configFolder, "application.rb"));
supportingFiles.add(new SupportingFile("boot.rb", configFolder, "boot.rb"));
supportingFiles.add(new SupportingFile("cable.yml", configFolder, "cable.yml"));
supportingFiles.add(new SupportingFile("database.yml", configFolder, "database.yml"));
supportingFiles.add(new SupportingFile("environment.rb", configFolder, "environment.rb"));
supportingFiles.add(new SupportingFile("puma.rb", configFolder, "puma.rb"));
supportingFiles.add(new SupportingFile("routes.mustache", configFolder, "routes.rb"));
supportingFiles.add(new SupportingFile("secrets.yml", configFolder, "secrets.yml"));
supportingFiles.add(new SupportingFile("spring.rb", configFolder, "spring.rb"));
supportingFiles.add(new SupportingFile(".keep", migrateFolder, ".keep"));
supportingFiles.add(new SupportingFile("migrate.mustache", migrateFolder, "0_init_tables.rb"));
supportingFiles.add(new SupportingFile("schema.rb", dbFolder, "schema.rb"));
supportingFiles.add(new SupportingFile("seeds.rb", dbFolder, "seeds.rb"));
supportingFiles.add(new SupportingFile(".keep", tasksFolder, ".keep"));
supportingFiles.add(new SupportingFile(".keep", logFolder, ".keep"));
supportingFiles.add(new SupportingFile("404.html", publicFolder, "404.html"));
supportingFiles.add(new SupportingFile("422.html", publicFolder, "422.html"));
supportingFiles.add(new SupportingFile("500.html", publicFolder, "500.html"));
supportingFiles.add(new SupportingFile("apple-touch-icon-precomposed.png", publicFolder, "apple-touch-icon-precomposed.png"));
supportingFiles.add(new SupportingFile("apple-touch-icon.png", publicFolder, "apple-touch-icon.png"));
supportingFiles.add(new SupportingFile("favicon.ico", publicFolder, "favicon.ico"));
supportingFiles.add(new SupportingFile("robots.txt", publicFolder, "robots.txt"));
supportingFiles.add(new SupportingFile("robots.txt", publicFolder, "robots.txt"));
supportingFiles.add(new SupportingFile("test_helper.rb", testFolder, "test_helper.rb"));
supportingFiles.add(new SupportingFile(".keep", cacheFolder, ".keep"));
supportingFiles.add(new SupportingFile(".keep", pidFolder, ".keep"));
supportingFiles.add(new SupportingFile(".keep", socketsFolder, ".keep"));
supportingFiles.add(new SupportingFile("restart.txt", tmpFolder, "restart.txt"));
supportingFiles.add(new SupportingFile(".keep", vendorFolder, ".keep"));
}
@Override
public CodegenType getTag() {
return CodegenType.SERVER;
}
@Override
public String getName() {
return "rails5";
}
@Override
public String getHelp() {
return "Generates a Rails5 server library.";
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
}
@Override
public String apiFileFolder() {
return outputFolder + File.separator + apiPackage.replace("/", File.separator);
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]";
}
return super.getTypeDeclaration(p);
}
@Override
public String toDefaultValue(Property p) {
return "null";
}
@Override
public String toVarName(String name) {
// 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'.
// if it's all uppper case, convert to lower case
if (name.matches("^[A-Z_]*$")) {
name = name.toLowerCase();
}
// camelize (lower first character) the variable name
// petId => pet_id
name = underscore(name);
// for reserved word or word starting with number, append _
if (isReservedWord(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
}
return name;
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
return typeMapping.get(swaggerType);
}
return "string";
}
@Override
public String toParamName(String name) {
// should be the same as variable name
return toVarName(name);
}
@Override
public String toModelName(String name) {
// model name cannot use reserved keyword, e.g. return
if (isReservedWord(name)) {
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
}
// camelize the model name
// phone_number => PhoneNumber
return camelize(name);
}
@Override
public String toModelFilename(String name) {
// model name cannot use reserved keyword, e.g. return
if (isReservedWord(name)) {
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
}
// underscore the model file name
// PhoneNumber.rb => phone_number.rb
return underscore(name);
}
@Override
public String toApiFilename(String name) {
// 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'.
// e.g. PhoneNumberApi.rb => phone_number_api.rb
return underscore(name) + "_controllers";
}
@Override
public String toApiName(String name) {
if (name.length() == 0) {
return "ApiController";
}
// e.g. phone_number_api => PhoneNumberApi
return camelize(name) + "Controller";
}
@Override
public String toOperationId(String operationId) {
// method name cannot use reserved keyword, e.g. return
if (isReservedWord(operationId)) {
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
}
return underscore(operationId);
}
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
Swagger swagger = (Swagger)objs.get("swagger");
if(swagger != null) {
try {
objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger));
} catch (JsonProcessingException e) {
LOGGER.error(e.getMessage(), e);
}
}
return super.postProcessSupportingFileData(objs);
}
}

View File

@ -5,6 +5,7 @@ import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
@ -224,6 +225,9 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
supportingFiles.add(new SupportingFile("LICENSE", "", "LICENSE"));
// test files should not be overwritten
writeOptional(outputFolder, new SupportingFile("rspec.mustache", "", ".rspec"));
writeOptional(outputFolder, new SupportingFile("spec_helper.mustache", specFolder, "spec_helper.rb"));
writeOptional(outputFolder, new SupportingFile("configuration_spec.mustache", specFolder, "configuration_spec.rb"));
@ -527,6 +531,57 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
return camelize(name) + "Api";
}
@Override
public String toEnumValue(String value, String datatype) {
if ("Integer".equals(datatype) || "Float".equals(datatype)) {
return value;
} else {
return "\"" + escapeText(value) + "\"";
}
}
@Override
public String toEnumVarName(String name, String datatype) {
// number
if ("Integer".equals(datatype) || "Float".equals(datatype)) {
String varName = new String(name);
varName = varName.replaceAll("-", "MINUS_");
varName = varName.replaceAll("\\+", "PLUS_");
varName = varName.replaceAll("\\.", "_DOT_");
return varName;
}
// string
String enumName = sanitizeName(underscore(name).toUpperCase());
enumName = enumName.replaceFirst("^_", "");
enumName = enumName.replaceFirst("_$", "");
if (enumName.matches("\\d.*")) { // starts with number
return "N" + enumName;
} else {
return enumName;
}
}
@Override
public String toEnumName(CodegenProperty property) {
String enumName = underscore(toModelName(property.name)).toUpperCase();
enumName = enumName.replaceFirst("^_", "");
enumName = enumName.replaceFirst("_$", "");
if (enumName.matches("\\d.*")) { // starts with number
return "N" + enumName;
} else {
return enumName;
}
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
// process enum in models
return postProcessModelsEnum(objs);
}
@Override
public String toOperationId(String operationId) {
// rename to empty_method_name_1 (e.g.) if method name is empty

View File

@ -35,6 +35,7 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig
protected String artifactVersion = "1.0.0";
protected String sourceFolder = "src/main/scala";
protected String authScheme = "";
protected String gradleWrapperPackage = "gradle.wrapper";
protected boolean authPreemptive;
protected boolean asyncHttpClient = !authScheme.isEmpty();
@ -74,6 +75,17 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig
(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"));
// gradle settings
supportingFiles.add(new SupportingFile("build.gradle.mustache", "", "build.gradle"));
supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle"));
supportingFiles.add(new SupportingFile("gradle.properties.mustache", "", "gradle.properties"));
// gradleWrapper files
supportingFiles.add(new SupportingFile( "gradlew.mustache", "", "gradlew") );
supportingFiles.add(new SupportingFile( "gradlew.bat.mustache", "", "gradlew.bat") );
supportingFiles.add(new SupportingFile( "gradle-wrapper.properties.mustache",
gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.properties") );
supportingFiles.add(new SupportingFile( "gradle-wrapper.jar",
gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.jar") );
importMapping.remove("List");
importMapping.remove("Set");

View File

@ -10,16 +10,20 @@ import java.util.*;
public class SpringBootServerCodegen extends JavaClientCodegen implements CodegenConfig{
public static final String CONFIG_PACKAGE = "configPackage";
public static final String BASE_PACKAGE = "basePackage";
public static final String INTERFACE_ONLY = "interfaceOnly";
public static final String SINGLE_CONTENT_TYPES = "singleContentTypes";
protected String title = "Petstore Server";
protected String configPackage = "";
protected String basePackage = "";
protected boolean interfaceOnly = false;
protected boolean singleContentTypes = false;
protected String templateFileName = "api.mustache";
public SpringBootServerCodegen() {
super();
outputFolder = "generated-code/javaSpringBoot";
modelTemplateFiles.put("model.mustache", ".java");
apiTemplateFiles.put(templateFileName, ".java");
apiTestTemplateFiles.clear(); // TODO: add test template
embeddedTemplateDir = templateDir = "JavaSpringBoot";
apiPackage = "io.swagger.api";
modelPackage = "io.swagger.model";
@ -39,7 +43,9 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege
cliOptions.add(new CliOption(CONFIG_PACKAGE, "configuration package for generated code"));
cliOptions.add(new CliOption(BASE_PACKAGE, "base package for generated code"));
cliOptions.add(CliOption.newBoolean(INTERFACE_ONLY, "Whether to generate only API interface stubs without the server files."));
cliOptions.add(CliOption.newBoolean(SINGLE_CONTENT_TYPES, "Whether to select only one produces/consumes content-type by operation."));
supportedLibraries.clear();
supportedLibraries.put(DEFAULT_LIBRARY, "Default Spring Boot server stub.");
supportedLibraries.put("j8-async", "Use async servlet feature and Java 8's default interface. Generating interface with service " +
@ -78,30 +84,37 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege
this.setBasePackage((String) additionalProperties.get(BASE_PACKAGE));
}
if (additionalProperties.containsKey(INTERFACE_ONLY)) {
this.setInterfaceOnly(Boolean.valueOf(additionalProperties.get(INTERFACE_ONLY).toString()));
}
if (additionalProperties.containsKey(SINGLE_CONTENT_TYPES)) {
this.setSingleContentTypes(Boolean.valueOf(additionalProperties.get(SINGLE_CONTENT_TYPES).toString()));
}
supportingFiles.clear();
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("apiException.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java"));
supportingFiles.add(new SupportingFile("apiOriginFilter.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiOriginFilter.java"));
supportingFiles.add(new SupportingFile("apiResponseMessage.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java"));
supportingFiles.add(new SupportingFile("notFoundException.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java"));
supportingFiles.add(new SupportingFile("swaggerDocumentationConfig.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerDocumentationConfig.java"));
supportingFiles.add(new SupportingFile("homeController.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "HomeController.java"));
supportingFiles.add(new SupportingFile("swagger2SpringBoot.mustache",
(sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator), "Swagger2SpringBoot.java"));
supportingFiles.add(new SupportingFile("application.properties",
("src.main.resources").replace(".", java.io.File.separator), "application.properties"));
if(!this.interfaceOnly) {
apiTemplateFiles.put("apiController.mustache", "Controller.java");
supportingFiles.add(new SupportingFile("apiException.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java"));
supportingFiles.add(new SupportingFile("apiOriginFilter.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiOriginFilter.java"));
supportingFiles.add(new SupportingFile("apiResponseMessage.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java"));
supportingFiles.add(new SupportingFile("notFoundException.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java"));
supportingFiles.add(new SupportingFile("swaggerDocumentationConfig.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerDocumentationConfig.java"));
supportingFiles.add(new SupportingFile("homeController.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "HomeController.java"));
supportingFiles.add(new SupportingFile("swagger2SpringBoot.mustache",
(sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator), "Swagger2SpringBoot.java"));
supportingFiles.add(new SupportingFile("application.properties",
("src.main.resources").replace(".", java.io.File.separator), "application.properties"));
}
}
@Override
@ -118,9 +131,6 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege
if (basePath == "") {
basePath = "default";
} else {
if (co.path.startsWith("/" + basePath)) {
co.path = co.path.substring(("/" + basePath).length());
}
co.subresourceOperation = !co.path.isEmpty();
}
List<CodegenOperation> opList = operations.get(basePath);
@ -131,10 +141,10 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege
opList.add(co);
co.baseName = basePath;
}
@Override
public void preprocessSwagger(Swagger swagger) {
System.out.println("preprocessSwagger");
super.preprocessSwagger(swagger);
if ("/".equals(swagger.getBasePath())) {
swagger.setBasePath("");
}
@ -147,7 +157,7 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege
port = parts[1];
}
}
this.additionalProperties.put("serverPort", port);
if (swagger != null && swagger.getPaths() != null) {
for (String pathname : swagger.getPaths().keySet()) {
@ -255,6 +265,14 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege
public void setBasePackage(String configPackage) {
this.basePackage = configPackage;
}
public void setInterfaceOnly(boolean interfaceOnly) {
this.interfaceOnly = interfaceOnly;
}
public void setSingleContentTypes(boolean singleContentTypes) {
this.singleContentTypes = singleContentTypes;
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {

View File

@ -18,12 +18,14 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen
outputFolder = "generated-code/javaSpringMVC";
modelTemplateFiles.put("model.mustache", ".java");
apiTemplateFiles.put(templateFileName, ".java");
apiTestTemplateFiles.clear(); // TODO: add test template
embeddedTemplateDir = templateDir = "JavaSpringMVC";
apiPackage = "io.swagger.api";
modelPackage = "io.swagger.model";
configPackage = "io.swagger.configuration";
invokerPackage = "io.swagger.api";
artifactId = "swagger-spring-mvc-server";
dateLibrary = "legacy";
additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
additionalProperties.put(CodegenConstants.GROUP_ID, groupId);

View File

@ -342,7 +342,7 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
// Ensure that the enum type doesn't match a reserved word or
// the variable name doesn't match the generated enum type or the
// Swift compiler will generate an error
if (isReservedWord(codegenProperty.datatypeWithEnum) || name.equals(codegenProperty.datatypeWithEnum)) {
if (isReservedWord(codegenProperty.datatypeWithEnum) || toVarName(name).equals(codegenProperty.datatypeWithEnum)) {
codegenProperty.datatypeWithEnum = codegenProperty.datatypeWithEnum + "Enum";
}
}
@ -355,8 +355,8 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
if (value.matches("[A-Z][a-z0-9]+[a-zA-Z0-9]*")) {
return value;
}
char[] separators = {'-', '_', ' '};
return WordUtils.capitalizeFully(StringUtils.lowerCase(value), separators).replaceAll("[-_ ]", "");
char[] separators = {'-', '_', ' ', ':'};
return WordUtils.capitalizeFully(StringUtils.lowerCase(value), separators).replaceAll("[-_ :]", "");
}
@ -502,6 +502,7 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toEnumVarName(String name, String datatype) {
// TODO: this code is probably useless, because the var name is computed from the value in map.put("enum", toSwiftyEnumName(value));
// number
if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) {
String varName = new String(name);
@ -525,8 +526,9 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toEnumName(CodegenProperty property) {
String enumName = underscore(toModelName(property.name)).toUpperCase();
String enumName = toModelName(property.name);
// TODO: toModelName already does something for names starting with number, so this code is probably never called
if (enumName.matches("\\d.*")) { // starts with number
return "_" + enumName;
} else {

View File

@ -5,12 +5,15 @@ import java.text.SimpleDateFormat;
import java.util.Date;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.ModelImpl;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.FileProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.ObjectProperty;
import io.swagger.models.properties.Property;
public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCodegen {
@ -43,6 +46,12 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod
this.cliOptions.add(new CliOption(SNAPSHOT, "When setting this property to true the version will be suffixed with -SNAPSHOT.yyyyMMddHHmm", BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString()));
}
@Override
protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, ModelImpl swaggerModel) {
codegenModel.additionalPropertiesType = getSwaggerType(swaggerModel.getAdditionalProperties());
addImport(codegenModel, codegenModel.additionalPropertiesType);
}
@Override
public String getName() {
return "typescript-angular2";
@ -106,14 +115,19 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod
MapProperty mp = (MapProperty)p;
inner = mp.getAdditionalProperties();
return "{ [key: string]: " + this.getTypeDeclaration(inner) + "; }";
} else if(p instanceof FileProperty || p instanceof ObjectProperty) {
return "any";
} else {
return p instanceof FileProperty ? "any" : super.getTypeDeclaration(p);
return super.getTypeDeclaration(p);
}
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
if(languageSpecificPrimitives.contains(swaggerType)) {
return swaggerType;
}
return addModelPrefix(swaggerType);
}
@ -121,13 +135,25 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type))
return type;
} else
} else {
type = swaggerType;
}
if (!startsWithLanguageSpecificPrimitiv(type)) {
type = "models." + swaggerType;
}
return type;
}
private boolean startsWithLanguageSpecificPrimitiv(String type) {
for (String langPrimitive:languageSpecificPrimitives) {
if (type.startsWith(langPrimitive)) {
return true;
}
}
return false;
}
@Override
public void postProcessParameter(CodegenParameter parameter) {
super.postProcessParameter(parameter);

View File

@ -26,7 +26,6 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege
super.processOpts();
supportingFiles.add(new SupportingFile("api.mustache", "", "api.ts"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("assign.ts", "", "assign.ts"));
supportingFiles.add(new SupportingFile("README.md", "", "README.md"));
supportingFiles.add(new SupportingFile("package.json.mustache", "", "package.json"));
supportingFiles.add(new SupportingFile("typings.json.mustache", "", "typings.json"));

View File

@ -42,7 +42,6 @@ public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen
supportingFiles.add(new SupportingFile("api.mustache", null, "api.ts"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
LOGGER.warn("check additionals: " + additionalProperties.get(NPM_NAME));
if(additionalProperties.containsKey(NPM_NAME)) {
addNpmPackageGeneration();
}

View File

@ -1,22 +1,28 @@
{{>licenseInfo}}
package {{invokerPackage}};
{{>generatedAnnotation}}
public class Configuration {
private static ApiClient defaultApiClient = new ApiClient();
private static ApiClient defaultApiClient = new ApiClient();
/**
* Get the default API client, which would be used when creating API
* instances without providing an API client.
*/
public static ApiClient getDefaultApiClient() {
return defaultApiClient;
}
/**
* Get the default API client, which would be used when creating API
* instances without providing an API client.
*
* @return Default API client
*/
public static ApiClient getDefaultApiClient() {
return defaultApiClient;
}
/**
* Set the default API client, which would be used when creating API
* instances without providing an API client.
*/
public static void setDefaultApiClient(ApiClient apiClient) {
defaultApiClient = apiClient;
}
/**
* Set the default API client, which would be used when creating API
* instances without providing an API client.
*
* @param apiClient API client
*/
public static void setDefaultApiClient(ApiClient apiClient) {
defaultApiClient = apiClient;
}
}

View File

@ -1,3 +1,5 @@
{{>licenseInfo}}
package {{invokerPackage}};
{{>generatedAnnotation}}

View File

@ -1,3 +1,5 @@
{{>licenseInfo}}
package {{invokerPackage}};
{{>generatedAnnotation}}

View File

@ -78,12 +78,12 @@ public class {{classname}} {
{{/formParams}}
final String[] {{localVariablePrefix}}localVarAccepts = {
{{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}}
{{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}}
};
final String {{localVariablePrefix}}localVarAccept = {{localVariablePrefix}}apiClient.selectHeaderAccept({{localVariablePrefix}}localVarAccepts);
final String[] {{localVariablePrefix}}localVarContentTypes = {
{{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}
{{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}
};
final String {{localVariablePrefix}}localVarContentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}localVarContentTypes);

View File

@ -1,3 +1,5 @@
{{>licenseInfo}}
package {{invokerPackage}};
import java.util.Map;
@ -5,65 +7,74 @@ import java.util.List;
{{>generatedAnnotation}}
public class ApiException extends Exception {
private int code = 0;
private Map<String, List<String>> responseHeaders = null;
private String responseBody = null;
private int code = 0;
private Map<String, List<String>> responseHeaders = null;
private String responseBody = null;
public ApiException() {}
public ApiException() {}
public ApiException(Throwable throwable) {
super(throwable);
}
public ApiException(Throwable throwable) {
super(throwable);
}
public ApiException(String message) {
super(message);
}
public ApiException(String message) {
super(message);
}
public ApiException(String message, Throwable throwable, int code, Map<String, List<String>> responseHeaders, String responseBody) {
super(message, throwable);
this.code = code;
this.responseHeaders = responseHeaders;
this.responseBody = responseBody;
}
public ApiException(String message, Throwable throwable, int code, Map<String, List<String>> responseHeaders, String responseBody) {
super(message, throwable);
this.code = code;
this.responseHeaders = responseHeaders;
this.responseBody = responseBody;
}
public ApiException(String message, int code, Map<String, List<String>> responseHeaders, String responseBody) {
this(message, (Throwable) null, code, responseHeaders, responseBody);
}
public ApiException(String message, int code, Map<String, List<String>> responseHeaders, String responseBody) {
this(message, (Throwable) null, code, responseHeaders, responseBody);
}
public ApiException(String message, Throwable throwable, int code, Map<String, List<String>> responseHeaders) {
this(message, throwable, code, responseHeaders, null);
}
public ApiException(String message, Throwable throwable, int code, Map<String, List<String>> responseHeaders) {
this(message, throwable, code, responseHeaders, null);
}
public ApiException(int code, Map<String, List<String>> responseHeaders, String responseBody) {
this((String) null, (Throwable) null, code, responseHeaders, responseBody);
}
public ApiException(int code, Map<String, List<String>> responseHeaders, String responseBody) {
this((String) null, (Throwable) null, code, responseHeaders, responseBody);
}
public ApiException(int code, String message) {
super(message);
this.code = code;
}
public ApiException(int code, String message) {
super(message);
this.code = code;
}
public ApiException(int code, String message, Map<String, List<String>> responseHeaders, String responseBody) {
this(code, message);
this.responseHeaders = responseHeaders;
this.responseBody = responseBody;
}
public ApiException(int code, String message, Map<String, List<String>> responseHeaders, String responseBody) {
this(code, message);
this.responseHeaders = responseHeaders;
this.responseBody = responseBody;
}
public int getCode() {
return code;
}
/**
* Get the HTTP status code.
*
* @return HTTP status code
*/
public int getCode() {
return code;
}
/**
* Get the HTTP response headers.
*/
public Map<String, List<String>> getResponseHeaders() {
return responseHeaders;
}
/**
* Get the HTTP response headers.
*
* @return A map of list of string
*/
public Map<String, List<String>> getResponseHeaders() {
return responseHeaders;
}
/**
* Get the HTTP response body.
*/
public String getResponseBody() {
return responseBody;
}
/**
* Get the HTTP response body.
*
* @return Response body in the form of string
*/
public String getResponseBody() {
return responseBody;
}
}

View File

@ -75,8 +75,8 @@ Name | Type | Description | Notes
### HTTP request headers
- **Content-Type**: {{#consumes}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}}
- **Accept**: {{#produces}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}}
- **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}}
- **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}}
{{/operation}}
{{/operations}}

View File

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

View File

@ -1,3 +1,5 @@
{{>licenseInfo}}
package {{invokerPackage}}.auth;
import {{invokerPackage}}.Pair;

View File

@ -1,3 +1,5 @@
{{>licenseInfo}}
package {{invokerPackage}}.auth;
import {{invokerPackage}}.Pair;
@ -6,6 +8,11 @@ import java.util.Map;
import java.util.List;
public interface Authentication {
/** Apply authentication settings to header and query params. */
void applyToParams(List<Pair> queryParams, Map<String, String> headerParams);
/**
* Apply authentication settings to header and query params.
*
* @param queryParams List of query parameters
* @param headerParams Map of header parameters
*/
void applyToParams(List<Pair> queryParams, Map<String, String> headerParams);
}

View File

@ -1,3 +1,5 @@
{{>licenseInfo}}
package {{invokerPackage}}.auth;
import {{invokerPackage}}.Pair;

View File

@ -1,3 +1,5 @@
{{>licenseInfo}}
package {{invokerPackage}}.auth;
import {{invokerPackage}}.Pair;

View File

@ -1,5 +1,7 @@
{{>licenseInfo}}
package {{invokerPackage}}.auth;
public enum OAuthFlow {
accessCode, implicit, password, application
}
}

View File

@ -8,5 +8,8 @@
*.war
*.ear
# exclude jar for gradle wrapper
!gradle/wrapper/*.jar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*

View File

@ -0,0 +1,6 @@
#Tue May 17 23:08:05 CST 2016
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-bin.zip

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