Merge branch 'master' into new-sync-master-to-2.3.0

This commit is contained in:
Paŭlo Ebermann 2017-03-13 21:10:53 +01:00
commit 9be178b26a
1040 changed files with 17614 additions and 5102 deletions

View File

@ -14,17 +14,17 @@ Also please indicate in the issue title which language/library is concerned. Eg:
##### 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.
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

View File

@ -1,6 +1,6 @@
### PR checklist
- [ ] Read the [contribution guildelines](https://github.com/swagger-api/swagger-codegen/blob/master/CONTRIBUTING.md).
- [ ] Read the [contribution guidelines](https://github.com/swagger-api/swagger-codegen/blob/master/CONTRIBUTING.md).
- [ ] Ran the shell/batch script under `./bin/` to update Petstore sample so that CIs can verify the change. (For instance, only need to run `./bin/{LANG}-petstore.sh` and `./bin/security/{LANG}-petstore.sh` if updating the {LANG} (e.g. php, ruby, python, etc) code generator or {LANG} client's mustache templates)
- [ ] Filed the PR against the correct branch: master for non-breaking changes and `2.3.0` branch for breaking (non-backward compatible) changes.

2
.gitignore vendored
View File

@ -144,6 +144,8 @@ samples/client/petstore/typescript-node/**/typings
samples/client/petstore/typescript-angular/**/typings
samples/client/petstore/typescript-fetch/**/dist/
samples/client/petstore/typescript-fetch/**/typings
samples/client/petstore/typescript-angular2/npm/npm-debug.log
samples/client/petstore/typescript-node/npm/npm-debug.log
# aspnetcore
samples/server/petstore/aspnetcore/.vs/

View File

@ -7,6 +7,22 @@ jdk:
cache:
directories:
- $HOME/.m2
- $HOME/.ivy2
- $HOME/samples/client/petstore/php/SwaggerClient-php/vendor
- $HOME/samples/client/petstore/ruby/venodr/bundle
- $HOME/samples/client/petstore/python/.venv/
- $HOME/samples/client/petstore/typescript-node/npm/node_modules
- $HOME/samples/client/petstore/typescript-node/npm/typings/
- $HOME/samples/client/petstore/typescript-fetch/tests/default/node_modules
- $HOME/samples/client/petstore/typescript-fetch/tests/default/typings
- $HOME/samples/client/petstore/typescript-fetch/builds/default/node_modules
- $HOME/samples/client/petstore/typescript-fetch/builds/default/typings
- $HOME/samples/client/petstore/typescript-fetch/builds/es6-target/node_modules
- $HOME/samples/client/petstore/typescript-fetch/builds/es6-target/typings
- $HOME/samples/client/petstore/typescript-fetch/builds/with-npm-version/node_modules
- $HOME/samples/client/petstore/typescript-fetch/npm/with-npm-version/typings
- $HOME/samples/client/petstore/typescript-angular/node_modules
- $HOME/samples/client/petstore/typescript-angular/typings
services:
- docker
@ -47,9 +63,11 @@ script:
# fail if generators contain tab '\t'
- /bin/bash ./bin/utils/detect_tab_in_java_class.sh
# run integration tests defined in maven pom.xml
- mvn verify -Psamples
# docker test
- if [ $DOCKER_HUB_USERNAME ]; then docker login --email=$DOCKER_HUB_EMAIL --username=$DOCKER_HUB_USERNAME --password=$DOCKER_HUB_PASSWORD && docker build -t $DOCKER_IMAGE_NAME ./modules/swagger-generator && if [ ! -z "$TRAVIS_TAG" ]; then docker tag $DOCKER_IMAGE_NAME:latest $DOCKER_IMAGE_NAME:$TRAVIS_TAG; fi && docker push $DOCKER_IMAGE_NAME; fi
- mvn --batch-mode verify -Psamples
# docker: build generator image and push to Docker Hub
- if [ $DOCKER_HUB_USERNAME ]; then docker login --email=$DOCKER_HUB_EMAIL --username=$DOCKER_HUB_USERNAME --password=$DOCKER_HUB_PASSWORD && docker build -t $DOCKER_GENERATOR_IMAGE_NAME ./modules/swagger-generator && if [ ! -z "$TRAVIS_TAG" ]; then docker tag $DOCKER_GENERATOR_IMAGE_NAME:latest $DOCKER_GENERATOR_IMAGE_NAME:$TRAVIS_TAG; fi && if [ ! -z "$TRAVIS_TAG" ] || [ "$TRAVIS_BRANCH" = "master" ]; then docker push $DOCKER_GENERATOR_IMAGE_NAME; fi; fi
# docker: build cli image and push to Docker Hub
- if [ $DOCKER_HUB_USERNAME ]; then docker login --email=$DOCKER_HUB_EMAIL --username=$DOCKER_HUB_USERNAME --password=$DOCKER_HUB_PASSWORD && docker build -t $DOCKER_CODEGEN_CLI_IMAGE_NAME ./modules/swagger-codegen-cli && if [ ! -z "$TRAVIS_TAG" ]; then docker tag $DOCKER_CODEGEN_CLI_IMAGE_NAME:latest $DOCKER_CODEGEN_CLI_IMAGE_NAME:$TRAVIS_TAG; fi && if [ ! -z "$TRAVIS_TAG" ] || [ "$TRAVIS_BRANCH" = "master" ]; then docker push $DOCKER_CODEGEN_CLI_IMAGE_NAME; fi; fi
env:
- DOCKER_IMAGE_NAME=swaggerapi/swagger-generator
- DOCKER_GENERATOR_IMAGE_NAME=swaggerapi/swagger-generator DOCKER_CODEGEN_CLI_IMAGE_NAME=swaggerapi/swagger-codegen-cli

View File

@ -1,6 +1,6 @@
# Swagger Code Generator
[![Build Status](https://img.shields.io/travis/swagger-api/swagger-codegen.svg?label=Petstore%20Integration%20Test)](https://travis-ci.org/swagger-api/swagger-codegen)
[![Build Status](https://img.shields.io/travis/swagger-api/swagger-codegen/master.svg?label=Petstore%20Integration%20Test)](https://travis-ci.org/swagger-api/swagger-codegen)
[![Run Status](https://img.shields.io/shippable/5782588a3be4f4faa56c5bea.svg?label=Mustache%20Template%20Test)](https://app.shippable.com/projects/5782588a3be4f4faa56c5bea)
[![Windows Test](https://ci.appveyor.com/api/projects/status/github/swagger-api/swagger-codegen?branch=master&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/swagger-codegen-wh2wu)
[![Maven Central](https://maven-badges.herokuapp.com/maven-central/io.swagger/swagger-codegen-project/badge.svg?style=plastic)](https://maven-badges.herokuapp.com/maven-central/io.swagger/swagger-codegen-project)
@ -12,6 +12,8 @@
:warning: If the OpenAPI/Swagger spec is obtained from an untrusted source, please make sure you've reviewed the spec before using Swagger Codegen to generate the API client, server stub or documentation as [code injection](https://en.wikipedia.org/wiki/Code_injection) may occur :warning:
:rocket: ProductHunt: https://producthunt.com/posts/swagger-codegen :rocket:
## Overview
This is the swagger codegen project, which allows generation of API client libraries (SDK generation), server stubs and documentation automatically given an [OpenAPI Spec](https://github.com/OAI/OpenAPI-Specification). Currently, the following languages/frameworks are supported:
@ -66,19 +68,20 @@ The OpenAPI Specification has undergone 3 revisions since initial creation in 20
Swagger Codegen Version | Release Date | OpenAPI Spec compatibility | Notes
-------------------------- | ------------ | -------------------------- | -----
2.3.0 (upcoming minor release) | TBD | 1.0, 1.1, 1.2, 2.0 | Minor release with breaking changes
2.2.2 (upcoming patch release) | TBD | 1.0, 1.1, 1.2, 2.0 | Patch release (without breaking changes)
2.2.1 (**current stable**) | 2016-08-07 | 1.0, 1.1, 1.2, 2.0 | [tag v2.2.1](https://github.com/swagger-api/swagger-codegen/tree/v2.2.1)
2.3.0 (upcoming minor release) | Apr/May 2017 | 1.0, 1.1, 1.2, 2.0 | Minor release with breaking changes
2.2.3 (upcoming patch release) | TBD | 1.0, 1.1, 1.2, 2.0 | Patch release without breaking changes
2.2.2 (**current stable**) | 2017-03-01 | 1.0, 1.1, 1.2, 2.0 | [tag v2.2.2](https://github.com/swagger-api/swagger-codegen/tree/v2.2.2)
2.2.1 | 2016-08-07 | 1.0, 1.1, 1.2, 2.0 | [tag v2.2.1](https://github.com/swagger-api/swagger-codegen/tree/v2.2.1)
2.1.6 | 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)
### Prerequisites
If you're looking for the latest stable version, you can grab it directly from maven central (you'll need java 7 runtime at a minimum):
If you're looking for the latest stable version, you can grab it directly from Maven.org (Java 7 runtime at a minimum):
```
wget http://repo1.maven.org/maven2/io/swagger/swagger-codegen-cli/2.2.1/swagger-codegen-cli-2.2.1.jar -O swagger-codegen-cli.jar
wget http://central.maven.org/maven2/io/swagger/swagger-codegen-cli/2.2.2/swagger-codegen-cli-2.2.2.jar -O swagger-codegen-cli.jar
java -jar swagger-codegen-cli.jar help
```
@ -161,7 +164,7 @@ cd /vagrant
- https://hub.docker.com/r/swaggerapi/swagger-generator/ (official web service)
- https://hub.docker.com/r/swaggerapi/swagger-codegen-cli/ (official CLI)
=======
##### Swagger Generator Docker Image
@ -188,7 +191,7 @@ docker stop $CID && docker rm $CID
In the example above, `result.zip` will contain the generated client.
##### Swagger Codegen Docker Image
##### Swagger Codegen CLI Docker Image
The Swagger Codegen image acts as a standalone executable. It can be used as an alternative to installing via homebrew, or for developers who are unable to install Java or upgrade the installed version.
@ -197,7 +200,7 @@ To generate code with this image, you'll need to mount a local location as a vol
Example:
```
docker run --rm -v ${PWD}:/local swagger-api/swagger-codegen generate \
docker run --rm -v ${PWD}:/local swaggerapi/swagger-codegen-cli generate \
-i http://petstore.swagger.io/v2/swagger.json \
-l go \
-o /local/out/go
@ -219,7 +222,7 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
```
(if you're on Windows, replace the last command with `java -jar modules\swagger-codegen-cli\target\swagger-codegen-cli.jar generate -i http://petstore.swagger.io/v2/swagger.json -l php -o c:\temp\php_api_client`)
You can also download the JAR (latest release) directly from [maven.org](http://central.maven.org/maven2/io/swagger/swagger-codegen-cli/2.2.1/swagger-codegen-cli-2.2.1.jar )
You can also download the JAR (latest release) directly from [maven.org](http://central.maven.org/maven2/io/swagger/swagger-codegen-cli/2.2.2/swagger-codegen-cli-2.2.2.jar)
To get a list of **general** options available, please run `java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar help generate`
@ -849,11 +852,13 @@ Here are some companies/projects using Swagger Codegen in production. To add you
- [Flat](https://flat.io)
- [Finder](http://en.finder.pl/)
- [FH Münster - University of Applied Sciences](http://www.fh-muenster.de)
- [Fotition](https://www.fotition.com/)
- [Gear Zero Network](https://www.gearzero.ca)
- [Germin8](http://www.germin8.com)
- [goTransverse](http://www.gotransverse.com/api)
- [GraphHopper](https://graphhopper.com/)
- [Gravitate Solutions](http://gravitatesolutions.com/)
- [HashData](http://www.hashdata.cn/)
- [Hewlett Packard Enterprise](https://hpe.com)
- [High Technologies Center](http://htc-cs.com)
- [IMS Health](http://www.imshealth.com/en/solution-areas/technology-and-applications)
@ -887,6 +892,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you
- [Prill Tecnologia](http://www.prill.com.br)
- [QAdept](http://qadept.com/)
- [QuantiModo](https://quantimo.do/)
- [QuickBlox](https://quickblox.com/)
- [Rapid7](https://rapid7.com/)
- [Reload! A/S](https://reload.dk/)
- [REstore](https://www.restore.eu)
@ -903,6 +909,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you
- [snapCX](https://snapcx.io)
- [SPINEN](http://www.spinen.com)
- [SRC](https://www.src.si/)
- [Stingray](http://www.stingray.com)
- [StyleRecipe](http://stylerecipe.co.jp)
- [Svenska Spel AB](https://www.svenskaspel.se/)
- [TaskData](http://www.taskdata.com/)
@ -955,6 +962,7 @@ Swagger Codegen core team members are contributors who have been making signific
| Java Spring Boot | @cbornet (2016/07/19) |
| Java Spring MVC | @kolyjjj (2016/05/01) @cbornet (2016/07/19) |
| Java JAX-RS | |
| Java Play Framework | |
| NancyFX | |
| NodeJS | @kolyjjj (2016/05/01) |
| PHP Lumen | @abcsum (2016/05/01) |
@ -1002,9 +1010,11 @@ Here is a list of template creators:
* Java MSF4J: @sanjeewa-malalgoda
* Java Spring Boot: @diyfr
* Java Undertow: @stevehu
* Java Play Framework: @JFCote
* JAX-RS RestEasy: @chameleon82
* JAX-RS CXF: @hiveship
* JAX-RS CXF (CDI): @nickcmaynard
* JAX-RS RestEasy (JBoss EAP): @jfiala
* PHP Lumen: @abcsum
* PHP Slim: @jfastnacht
* PHP Zend Expressive (with Path Handler): @Articus
@ -1073,3 +1083,4 @@ limitations under the License.
---
<img src="http://swagger.io/wp-content/uploads/2016/02/logo.jpg"/>

View File

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

View File

@ -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/JavaInflector -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l inflector -o samples/server/petstore/java-inflector"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaInflector -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l inflector -o samples/server/petstore/java-inflector -DhideGenerationTimestamp=true"
java $JAVA_OPTS -jar $executable $ags

View File

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

View File

@ -0,0 +1,3 @@
{
"implicitHeaders": true
}

View File

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

View File

@ -0,0 +1,3 @@
call .\bin\windows\swift-petstore.bat
call .\bin\windows\swift-petstore-promisekit.bat
call .\bin\windows\swift-petstore-rxswift.bat

View File

@ -0,0 +1,10 @@
set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar
If Not Exist %executable% (
mvn clean package
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
set ags=generate -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

@ -0,0 +1,10 @@
set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar
If Not Exist %executable% (
mvn clean package
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l swift -c bin\swift-petstore-rxswift.json -o samples\client\petstore\swift\rxswift
java %JAVA_OPTS% -jar %executable% %ags%

View File

@ -5,6 +5,6 @@ If Not Exist %executable% (
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l swift -o samples\client\petstore\swift
set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l swift -o samples\client\petstore\swift\default
java %JAVA_OPTS% -jar %executable% %ags%

View File

@ -0,0 +1,3 @@
call .\bin\windows\swift3-petstore.bat
call .\bin\windows\swift3-petstore-promisekit.bat
call .\bin\windows\swift3-petstore-rxswift.bat

View File

@ -0,0 +1,10 @@
set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar
If Not Exist %executable% (
mvn clean package
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -l swift3 -c bin\swift3-petstore-promisekit.json -o samples\client\petstore\swift3\promisekit
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
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -l swift3 -c bin\swift3-petstore-rxswift.json -o samples\client\petstore\swift3\rxswift
java %JAVA_OPTS% -jar %executable% %ags%

10
bin/windows/swift3-petstore.bat Executable file
View File

@ -0,0 +1,10 @@
set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar
If Not Exist %executable% (
mvn clean package
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -l swift3 -o samples\client\petstore\swift3\default
java %JAVA_OPTS% -jar %executable% %ags%

View File

@ -6,28 +6,33 @@ import java.util.Map;
import java.util.List;
public class CodegenParameter {
public Boolean isFormParam, isQueryParam, isPathParam, isHeaderParam,
public boolean isFormParam, isQueryParam, isPathParam, isHeaderParam,
isCookieParam, isBodyParam, hasMore, isContainer,
secondaryParam, isCollectionFormatMulti, isPrimitiveType;
public String baseName, paramName, dataType, datatypeWithEnum, dataFormat, collectionFormat, description, unescapedDescription, baseType, defaultValue, enumName;
public String baseName, paramName, dataType, datatypeWithEnum, dataFormat,
collectionFormat, description, unescapedDescription, baseType, defaultValue, enumName;
//This was added for javaPlayFramework specifically to get around a bug in swagger-play. See generator for more info on the bug.
public String dataTypeForImplicitParam;
public String example; // example value (x-example)
public String jsonSchema;
public Boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, isBoolean, isDate, isDateTime;
public Boolean isListContainer, isMapContainer;
public Boolean isFile, notFile;
public boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, isBoolean, isDate, isDateTime;
public boolean isListContainer, isMapContainer;
public boolean isFile, notFile;
public boolean isEnum;
public List<String> _enum;
public Map<String, Object> allowableValues;
public CodegenProperty items;
public Map<String, Object> vendorExtensions;
public Boolean hasValidation;
public boolean hasValidation;
/**
* Determines whether this parameter is mandatory. If the parameter is in "path",
* this property is required and its value MUST be true. Otherwise, the property
* MAY be included and its default value is false.
*/
public Boolean required;
public boolean required;
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor17.
@ -36,7 +41,7 @@ public class CodegenParameter {
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor17
*/
public Boolean exclusiveMaximum;
public boolean exclusiveMaximum;
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor21
*/
@ -44,7 +49,7 @@ public class CodegenParameter {
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor21
*/
public Boolean exclusiveMinimum;
public boolean exclusiveMinimum;
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor26
*/
@ -68,7 +73,7 @@ public class CodegenParameter {
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor49
*/
public Boolean uniqueItems;
public boolean uniqueItems;
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor14
*/
@ -156,27 +161,27 @@ public class CodegenParameter {
CodegenParameter that = (CodegenParameter) o;
if (isEnum != that.isEnum) return false;
if (isFormParam != null ? !isFormParam.equals(that.isFormParam) : that.isFormParam != null)
if (isFormParam != that.isFormParam)
return false;
if (isQueryParam != null ? !isQueryParam.equals(that.isQueryParam) : that.isQueryParam != null)
if (isQueryParam != that.isQueryParam)
return false;
if (isPathParam != null ? !isPathParam.equals(that.isPathParam) : that.isPathParam != null)
if (isPathParam != that.isPathParam)
return false;
if (isHeaderParam != null ? !isHeaderParam.equals(that.isHeaderParam) : that.isHeaderParam != null)
if (isHeaderParam != that.isHeaderParam)
return false;
if (isCookieParam != null ? !isCookieParam.equals(that.isCookieParam) : that.isCookieParam != null)
if (isCookieParam != that.isCookieParam)
return false;
if (isBodyParam != null ? !isBodyParam.equals(that.isBodyParam) : that.isBodyParam != null)
if (isBodyParam != that.isBodyParam)
return false;
if (hasMore != null ? !hasMore.equals(that.hasMore) : that.hasMore != null)
if (hasMore != that.hasMore)
return false;
if (isContainer != null ? !isContainer.equals(that.isContainer) : that.isContainer != null)
if (isContainer != that.isContainer)
return false;
if (secondaryParam != null ? !secondaryParam.equals(that.secondaryParam) : that.secondaryParam != null)
if (secondaryParam != that.secondaryParam)
return false;
if (isCollectionFormatMulti != null ? !isCollectionFormatMulti.equals(that.isCollectionFormatMulti) : that.isCollectionFormatMulti != null)
if (isCollectionFormatMulti != that.isCollectionFormatMulti)
return false;
if (isPrimitiveType != null ? !isPrimitiveType.equals(that.isPrimitiveType) : that.isPrimitiveType != null)
if (isPrimitiveType != that.isPrimitiveType)
return false;
if (baseName != null ? !baseName.equals(that.baseName) : that.baseName != null)
return false;
@ -204,33 +209,33 @@ public class CodegenParameter {
return false;
if (jsonSchema != null ? !jsonSchema.equals(that.jsonSchema) : that.jsonSchema != null)
return false;
if (isString != null ? !isString.equals(that.isString) : that.isString != null)
if (isString != that.isString)
return false;
if (isInteger != null ? !isInteger.equals(that.isInteger) : that.isInteger != null)
if (isInteger != that.isInteger)
return false;
if (isLong != null ? !isLong.equals(that.isLong) : that.isLong != null)
if (isLong != that.isLong)
return false;
if (isFloat != null ? !isFloat.equals(that.isFloat) : that.isFloat != null)
if (isFloat != that.isFloat)
return false;
if (isDouble != null ? !isDouble.equals(that.isDouble) : that.isDouble != null)
if (isDouble != that.isDouble)
return false;
if (isByteArray != null ? !isByteArray.equals(that.isByteArray) : that.isByteArray != null)
if (isByteArray != that.isByteArray)
return false;
if (isBinary != null ? !isBinary.equals(that.isBinary) : that.isBinary != null)
if (isBinary != that.isBinary)
return false;
if (isBoolean != null ? !isBoolean.equals(that.isBoolean) : that.isBoolean != null)
if (isBoolean != that.isBoolean)
return false;
if (isDate != null ? !isDate.equals(that.isDate) : that.isDate != null)
if (isDate != that.isDate)
return false;
if (isDateTime != null ? !isDateTime.equals(that.isDateTime) : that.isDateTime != null)
if (isDateTime != that.isDateTime)
return false;
if (isListContainer != null ? !isListContainer.equals(that.isListContainer) : that.isListContainer != null)
if (isListContainer != that.isListContainer)
return false;
if (isMapContainer != null ? !isMapContainer.equals(that.isMapContainer) : that.isMapContainer != null)
if (isMapContainer != that.isMapContainer)
return false;
if (isFile != null ? !isFile.equals(that.isFile) : that.isFile != null)
if (isFile != that.isFile)
return false;
if (notFile != null ? !notFile.equals(that.notFile) : that.notFile != null)
if (notFile != that.notFile)
return false;
if (_enum != null ? !_enum.equals(that._enum) : that._enum != null)
return false;
@ -240,17 +245,17 @@ public class CodegenParameter {
return false;
if (vendorExtensions != null ? !vendorExtensions.equals(that.vendorExtensions) : that.vendorExtensions != null)
return false;
if (hasValidation != null ? !hasValidation.equals(that.hasValidation) : that.hasValidation != null)
if (hasValidation != that.hasValidation)
return false;
if (required != null ? !required.equals(that.required) : that.required != null)
if (required != that.required)
return false;
if (maximum != null ? !maximum.equals(that.maximum) : that.maximum != null)
return false;
if (exclusiveMaximum != null ? !exclusiveMaximum.equals(that.exclusiveMaximum) : that.exclusiveMaximum != null)
if (exclusiveMaximum != that.exclusiveMaximum)
return false;
if (minimum != null ? !minimum.equals(that.minimum) : that.minimum != null)
return false;
if (exclusiveMinimum != null ? !exclusiveMinimum.equals(that.exclusiveMinimum) : that.exclusiveMinimum != null)
if (exclusiveMinimum != that.exclusiveMinimum)
return false;
if (maxLength != null ? !maxLength.equals(that.maxLength) : that.maxLength != null)
return false;
@ -262,7 +267,7 @@ public class CodegenParameter {
return false;
if (minItems != null ? !minItems.equals(that.minItems) : that.minItems != null)
return false;
if (uniqueItems != null ? !uniqueItems.equals(that.uniqueItems) : that.uniqueItems != null)
if (uniqueItems != that.uniqueItems)
return false;
return multipleOf != null ? multipleOf.equals(that.multipleOf) : that.multipleOf == null;
@ -270,17 +275,17 @@ public class CodegenParameter {
@Override
public int hashCode() {
int result = isFormParam != null ? isFormParam.hashCode() : 0;
result = 31 * result + (isQueryParam != null ? isQueryParam.hashCode() : 0);
result = 31 * result + (isPathParam != null ? isPathParam.hashCode() : 0);
result = 31 * result + (isHeaderParam != null ? isHeaderParam.hashCode() : 0);
result = 31 * result + (isCookieParam != null ? isCookieParam.hashCode() : 0);
result = 31 * result + (isBodyParam != null ? isBodyParam.hashCode() : 0);
result = 31 * result + (hasMore != null ? hasMore.hashCode() : 0);
result = 31 * result + (isContainer != null ? isContainer.hashCode() : 0);
result = 31 * result + (secondaryParam != null ? secondaryParam.hashCode() : 0);
result = 31 * result + (isCollectionFormatMulti != null ? isCollectionFormatMulti.hashCode() : 0);
result = 31 * result + (isPrimitiveType != null ? isPrimitiveType.hashCode() : 0);
int result = isFormParam ? 13:31;
result = 31 * result + (isQueryParam ? 13:31);
result = 31 * result + (isPathParam ? 13:31);
result = 31 * result + (isHeaderParam ? 13:31);
result = 31 * result + (isCookieParam ? 13:31);
result = 31 * result + (isBodyParam ? 13:31);
result = 31 * result + (hasMore ? 13:31);
result = 31 * result + (isContainer ? 13:31);
result = 31 * result + (secondaryParam ? 13:31);
result = 31 * result + (isCollectionFormatMulti ? 13:31);
result = 31 * result + (isPrimitiveType ? 13:31);
result = 31 * result + (baseName != null ? baseName.hashCode() : 0);
result = 31 * result + (paramName != null ? paramName.hashCode() : 0);
result = 31 * result + (dataType != null ? dataType.hashCode() : 0);
@ -294,37 +299,37 @@ public class CodegenParameter {
result = 31 * result + (defaultValue != null ? defaultValue.hashCode() : 0);
result = 31 * result + (example != null ? example.hashCode() : 0);
result = 31 * result + (jsonSchema != null ? jsonSchema.hashCode() : 0);
result = 31 * result + (isString != null ? isString.hashCode() : 0);
result = 31 * result + (isInteger != null ? isInteger.hashCode() : 0);
result = 31 * result + (isLong != null ? isLong.hashCode() : 0);
result = 31 * result + (isFloat != null ? isFloat.hashCode() : 0);
result = 31 * result + (isDouble != null ? isDouble.hashCode() : 0);
result = 31 * result + (isByteArray != null ? isByteArray.hashCode() : 0);
result = 31 * result + (isBinary != null ? isBinary.hashCode() : 0);
result = 31 * result + (isBoolean != null ? isBoolean.hashCode() : 0);
result = 31 * result + (isDate != null ? isDate.hashCode() : 0);
result = 31 * result + (isDateTime != null ? isDateTime.hashCode() : 0);
result = 31 * result + (isListContainer != null ? isListContainer.hashCode() : 0);
result = 31 * result + (isMapContainer != null ? isMapContainer.hashCode() : 0);
result = 31 * result + (isFile != null ? isFile.hashCode() : 0);
result = 31 * result + (notFile != null ? notFile.hashCode() : 0);
result = 31 * result + (isString ? 13:31);
result = 31 * result + (isInteger ? 13:31);
result = 31 * result + (isLong ? 13:31);
result = 31 * result + (isFloat ? 13:31);
result = 31 * result + (isDouble ? 13:31);
result = 31 * result + (isByteArray ? 13:31);
result = 31 * result + (isBinary ? 13:31);
result = 31 * result + (isBoolean ? 13:31);
result = 31 * result + (isDate ? 13:31);
result = 31 * result + (isDateTime ? 13:31);
result = 31 * result + (isListContainer ? 13:31);
result = 31 * result + (isMapContainer ? 13:31);
result = 31 * result + (isFile ? 13:31);
result = 31 * result + (notFile ? 13:31);
result = 31 * result + (isEnum ? 1 : 0);
result = 31 * result + (_enum != null ? _enum.hashCode() : 0);
result = 31 * result + (allowableValues != null ? allowableValues.hashCode() : 0);
result = 31 * result + (items != null ? items.hashCode() : 0);
result = 31 * result + (vendorExtensions != null ? vendorExtensions.hashCode() : 0);
result = 31 * result + (hasValidation != null ? hasValidation.hashCode() : 0);
result = 31 * result + (required != null ? required.hashCode() : 0);
result = 31 * result + (hasValidation ? 13:31);
result = 31 * result + (required ? 13:31);
result = 31 * result + (maximum != null ? maximum.hashCode() : 0);
result = 31 * result + (exclusiveMaximum != null ? exclusiveMaximum.hashCode() : 0);
result = 31 * result + (exclusiveMaximum ? 13:31);
result = 31 * result + (minimum != null ? minimum.hashCode() : 0);
result = 31 * result + (exclusiveMinimum != null ? exclusiveMinimum.hashCode() : 0);
result = 31 * result + (exclusiveMinimum ? 13:31);
result = 31 * result + (maxLength != null ? maxLength.hashCode() : 0);
result = 31 * result + (minLength != null ? minLength.hashCode() : 0);
result = 31 * result + (pattern != null ? pattern.hashCode() : 0);
result = 31 * result + (maxItems != null ? maxItems.hashCode() : 0);
result = 31 * result + (minItems != null ? minItems.hashCode() : 0);
result = 31 * result + (uniqueItems != null ? uniqueItems.hashCode() : 0);
result = 31 * result + (uniqueItems ? 13:31);
result = 31 * result + (multipleOf != null ? multipleOf.hashCode() : 0);
return result;
}

View File

@ -7,24 +7,22 @@ import java.util.Map;
public class CodegenResponse {
public final List<CodegenProperty> headers = new ArrayList<CodegenProperty>();
public String code, message;
public Boolean hasMore;
public boolean hasMore;
public List<Map<String, Object>> examples;
public String dataType, baseType, containerType;
public Boolean isDefault;
public Boolean simpleType;
public Boolean primitiveType;
public Boolean isMapContainer;
public Boolean isListContainer;
public Boolean isBinary = Boolean.FALSE;
public Boolean isFile = Boolean.FALSE;
public boolean hasHeaders;
public boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBoolean, isDate, isDateTime;
public boolean isDefault;
public boolean simpleType;
public boolean primitiveType;
public boolean isMapContainer;
public boolean isListContainer;
public boolean isBinary = false;
public boolean isFile = false;
public Object schema;
public String jsonSchema;
public Map<String, Object> vendorExtensions;
public boolean isWildcard() {
return "0".equals(code) || "default".equals(code);
}
@Override
public String toString() {
return String.format("%s(%s)", code, containerType);
@ -43,7 +41,7 @@ public class CodegenResponse {
return false;
if (message != null ? !message.equals(that.message) : that.message != null)
return false;
if (hasMore != null ? !hasMore.equals(that.hasMore) : that.hasMore != null)
if (hasMore != that.hasMore)
return false;
if (examples != null ? !examples.equals(that.examples) : that.examples != null)
return false;
@ -53,19 +51,19 @@ public class CodegenResponse {
return false;
if (containerType != null ? !containerType.equals(that.containerType) : that.containerType != null)
return false;
if (isDefault != null ? !isDefault.equals(that.isDefault) : that.isDefault != null)
if (isDefault != that.isDefault)
return false;
if (simpleType != null ? !simpleType.equals(that.simpleType) : that.simpleType != null)
if (simpleType != that.simpleType)
return false;
if (primitiveType != null ? !primitiveType.equals(that.primitiveType) : that.primitiveType != null)
if (primitiveType != that.primitiveType)
return false;
if (isMapContainer != null ? !isMapContainer.equals(that.isMapContainer) : that.isMapContainer != null)
if (isMapContainer != that.isMapContainer)
return false;
if (isListContainer != null ? !isListContainer.equals(that.isListContainer) : that.isListContainer != null)
if (isListContainer != that.isListContainer)
return false;
if (isBinary != null ? !isBinary.equals(that.isBinary) : that.isBinary != null)
if (isBinary != that.isBinary)
return false;
if (isFile != null ? !isFile.equals(that.isFile) : that.isFile != null)
if (isFile != that.isFile)
return false;
if (schema != null ? !schema.equals(that.schema) : that.schema != null)
return false;
@ -80,18 +78,18 @@ public class CodegenResponse {
int result = headers.hashCode();
result = 31 * result + (code != null ? code.hashCode() : 0);
result = 31 * result + (message != null ? message.hashCode() : 0);
result = 31 * result + (hasMore != null ? hasMore.hashCode() : 0);
result = 31 * result + (hasMore ? 13:31);
result = 31 * result + (examples != null ? examples.hashCode() : 0);
result = 31 * result + (dataType != null ? dataType.hashCode() : 0);
result = 31 * result + (baseType != null ? baseType.hashCode() : 0);
result = 31 * result + (containerType != null ? containerType.hashCode() : 0);
result = 31 * result + (isDefault != null ? isDefault.hashCode() : 0);
result = 31 * result + (simpleType != null ? simpleType.hashCode() : 0);
result = 31 * result + (primitiveType != null ? primitiveType.hashCode() : 0);
result = 31 * result + (isMapContainer != null ? isMapContainer.hashCode() : 0);
result = 31 * result + (isListContainer != null ? isListContainer.hashCode() : 0);
result = 31 * result + (isBinary != null ? isBinary.hashCode() : 0);
result = 31 * result + (isFile != null ? isFile.hashCode() : 0);
result = 31 * result + (isDefault ? 13:31);
result = 31 * result + (simpleType ? 13:31);
result = 31 * result + (primitiveType ? 13:31);
result = 31 * result + (isMapContainer ? 13:31);
result = 31 * result + (isListContainer ? 13:31);
result = 31 * result + (isBinary ? 13:31);
result = 31 * result + (isFile ? 13:31);
result = 31 * result + (schema != null ? schema.hashCode() : 0);
result = 31 * result + (jsonSchema != null ? jsonSchema.hashCode() : 0);
result = 31 * result + (vendorExtensions != null ? vendorExtensions.hashCode() : 0);

View File

@ -811,6 +811,7 @@ public class DefaultCodegen {
typeMapping.put("ByteArray", "byte[]");
typeMapping.put("binary", "byte[]");
typeMapping.put("file", "File");
typeMapping.put("UUID", "UUID");
instantiationTypes = new HashMap<String, String>();
@ -1481,7 +1482,10 @@ public class DefaultCodegen {
property.title = p.getTitle();
property.getter = "get" + getterAndSetterCapitalize(name);
property.setter = "set" + getterAndSetterCapitalize(name);
property.example = toExampleValue(p);
String example = toExampleValue(p);
if(!"null".equals(example)) {
property.example = example;
}
property.defaultValue = toDefaultValue(p);
property.defaultValueWithParam = toDefaultValueWithParam(name, p);
property.jsonSchema = Json.pretty(p);
@ -2046,10 +2050,10 @@ public class DefaultCodegen {
}
r.isDefault = response == methodResponse;
op.responses.add(r);
if (r.isBinary && r.isDefault){
if (Boolean.TRUE.equals(r.isBinary) && Boolean.TRUE.equals(r.isDefault)){
op.isResponseBinary = Boolean.TRUE;
}
if (r.isFile && r.isDefault){
if (Boolean.TRUE.equals(r.isFile) && Boolean.TRUE.equals(r.isDefault)){
op.isResponseFile = Boolean.TRUE;
}
}
@ -2161,7 +2165,7 @@ public class DefaultCodegen {
} else if (param instanceof FormParameter) {
formParams.add(p.copy());
}
if (p.required == null || !p.required) {
if (!p.required) {
op.hasOptionalParams = true;
}
}
@ -2179,10 +2183,8 @@ public class DefaultCodegen {
Collections.sort(allParams, new Comparator<CodegenParameter>() {
@Override
public int compare(CodegenParameter one, CodegenParameter another) {
boolean oneRequired = one.required == null ? false : one.required;
boolean anotherRequired = another.required == null ? false : another.required;
if (oneRequired == anotherRequired) return 0;
else if (oneRequired) return -1;
if (one.required == another.required) return 0;
else if (one.required) return -1;
else return 1;
}
});
@ -2233,6 +2235,7 @@ public class DefaultCodegen {
r.jsonSchema = Json.pretty(response);
r.vendorExtensions = response.getVendorExtensions();
addHeaders(response, r.headers);
r.hasHeaders = !r.headers.isEmpty();
if (r.schema != null) {
Property responseProperty = response.getSchema();
@ -2251,8 +2254,33 @@ public class DefaultCodegen {
}
}
r.dataType = cm.datatype;
r.isBinary = isDataTypeBinary(cm.datatype);
r.isFile = isDataTypeFile(cm.datatype);
if (Boolean.TRUE.equals(cm.isString)) {
r.isString = true;
} else if (Boolean.TRUE.equals(cm.isBoolean)) {
r.isBoolean = true;
} else if (Boolean.TRUE.equals(cm.isLong)) {
r.isLong = true;
} else if (Boolean.TRUE.equals(cm.isInteger)) {
r.isInteger = true;
} else if (Boolean.TRUE.equals(cm.isDouble)) {
r.isDouble = true;
} else if (Boolean.TRUE.equals(cm.isFloat)) {
r.isFloat = true;
} else if (Boolean.TRUE.equals(cm.isByteArray)) {
r.isByteArray = true;
} else if (Boolean.TRUE.equals(cm.isBinary)) {
r.isBinary = true;
} else if (Boolean.TRUE.equals(cm.isFile)) {
r.isFile = true;
} else if (Boolean.TRUE.equals(cm.isDate)) {
r.isDate = true;
} else if (Boolean.TRUE.equals(cm.isDateTime)) {
r.isDateTime = true;
} else {
LOGGER.debug("Property type is not primitive: " + cm.datatype);
}
if (cm.isContainer) {
r.simpleType = false;
r.containerType = cm.containerType;
@ -2410,14 +2438,14 @@ public class DefaultCodegen {
p.minimum = qp.getMinimum() == null ? null : String.valueOf(qp.getMinimum());
}
p.exclusiveMaximum = qp.isExclusiveMaximum();
p.exclusiveMinimum = qp.isExclusiveMinimum();
p.exclusiveMaximum = qp.isExclusiveMaximum() == null ? false : qp.isExclusiveMaximum();
p.exclusiveMinimum = qp.isExclusiveMinimum() == null ? false : qp.isExclusiveMinimum();
p.maxLength = qp.getMaxLength();
p.minLength = qp.getMinLength();
p.pattern = toRegularExpression(qp.getPattern());
p.maxItems = qp.getMaxItems();
p.minItems = qp.getMinItems();
p.uniqueItems = qp.isUniqueItems();
p.uniqueItems = qp.isUniqueItems() == null ? false : qp.isUniqueItems();
p.multipleOf = qp.getMultipleOf();
// exclusive* are noop without corresponding min/max
@ -2452,6 +2480,9 @@ public class DefaultCodegen {
p.isPrimitiveType = cp.isPrimitiveType;
p.isBinary = isDataTypeBinary(cp.datatype);
p.isFile = isDataTypeFile(cp.datatype);
if (cp.complexType != null) {
imports.add(cp.complexType);
}
}
// set boolean flag (e.g. isString)

View File

@ -75,12 +75,12 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
StringBuilder hostBuilder = new StringBuilder();
hostBuilder.append(getScheme());
hostBuilder.append("://");
if (swagger.getHost() != null) {
if (!StringUtils.isEmpty(swagger.getHost())) {
hostBuilder.append(swagger.getHost());
} else {
hostBuilder.append("localhost");
}
if (swagger.getBasePath() != null) {
if (!StringUtils.isEmpty(swagger.getBasePath()) && !swagger.getBasePath().equals("/")) {
hostBuilder.append(swagger.getBasePath());
}
return hostBuilder.toString();
@ -154,8 +154,10 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
// set a default description if none if provided
config.additionalProperties().put("appDescription",
"No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)");
config.additionalProperties().put("unescapedAppDescription", "No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)");
} else {
config.additionalProperties().put("appDescription", config.escapeText(info.getDescription()));
config.additionalProperties().put("unescapedAppDescription", info.getDescription());
}
if (info.getContact() != null) {

View File

@ -19,6 +19,7 @@ import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.HashSet;
@ -34,7 +35,7 @@ import static org.apache.commons.lang3.StringUtils.isNotEmpty;
* It also has a convenience method for creating a ClientOptInput class which is THE object DefaultGenerator.java needs
* to generate code.
*/
public class CodegenConfigurator {
public class CodegenConfigurator implements Serializable {
public static final Logger LOGGER = LoggerFactory.getLogger(CodegenConfigurator.class);

View File

@ -1,5 +1,8 @@
package io.swagger.codegen.examples;
import static io.swagger.models.properties.StringProperty.Format.URI;
import static io.swagger.models.properties.StringProperty.Format.URL;
import io.swagger.models.Model;
import io.swagger.models.ModelImpl;
import io.swagger.models.properties.ArrayProperty;
@ -11,7 +14,6 @@ import io.swagger.models.properties.DecimalProperty;
import io.swagger.models.properties.DoubleProperty;
import io.swagger.models.properties.FileProperty;
import io.swagger.models.properties.FloatProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.ObjectProperty;
@ -20,10 +22,12 @@ import io.swagger.models.properties.RefProperty;
import io.swagger.models.properties.StringProperty;
import io.swagger.models.properties.UUIDProperty;
import io.swagger.util.Json;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@ -31,6 +35,17 @@ import java.util.Map;
import java.util.Set;
public class ExampleGenerator {
private static final Logger logger = LoggerFactory.getLogger(ExampleGenerator.class);
// TODO: move constants to more appropriate location
private static final String MIME_TYPE_JSON = "application/json";
private static final String MIME_TYPE_XML = "application/xml";
private static final String EXAMPLE = "example";
private static final String CONTENT_TYPE = "contentType";
private static final String OUTPUT = "output";
private static final String NONE = "none";
protected Map<String, Model> examples;
public ExampleGenerator(Map<String, Model> examples) {
@ -38,53 +53,76 @@ public class ExampleGenerator {
}
public List<Map<String, String>> generate(Map<String, Object> examples, List<String> mediaTypes, Property property) {
List<Map<String, String>> output = new ArrayList<Map<String, String>>();
Set<String> processedModels = new HashSet<String>();
List<Map<String, String>> output = new ArrayList<>();
Set<String> processedModels = new HashSet<>();
if (examples == null) {
if (mediaTypes == null) {
// assume application/json for this
mediaTypes = Arrays.asList("application/json"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
mediaTypes = Collections.singletonList(MIME_TYPE_JSON); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
}
for (String mediaType : mediaTypes) {
Map<String, String> kv = new HashMap<String, String>();
kv.put("contentType", mediaType);
if (property != null && mediaType.startsWith("application/json")) {
Map<String, String> kv = new HashMap<>();
kv.put(CONTENT_TYPE, mediaType);
if (property != null && mediaType.startsWith(MIME_TYPE_JSON)) {
String example = Json.pretty(resolvePropertyToExample(mediaType, property, processedModels));
if (example != null) {
kv.put("example", example);
kv.put(EXAMPLE, example);
output.add(kv);
}
} else if (property != null && mediaType.startsWith("application/xml")) {
} else if (property != null && mediaType.startsWith(MIME_TYPE_XML)) {
String example = new XmlExampleGenerator(this.examples).toXml(property);
if (example != null) {
kv.put("example", example);
kv.put(EXAMPLE, example);
output.add(kv);
}
}
}
} else {
for (Map.Entry<String, Object> entry : examples.entrySet()) {
final Map<String, String> kv = new HashMap<String, String>();
kv.put("contentType", entry.getKey());
kv.put("example", Json.pretty(entry.getValue()));
final Map<String, String> kv = new HashMap<>();
kv.put(CONTENT_TYPE, entry.getKey());
kv.put(EXAMPLE, Json.pretty(entry.getValue()));
output.add(kv);
}
}
if (output.size() == 0) {
Map<String, String> kv = new HashMap<String, String>();
kv.put("output", "none");
Map<String, String> kv = new HashMap<>();
kv.put(OUTPUT, NONE);
output.add(kv);
}
return output;
}
protected Object resolvePropertyToExample(String mediaType, Property property, Set<String> processedModels) {
private Object resolvePropertyToExample(String mediaType, Property property, Set<String> processedModels) {
logger.debug("Resolving example for property {}...", property);
if (property.getExample() != null) {
logger.debug("Example set in swagger spec, returning example: '{}'", property.getExample().toString());
return property.getExample();
} else if (property instanceof StringProperty) {
logger.debug("String property");
String defaultValue = ((StringProperty) property).getDefault();
if (defaultValue != null && !defaultValue.isEmpty()) {
logger.debug("Default value found: '{}'", defaultValue);
return defaultValue;
}
List<String> enumValues = ((StringProperty) property).getEnum();
if (enumValues != null && !enumValues.isEmpty()) {
logger.debug("Enum value found: '{}'", enumValues.get(0));
return enumValues.get(0);
}
String format = property.getFormat();
if (format != null && (URI.getName().equals(format) || URL.getName().equals(format))) {
logger.debug("URI or URL format, without default or enum, generating random one.");
return "http://example.com/aeiou";
}
logger.debug("No values found, using default string 'aeiou' as example");
return "aeiou";
} else if (property instanceof BooleanProperty) {
Boolean defaultValue = ((BooleanProperty) property).getDefault();
if (defaultValue != null) {
return defaultValue;
}
return Boolean.TRUE;
} else if (property instanceof ArrayProperty) {
Property innerType = ((ArrayProperty) property).getItems();
@ -97,21 +135,28 @@ public class ExampleGenerator {
return "2000-01-23";
} else if (property instanceof DateTimeProperty) {
return "2000-01-23T04:56:07.000+00:00";
} else if (property instanceof DecimalProperty) {
return new BigDecimal(1.3579);
} else if (property instanceof DoubleProperty) {
return 3.149;
Double min = ((DecimalProperty) property).getMinimum() == null ? null : ((DecimalProperty) property).getMinimum().doubleValue();
Double max = ((DecimalProperty) property).getMaximum() == null ? null : ((DecimalProperty) property).getMaximum().doubleValue();
return randomNumber(min, max);
} else if (property instanceof FloatProperty) {
Double min = ((DecimalProperty) property).getMinimum() == null ? null : ((DecimalProperty) property).getMinimum().doubleValue();
Double max = ((DecimalProperty) property).getMaximum() == null ? null : ((DecimalProperty) property).getMaximum().doubleValue();
return (float) randomNumber(min, max);
} else if (property instanceof DecimalProperty) {
Double min = ((DecimalProperty) property).getMinimum() == null ? null : ((DecimalProperty) property).getMinimum().doubleValue();
Double max = ((DecimalProperty) property).getMaximum() == null ? null : ((DecimalProperty) property).getMaximum().doubleValue();
return new BigDecimal(randomNumber(min, max));
} else if (property instanceof FileProperty) {
return ""; // TODO
} else if (property instanceof FloatProperty) {
return 1.23f;
} else if (property instanceof IntegerProperty) {
return 123;
} else if (property instanceof LongProperty) {
return 123456789L;
// Properties that are not Integer or Long may still be BaseInteger
} else if (property instanceof BaseIntegerProperty) {
return 123;
Double min = ((BaseIntegerProperty) property).getMinimum() == null ? null : ((BaseIntegerProperty) property).getMinimum().doubleValue();
Double max = ((BaseIntegerProperty) property).getMaximum() == null ? null : ((BaseIntegerProperty) property).getMaximum().doubleValue();
return (long) randomNumber(min, max);
} else if (property instanceof BaseIntegerProperty) { // Includes IntegerProperty
Double min = ((BaseIntegerProperty) property).getMinimum() == null ? null : ((BaseIntegerProperty) property).getMinimum().doubleValue();
Double max = ((BaseIntegerProperty) property).getMaximum() == null ? null : ((BaseIntegerProperty) property).getMaximum().doubleValue();
return (int) randomNumber(min, max);
} else if (property instanceof MapProperty) {
Map<String, Object> mp = new HashMap<String, Object>();
if (property.getName() != null) {
@ -126,10 +171,12 @@ public class ExampleGenerator {
return "{}";
} else if (property instanceof RefProperty) {
String simpleName = ((RefProperty) property).getSimpleRef();
logger.debug("Ref property, simple name: {}", simpleName);
Model model = examples.get(simpleName);
if (model != null) {
return resolveModelToExample(simpleName, mediaType, model, processedModels);
}
logger.warn("Ref property with empty model.");
} else if (property instanceof UUIDProperty) {
return "046b6c7f-0b8a-43b9-b35d-6489e6daee91";
}
@ -137,16 +184,35 @@ public class ExampleGenerator {
return "";
}
public Object resolveModelToExample(String name, String mediaType, Model model, Set<String> processedModels) {
private double randomNumber(Double min, Double max) {
if (min != null && max != null) {
double range = max - min;
return Math.random() * range + min;
} else if (min != null) {
return Math.random() + min;
} else if (max != null) {
return Math.random() * max;
} else {
return Math.random() * 10;
}
}
private Object resolveModelToExample(String name, String mediaType, Model model, Set<String> processedModels) {
if (processedModels.contains(name)) {
return "";
}
if (model instanceof ModelImpl) {
processedModels.add(name);
ModelImpl impl = (ModelImpl) model;
Map<String, Object> values = new HashMap<String, Object>();
Map<String, Object> values = new HashMap<>();
if (impl.getProperties() != null) {
logger.debug("Resolving model '{}' to example", name);
if (impl.getExample() != null) {
logger.debug("Using example from spec: {}", impl.getExample());
return impl.getExample();
} else if (impl.getProperties() != null) {
logger.debug("Creating example from model values");
for (String propertyName : impl.getProperties().keySet()) {
Property property = impl.getProperties().get(propertyName);
values.put(propertyName, resolvePropertyToExample(mediaType, property, processedModels));

View File

@ -20,7 +20,7 @@ import io.swagger.models.properties.Property;
import io.swagger.models.properties.RefProperty;
import io.swagger.models.properties.StringProperty;
import org.codehaus.plexus.util.StringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -45,7 +45,7 @@ public class CodegenIgnoreProcessor {
if (directory.exists() && directory.isDirectory()) {
loadFromFile(targetIgnoreFile);
} else {
LOGGER.warn("Directory does not exist, or is inaccessible. No file will be evaluated.");
LOGGER.warn("Output directory does not exist, or is inaccessible. No file (.swager-codegen-ignore) will be evaluated.");
}
}

View File

@ -318,6 +318,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
typeMapping.put("array", "java.util.List");
typeMapping.put("map", "java.util.Map");
typeMapping.put("DateTime", "java.util.Date");
typeMapping.put("UUID", "java.util.UUID");
typeMapping.remove("List");
importMapping.remove("Date");
importMapping.remove("Map");
@ -327,6 +328,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
importMapping.remove("List");
importMapping.remove("Set");
importMapping.remove("DateTime");
importMapping.remove("UUID");
instantiationTypes.put("array", "java.util.ArrayList");
instantiationTypes.put("map", "java.util.HashMap");
}

View File

@ -21,7 +21,7 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
protected String testResourcesFolder = "src/test/resources";
protected String title = "Swagger Server";
protected boolean useBeanValidation = true;
protected boolean useBeanValidation = true;
static Logger LOGGER = LoggerFactory.getLogger(AbstractJavaJAXRSServerCodegen.class);
@ -44,7 +44,7 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
cliOptions.add(new CliOption(CodegenConstants.IMPL_FOLDER, CodegenConstants.IMPL_FOLDER_DESC));
cliOptions.add(new CliOption("title", "a title describing the application"));
cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations"));
cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations"));
}
@ -67,13 +67,13 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
implFolder = (String) additionalProperties.get(CodegenConstants.IMPL_FOLDER);
}
if (additionalProperties.containsKey(USE_BEANVALIDATION)) {
this.setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION));
}
if (additionalProperties.containsKey(USE_BEANVALIDATION)) {
this.setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION));
}
if (useBeanValidation) {
writePropertyBack(USE_BEANVALIDATION, useBeanValidation);
}
if (useBeanValidation) {
writePropertyBack(USE_BEANVALIDATION, useBeanValidation);
}
}
@ -153,6 +153,12 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
if ( "0".equals(resp.code) ) {
resp.code = "200";
}
// set vendorExtensions.x-java-is-response-void to true as dataType is set to "void"
if (resp.dataType == null) {
resp.vendorExtensions.put("x-java-is-response-void", true);
}
}
}
@ -220,8 +226,8 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
return outputFolder + "/" + output + "/" + apiPackage().replace('.', '/');
}
public void setUseBeanValidation(boolean useBeanValidation) {
this.useBeanValidation = useBeanValidation;
}
public void setUseBeanValidation(boolean useBeanValidation) {
this.useBeanValidation = useBeanValidation;
}
}

View File

@ -1,29 +1,31 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.properties.*;
import io.swagger.models.parameters.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Swagger;
import io.swagger.models.parameters.BodyParameter;
import io.swagger.models.parameters.Parameter;
import io.swagger.models.parameters.SerializableParameter;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import java.util.HashMap;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.io.File;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.util.Set;
public class BashClientCodegen extends DefaultCodegen implements CodegenConfig {
@ -194,29 +196,22 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public void processOpts() {
super.processOpts();
String curlopts = "";
if (additionalProperties.containsKey(CURL_OPTIONS)) {
setCurlOptions(additionalProperties.get(CURL_OPTIONS).toString());
additionalProperties.put("x-codegen-curl-options", curlopts);
additionalProperties.put("x-codegen-curl-options", this.curlOptions);
}
if (additionalProperties.containsKey(PROCESS_MARKDOWN)) {
setProcessMarkdown(
Boolean.parseBoolean(
additionalProperties.get(PROCESS_MARKDOWN).toString()));
setProcessMarkdown(convertPropertyToBooleanAndWriteBack(PROCESS_MARKDOWN));
}
if (additionalProperties.containsKey(GENERATE_BASH_COMPLETION)) {
setGenerateBashCompletion(
Boolean.parseBoolean(
additionalProperties.get(GENERATE_BASH_COMPLETION).toString()));
setGenerateBashCompletion(convertPropertyToBooleanAndWriteBack(GENERATE_BASH_COMPLETION));
}
if (additionalProperties.containsKey(GENERATE_ZSH_COMPLETION)) {
setGenerateZshCompletion(
Boolean.parseBoolean(
additionalProperties.get(GENERATE_ZSH_COMPLETION).toString()));
setGenerateZshCompletion(convertPropertyToBooleanAndWriteBack(GENERATE_ZSH_COMPLETION));
}
if (additionalProperties.containsKey(SCRIPT_NAME)) {
@ -578,16 +573,17 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig {
List codesamples = (List)op.vendorExtensions.get("x-code-samples");
for (Object codesample : codesamples) {
ObjectNode codesample_object = (ObjectNode)codesample;
if(codesample instanceof ObjectNode) {
ObjectNode codesample_object = (ObjectNode) codesample;
if((codesample_object.get("lang").asText()).equals("Shell")) {
if ((codesample_object.get("lang").asText()).equals("Shell")) {
op.vendorExtensions.put("x-bash-codegen-sample",
escapeUnsafeCharacters(
codesample_object.get("source").asText()));
}
op.vendorExtensions.put("x-bash-codegen-sample",
escapeUnsafeCharacters(
codesample_object.get("source").asText()));
}
}
}
}

View File

@ -113,6 +113,7 @@ public class CppRestClientCodegen extends DefaultCodegen implements CodegenConfi
typeMapping.put("file", "HttpContent");
typeMapping.put("object", "Object");
typeMapping.put("binary", "std::string");
typeMapping.put("number", "double");
super.importMapping = new HashMap<String, String>();
importMapping.put("std::vector", "#include <vector>");

View File

@ -117,8 +117,7 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
super.processOpts();
if (additionalProperties.containsKey(BROWSER_CLIENT)) {
this.setBrowserClient(Boolean.parseBoolean((String) additionalProperties.get(BROWSER_CLIENT)));
additionalProperties.put(BROWSER_CLIENT, browserClient);
this.setBrowserClient(convertPropertyToBooleanAndWriteBack(BROWSER_CLIENT));
} else {
//not set, use to be passed to template
additionalProperties.put(BROWSER_CLIENT, browserClient);
@ -149,6 +148,14 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER));
}
// default HIDE_GENERATION_TIMESTAMP to true
if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) {
additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString());
} else {
additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP,
Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString()));
}
// make api and model doc path available in mustache template
additionalProperties.put("apiDocPath", apiDocPath);
additionalProperties.put("modelDocPath", modelDocPath);

View File

@ -15,12 +15,12 @@ import java.util.List;
import java.util.Map;
public class FinchServerCodegen extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage = "io.swagger.petstore.client";
protected String invokerPackage = "io.swagger.client";
protected String groupId = "io.swagger";
protected String artifactId = "finch-server";
protected String artifactVersion = "1.0.0";
protected String sourceFolder = "src/main/scala";
protected String packageName = "io.swagger.petstore";
protected String packageName = "io.swagger";
public FinchServerCodegen() {
super();
@ -156,7 +156,7 @@ public class FinchServerCodegen extends DefaultCodegen implements CodegenConfig
importMapping.put("LocalTime", "java.time.LocalTime");
cliOptions.clear();
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Finch package name (e.g. io.swagger.petstore).")
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Finch package name (e.g. io.swagger).")
.defaultValue(this.packageName));
cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC));
cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC));

View File

@ -50,6 +50,7 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
languageSpecificPrimitives.add("datetime");
languageSpecificPrimitives.add("date");
languageSpecificPrimitives.add("file");
languageSpecificPrimitives.add("object");
typeMapping.clear();
typeMapping.put("integer", "int");
@ -413,33 +414,9 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
@Override
public String toModelFilename(String name) {
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// remove dollar sign
name = name.replaceAll("$", "");
// model name cannot use reserved keyword, e.g. return
if (isReservedWord(name)) {
LOGGER.warn(name + " (reserved word) cannot be used as model filename. Renamed to " + underscore(dropDots("model_" + name)));
name = "model_" + name; // e.g. return => ModelReturn (after camelize)
}
// model name starts with number
if (name.matches("^\\d.*")) {
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + underscore("model_" + name));
name = "model_" + name; // e.g. 200Response => Model200Response (after camelize)
}
if (!StringUtils.isEmpty(modelNamePrefix)) {
name = modelNamePrefix + "_" + name;
}
if (!StringUtils.isEmpty(modelNameSuffix)) {
name = name + "_" + modelNameSuffix;
}
// underscore the model file name
// PhoneNumber => phone_number
return underscore(dropDots(name));
return underscore(dropDots(toModelName(name)));
}
@Override

View File

@ -389,7 +389,7 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
// Query parameters appended to routes
for (CodegenParameter param : op.queryParams) {
String paramType = param.dataType;
if(param.isListContainer != null && param.isListContainer) {
if (param.isListContainer) {
paramType = makeQueryListType(paramType, param.collectionFormat);
}
path.add("QueryParam \"" + param.baseName + "\" " + paramType);
@ -420,7 +420,7 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
path.add("Header \"" + param.baseName + "\" " + param.dataType);
String paramType = param.dataType;
if(param.isListContainer != null && param.isListContainer) {
if (param.isListContainer) {
paramType = makeQueryListType(paramType, param.collectionFormat);
}
type.add("Maybe " + paramType);

View File

@ -63,7 +63,6 @@ public class JavaCXFClientCodegen extends AbstractJavaCodegen
typeMapping.put("date", "LocalDate");
typeMapping.put("DateTime", "javax.xml.datatype.XMLGregorianCalendar"); // Map DateTime fields to Java standart class 'XMLGregorianCalendar'
importMapping.put("LocalDate", "org.joda.time.LocalDate");

View File

@ -78,7 +78,6 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen
typeMapping.put("date", "LocalDate");
typeMapping.put("DateTime", "javax.xml.datatype.XMLGregorianCalendar"); // Map DateTime fields to Java standart class 'XMLGregorianCalendar'
importMapping.put("LocalDate", "org.joda.time.LocalDate");

View File

@ -2,6 +2,7 @@ package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.codegen.languages.features.BeanValidationFeatures;
import io.swagger.codegen.languages.features.GzipFeatures;
import io.swagger.codegen.languages.features.PerformBeanValidationFeatures;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
@ -13,13 +14,17 @@ import java.util.*;
import java.util.regex.Pattern;
public class JavaClientCodegen extends AbstractJavaCodegen
implements BeanValidationFeatures, PerformBeanValidationFeatures {
implements BeanValidationFeatures, PerformBeanValidationFeatures,
GzipFeatures
{
static final String MEDIA_TYPE = "mediaType";
@SuppressWarnings("hiding")
@SuppressWarnings("hiding")
private static final Logger LOGGER = LoggerFactory.getLogger(JavaClientCodegen.class);
public static final String USE_RX_JAVA = "useRxJava";
public static final String USE_RX_JAVA2 = "useRxJava2";
public static final String DO_NOT_USE_RX = "doNotUseRx";
public static final String USE_PLAY24_WS = "usePlay24WS";
public static final String PARCELABLE_MODEL = "parcelableModel";
@ -28,10 +33,13 @@ public class JavaClientCodegen extends AbstractJavaCodegen
protected String gradleWrapperPackage = "gradle.wrapper";
protected boolean useRxJava = false;
protected boolean useRxJava2 = false;
protected boolean doNotUseRx = true; // backwards compatibility for swagger configs that specify neither rx1 nor rx2 (mustache does not allow for boolean operators so we need this extra field)
protected boolean usePlay24WS = false;
protected boolean parcelableModel = false;
protected boolean useBeanValidation = false;
protected boolean performBeanValidation = false;
protected boolean useGzipFeature = false;
public JavaClientCodegen() {
super();
@ -43,18 +51,20 @@ public class JavaClientCodegen extends AbstractJavaCodegen
modelPackage = "io.swagger.client.model";
cliOptions.add(CliOption.newBoolean(USE_RX_JAVA, "Whether to use the RxJava adapter with the retrofit2 library."));
cliOptions.add(CliOption.newBoolean(USE_RX_JAVA2, "Whether to use the RxJava2 adapter with the retrofit2 library."));
cliOptions.add(CliOption.newBoolean(PARCELABLE_MODEL, "Whether to generate models for Android that implement Parcelable with the okhttp-gson library."));
cliOptions.add(CliOption.newBoolean(USE_PLAY24_WS, "Use Play! 2.4 Async HTTP client (Play WS API)"));
cliOptions.add(CliOption.newBoolean(SUPPORT_JAVA6, "Whether to support Java6 with the Jersey1 library."));
cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations"));
cliOptions.add(CliOption.newBoolean(PERFORM_BEANVALIDATION, "Perform BeanValidation"));
cliOptions.add(CliOption.newBoolean(USE_GZIP_FEATURE, "Send gzip-encoded requests"));
supportedLibraries.put("jersey1", "HTTP client: Jersey client 1.19.1. JSON processing: Jackson 2.7.0. Enable Java6 support using '-DsupportJava6=true'.");
supportedLibraries.put("jersey1", "HTTP client: Jersey client 1.19.1. JSON processing: Jackson 2.7.0. Enable Java6 support using '-DsupportJava6=true'. Enable gzip request encoding using '-DuseGzipFeature=true'.");
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. Enable Parcelable modles on Android using '-DparcelableModel=true'");
supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.6.2. Enable Parcelable modles on Android using '-DparcelableModel=true'. Enable gzip request encoding using '-DuseGzipFeature=true'.");
supportedLibraries.put(RETROFIT_1, "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.3.1 (Retrofit 1.9.0). IMPORTANT NOTE: retrofit1.x is no longer actively maintained so please upgrade to 'retrofit2' instead.");
supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 3.2.0. JSON processing: Gson 2.6.1 (Retrofit 2.0.2). Enable the RxJava adapter using '-DuseRxJava=true'. (RxJava 1.1.3)");
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[2]=true'. (RxJava 1.x or 2.x)");
CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use");
libraryOption.setEnum(supportedLibraries);
@ -84,9 +94,17 @@ public class JavaClientCodegen extends AbstractJavaCodegen
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey(USE_RX_JAVA)) {
if (additionalProperties.containsKey(USE_RX_JAVA) && additionalProperties.containsKey(USE_RX_JAVA2)) {
LOGGER.warn("You specified both RxJava versions 1 and 2 but they are mutually exclusive. Defaulting to v2.");
} else if (additionalProperties.containsKey(USE_RX_JAVA)) {
this.setUseRxJava(Boolean.valueOf(additionalProperties.get(USE_RX_JAVA).toString()));
}
if (additionalProperties.containsKey(USE_RX_JAVA2)) {
this.setUseRxJava2(Boolean.valueOf(additionalProperties.get(USE_RX_JAVA2).toString()));
}
if (!useRxJava && !useRxJava2) {
additionalProperties.put(DO_NOT_USE_RX, true);
}
if (additionalProperties.containsKey(USE_PLAY24_WS)) {
this.setUsePlay24WS(Boolean.valueOf(additionalProperties.get(USE_PLAY24_WS).toString()));
}
@ -106,6 +124,10 @@ public class JavaClientCodegen extends AbstractJavaCodegen
this.setPerformBeanValidation(convertPropertyToBooleanAndWriteBack(PERFORM_BEANVALIDATION));
}
if (additionalProperties.containsKey(USE_GZIP_FEATURE)) {
this.setUseGzipFeature(convertPropertyToBooleanAndWriteBack(USE_GZIP_FEATURE));
}
final String invokerFolder = (sourceFolder + '/' + invokerPackage).replace(".", "/");
final String authFolder = (sourceFolder + '/' + invokerPackage + ".auth").replace(".", "/");
@ -161,6 +183,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java"));
supportingFiles.add(new SupportingFile("ProgressRequestBody.mustache", invokerFolder, "ProgressRequestBody.java"));
supportingFiles.add(new SupportingFile("ProgressResponseBody.mustache", invokerFolder, "ProgressResponseBody.java"));
supportingFiles.add(new SupportingFile("GzipRequestInterceptor.mustache", invokerFolder, "GzipRequestInterceptor.java"));
additionalProperties.put("gson", "true");
} else if (usesAnyRetrofitLibrary()) {
supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java"));
@ -341,6 +364,16 @@ public class JavaClientCodegen extends AbstractJavaCodegen
public void setUseRxJava(boolean useRxJava) {
this.useRxJava = useRxJava;
doNotUseRx = false;
}
public void setUseRxJava2(boolean useRxJava2) {
this.useRxJava2 = useRxJava2;
doNotUseRx = false;
}
public void setDoNotUseRx(boolean doNotUseRx) {
this.doNotUseRx = doNotUseRx;
}
public void setUsePlay24WS(boolean usePlay24WS) {
@ -360,6 +393,10 @@ public class JavaClientCodegen extends AbstractJavaCodegen
this.performBeanValidation = performBeanValidation;
}
public void setUseGzipFeature(boolean useGzipFeature) {
this.useGzipFeature = useGzipFeature;
}
final private static Pattern JSON_MIME_PATTERN = Pattern.compile("(?i)application\\/json(;.*)?");
final private static Pattern JSON_VENDOR_MIME_PATTERN = Pattern.compile("(?i)application\\/vnd.(.*)+json(;.*)?");

View File

@ -48,7 +48,6 @@ public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen
additionalProperties.put("title", title);
typeMapping.put("date", "LocalDate");
typeMapping.put("DateTime", "javax.xml.datatype.XMLGregorianCalendar"); // Map DateTime fields to Java standart class 'XMLGregorianCalendar'
importMapping.put("LocalDate", "org.joda.time.LocalDate");

View File

@ -0,0 +1,248 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.codegen.languages.features.BeanValidationFeatures;
import java.io.File;
import java.util.List;
import java.util.Map;
public class JavaPlayFrameworkCodegen extends AbstractJavaCodegen implements BeanValidationFeatures {
public static final String TITLE = "title";
public static final String CONFIG_PACKAGE = "configPackage";
public static final String BASE_PACKAGE = "basePackage";
public static final String CONTROLLER_ONLY = "controllerOnly";
public static final String SINGLE_CONTENT_TYPES = "singleContentTypes";
public static final String RESPONSE_WRAPPER = "responseWrapper";
public static final String USE_TAGS = "useTags";
protected String title = "swagger-petstore";
protected String configPackage = "io.swagger.configuration";
protected String basePackage = "io.swagger";
protected boolean controllerOnly = false;
protected boolean singleContentTypes = false;
protected String responseWrapper = "";
protected boolean useTags = false;
protected boolean useBeanValidation = true;
public JavaPlayFrameworkCodegen() {
super();
outputFolder = "generated-code/javaPlayFramework";
apiTestTemplateFiles.clear();
embeddedTemplateDir = templateDir = "JavaPlayFramework";
apiPackage = "controllers";
modelPackage = "apimodels";
invokerPackage = "io.swagger.api";
artifactId = "swagger-java-playframework";
projectFolder = "";
sourceFolder = projectFolder + File.separator + "app";
projectTestFolder = projectFolder + File.separator + "test";
testFolder = projectTestFolder;
additionalProperties.put(CONFIG_PACKAGE, configPackage);
additionalProperties.put(BASE_PACKAGE, basePackage);
additionalProperties.put("jackson", "true");
cliOptions.add(new CliOption(TITLE, "server title name or client service name"));
cliOptions.add(new CliOption(CONFIG_PACKAGE, "configuration package for generated code"));
cliOptions.add(new CliOption(BASE_PACKAGE, "base package for generated code"));
cliOptions.add(CliOption.newBoolean(CONTROLLER_ONLY, "Whether to generate only API interface stubs without the server files."));
cliOptions.add(CliOption.newBoolean(SINGLE_CONTENT_TYPES, "Whether to select only one produces/consumes content-type by operation."));
cliOptions.add(new CliOption(RESPONSE_WRAPPER, "wrap the responses in given type (Future,Callable,CompletableFuture,ListenableFuture,DeferredResult,HystrixCommand,RxObservable,RxSingle or fully qualified type)"));
cliOptions.add(CliOption.newBoolean(USE_TAGS, "use tags for creating interface and controller classnames"));
cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations"));
}
@Override
public CodegenType getTag() {
return CodegenType.SERVER;
}
@Override
public String getName() {
return "java-play-framework";
}
@Override
public String getHelp() {
return "Generates a Java Play Framework Server application.";
}
@Override
public void processOpts() {
super.processOpts();
// clear model and api doc template as this codegen
// does not support auto-generated markdown doc at the moment
//TODO: add doc templates
modelDocTemplateFiles.remove("model_doc.mustache");
apiDocTemplateFiles.remove("api_doc.mustache");
if (additionalProperties.containsKey(TITLE)) {
this.setTitle((String) additionalProperties.get(TITLE));
}
if (additionalProperties.containsKey(CONFIG_PACKAGE)) {
this.setConfigPackage((String) additionalProperties.get(CONFIG_PACKAGE));
}
if (additionalProperties.containsKey(BASE_PACKAGE)) {
this.setBasePackage((String) additionalProperties.get(BASE_PACKAGE));
}
if (additionalProperties.containsKey(CONTROLLER_ONLY)) {
this.setControllerOnly(Boolean.valueOf(additionalProperties.get(CONTROLLER_ONLY).toString()));
}
if (additionalProperties.containsKey(SINGLE_CONTENT_TYPES)) {
this.setSingleContentTypes(Boolean.valueOf(additionalProperties.get(SINGLE_CONTENT_TYPES).toString()));
}
if (additionalProperties.containsKey(RESPONSE_WRAPPER)) {
this.setResponseWrapper((String) additionalProperties.get(RESPONSE_WRAPPER));
}
if (additionalProperties.containsKey(USE_TAGS)) {
this.setUseTags(Boolean.valueOf(additionalProperties.get(USE_TAGS).toString()));
}
if (additionalProperties.containsKey(USE_BEANVALIDATION)) {
this.setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION));
}
if (useBeanValidation) {
writePropertyBack(USE_BEANVALIDATION, useBeanValidation);
}
//Root folder
supportingFiles.add(new SupportingFile("README.mustache", "", "README"));
supportingFiles.add(new SupportingFile("LICENSE.mustache", "", "LICENSE"));
supportingFiles.add(new SupportingFile("build.mustache", "", "build.sbt"));
//Project folder
supportingFiles.add(new SupportingFile("buildproperties.mustache", "project", "build.properties"));
supportingFiles.add(new SupportingFile("plugins.mustache", "project", "plugins.sbt"));
//Conf folder
supportingFiles.add(new SupportingFile("logback.mustache", "conf", "logback.xml"));
supportingFiles.add(new SupportingFile("application.mustache", "conf", "application.conf"));
supportingFiles.add(new SupportingFile("routes.mustache", "conf", "routes"));
//App/Utils folder
supportingFiles.add(new SupportingFile("swaggerUtils.mustache", "app/swagger", "SwaggerUtils.java"));
//App/Controllers
supportingFiles.add(new SupportingFile("apiDocController.mustache", "app/controllers", "ApiDocController.java"));
//We remove the default api.mustache that is used
apiTemplateFiles.remove("api.mustache");
apiTemplateFiles.put("newApiController.mustache", "Controller.java");
if (!this.controllerOnly) {
apiTemplateFiles.put("newApi.mustache", "ControllerImp.java");
}
additionalProperties.put("javaVersion", "1.8");
additionalProperties.put("jdk8", "true");
typeMapping.put("date", "LocalDate");
typeMapping.put("DateTime", "OffsetDateTime");
importMapping.put("LocalDate", "java.time.LocalDate");
importMapping.put("OffsetDateTime", "java.time.OffsetDateTime");
// Some well-known Spring or Spring-Cloud response wrappers
switch (this.responseWrapper) {
case "Future":
case "Callable":
case "CompletableFuture":
additionalProperties.put(RESPONSE_WRAPPER, "java.util.concurrent" + this.responseWrapper);
break;
default:
break;
}
}
public void setTitle(String title) {
this.title = title;
}
public void setConfigPackage(String configPackage) {
this.configPackage = configPackage;
}
public void setBasePackage(String configPackage) {
this.basePackage = configPackage;
}
public void setControllerOnly(boolean controllerOnly) { this.controllerOnly = controllerOnly; }
public void setSingleContentTypes(boolean singleContentTypes) {
this.singleContentTypes = singleContentTypes;
}
public void setResponseWrapper(String responseWrapper) { this.responseWrapper = responseWrapper; }
public void setUseTags(boolean useTags) {
this.useTags = useTags;
}
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
if (operations != null) {
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation operation : ops) {
//This is to fix this bug in the swagger-play project: https://github.com/swagger-api/swagger-play/issues/131
//We need to explicitly add the model package name in front of the dataType because if we don't, the
//implicitParam is not valid and show error when loading the documentation
//This can be removed safely after the bug has been fixed
for (CodegenParameter param : operation.allParams) {
if (!param.isPathParam ) {
if (!param.isPrimitiveType && !param.isListContainer && !param.isMapContainer) {
param.dataTypeForImplicitParam = String.format("%s.%s", modelPackage, param.dataType);
} else {
param.dataTypeForImplicitParam = param.dataType;
}
}
}
if (operation.path.contains("{")) {
operation.path = operation.path.replace("{", ":").replace("}", "");
}
if (operation.returnType != null) {
if (operation.returnType.startsWith("List")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("List<".length(), end).trim();
operation.returnContainer = "List";
}
} else if (operation.returnType.startsWith("Map")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("Map<".length(), end).split(",")[1].trim();
operation.returnContainer = "Map";
}
} else if (operation.returnType.startsWith("Set")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("Set<".length(), end).trim();
operation.returnContainer = "Set";
}
}
}
}
}
return objs;
}
public void setUseBeanValidation(boolean useBeanValidation) {
this.useBeanValidation = useBeanValidation;
}
}

View File

@ -0,0 +1,231 @@
package io.swagger.codegen.languages;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.BooleanUtils;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenResponse;
import io.swagger.codegen.SupportingFile;
import io.swagger.codegen.languages.features.BeanValidationFeatures;
import io.swagger.codegen.languages.features.JbossFeature;
import io.swagger.codegen.languages.features.SwaggerFeatures;
import io.swagger.models.Operation;
public class JavaResteasyEapServerCodegen extends AbstractJavaJAXRSServerCodegen
implements JbossFeature, BeanValidationFeatures, SwaggerFeatures {
protected boolean useBeanValidation = true;
protected boolean generateJbossDeploymentDescriptor = true;
protected boolean useSwaggerFeature = false;
public JavaResteasyEapServerCodegen() {
super();
artifactId = "swagger-jaxrs-resteasy-eap-server";
outputFolder = "generated-code/JavaJaxRS-Resteasy-eap";
apiTemplateFiles.put("apiServiceImpl.mustache", ".java");
apiTestTemplateFiles.clear(); // TODO: add test template
// clear model and api doc template as AbstractJavaJAXRSServerCodegen
// does not support auto-generated markdown doc at the moment
//TODO: add doc templates
modelDocTemplateFiles.remove("model_doc.mustache");
apiDocTemplateFiles.remove("api_doc.mustache");
dateLibrary = "legacy";// TODO: change to joda
embeddedTemplateDir = templateDir = "JavaJaxRS" + File.separator + "resteasy" + File.separator + "eap";
cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations"));
cliOptions.add(CliOption.newBoolean(GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR, "Generate Jboss Deployment Descriptor"));
cliOptions.add(CliOption.newBoolean(USE_SWAGGER_FEATURE, "Use dynamic Swagger generator"));
}
@Override
public String getName() {
return "jaxrs-resteasy-eap";
}
@Override
public String getHelp() {
return "Generates a Java JAXRS-Resteasy Server application.";
}
@Override
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey(GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR)) {
boolean generateJbossDeploymentDescriptorProp = convertPropertyToBooleanAndWriteBack(GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR);
this.setGenerateJbossDeploymentDescriptor(generateJbossDeploymentDescriptorProp);
}
if (additionalProperties.containsKey(USE_BEANVALIDATION)) {
this.setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION));
}
if (useBeanValidation) {
writePropertyBack(USE_BEANVALIDATION, useBeanValidation);
}
if (additionalProperties.containsKey(USE_SWAGGER_FEATURE)) {
this.setUseSwaggerFeature(convertPropertyToBoolean(USE_SWAGGER_FEATURE));
}
if (useSwaggerFeature) {
writePropertyBack(USE_SWAGGER_FEATURE, useSwaggerFeature);
}
writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml"));
writeOptional(outputFolder, new SupportingFile("gradle.mustache", "", "build.gradle"));
writeOptional(outputFolder, new SupportingFile("settingsGradle.mustache", "", "settings.gradle"));
writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md"));
writeOptional(outputFolder, new SupportingFile("web.mustache", ("src/main/webapp/WEB-INF"), "web.xml"));
supportingFiles.add(new SupportingFile("JacksonConfig.mustache", (projectFolder + File.separator + "java" + '/' + invokerPackage).replace(".", "/"), "JacksonConfig.java"));
if (generateJbossDeploymentDescriptor) {
writeOptional(outputFolder, new SupportingFile("jboss-web.mustache", ("src/main/webapp/WEB-INF"), "jboss-web.xml"));
}
writeOptional(outputFolder, new SupportingFile("RestApplication.mustache", (projectFolder + File.separator + "java" + '/' + invokerPackage).replace(".", "/"), "RestApplication.java"));
}
@Override
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
String basePath = resourcePath;
if (basePath.startsWith("/")) {
basePath = basePath.substring(1);
}
int pos = basePath.indexOf("/");
if (pos > 0) {
basePath = basePath.substring(0, pos);
}
if (basePath == "") {
basePath = "default";
} else {
if (co.path.startsWith("/" + basePath)) {
co.path = co.path.substring(("/" + basePath).length());
}
co.subresourceOperation = !co.path.isEmpty();
}
List<CodegenOperation> opList = operations.get(basePath);
if (opList == null) {
opList = new ArrayList<CodegenOperation>();
operations.put(basePath, opList);
}
opList.add(co);
co.baseName = basePath;
}
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
if (operations != null) {
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation operation : ops) {
if (operation.hasConsumes == Boolean.TRUE) {
Map<String, String> firstType = operation.consumes.get(0);
if (firstType != null) {
if ("multipart/form-data".equals(firstType.get("mediaType"))) {
operation.isMultipart = Boolean.TRUE;
}
}
}
List<CodegenResponse> responses = operation.responses;
if (responses != null) {
for (CodegenResponse resp : responses) {
if ("0".equals(resp.code)) {
resp.code = "200";
}
}
}
if (operation.returnType == null) {
operation.returnType = "Void";
} else if (operation.returnType.startsWith("List")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("List<".length(), end).trim();
operation.returnContainer = "List";
}
} else if (operation.returnType.startsWith("Map")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("Map<".length(), end).split(",")[1].trim();
operation.returnContainer = "Map";
}
} else if (operation.returnType.startsWith("Set")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("Set<".length(), end).trim();
operation.returnContainer = "Set";
}
}
}
}
return objs;
}
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
// Add imports for Jackson
if (!BooleanUtils.toBoolean(model.isEnum)) {
model.imports.add("JsonProperty");
if (BooleanUtils.toBoolean(model.hasEnums)) {
model.imports.add("JsonValue");
}
}
}
@Override
public Map<String, Object> postProcessModelsEnum(Map<String, Object> objs) {
objs = super.postProcessModelsEnum(objs);
// Add imports for Jackson
List<Map<String, String>> imports = (List<Map<String, String>>) objs.get("imports");
List<Object> models = (List<Object>) objs.get("models");
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
// for enum model
if (Boolean.TRUE.equals(cm.isEnum) && cm.allowableValues != null) {
cm.imports.add(importMapping.get("JsonValue"));
Map<String, String> item = new HashMap<String, String>();
item.put("import", importMapping.get("JsonValue"));
imports.add(item);
}
}
return objs;
}
public void setUseBeanValidation(boolean useBeanValidation) {
this.useBeanValidation = useBeanValidation;
}
public void setGenerateJbossDeploymentDescriptor(boolean generateJbossDeploymentDescriptor) {
this.generateJbossDeploymentDescriptor = generateJbossDeploymentDescriptor;
}
public void setUseSwaggerFeature(boolean useSwaggerFeature) {
this.useSwaggerFeature = useSwaggerFeature;
}
}

View File

@ -202,7 +202,6 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString()));
}
if (additionalProperties.containsKey(PROJECT_NAME)) {
setProjectName(((String) additionalProperties.get(PROJECT_NAME)));
}
@ -228,19 +227,19 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE));
}
if (additionalProperties.containsKey(USE_PROMISES)) {
setUsePromises(Boolean.parseBoolean((String)additionalProperties.get(USE_PROMISES)));
setUsePromises(convertPropertyToBooleanAndWriteBack(USE_PROMISES));
}
if (additionalProperties.containsKey(USE_INHERITANCE)) {
setUseInheritance(Boolean.parseBoolean((String)additionalProperties.get(USE_INHERITANCE)));
setUseInheritance(convertPropertyToBooleanAndWriteBack(USE_INHERITANCE));
} else {
supportsInheritance = true;
supportsMixins = true;
}
if (additionalProperties.containsKey(EMIT_MODEL_METHODS)) {
setEmitModelMethods(Boolean.parseBoolean((String)additionalProperties.get(EMIT_MODEL_METHODS)));
setEmitModelMethods(convertPropertyToBooleanAndWriteBack(EMIT_MODEL_METHODS));
}
if (additionalProperties.containsKey(EMIT_JS_DOC)) {
setEmitJSDoc(Boolean.parseBoolean((String)additionalProperties.get(EMIT_JS_DOC)));
setEmitJSDoc(convertPropertyToBooleanAndWriteBack(EMIT_JS_DOC));
}
}
@ -710,7 +709,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
CodegenParameter lastRequired = null;
CodegenParameter lastOptional = null;
for (CodegenParameter p : op.allParams) {
if (p.required != null && p.required) {
if (p.required) {
lastRequired = p;
} else {
lastOptional = p;
@ -778,12 +777,6 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
+ (StringUtils.isEmpty(modelPackage) ? "" : (modelPackage + "/")) + dataType;
}
/*
private String getJSDocTypeWithBraces(CodegenModel cm, CodegenProperty cp) {
return "{" + getJSDocType(cm, cp) + "}";
}
*/
private String getJSDocType(CodegenModel cm, CodegenProperty cp) {
if (Boolean.TRUE.equals(cp.isContainer)) {
if (cp.containerType.equals("array"))
@ -805,12 +798,6 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
return cp.isEnum || !languageSpecificPrimitives.contains(cp.baseType == null ? cp.datatype : cp.baseType);
}
/*
private String getJSDocTypeWithBraces(CodegenParameter cp) {
return "{" + getJSDocType(cp) + "}";
}
*/
private String getJSDocType(CodegenParameter cp) {
String dataType = trimBrackets(cp.dataType);
if (isModelledType(cp))
@ -828,13 +815,6 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
return cp.isEnum || !languageSpecificPrimitives.contains(cp.baseType == null ? cp.dataType : cp.baseType);
}
/*
private String getJSDocTypeWithBraces(CodegenOperation co) {
String jsDocType = getJSDocType(co);
return jsDocType == null ? null : "{" + jsDocType + "}";
}
*/
private String getJSDocType(CodegenOperation co) {
String returnType = trimBrackets(co.returnType);
if (returnType != null) {
@ -866,7 +846,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
List<String> argList = new ArrayList<String>();
boolean hasOptionalParams = false;
for (CodegenParameter p : operation.allParams) {
if (p.required != null && p.required) {
if (p.required) {
argList.add(p.paramName);
} else {
hasOptionalParams = true;
@ -950,15 +930,6 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
return !defaultIncludes.contains(type)
&& !languageSpecificPrimitives.contains(type);
}
/*
@Override
public String findCommonPrefixOfVars(List<String> vars) {
String prefix = StringUtils.getCommonPrefix(vars.toArray(new String[vars.size()]));
// exclude trailing characters that should be part of a valid variable
// e.g. ["status-on", "status-off"] => "status-" (not "status-o")
return prefix.replaceAll("[a-zA-Z0-9]+\\z", "");
}
*/
private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) {
// This generator uses inline classes to define enums, which breaks when

View File

@ -17,6 +17,7 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
@ -519,7 +520,10 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
if (p instanceof StringProperty) {
StringProperty dp = (StringProperty) p;
if (dp.getDefault() != null) {
return "'" + dp.getDefault() + "'";
if (Pattern.compile("\r\n|\r|\n").matcher(dp.getDefault()).find())
return "'''" + dp.getDefault() + "'''";
else
return "'" + dp.getDefault() + "'";
}
} else if (p instanceof BooleanProperty) {
BooleanProperty dp = (BooleanProperty) p;

View File

@ -272,7 +272,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
CodegenParameter lastRequired = null;
CodegenParameter lastOptional = null;
for (CodegenParameter p : op.allParams) {
if (p.required != null && p.required) {
if (p.required) {
lastRequired = p;
} else {
lastOptional = p;

View File

@ -3,6 +3,7 @@ package io.swagger.codegen.languages;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
@ -13,6 +14,10 @@ import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
public class SilexServerCodegen extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage;
@ -213,4 +218,28 @@ public class SilexServerCodegen extends DefaultCodegen implements CodegenConfig
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
@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) {
String path = new String(op.path);
String[] items = path.split("/", -1);
String opsPath = "";
int pathParamIndex = 0;
for (int i = 0; i < items.length; ++i) {
if (items[i].matches("^\\{(.*)\\}$")) { // wrap in {}
// camelize path variable
items[i] = "{" + camelize(items[i].substring(1, items[i].length()-1), true) + "}";
}
}
op.path = StringUtils.join(items, "/");
}
return objs;
}
}

View File

@ -23,6 +23,7 @@ public class SpringCodegen extends AbstractJavaCodegen implements BeanValidation
public static final String USE_TAGS = "useTags";
public static final String SPRING_MVC_LIBRARY = "spring-mvc";
public static final String SPRING_CLOUD_LIBRARY = "spring-cloud";
public static final String IMPLICIT_HEADERS = "implicitHeaders";
protected String title = "swagger-petstore";
protected String configPackage = "io.swagger.configuration";
@ -34,7 +35,8 @@ public class SpringCodegen extends AbstractJavaCodegen implements BeanValidation
protected boolean async = false;
protected String responseWrapper = "";
protected boolean useTags = false;
protected boolean useBeanValidation = true;
protected boolean useBeanValidation = true;
protected boolean implicitHeaders = false;
public SpringCodegen() {
super();
@ -63,6 +65,7 @@ public class SpringCodegen extends AbstractJavaCodegen implements BeanValidation
cliOptions.add(new CliOption(RESPONSE_WRAPPER, "wrap the responses in given type (Future,Callable,CompletableFuture,ListenableFuture,DeferredResult,HystrixCommand,RxObservable,RxSingle or fully qualified type)"));
cliOptions.add(CliOption.newBoolean(USE_TAGS, "use tags for creating interface and controller classnames"));
cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations"));
cliOptions.add(CliOption.newBoolean(IMPLICIT_HEADERS, "Use of @ApiImplicitParams for headers."));
supportedLibraries.put(DEFAULT_LIBRARY, "Spring-boot Server application using the SpringFox integration.");
supportedLibraries.put(SPRING_MVC_LIBRARY, "Spring-MVC Server application using the SpringFox integration.");
@ -162,6 +165,11 @@ public class SpringCodegen extends AbstractJavaCodegen implements BeanValidation
writePropertyBack(USE_BEANVALIDATION, useBeanValidation);
}
if (additionalProperties.containsKey(IMPLICIT_HEADERS)) {
this.setImplicitHeaders(Boolean.valueOf(additionalProperties.get(IMPLICIT_HEADERS).toString()));
}
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
@ -410,12 +418,36 @@ public class SpringCodegen extends AbstractJavaCodegen implements BeanValidation
operation.returnContainer = "Set";
}
}
if(implicitHeaders){
removeHeadersFromAllParams(operation.allParams);
}
}
}
return objs;
}
/**
* This method removes header parameters from the list of parameters and also
* corrects last allParams hasMore state.
* @param allParams list of all parameters
*/
private void removeHeadersFromAllParams(List<CodegenParameter> allParams) {
if(allParams.isEmpty()){
return;
}
final ArrayList<CodegenParameter> copy = new ArrayList<>(allParams);
allParams.clear();
for(CodegenParameter p : copy){
if(!p.isHeaderParam){
allParams.add(p);
}
}
allParams.get(allParams.size()-1).hasMore =false;
}
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
if(library.equals(SPRING_CLOUD_LIBRARY)) {
@ -468,6 +500,10 @@ public class SpringCodegen extends AbstractJavaCodegen implements BeanValidation
this.useTags = useTags;
}
public void setImplicitHeaders(boolean implicitHeaders) {
this.implicitHeaders = implicitHeaders;
}
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
super.postProcessModelProperty(model, property);

View File

@ -1,15 +1,24 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
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.CodegenResponse;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Info;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Swagger;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.Info;
import org.apache.commons.lang3.StringUtils;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@ -113,6 +122,11 @@ public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfi
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation op : operationList) {
op.httpMethod = op.httpMethod.toLowerCase();
for (CodegenResponse response : op.responses){
if ("0".equals(response.code)){
response.code = "default";
}
}
}
return objs;
}
@ -158,7 +172,7 @@ public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfi
CodegenParameter lastRequired = null;
CodegenParameter lastOptional = null;
for (CodegenParameter p : op.allParams) {
if (p.required != null && p.required) {
if (p.required) {
lastRequired = p;
} else {
lastOptional = p;

View File

@ -4,6 +4,7 @@ import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenResponse;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
@ -96,12 +97,17 @@ public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig
return super.getTypeDeclaration(p);
}
@Override
@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.httpMethod = op.httpMethod.toLowerCase();
for (CodegenResponse response : op.responses) {
if ("0".equals(response.code)) {
response.code = "default";
}
}
}
return objs;
}

View File

@ -52,4 +52,16 @@ public class SwaggerGenerator extends DefaultCodegen implements CodegenConfig {
LOGGER.error(e.getMessage(), e);
}
}
@Override
public String escapeQuotationMark(String input) {
// just return the original string
return input;
}
@Override
public String escapeUnsafeCharacters(String input) {
// just return the original string
return input;
}
}

View File

@ -61,4 +61,17 @@ public class SwaggerYamlGenerator extends DefaultCodegen implements CodegenConfi
LOGGER.error(e.getMessage(), e);
}
}
@Override
public String escapeQuotationMark(String input) {
// just return the original string
return input;
}
@Override
public String escapeUnsafeCharacters(String input) {
// just return the original string
return input;
}
}

View File

@ -184,7 +184,7 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig {
// Setup unwrapRequired option, which makes all the properties with "required" non-optional
if (additionalProperties.containsKey(UNWRAP_REQUIRED)) {
setUnwrapRequired(Boolean.parseBoolean(String.valueOf(additionalProperties.get(UNWRAP_REQUIRED))));
setUnwrapRequired(convertPropertyToBooleanAndWriteBack(UNWRAP_REQUIRED));
}
additionalProperties.put(UNWRAP_REQUIRED, unwrapRequired);
@ -207,9 +207,8 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig {
// Setup swiftUseApiNamespace option, which makes all the API classes inner-class of {{projectName}}API
if (additionalProperties.containsKey(SWIFT_USE_API_NAMESPACE)) {
swiftUseApiNamespace = Boolean.parseBoolean(String.valueOf(additionalProperties.get(SWIFT_USE_API_NAMESPACE)));
setSwiftUseApiNamespace(convertPropertyToBooleanAndWriteBack(SWIFT_USE_API_NAMESPACE));
}
additionalProperties.put(SWIFT_USE_API_NAMESPACE, swiftUseApiNamespace);
if (!additionalProperties.containsKey(POD_AUTHORS)) {
additionalProperties.put(POD_AUTHORS, DEFAULT_POD_AUTHORS);
@ -496,6 +495,10 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig {
this.responseAs = responseAs;
}
public void setSwiftUseApiNamespace(boolean swiftUseApiNamespace) {
this.swiftUseApiNamespace = swiftUseApiNamespace;
}
@Override
public String toEnumValue(String value, String datatype) {
return String.valueOf(value);

View File

@ -184,9 +184,8 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
// Setup unwrapRequired option, which makes all the properties with "required" non-optional
if (additionalProperties.containsKey(UNWRAP_REQUIRED)) {
setUnwrapRequired(Boolean.parseBoolean(String.valueOf(additionalProperties.get(UNWRAP_REQUIRED))));
setUnwrapRequired(convertPropertyToBooleanAndWriteBack(UNWRAP_REQUIRED));
}
additionalProperties.put(UNWRAP_REQUIRED, unwrapRequired);
// Setup unwrapRequired option, which makes all the properties with "required" non-optional
if (additionalProperties.containsKey(RESPONSE_AS)) {
@ -207,9 +206,8 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
// Setup swiftUseApiNamespace option, which makes all the API classes inner-class of {{projectName}}API
if (additionalProperties.containsKey(SWIFT_USE_API_NAMESPACE)) {
swiftUseApiNamespace = Boolean.parseBoolean(String.valueOf(additionalProperties.get(SWIFT_USE_API_NAMESPACE)));
setSwiftUseApiNamespace(convertPropertyToBooleanAndWriteBack(SWIFT_USE_API_NAMESPACE));
}
additionalProperties.put(SWIFT_USE_API_NAMESPACE, swiftUseApiNamespace);
if (!additionalProperties.containsKey(POD_AUTHORS)) {
additionalProperties.put(POD_AUTHORS, DEFAULT_POD_AUTHORS);
@ -531,6 +529,10 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
this.responseAs = responseAs;
}
public void setSwiftUseApiNamespace(boolean swiftUseApiNamespace) {
this.swiftUseApiNamespace = swiftUseApiNamespace;
}
@Override
public String toEnumValue(String value, String datatype) {
if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) {

View File

@ -5,8 +5,7 @@ package io.swagger.codegen.languages.features;
*
*/
public interface CXFServerFeatures
extends CXFFeatures, SwaggerFeatures, SpringFeatures, JbossFeature, BeanValidationExtendedFeatures,
SwaggerUIFeatures
extends CXFFeatures, SwaggerFeatures, SpringFeatures, JbossFeature, BeanValidationExtendedFeatures, SwaggerUIFeatures
{
public static final String USE_WADL_FEATURE = "useWadlFeature";

View File

@ -1,6 +1,6 @@
package io.swagger.codegen.languages.features;
public interface SwaggerFeatures extends CXFFeatures {
public interface SwaggerFeatures {
public static final String USE_SWAGGER_FEATURE = "useSwaggerFeature";

View File

@ -18,7 +18,7 @@ class {{classname}} {
{{#operation}}
def {{operationId}} ({{#allParams}} {{{dataType}}} {{paramName}},{{/allParams}} Closure onSuccess, Closure onFailure) {
// create path and map variables
// create path and map path parameters (TODO)
String resourcePath = "{{path}}"
// query params
@ -35,13 +35,15 @@ class {{classname}} {
{{/allParams}}
{{#queryParams}}if (!"null".equals(String.valueOf({{paramName}})))
queryParams.put("{{paramName}}", String.valueOf({{paramName}}))
queryParams.put("{{baseName}}", String.valueOf({{paramName}}))
{{/queryParams}}
{{#headerParams}}
headerParams.put("{{paramName}}", {{paramName}})
headerParams.put("{{baseName}}", {{paramName}})
{{/headerParams}}
// Also still TODO: form params, body param
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"{{httpMethod}}", "{{returnContainer}}",
{{#returnBaseType}}{{{returnBaseType}}}.class {{/returnBaseType}}{{^returnBaseType}}null {{/returnBaseType}})

View File

@ -22,6 +22,7 @@ import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.client.filter.GZIPContentEncodingFilter;
import com.sun.jersey.api.client.filter.LoggingFilter;
import com.sun.jersey.api.client.WebResource.Builder;
@ -124,6 +125,7 @@ public class ApiClient {
DefaultClientConfig conf = new DefaultClientConfig();
conf.getSingletons().add(jsonProvider);
Client client = Client.create(conf);
client.addFilter(new GZIPContentEncodingFilter({{#useGzipFeature}}true{{/useGzipFeature}}{{^useGzipFeature}}false{{/useGzipFeature}}));
if (debugging) {
client.addFilter(new LoggingFilter());
}

View File

@ -130,7 +130,7 @@ Class | Method | HTTP request | Description
{{/isBasic}}
{{#isOAuth}}- **Type**: OAuth
- **Flow**: {{flow}}
- **Authorizatoin URL**: {{authorizationUrl}}
- **Authorization URL**: {{authorizationUrl}}
- **Scopes**: {{^scopes}}N/A{{/scopes}}
{{#scopes}} - {{scope}}: {{description}}
{{/scopes}}

View File

@ -62,7 +62,7 @@ public class {{classname}} {
}
{{/required}}{{/allParams}}
// create path and map variables
String {{localVariablePrefix}}localVarPath = "{{{path}}}".replaceAll("\\{format\\}","json"){{#pathParams}}
String {{localVariablePrefix}}localVarPath = "{{{path}}}"{{#pathParams}}
.replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}};
// query params

View File

@ -1,53 +1,4 @@
{{#required}}
@NotNull
{{/required}}
{{#pattern}}
@Pattern(regexp="{{pattern}}")
{{/pattern}}
{{#minLength}}
{{#maxLength}}
@Size(min={{minLength}},max={{maxLength}})
{{/maxLength}}
{{/minLength}}
{{#minLength}}
{{^maxLength}}
@Size(min={{minLength}})
{{/maxLength}}
{{/minLength}}
{{^minLength}}
{{#maxLength}}
@Size(max={{maxLength}})
{{/maxLength}}
{{/minLength}}
{{#minItems}}
{{#maxItems}}
@Size(min={{minItems}},max={{maxItems}})
{{/maxItems}}
{{/minItems}}
{{#minItems}}
{{^maxItems}}
@Size(min={{minItems}})
{{/maxItems}}
{{/minItems}}
{{^minItems}}
{{#maxItems}}
@Size(max={{maxItems}})
{{/maxItems}}
{{/minItems}}
{{! check for integer / number=decimal type}}
{{#isInteger}}
{{#minimum}}
@Min({{minimum}})
{{/minimum}}
{{#maximum}}
@Max({{maximum}})
{{/maximum}}
{{/isInteger}}
{{^isInteger}}
{{#minimum}}
@DecimalMin("{{minimum}}")
{{/minimum}}
{{#maximum}}
@DecimalMax("{{maximum}}")
{{/maximum}}
{{/isInteger}}
{{>beanValidationCore}}

View File

@ -0,0 +1,20 @@
{{#pattern}} @Pattern(regexp="{{pattern}}"){{/pattern}}{{!
minLength && maxLength set
}}{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{!
minLength set, maxLength not
}}{{#minLength}}{{^maxLength}} @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{!
minLength not set, maxLength set
}}{{^minLength}}{{#maxLength}} @Size(max={{maxLength}}){{/maxLength}}{{/minLength}}{{!
@Size: minItems && maxItems set
}}{{#minItems}}{{#maxItems}} @Size(min={{minItems}},max={{maxItems}}){{/maxItems}}{{/minItems}}{{!
@Size: minItems set, maxItems not
}}{{#minItems}}{{^maxItems}} @Size(min={{minItems}}){{/maxItems}}{{/minItems}}{{!
@Size: minItems not set && maxItems set
}}{{^minItems}}{{#maxItems}} @Size(max={{maxItems}}){{/maxItems}}{{/minItems}}{{!
check for integer or long / all others=decimal type with @Decimal*
isInteger set
}}{{#isInteger}}{{#minimum}} @Min({{minimum}}){{/minimum}}{{#maximum}} @Max({{maximum}}){{/maximum}}{{/isInteger}}{{!
isLong set
}}{{#isLong}}{{#minimum}} @Min({{minimum}}){{/minimum}}{{#maximum}} @Max({{maximum}}){{/maximum}}{{/isLong}}{{!
Not Integer, not Long => we have a decimal value!
}}{{^isInteger}}{{^isLong}}{{#minimum}} @DecimalMin("{{minimum}}"){{/minimum}}{{#maximum}} @DecimalMax("{{maximum}}"){{/maximum}}{{/isLong}}{{/isInteger}}

View File

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

View File

@ -51,17 +51,27 @@ public class ApiClient {
public ApiClient(String[] authNames) {
this();
for(String authName : authNames) { {{#hasAuthMethods}}
for(String authName : authNames) {
{{#hasAuthMethods}}
RequestInterceptor auth;
{{#authMethods}}if ("{{name}}".equals(authName)) { {{#isBasic}}
auth = new HttpBasicAuth();{{/isBasic}}{{#isApiKey}}
auth = new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}");{{/isApiKey}}{{#isOAuth}}
auth = new OAuth(OAuthFlow.{{flow}}, "{{authorizationUrl}}", "{{tokenUrl}}", "{{#scopes}}{{scope}}{{#hasMore}}, {{/hasMore}}{{/scopes}}");{{/isOAuth}}
{{#authMethods}}if ("{{name}}".equals(authName)) {
{{#isBasic}}
auth = new HttpBasicAuth();
{{/isBasic}}
{{#isApiKey}}
auth = new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}");
{{/isApiKey}}
{{#isOAuth}}
auth = new OAuth(OAuthFlow.{{flow}}, "{{authorizationUrl}}", "{{tokenUrl}}", "{{#scopes}}{{scope}}{{#hasMore}}, {{/hasMore}}{{/scopes}}");
{{/isOAuth}}
} else {{/authMethods}}{
throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names");
}
addAuthorization(authName, auth);{{/hasAuthMethods}}{{^hasAuthMethods}}
throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names");{{/hasAuthMethods}}
addAuthorization(authName, auth);
{{/hasAuthMethods}}
{{^hasAuthMethods}}
throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names");
{{/hasAuthMethods}}
}
}

View File

@ -251,7 +251,7 @@
<java.version>{{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}}</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<swagger-core-version>1.5.9</swagger-core-version>
<swagger-core-version>1.5.12</swagger-core-version>
<feign-version>8.17.0</feign-version>
<feign-form-version>2.0.2</feign-form-version>
<jackson-version>2.7.5</jackson-version>

View File

@ -59,7 +59,7 @@ public class {{classname}} {
}
{{/required}}{{/allParams}}
// create path and map variables
String {{localVariablePrefix}}localVarPath = "{{{path}}}".replaceAll("\\{format\\}","json"){{#pathParams}}
String {{localVariablePrefix}}localVarPath = "{{{path}}}"{{#pathParams}}
.replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}};
// query params

View File

@ -273,7 +273,7 @@
</dependency>
</dependencies>
<properties>
<swagger-core-version>1.5.9</swagger-core-version>
<swagger-core-version>1.5.12</swagger-core-version>
<jersey-version>2.22.2</jersey-version>
{{#supportJava6}}
<commons_io_version>2.5</commons_io_version>

View File

@ -80,7 +80,17 @@ public class ApiClient {
{{/useGzipFeature}}
verifyingSsl = true;
json = new JSON();
json = new JSON(this);
/*
* Use RFC3339 format for date and datetime.
* See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14
*/
this.dateFormat = new SimpleDateFormat("yyyy-MM-dd");
// Always use UTC as the default time zone when dealing with date (without time).
this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
initDatetimeFormat();
// Set default User-Agent.
setUserAgent("{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{artifactVersion}}}/java{{/httpUserAgent}}");

View File

@ -0,0 +1,70 @@
{{>licenseInfo}}
package {{invokerPackage}};
import com.squareup.okhttp.*;
import okio.Buffer;
import okio.BufferedSink;
import okio.GzipSink;
import okio.Okio;
import java.io.IOException;
/**
* Encodes request bodies using gzip.
*
* Taken from https://github.com/square/okhttp/issues/350
*/
class GzipRequestInterceptor implements Interceptor {
@Override public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
return chain.proceed(originalRequest);
}
Request compressedRequest = originalRequest.newBuilder()
.header("Content-Encoding", "gzip")
.method(originalRequest.method(), forceContentLength(gzip(originalRequest.body())))
.build();
return chain.proceed(compressedRequest);
}
private RequestBody forceContentLength(final RequestBody requestBody) throws IOException {
final Buffer buffer = new Buffer();
requestBody.writeTo(buffer);
return new RequestBody() {
@Override
public MediaType contentType() {
return requestBody.contentType();
}
@Override
public long contentLength() {
return buffer.size();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
sink.write(buffer.snapshot());
}
};
}
private RequestBody gzip(final RequestBody body) {
return new RequestBody() {
@Override public MediaType contentType() {
return body.contentType();
}
@Override public long contentLength() {
return -1; // We don't know the compressed length in advance!
}
@Override public void writeTo(BufferedSink sink) throws IOException {
BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
body.writeTo(gzipSink);
gzipSink.close();
}
};
}
}

View File

@ -63,13 +63,20 @@ public class {{classname}} {
}
{{#operation}}
/* Build call for {{operationId}} */
private com.squareup.okhttp.Call {{operationId}}Call({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
/**
* Build call for {{operationId}}{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call {{operationId}}Call({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object {{localVariablePrefix}}localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
// create path and map variables
String {{localVariablePrefix}}localVarPath = "{{{path}}}".replaceAll("\\{format\\}","json"){{#pathParams}}
.replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}};
String {{localVariablePrefix}}localVarPath = "{{{path}}}"{{#pathParams}}
.replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}};
{{javaUtilPrefix}}List<Pair> {{localVariablePrefix}}localVarQueryParams = new {{javaUtilPrefix}}ArrayList<Pair>();{{#queryParams}}
if ({{paramName}} != null)

View File

@ -237,7 +237,7 @@
<java.version>{{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}}</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<swagger-core-version>1.5.9</swagger-core-version>
<swagger-core-version>1.5.12</swagger-core-version>
<okhttp-version>2.7.5</okhttp-version>
<gson-version>2.6.2</gson-version>
{{#joda}}

View File

@ -52,17 +52,26 @@ public class ApiClient {
public ApiClient(String[] authNames) {
this();
for(String authName : authNames) { {{#hasAuthMethods}}
for(String authName : authNames) {
{{#hasAuthMethods}}
Interceptor auth;
{{#authMethods}}if ("{{name}}".equals(authName)) { {{#isBasic}}
auth = new HttpBasicAuth();{{/isBasic}}{{#isApiKey}}
auth = new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}");{{/isApiKey}}{{#isOAuth}}
auth = new OAuth(OAuthFlow.{{flow}}, "{{authorizationUrl}}", "{{tokenUrl}}", "{{#scopes}}{{scope}}{{#hasMore}}, {{/hasMore}}{{/scopes}}");{{/isOAuth}}
{{#authMethods}}if ("{{name}}".equals(authName)) {
{{#isBasic}}
auth = new HttpBasicAuth();
{{/isBasic}}
{{#isApiKey}}
auth = new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}");{{/isApiKey}}
{{#isOAuth}}
auth = new OAuth(OAuthFlow.{{flow}}, "{{authorizationUrl}}", "{{tokenUrl}}", "{{#scopes}}{{scope}}{{#hasMore}}, {{/hasMore}}{{/scopes}}");
{{/isOAuth}}
} else {{/authMethods}}{
throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names");
}
addAuthorization(authName, auth);{{/hasAuthMethods}}{{^hasAuthMethods}}
throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names");{{/hasAuthMethods}}
addAuthorization(authName, auth);
{{/hasAuthMethods}}
{{^hasAuthMethods}}
throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names");
{{/hasAuthMethods}}
}
}

View File

@ -212,7 +212,7 @@
</dependency>
</dependencies>
<properties>
<swagger-core-version>1.5.9</swagger-core-version>
<swagger-core-version>1.5.12</swagger-core-version>
<retrofit-version>1.9.0</retrofit-version>
<okhttp-version>2.7.5</okhttp-version>
<jodatime-version>2.9.3</jodatime-version>

View File

@ -19,6 +19,9 @@ import retrofit2.Retrofit;
{{#useRxJava}}
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
{{/useRxJava}}
{{#useRxJava2}}
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
{{/useRxJava2}}
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import {{invokerPackage}}.auth.HttpBasicAuth;
@ -134,7 +137,9 @@ public class ApiClient {
.baseUrl(baseUrl)
{{#useRxJava}}
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
{{/useRxJava}}
{{/useRxJava}}{{#useRxJava2}}
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
{{/useRxJava2}}
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonCustomConverterFactory.create(json.getGson()));
}

View File

@ -3,7 +3,8 @@ package {{package}};
import {{invokerPackage}}.CollectionFormats.*;
{{#useRxJava}}import rx.Observable;{{/useRxJava}}
{{^useRxJava}}import retrofit2.Call;{{/useRxJava}}
{{#useRxJava2}}import io.reactivex.Observable;{{/useRxJava2}}
{{#doNotUseRx}}import retrofit2.Call;{{/doNotUseRx}}
import retrofit2.http.*;
import okhttp3.RequestBody;
@ -46,7 +47,7 @@ public interface {{classname}} {
{{/prioritizedContentTypes}}
{{/formParams}}
@{{httpMethod}}("{{path}}")
{{^usePlay24WS}}{{#useRxJava}}Observable{{/useRxJava}}{{^useRxJava}}Call{{/useRxJava}}{{/usePlay24WS}}{{#usePlay24WS}}F.Promise<Response{{/usePlay24WS}}<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}>{{#usePlay24WS}}>{{/usePlay24WS}} {{operationId}}({{^allParams}});{{/allParams}}
{{^usePlay24WS}}{{^doNotUseRx}}Observable{{/doNotUseRx}}{{#doNotUseRx}}Call{{/doNotUseRx}}{{/usePlay24WS}}{{#usePlay24WS}}F.Promise<Response{{/usePlay24WS}}<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}>{{#usePlay24WS}}>{{/usePlay24WS}} {{operationId}}({{^allParams}});{{/allParams}}
{{#allParams}}{{>libraries/retrofit2/queryParams}}{{>libraries/retrofit2/pathParams}}{{>libraries/retrofit2/headerParams}}{{>libraries/retrofit2/bodyParams}}{{>libraries/retrofit2/formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}}
);{{/hasMore}}{{/allParams}}

View File

@ -101,6 +101,9 @@ ext {
{{#useRxJava}}
rx_java_version = "1.1.3"
{{/useRxJava}}
{{#useRxJava2}}
rx_java_version = "2.0.5"
{{/useRxJava2}}
{{#joda}}
jodatime_version = "2.9.3"
{{/joda}}
@ -117,6 +120,10 @@ dependencies {
compile "com.squareup.retrofit2:adapter-rxjava:$retrofit_version"
compile "io.reactivex:rxjava:$rx_java_version"
{{/useRxJava}}
{{#useRxJava2}}
compile "com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0"
compile "io.reactivex.rxjava2:rxjava:$rx_java_version"
{{/useRxJava2}}
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version"
{{#joda}}

View File

@ -16,6 +16,10 @@ lazy val root = (project in file(".")).
"com.squareup.retrofit2" % "adapter-rxjava" % "2.0.2" % "compile",
"io.reactivex" % "rxjava" % "1.1.3" % "compile",
{{/useRxJava}}
{{#useRxJava2}}
"com.jakewharton.retrofit" % "retrofit2-rxjava2-adapter" % "1.0.0" % "compile",
"io.reactivex.rxjava2" % "rxjava" % "2.0.5" % "compile",
{{/useRxJava2}}
"io.swagger" % "swagger-annotations" % "1.5.8" % "compile",
"org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile",
{{#joda}}

View File

@ -220,6 +220,18 @@
<version>${retrofit-version}</version>
</dependency>
{{/useRxJava}}
{{#useRxJava2}}
<dependency>
<groupId>io.reactivex.rxjava2</groupId>
<artifactId>rxjava</artifactId>
<version>${rxjava-version}</version>
</dependency>
<dependency>
<groupId>com.jakewharton.retrofit</groupId>
<artifactId>retrofit2-rxjava2-adapter</artifactId>
<version>1.0.0</version>
</dependency>
{{/useRxJava2}}
{{#usePlay24WS}}
<!-- JSON processing: jackson -->
@ -268,7 +280,7 @@
<java.version>{{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}}</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<swagger-core-version>1.5.9</swagger-core-version>
<swagger-core-version>1.5.12</swagger-core-version>
<retrofit-version>2.1.0</retrofit-version>
{{#usePlay24WS}}
<jackson-version>2.7.5</jackson-version>
@ -276,6 +288,9 @@
{{#useRxJava}}
<rxjava-version>1.1.6</rxjava-version>
{{/useRxJava}}
{{#useRxJava2}}
<rxjava-version>2.0.5</rxjava-version>
{{/useRxJava2}}
{{#joda}}
<jodatime-version>2.9.3</jodatime-version>
{{/joda}}

View File

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

View File

@ -47,7 +47,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali
{{/vars}}
@Override
public boolean equals(Object o) {
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
@ -79,7 +79,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}

View File

@ -119,7 +119,7 @@
</repositories>
<properties>
<maven-plugin-version>1.0.0</maven-plugin-version>
<swagger-inflector-version>1.0.8</swagger-inflector-version>
<swagger-inflector-version>1.0.11</swagger-inflector-version>
<jetty-version>9.2.9.v20150224</jetty-version>
<logback-version>1.0.1</logback-version>
<junit-version>4.8.2</junit-version>

View File

@ -1,53 +1,4 @@
{{#required}}
@NotNull
{{/required}}
{{#pattern}}
@Pattern(regexp="{{pattern}}")
{{/pattern}}
{{#minLength}}
{{#maxLength}}
@Size(min={{minLength}},max={{maxLength}})
{{/maxLength}}
{{/minLength}}
{{#minLength}}
{{^maxLength}}
@Size(min={{minLength}})
{{/maxLength}}
{{/minLength}}
{{^minLength}}
{{#maxLength}}
@Size(max={{maxLength}})
{{/maxLength}}
{{/minLength}}
{{#minItems}}
{{#maxItems}}
@Size(min={{minItems}},max={{maxItems}})
{{/maxItems}}
{{/minItems}}
{{#minItems}}
{{^maxItems}}
@Size(min={{minItems}})
{{/maxItems}}
{{/minItems}}
{{^minItems}}
{{#maxItems}}
@Size(max={{maxItems}})
{{/maxItems}}
{{/minItems}}
{{! check for integer / number=decimal type}}
{{#isInteger}}
{{#minimum}}
@Min({{minimum}})
{{/minimum}}
{{#maximum}}
@Max({{maximum}})
{{/maximum}}
{{/isInteger}}
{{^isInteger}}
{{#minimum}}
@DecimalMin("{{minimum}}")
{{/minimum}}
{{#maximum}}
@DecimalMax("{{maximum}}")
{{/maximum}}
{{/isInteger}}
{{>beanValidationCore}}

View File

@ -0,0 +1,20 @@
{{#pattern}} @Pattern(regexp="{{pattern}}"){{/pattern}}{{!
minLength && maxLength set
}}{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{!
minLength set, maxLength not
}}{{#minLength}}{{^maxLength}} @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{!
minLength not set, maxLength set
}}{{^minLength}}{{#maxLength}} @Size(max={{maxLength}}){{/maxLength}}{{/minLength}}{{!
@Size: minItems && maxItems set
}}{{#minItems}}{{#maxItems}} @Size(min={{minItems}},max={{maxItems}}){{/maxItems}}{{/minItems}}{{!
@Size: minItems set, maxItems not
}}{{#minItems}}{{^maxItems}} @Size(min={{minItems}}){{/maxItems}}{{/minItems}}{{!
@Size: minItems not set && maxItems set
}}{{^minItems}}{{#maxItems}} @Size(max={{maxItems}}){{/maxItems}}{{/minItems}}{{!
check for integer or long / all others=decimal type with @Decimal*
isInteger set
}}{{#isInteger}}{{#minimum}} @Min({{minimum}}){{/minimum}}{{#maximum}} @Max({{maximum}}){{/maximum}}{{/isInteger}}{{!
isLong set
}}{{#isLong}}{{#minimum}} @Min({{minimum}}){{/minimum}}{{#maximum}} @Max({{maximum}}){{/maximum}}{{/isLong}}{{!
Not Integer, not Long => we have a decimal value!
}}{{^isInteger}}{{^isLong}}{{#minimum}} @DecimalMin("{{minimum}}"){{/minimum}}{{#maximum}} @DecimalMax("{{maximum}}"){{/maximum}}{{/isLong}}{{/isInteger}}

View File

@ -1 +1 @@
{{! PathParam is always required, no @NotNull necessary }}{{#pattern}} @Pattern(regexp="{{pattern}}"){{/pattern}}{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} @Size(max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minItems}}{{#maxItems}} @Size(min={{minItems}},max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minItems}}{{^maxItems}} @Size(min={{minItems}}){{/maxItems}}{{/minItems}}{{^minItems}}{{#maxItems}} @Size(max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minimum}} @Min({{minimum}}){{/minimum}}{{#maximum}} @Max({{maximum}}){{/maximum}}
{{! PathParam is always required, no @NotNull necessary }}{{>beanValidationCore}}

View File

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

View File

@ -1 +1 @@
{{#isFormParam}}{{#notFile}}@Multipart(value = "{{paramName}}"{{^required}}, required = false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}} @Multipart(value = "{{paramName}}"{{^required}}, required = false{{/required}}) InputStream {{paramName}}InputStream, @Multipart(value = "{{paramName}}" {{^required}}, required = false{{/required}}) Attachment {{paramName}}Detail{{/isFile}}{{/isFormParam}}
{{#isFormParam}}{{#notFile}}@Multipart(value = "{{baseName}}"{{^required}}, required = false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}} @Multipart(value = "{{baseName}}"{{^required}}, required = false{{/required}}) InputStream {{paramName}}InputStream, @Multipart(value = "{{baseName}}" {{^required}}, required = false{{/required}}) Attachment {{paramName}}Detail{{/isFile}}{{/isFormParam}}

View File

@ -37,7 +37,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali
{{/vars}}
@Override
public boolean equals(Object o) {
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
@ -69,7 +69,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}

View File

@ -14,6 +14,8 @@ import org.apache.cxf.jaxrs.ext.multipart.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.ApiResponse;
import io.swagger.jaxrs.PATCH;
{{#useBeanValidation}}
import javax.validation.constraints.*;
@ -38,6 +40,8 @@ public interface {{classname}} {
@Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} })
{{/hasProduces}}
@ApiOperation(value = "{{{summary}}}", tags={ {{#vendorExtensions.x-tags}}"{{tag}}"{{#hasMore}}, {{/hasMore}}{{/vendorExtensions.x-tags}} })
@ApiResponses(value = { {{#responses}}
@ApiResponse(code = {{{code}}}, message = "{{{message}}}"{{^vendorExtensions.x-java-is-response-void}}, response = {{{baseType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}{{/vendorExtensions.x-java-is-response-void}}){{#hasMore}},{{/hasMore}}{{/responses}} })
public {{>returnTypes}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
{{/operation}}
}

View File

@ -103,7 +103,7 @@ public class {{classname}}Test {
{{#allParams}}
{{^isFile}}{{{dataType}}} {{paramName}} = null;{{/isFile}}{{#isFile}}org.apache.cxf.jaxrs.ext.multipart.Attachment {{paramName}} = null;{{/isFile}}
{{/allParams}}
//{{^vendorExtensions.x-java-is-response-void}}{{>returnTypes}} response = {{/vendorExtensions.x-java-is-response-void}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
//{{^vendorExtensions.x-java-is-response-void}}{{>returnTypes}} response = {{/vendorExtensions.x-java-is-response-void}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
{{^vendorExtensions.x-java-is-response-void}}//assertNotNull(response);{{/vendorExtensions.x-java-is-response-void}}
// TODO: test validations

View File

@ -1,53 +1,4 @@
{{#required}}
@NotNull
{{/required}}
{{#pattern}}
@Pattern(regexp="{{pattern}}")
{{/pattern}}
{{#minLength}}
{{#maxLength}}
@Size(min={{minLength}},max={{maxLength}})
{{/maxLength}}
{{/minLength}}
{{#minLength}}
{{^maxLength}}
@Size(min={{minLength}})
{{/maxLength}}
{{/minLength}}
{{^minLength}}
{{#maxLength}}
@Size(max={{maxLength}})
{{/maxLength}}
{{/minLength}}
{{#minItems}}
{{#maxItems}}
@Size(min={{minItems}},max={{maxItems}})
{{/maxItems}}
{{/minItems}}
{{#minItems}}
{{^maxItems}}
@Size(min={{minItems}})
{{/maxItems}}
{{/minItems}}
{{^minItems}}
{{#maxItems}}
@Size(max={{maxItems}})
{{/maxItems}}
{{/minItems}}
{{! check for integer / number=decimal type}}
{{#isInteger}}
{{#minimum}}
@Min({{minimum}})
{{/minimum}}
{{#maximum}}
@Max({{maximum}})
{{/maximum}}
{{/isInteger}}
{{^isInteger}}
{{#minimum}}
@DecimalMin("{{minimum}}")
{{/minimum}}
{{#maximum}}
@DecimalMax("{{maximum}}")
{{/maximum}}
{{/isInteger}}
{{>beanValidationCore}}

View File

@ -0,0 +1,20 @@
{{#pattern}} @Pattern(regexp="{{pattern}}"){{/pattern}}{{!
minLength && maxLength set
}}{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{!
minLength set, maxLength not
}}{{#minLength}}{{^maxLength}} @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{!
minLength not set, maxLength set
}}{{^minLength}}{{#maxLength}} @Size(max={{maxLength}}){{/maxLength}}{{/minLength}}{{!
@Size: minItems && maxItems set
}}{{#minItems}}{{#maxItems}} @Size(min={{minItems}},max={{maxItems}}){{/maxItems}}{{/minItems}}{{!
@Size: minItems set, maxItems not
}}{{#minItems}}{{^maxItems}} @Size(min={{minItems}}){{/maxItems}}{{/minItems}}{{!
@Size: minItems not set && maxItems set
}}{{^minItems}}{{#maxItems}} @Size(max={{maxItems}}){{/maxItems}}{{/minItems}}{{!
check for integer or long / all others=decimal type with @Decimal*
isInteger set
}}{{#isInteger}}{{#minimum}} @Min({{minimum}}){{/minimum}}{{#maximum}} @Max({{maximum}}){{/maximum}}{{/isInteger}}{{!
isLong set
}}{{#isLong}}{{#minimum}} @Min({{minimum}}){{/minimum}}{{#maximum}} @Max({{maximum}}){{/maximum}}{{/isLong}}{{!
Not Integer, not Long => we have a decimal value!
}}{{^isInteger}}{{^isLong}}{{#minimum}} @DecimalMin("{{minimum}}"){{/minimum}}{{#maximum}} @DecimalMax("{{maximum}}"){{/maximum}}{{/isLong}}{{/isInteger}}

View File

@ -0,0 +1 @@
{{! PathParam is always required, no @NotNull necessary }}{{>beanValidationCore}}

View File

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

View File

@ -1 +1 @@
{{#isFormParam}}{{#notFile}}@Multipart(value = "{{paramName}}"{{^required}}, required = false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}} @Multipart(value = "{{paramName}}" {{^required}}, required = false{{/required}}) Attachment {{paramName}}Detail{{/isFile}}{{/isFormParam}}
{{#isFormParam}}{{#notFile}}@Multipart(value = "{{baseName}}"{{^required}}, required = false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}} @Multipart(value = "{{baseName}}" {{^required}}, required = false{{/required}}) Attachment {{paramName}}Detail{{/isFile}}{{/isFormParam}}

View File

@ -1 +1 @@
{{#isPathParam}}@PathParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}}
{{#isPathParam}}@PathParam("{{baseName}}"){{#useBeanValidation}}{{>beanValidationPathParams}}{{/useBeanValidation}} {{{dataType}}} {{paramName}}{{/isPathParam}}

View File

@ -94,7 +94,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private static String toIndentedString(Object o) {
private static String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}

View File

@ -166,7 +166,7 @@
<java.version>{{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}}</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<swagger-core-version>1.5.9</swagger-core-version>
<swagger-core-version>1.5.12</swagger-core-version>
<jetty-version>9.2.9.v20150224</jetty-version>
<jersey2-version>2.22.2</jersey2-version>
<junit-version>4.12</junit-version>

View File

@ -160,6 +160,18 @@
<version>${cxf-version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>${jackson-jaxrs-version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>${jackson-jaxrs-version}</version>
<scope>compile</scope>
</dependency>
{{#generateSpringApplication}}
<!-- Spring -->
<dependency>
@ -217,7 +229,7 @@
<java.version>{{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}}</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<swagger-core-version>1.5.10</swagger-core-version>
<swagger-core-version>1.5.12</swagger-core-version>
<jetty-version>9.2.9.v20150224</jetty-version>
<jersey2-version>2.22.2</jersey2-version>
<junit-version>4.12</junit-version>
@ -233,6 +245,7 @@
<spring.boot-version>1.3.3.RELEASE</spring.boot-version>
{{/generateSpringBootApplication}}
<cxf-version>3.1.8</cxf-version>
<jackson-jaxrs-version>2.8.4</jackson-jaxrs-version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

View File

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

View File

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

View File

@ -138,6 +138,16 @@
<version>${jersey-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
@ -181,9 +191,10 @@
<java.version>{{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}}</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<swagger-core-version>1.5.9</swagger-core-version>
<swagger-core-version>1.5.12</swagger-core-version>
<jetty-version>9.2.9.v20150224</jetty-version>
<jersey-version>1.19.1</jersey-version>
<jackson-version>2.8.7</jackson-version>
<slf4j-version>1.7.21</slf4j-version>
<junit-version>4.12</junit-version>
<servlet-api-version>2.5</servlet-api-version>

View File

@ -133,7 +133,17 @@
<artifactId>jersey-media-multipart</artifactId>
<version>${jersey2-version}</version>
</dependency>
<!-- Base64 encoding that works in both JVM and Android -->
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>${jackson-version}</version>
</dependency>
<!-- Base64 encoding that works in both JVM and Android -->
<dependency>
<groupId>com.brsanthu</groupId>
<artifactId>migbase64</artifactId>
@ -178,9 +188,10 @@
<java.version>{{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}}</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<swagger-core-version>1.5.9</swagger-core-version>
<swagger-core-version>1.5.12</swagger-core-version>
<jetty-version>9.2.9.v20150224</jetty-version>
<jersey2-version>2.22.2</jersey2-version>
<jackson-version>2.8.7</jackson-version>
{{#supportJava6}}
<commons_io_version>2.5</commons_io_version>
<commons_lang3_version>3.5</commons_lang3_version>

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