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

This commit is contained in:
ant3 2016-06-15 22:13:56 +01:00
commit ae67961f60
642 changed files with 24133 additions and 13222 deletions

View File

@ -13,7 +13,19 @@ Also please indicate in the issue title which language/library is concerned. Eg:
##### Swagger declaration file content or url ##### Swagger declaration file content or url
<!-- if it is a bug, a json or yaml that produces it. --> <!-- if it is a bug, a json or yaml that produces it.
If you post the code inline, please wrap it with
```yaml
(here your code)
```
(for YAML code) or
```json
(here your code)
```
(for JSON code), so it becomes more readable. If it is longer than about ten lines,
please create a Gist (https://gist.github.com) or upload it somewhere else and
link it here.
-->
##### Command line used for generation ##### Command line used for generation

7
.gitignore vendored
View File

@ -63,6 +63,12 @@ samples/client/petstore/java/jersey2/.gradle/
samples/client/petstore/java/jersey2/build/ samples/client/petstore/java/jersey2/build/
samples/client/petstore/java/okhttp-gson/.gradle/ samples/client/petstore/java/okhttp-gson/.gradle/
samples/client/petstore/java/okhttp-gson/build/ samples/client/petstore/java/okhttp-gson/build/
samples/client/petstore/java/feign/build/
samples/client/petstore/java/retrofit/build/
samples/client/petstore/java/retrofit2/build/
samples/client/petstore/java/retrofit2rx/build/
samples/client/petstore/java/default/build/
samples/client/petstore/scala/build/
#PHP #PHP
samples/client/petstore/php/SwaggerClient-php/composer.lock samples/client/petstore/php/SwaggerClient-php/composer.lock
@ -106,6 +112,7 @@ samples/client/petstore/csharp/SwaggerClient/bin
samples/client/petstore/csharp/SwaggerClient/obj/Debug/ samples/client/petstore/csharp/SwaggerClient/obj/Debug/
samples/client/petstore/csharp/SwaggerClient/bin/Debug/ samples/client/petstore/csharp/SwaggerClient/bin/Debug/
samples/client/petstore/csharp/SwaggerClient/packages samples/client/petstore/csharp/SwaggerClient/packages
samples/client/petstore/csharp/SwaggerClient/TestResult.xml
# Python # Python
*.pyc *.pyc

View File

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

View File

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

View File

@ -860,6 +860,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you
- [everystory.us](http://everystory.us) - [everystory.us](http://everystory.us)
- [Expected Behavior](http://www.expectedbehavior.com/) - [Expected Behavior](http://www.expectedbehavior.com/)
- [FH Münster - University of Applied Sciences](http://www.fh-muenster.de) - [FH Münster - University of Applied Sciences](http://www.fh-muenster.de)
- [GraphHopper](https://graphhopper.com/)
- [IMS Health](http://www.imshealth.com/en/solution-areas/technology-and-applications) - [IMS Health](http://www.imshealth.com/en/solution-areas/technology-and-applications)
- [Interactive Intelligence](http://developer.mypurecloud.com/) - [Interactive Intelligence](http://developer.mypurecloud.com/)
- [LANDR Audio](https://www.landr.com/) - [LANDR Audio](https://www.landr.com/)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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

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

View File

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

0
bin/swift-petstore.sh Normal file → Executable file
View 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
)
set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -t modules\swagger-codegen\src\main\resources\java -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l java -o samples\client\petstore\java --library=okhttp-gson -DdateLibrary=joda,hideGenerationTimestamp=true
java %JAVA_OPTS% -jar %executable% %ags%

View File

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

View File

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

View File

@ -72,17 +72,13 @@ public abstract class AbstractGenerator {
* @return String Full template file path * @return String Full template file path
*/ */
public String getFullTemplateFile(CodegenConfig config, String templateFile) { public String getFullTemplateFile(CodegenConfig config, String templateFile) {
String template = config.templateDir() + File.separator + templateFile;
if (new File(template).exists()) {
return template;
} else {
String library = config.getLibrary(); String library = config.getLibrary();
if (library != null && !"".equals(library)) { if (library != null && !"".equals(library)) {
String libTemplateFile = config.templateDir() + File.separator + String libTemplateFile = config.embeddedTemplateDir() + File.separator +
"libraries" + File.separator + library + File.separator +
templateFile;
if (new File(libTemplateFile).exists()) {
return libTemplateFile;
}
libTemplateFile = config.embeddedTemplateDir() + File.separator +
"libraries" + File.separator + library + File.separator + "libraries" + File.separator + library + File.separator +
templateFile; templateFile;
if (embeddedTemplateExists(libTemplateFile)) { if (embeddedTemplateExists(libTemplateFile)) {
@ -90,10 +86,6 @@ public abstract class AbstractGenerator {
return libTemplateFile; return libTemplateFile;
} }
} }
String template = config.templateDir() + File.separator + templateFile;
if (new File(template).exists()) {
return template;
} else {
// Fall back to the template file embedded/packaged in the JAR file... // Fall back to the template file embedded/packaged in the JAR file...
return config.embeddedTemplateDir() + File.separator + templateFile; return config.embeddedTemplateDir() + File.separator + templateFile;
} }

View File

@ -792,7 +792,11 @@ public class DefaultCodegen {
importMapping.put("LocalDate", "org.joda.time.*"); importMapping.put("LocalDate", "org.joda.time.*");
importMapping.put("LocalTime", "org.joda.time.*"); importMapping.put("LocalTime", "org.joda.time.*");
supportingFiles.add(new GlobalSupportingFile("LICENSE", "LICENSE")); // we've used the .swagger-codegen-ignore approach as
// suppportingFiles can be cleared by code generator that extends
// the default codegen, leaving the commented code below for
// future reference
//supportingFiles.add(new GlobalSupportingFile("LICENSE", "LICENSE"));
cliOptions.add(CliOption.newBoolean(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, cliOptions.add(CliOption.newBoolean(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG,
CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC).defaultValue(Boolean.TRUE.toString())); CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC).defaultValue(Boolean.TRUE.toString()));
@ -1960,7 +1964,7 @@ public class DefaultCodegen {
} }
} }
r.dataType = cm.datatype; r.dataType = cm.datatype;
r.isBinary = cm.datatype.toLowerCase().startsWith("byte"); r.isBinary = isDataTypeBinary(cm.datatype);
if (cm.isContainer != null) { if (cm.isContainer != null) {
r.simpleType = false; r.simpleType = false;
r.containerType = cm.containerType; r.containerType = cm.containerType;
@ -2129,7 +2133,7 @@ public class DefaultCodegen {
p.baseType = cp.baseType; p.baseType = cp.baseType;
p.dataType = cp.datatype; p.dataType = cp.datatype;
p.isPrimitiveType = cp.isPrimitiveType; p.isPrimitiveType = cp.isPrimitiveType;
p.isBinary = cp.datatype.toLowerCase().startsWith("byte"); p.isBinary = isDataTypeBinary(cp.datatype);
} }
// set boolean flag (e.g. isString) // set boolean flag (e.g. isString)
@ -2226,7 +2230,7 @@ public class DefaultCodegen {
p.isCookieParam = true; p.isCookieParam = true;
} else if (param instanceof BodyParameter) { } else if (param instanceof BodyParameter) {
p.isBodyParam = true; p.isBodyParam = true;
p.isBinary = p.dataType.toLowerCase().startsWith("byte"); p.isBinary = isDataTypeBinary(p.dataType);
} else if (param instanceof FormParameter) { } else if (param instanceof FormParameter) {
if ("file".equalsIgnoreCase(((FormParameter) param).getType())) { if ("file".equalsIgnoreCase(((FormParameter) param).getType())) {
p.isFile = true; p.isFile = true;
@ -2242,6 +2246,10 @@ public class DefaultCodegen {
return p; return p;
} }
public boolean isDataTypeBinary(String dataType) {
return dataType.toLowerCase().startsWith("byte");
}
/** /**
* Convert map of Swagger SecuritySchemeDefinition objects to a list of Codegen Security objects * Convert map of Swagger SecuritySchemeDefinition objects to a list of Codegen Security objects
* *

View File

@ -26,6 +26,7 @@ public abstract class AbstractJavaJAXRSServerCodegen extends JavaClientCodegen {
public AbstractJavaJAXRSServerCodegen() public AbstractJavaJAXRSServerCodegen()
{ {
super(); super();
dateLibrary = "legacy";
apiTestTemplateFiles.clear(); // TODO: add test template apiTestTemplateFiles.clear(); // TODO: add test template
} }

View File

@ -233,12 +233,18 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
clientPackageDir, "ApiException.cs")); clientPackageDir, "ApiException.cs"));
supportingFiles.add(new SupportingFile("ApiResponse.mustache", supportingFiles.add(new SupportingFile("ApiResponse.mustache",
clientPackageDir, "ApiResponse.cs")); clientPackageDir, "ApiResponse.cs"));
supportingFiles.add(new SupportingFile("ExceptionFactory.mustache",
clientPackageDir, "ExceptionFactory.cs"));
supportingFiles.add(new SupportingFile("compile.mustache", "", "build.bat")); supportingFiles.add(new SupportingFile("compile.mustache", "", "build.bat"));
supportingFiles.add(new SupportingFile("compile-mono.sh.mustache", "", "build.sh")); supportingFiles.add(new SupportingFile("compile-mono.sh.mustache", "", "build.sh"));
// shell script to run the nunit test
supportingFiles.add(new SupportingFile("mono_nunit_test.mustache", "", "mono_nunit_test.sh"));
// copy package.config to nuget's standard location for project-level installs // copy package.config to nuget's standard location for project-level installs
supportingFiles.add(new SupportingFile("packages.config.mustache", packageFolder + File.separator, "packages.config")); supportingFiles.add(new SupportingFile("packages.config.mustache", packageFolder + File.separator, "packages.config"));
// .travis.yml for travis-ci.org CI
supportingFiles.add(new SupportingFile("travis.mustache", "", ".travis.yml"));
if(Boolean.FALSE.equals(excludeTests)) { if(Boolean.FALSE.equals(excludeTests)) {
supportingFiles.add(new SupportingFile("packages_test.config.mustache", testPackageFolder + File.separator, "packages.config")); supportingFiles.add(new SupportingFile("packages_test.config.mustache", testPackageFolder + File.separator, "packages.config"));
@ -248,7 +254,8 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
// apache v2 license // apache v2 license
supportingFiles.add(new SupportingFile("LICENSE", "", "LICENSE")); // UPDATE (20160612) no longer needed as the Apache v2 LICENSE is added globally
//supportingFiles.add(new SupportingFile("LICENSE", "", "LICENSE"));
if (optionalAssemblyInfoFlag) { if (optionalAssemblyInfoFlag) {
supportingFiles.add(new SupportingFile("AssemblyInfo.mustache", packageFolder + File.separator + "Properties", "AssemblyInfo.cs")); supportingFiles.add(new SupportingFile("AssemblyInfo.mustache", packageFolder + File.separator + "Properties", "AssemblyInfo.cs"));

View File

@ -27,6 +27,7 @@ public class GroovyClientCodegen extends JavaClientCodegen {
configPackage = "io.swagger.configuration"; configPackage = "io.swagger.configuration";
invokerPackage = "io.swagger.api"; invokerPackage = "io.swagger.api";
artifactId = "swagger-spring-mvc-server"; artifactId = "swagger-spring-mvc-server";
dateLibrary = "legacy";
additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
additionalProperties.put(CodegenConstants.GROUP_ID, groupId); additionalProperties.put(CodegenConstants.GROUP_ID, groupId);

View File

@ -30,7 +30,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
public static final String RETROFIT_1 = "retrofit"; public static final String RETROFIT_1 = "retrofit";
public static final String RETROFIT_2 = "retrofit2"; public static final String RETROFIT_2 = "retrofit2";
protected String dateLibrary = "default"; protected String dateLibrary = "joda";
protected String invokerPackage = "io.swagger.client"; protected String invokerPackage = "io.swagger.client";
protected String groupId = "io.swagger"; protected String groupId = "io.swagger";
protected String artifactId = "swagger-java-client"; protected String artifactId = "swagger-java-client";
@ -128,6 +128,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
Map<String, String> dateOptions = new HashMap<String, String>(); Map<String, String> dateOptions = new HashMap<String, String>();
dateOptions.put("java8", "Java 8 native"); dateOptions.put("java8", "Java 8 native");
dateOptions.put("joda", "Joda"); dateOptions.put("joda", "Joda");
dateOptions.put("legacy", "Legacy java.util.Date");
dateLibrary.setEnum(dateOptions); dateLibrary.setEnum(dateOptions);
cliOptions.add(dateLibrary); cliOptions.add(dateLibrary);
@ -261,7 +262,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
writeOptional(outputFolder, new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); writeOptional(outputFolder, new SupportingFile("settings.gradle.mustache", "", "settings.gradle"));
writeOptional(outputFolder, new SupportingFile("gradle.properties.mustache", "", "gradle.properties")); writeOptional(outputFolder, new SupportingFile("gradle.properties.mustache", "", "gradle.properties"));
writeOptional(outputFolder, new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml")); writeOptional(outputFolder, new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml"));
writeOptional(outputFolder, new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java")); supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java"));
supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java")); supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java"));
final String authFolder = (sourceFolder + '/' + invokerPackage + ".auth").replace(".", "/"); final String authFolder = (sourceFolder + '/' + invokerPackage + ".auth").replace(".", "/");
@ -275,6 +276,8 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.properties") ); gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.properties") );
supportingFiles.add( new SupportingFile( "gradle-wrapper.jar", supportingFiles.add( new SupportingFile( "gradle-wrapper.jar",
gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.jar") ); gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.jar") );
// "build.sbt" is for development with SBT
supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt"));
} }
supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java")); supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java"));
supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java")); supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java"));
@ -332,6 +335,8 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.properties") ); gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.properties") );
supportingFiles.add( new SupportingFile( "gradle-wrapper.jar", supportingFiles.add( new SupportingFile( "gradle-wrapper.jar",
gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.jar") ); gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.jar") );
// "build.sbt" is for development with SBT
supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt"));
//generate markdown docs for retrofit2 //generate markdown docs for retrofit2
if ( usesRetrofit2Library() ){ if ( usesRetrofit2Library() ){

View File

@ -29,6 +29,7 @@ public class JavaInflectorServerCodegen extends JavaClientCodegen {
embeddedTemplateDir = templateDir = "JavaInflector"; embeddedTemplateDir = templateDir = "JavaInflector";
invokerPackage = "io.swagger.handler"; invokerPackage = "io.swagger.handler";
artifactId = "swagger-inflector-server"; artifactId = "swagger-inflector-server";
dateLibrary = "legacy";
apiPackage = System.getProperty("swagger.codegen.inflector.apipackage", "io.swagger.handler"); apiPackage = System.getProperty("swagger.codegen.inflector.apipackage", "io.swagger.handler");
modelPackage = System.getProperty("swagger.codegen.inflector.modelpackage", "io.swagger.model"); modelPackage = System.getProperty("swagger.codegen.inflector.modelpackage", "io.swagger.model");

View File

@ -34,6 +34,7 @@ public class JavaResteasyServerCodegen extends JavaClientCodegen implements Code
apiTestTemplateFiles.clear(); // TODO: add test template apiTestTemplateFiles.clear(); // TODO: add test template
apiPackage = "io.swagger.api"; apiPackage = "io.swagger.api";
modelPackage = "io.swagger.model"; modelPackage = "io.swagger.model";
dateLibrary = "legacy";
additionalProperties.put("title", title); additionalProperties.put("title", title);

View File

@ -23,7 +23,6 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
public static final String GIT_REPO_URL = "gitRepoURL"; public static final String GIT_REPO_URL = "gitRepoURL";
public static final String DEFAULT_LICENSE = "Apache License, Version 2.0"; public static final String DEFAULT_LICENSE = "Apache License, Version 2.0";
public static final String CORE_DATA = "coreData"; public static final String CORE_DATA = "coreData";
public static final String BinaryDataType = "ObjcClientCodegenBinaryData";
protected Set<String> foundationClasses = new HashSet<String>(); protected Set<String> foundationClasses = new HashSet<String>();
protected String podName = "SwaggerClient"; protected String podName = "SwaggerClient";
@ -70,8 +69,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
defaultIncludes.add("NSMutableArray"); defaultIncludes.add("NSMutableArray");
defaultIncludes.add("NSMutableDictionary"); defaultIncludes.add("NSMutableDictionary");
defaultIncludes.add("NSManagedObject"); defaultIncludes.add("NSManagedObject");
defaultIncludes.add("NSData");
defaultIncludes.add(BinaryDataType);
advancedMapingTypes.add("NSDictionary"); advancedMapingTypes.add("NSDictionary");
advancedMapingTypes.add("NSArray"); advancedMapingTypes.add("NSArray");
@ -88,6 +86,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
languageSpecificPrimitives.add("NSString"); languageSpecificPrimitives.add("NSString");
languageSpecificPrimitives.add("NSObject"); languageSpecificPrimitives.add("NSObject");
languageSpecificPrimitives.add("NSDate"); languageSpecificPrimitives.add("NSDate");
languageSpecificPrimitives.add("NSData");
languageSpecificPrimitives.add("NSURL"); languageSpecificPrimitives.add("NSURL");
languageSpecificPrimitives.add("bool"); languageSpecificPrimitives.add("bool");
languageSpecificPrimitives.add("BOOL"); languageSpecificPrimitives.add("BOOL");
@ -109,8 +108,9 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
typeMapping.put("List", "NSArray"); typeMapping.put("List", "NSArray");
typeMapping.put("object", "NSObject"); typeMapping.put("object", "NSObject");
typeMapping.put("file", "NSURL"); typeMapping.put("file", "NSURL");
typeMapping.put("binary", BinaryDataType); typeMapping.put("binary", "NSData");
typeMapping.put("ByteArray", BinaryDataType); typeMapping.put("ByteArray", "NSData");
typeMapping.put("byte", "NSData");
// ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm // ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm
setReservedWordsLowerCase( setReservedWordsLowerCase(
@ -143,6 +143,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
"NSObject", "NSObject",
"NSString", "NSString",
"NSDate", "NSDate",
"NSData",
"NSURL", "NSURL",
"NSDictionary") "NSDictionary")
); );
@ -317,16 +318,10 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
if (p instanceof ArrayProperty) { if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p; ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems(); Property inner = ap.getItems();
String innerType = getSwaggerType(inner);
String innerTypeDeclaration = getTypeDeclaration(inner); String innerTypeDeclaration = getTypeDeclaration(inner);
if (innerTypeDeclaration.endsWith("*")) { if (innerTypeDeclaration.endsWith("*")) {
innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1);
} }
if(innerTypeDeclaration.equalsIgnoreCase(BinaryDataType)) {
return "NSData*";
}
// In this condition, type of property p is array of primitive, // In this condition, type of property p is array of primitive,
// return container type with pointer, e.g. `NSArray*<NSString*>*' // return container type with pointer, e.g. `NSArray*<NSString*>*'
if (languageSpecificPrimitives.contains(innerTypeDeclaration)) { if (languageSpecificPrimitives.contains(innerTypeDeclaration)) {
@ -363,7 +358,6 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
} }
} else { } else {
String swaggerType = getSwaggerType(p); String swaggerType = getSwaggerType(p);
// In this condition, type of p is objective-c primitive type, e.g. `NSSNumber', // In this condition, type of p is objective-c primitive type, e.g. `NSSNumber',
// return type of p with pointer, e.g. `NSNumber*' // return type of p with pointer, e.g. `NSNumber*'
if (languageSpecificPrimitives.contains(swaggerType) && if (languageSpecificPrimitives.contains(swaggerType) &&
@ -394,10 +388,6 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
if (innerTypeDeclaration.endsWith("*")) { if (innerTypeDeclaration.endsWith("*")) {
innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1);
} }
if(innerTypeDeclaration.equalsIgnoreCase(BinaryDataType)) {
return "NSData*";
}
// In this codition, type of property p is array of primitive, // In this codition, type of property p is array of primitive,
// return container type with pointer, e.g. `NSArray*<NSString*>*' // return container type with pointer, e.g. `NSArray*<NSString*>*'
if (languageSpecificPrimitives.contains(innerTypeDeclaration)) { if (languageSpecificPrimitives.contains(innerTypeDeclaration)) {
@ -454,6 +444,11 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
} }
} }
@Override
public boolean isDataTypeBinary(String dataType) {
return dataType.toLowerCase().startsWith("nsdata");
}
@Override @Override
public String toModelName(String type) { public String toModelName(String type) {
// model name cannot use reserved keyword // model name cannot use reserved keyword

View File

@ -1,5 +1,7 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConfig;
@ -24,6 +26,7 @@ import org.slf4j.LoggerFactory;
public class Rails5ServerCodegen extends DefaultCodegen implements CodegenConfig { public class Rails5ServerCodegen extends DefaultCodegen implements CodegenConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(Rails5ServerCodegen.class); private static final Logger LOGGER = LoggerFactory.getLogger(Rails5ServerCodegen.class);
private static final SimpleDateFormat MIGRATE_FILE_NAME_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss");
protected String gemName; protected String gemName;
protected String moduleName; protected String moduleName;
@ -57,12 +60,13 @@ public class Rails5ServerCodegen extends DefaultCodegen implements CodegenConfig
public Rails5ServerCodegen() { public Rails5ServerCodegen() {
super(); super();
apiPackage = "app/controllers";
outputFolder = "generated-code" + File.separator + "rails5"; outputFolder = "generated-code" + File.separator + "rails5";
apiPackage = "app/controllers";
// no model
modelTemplateFiles.clear();
apiTemplateFiles.put("controller.mustache", ".rb"); apiTemplateFiles.put("controller.mustache", ".rb");
modelPackage = "app/models";
modelTemplateFiles.put("model.mustache", ".rb");
embeddedTemplateDir = templateDir = "rails5"; embeddedTemplateDir = templateDir = "rails5";
typeMapping.clear(); typeMapping.clear();
@ -77,21 +81,21 @@ public class Rails5ServerCodegen extends DefaultCodegen implements CodegenConfig
"if", "not", "return", "undef", "yield") "if", "not", "return", "undef", "yield")
); );
languageSpecificPrimitives.add("int"); typeMapping.put("string", "string");
languageSpecificPrimitives.add("array"); typeMapping.put("char", "string");
languageSpecificPrimitives.add("map"); typeMapping.put("int", "integer");
languageSpecificPrimitives.add("string"); typeMapping.put("integer", "integer");
languageSpecificPrimitives.add("DateTime"); typeMapping.put("long", "integer");
typeMapping.put("short", "integer");
typeMapping.put("long", "int"); typeMapping.put("float", "float");
typeMapping.put("integer", "int"); typeMapping.put("double", "decimal");
typeMapping.put("Array", "array"); typeMapping.put("number", "float");
typeMapping.put("String", "string"); typeMapping.put("date", "date");
typeMapping.put("List", "array"); typeMapping.put("DateTime", "datetime");
typeMapping.put("map", "map"); typeMapping.put("boolean", "boolean");
//TODO binary should be mapped to byte array
// mapped to String as a workaround
typeMapping.put("binary", "string"); typeMapping.put("binary", "string");
typeMapping.put("ByteArray", "string");
typeMapping.put("UUID", "string");
// remove modelPackage and apiPackage added by default // remove modelPackage and apiPackage added by default
cliOptions.clear(); cliOptions.clear();
@ -145,6 +149,7 @@ public class Rails5ServerCodegen extends DefaultCodegen implements CodegenConfig
supportingFiles.add(new SupportingFile("secrets.yml", configFolder, "secrets.yml")); supportingFiles.add(new SupportingFile("secrets.yml", configFolder, "secrets.yml"));
supportingFiles.add(new SupportingFile("spring.rb", configFolder, "spring.rb")); supportingFiles.add(new SupportingFile("spring.rb", configFolder, "spring.rb"));
supportingFiles.add(new SupportingFile(".keep", migrateFolder, ".keep")); supportingFiles.add(new SupportingFile(".keep", migrateFolder, ".keep"));
supportingFiles.add(new SupportingFile("migrate.mustache", migrateFolder, "0_init_tables.rb"));
supportingFiles.add(new SupportingFile("schema.rb", dbFolder, "schema.rb")); supportingFiles.add(new SupportingFile("schema.rb", dbFolder, "schema.rb"));
supportingFiles.add(new SupportingFile("seeds.rb", dbFolder, "seeds.rb")); supportingFiles.add(new SupportingFile("seeds.rb", dbFolder, "seeds.rb"));
supportingFiles.add(new SupportingFile(".keep", tasksFolder, ".keep")); supportingFiles.add(new SupportingFile(".keep", tasksFolder, ".keep"));
@ -204,24 +209,6 @@ public class Rails5ServerCodegen extends DefaultCodegen implements CodegenConfig
return super.getTypeDeclaration(p); return super.getTypeDeclaration(p);
} }
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type)) {
return type;
}
} else {
type = swaggerType;
}
if (type == null) {
return null;
}
return type;
}
@Override @Override
public String toDefaultValue(Property p) { public String toDefaultValue(Property p) {
return "null"; return "null";
@ -249,6 +236,16 @@ public class Rails5ServerCodegen extends DefaultCodegen implements CodegenConfig
return name; return name;
} }
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
return typeMapping.get(swaggerType);
}
return "string";
}
@Override @Override
public String toParamName(String name) { public String toParamName(String name) {
// should be the same as variable name // should be the same as variable name

View File

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

View File

@ -10,15 +10,18 @@ import java.util.*;
public class SpringBootServerCodegen extends JavaClientCodegen implements CodegenConfig{ public class SpringBootServerCodegen extends JavaClientCodegen implements CodegenConfig{
public static final String CONFIG_PACKAGE = "configPackage"; public static final String CONFIG_PACKAGE = "configPackage";
public static final String BASE_PACKAGE = "basePackage"; public static final String BASE_PACKAGE = "basePackage";
public static final String INTERFACE_ONLY = "interfaceOnly";
public static final String SINGLE_CONTENT_TYPES = "singleContentTypes";
protected String title = "Petstore Server"; protected String title = "Petstore Server";
protected String configPackage = ""; protected String configPackage = "";
protected String basePackage = ""; protected String basePackage = "";
protected boolean interfaceOnly = false;
protected boolean singleContentTypes = false;
protected String templateFileName = "api.mustache"; protected String templateFileName = "api.mustache";
public SpringBootServerCodegen() { public SpringBootServerCodegen() {
super(); super();
outputFolder = "generated-code/javaSpringBoot"; outputFolder = "generated-code/javaSpringBoot";
modelTemplateFiles.put("model.mustache", ".java");
apiTemplateFiles.put(templateFileName, ".java"); apiTemplateFiles.put(templateFileName, ".java");
apiTestTemplateFiles.clear(); // TODO: add test template apiTestTemplateFiles.clear(); // TODO: add test template
embeddedTemplateDir = templateDir = "JavaSpringBoot"; embeddedTemplateDir = templateDir = "JavaSpringBoot";
@ -40,6 +43,8 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege
cliOptions.add(new CliOption(CONFIG_PACKAGE, "configuration package for generated code")); cliOptions.add(new CliOption(CONFIG_PACKAGE, "configuration package for generated code"));
cliOptions.add(new CliOption(BASE_PACKAGE, "base package for generated code")); cliOptions.add(new CliOption(BASE_PACKAGE, "base package for generated code"));
cliOptions.add(CliOption.newBoolean(INTERFACE_ONLY, "Whether to generate only API interface stubs without the server files."));
cliOptions.add(CliOption.newBoolean(SINGLE_CONTENT_TYPES, "Whether to select only one produces/consumes content-type by operation."));
supportedLibraries.clear(); supportedLibraries.clear();
supportedLibraries.put(DEFAULT_LIBRARY, "Default Spring Boot server stub."); supportedLibraries.put(DEFAULT_LIBRARY, "Default Spring Boot server stub.");
@ -79,9 +84,20 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege
this.setBasePackage((String) additionalProperties.get(BASE_PACKAGE)); this.setBasePackage((String) additionalProperties.get(BASE_PACKAGE));
} }
if (additionalProperties.containsKey(INTERFACE_ONLY)) {
this.setInterfaceOnly(Boolean.valueOf(additionalProperties.get(INTERFACE_ONLY).toString()));
}
if (additionalProperties.containsKey(SINGLE_CONTENT_TYPES)) {
this.setSingleContentTypes(Boolean.valueOf(additionalProperties.get(SINGLE_CONTENT_TYPES).toString()));
}
supportingFiles.clear(); supportingFiles.clear();
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
if(!this.interfaceOnly) {
apiTemplateFiles.put("apiController.mustache", "Controller.java");
supportingFiles.add(new SupportingFile("apiException.mustache", supportingFiles.add(new SupportingFile("apiException.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java")); (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java"));
supportingFiles.add(new SupportingFile("apiOriginFilter.mustache", supportingFiles.add(new SupportingFile("apiOriginFilter.mustache",
@ -90,19 +106,15 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java")); (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java"));
supportingFiles.add(new SupportingFile("notFoundException.mustache", supportingFiles.add(new SupportingFile("notFoundException.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java")); (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java"));
supportingFiles.add(new SupportingFile("swaggerDocumentationConfig.mustache", supportingFiles.add(new SupportingFile("swaggerDocumentationConfig.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerDocumentationConfig.java")); (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerDocumentationConfig.java"));
supportingFiles.add(new SupportingFile("homeController.mustache", supportingFiles.add(new SupportingFile("homeController.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "HomeController.java")); (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "HomeController.java"));
supportingFiles.add(new SupportingFile("swagger2SpringBoot.mustache", supportingFiles.add(new SupportingFile("swagger2SpringBoot.mustache",
(sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator), "Swagger2SpringBoot.java")); (sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator), "Swagger2SpringBoot.java"));
supportingFiles.add(new SupportingFile("application.properties", supportingFiles.add(new SupportingFile("application.properties",
("src.main.resources").replace(".", java.io.File.separator), "application.properties")); ("src.main.resources").replace(".", java.io.File.separator), "application.properties"));
}
} }
@Override @Override
@ -119,9 +131,6 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege
if (basePath == "") { if (basePath == "") {
basePath = "default"; basePath = "default";
} else { } else {
if (co.path.startsWith("/" + basePath)) {
co.path = co.path.substring(("/" + basePath).length());
}
co.subresourceOperation = !co.path.isEmpty(); co.subresourceOperation = !co.path.isEmpty();
} }
List<CodegenOperation> opList = operations.get(basePath); List<CodegenOperation> opList = operations.get(basePath);
@ -135,7 +144,7 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege
@Override @Override
public void preprocessSwagger(Swagger swagger) { public void preprocessSwagger(Swagger swagger) {
System.out.println("preprocessSwagger"); super.preprocessSwagger(swagger);
if ("/".equals(swagger.getBasePath())) { if ("/".equals(swagger.getBasePath())) {
swagger.setBasePath(""); swagger.setBasePath("");
} }
@ -257,6 +266,14 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege
this.basePackage = configPackage; this.basePackage = configPackage;
} }
public void setInterfaceOnly(boolean interfaceOnly) {
this.interfaceOnly = interfaceOnly;
}
public void setSingleContentTypes(boolean singleContentTypes) {
this.singleContentTypes = singleContentTypes;
}
@Override @Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) { public Map<String, Object> postProcessModels(Map<String, Object> objs) {
// remove the import of "Object" to avoid compilation error // remove the import of "Object" to avoid compilation error

View File

@ -25,6 +25,7 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen
configPackage = "io.swagger.configuration"; configPackage = "io.swagger.configuration";
invokerPackage = "io.swagger.api"; invokerPackage = "io.swagger.api";
artifactId = "swagger-spring-mvc-server"; artifactId = "swagger-spring-mvc-server";
dateLibrary = "legacy";
additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
additionalProperties.put(CodegenConstants.GROUP_ID, groupId); additionalProperties.put(CodegenConstants.GROUP_ID, groupId);

View File

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

View File

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

View File

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

View File

@ -1,3 +1,5 @@
{{>licenseInfo}}
package {{invokerPackage}}; package {{invokerPackage}};
import java.util.Map; import java.util.Map;
@ -49,12 +51,19 @@ public class ApiException extends Exception {
this.responseBody = responseBody; this.responseBody = responseBody;
} }
/**
* Get the HTTP status code.
*
* @return HTTP status code
*/
public int getCode() { public int getCode() {
return code; return code;
} }
/** /**
* Get the HTTP response headers. * Get the HTTP response headers.
*
* @return A map of list of string
*/ */
public Map<String, List<String>> getResponseHeaders() { public Map<String, List<String>> getResponseHeaders() {
return responseHeaders; return responseHeaders;
@ -62,6 +71,8 @@ public class ApiException extends Exception {
/** /**
* Get the HTTP response body. * Get the HTTP response body.
*
* @return Response body in the form of string
*/ */
public String getResponseBody() { public String getResponseBody() {
return responseBody; return responseBody;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,3 +1,5 @@
{{>licenseInfo}}
package {{invokerPackage}}.auth; package {{invokerPackage}}.auth;
public enum OAuthFlow { public enum OAuthFlow {

View File

@ -9,6 +9,7 @@ import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuil
import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import feign.Feign; import feign.Feign;
import feign.RequestInterceptor; import feign.RequestInterceptor;
@ -129,6 +130,8 @@ public class ApiClient {
objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.registerModule(new JodaModule());
return objectMapper; return objectMapper;
} }

View File

@ -0,0 +1,26 @@
lazy val root = (project in file(".")).
settings(
organization := "{{groupId}}",
name := "{{artifactId}}",
version := "{{artifactVersion}}",
scalaVersion := "2.11.4",
scalacOptions ++= Seq("-feature"),
javacOptions in compile ++= Seq("-Xlint:deprecation"),
publishArtifact in (Compile, packageDoc) := false,
resolvers += Resolver.mavenLocal,
libraryDependencies ++= Seq(
"io.swagger" % "swagger-annotations" % "1.5.8" % "compile",
"com.netflix.feign" % "feign-core" % "8.16.0" % "compile",
"com.netflix.feign" % "feign-jackson" % "8.16.0" % "compile",
"com.netflix.feign" % "feign-slf4j" % "8.16.0" % "compile",
"com.fasterxml.jackson.core" % "jackson-core" % "2.7.0" % "compile",
"com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.0" % "compile",
"com.fasterxml.jackson.core" % "jackson-databind" % "2.7.0" % "compile",
"com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.1.5" % "compile",
"joda-time" % "joda-time" % "2.9.3" % "compile",
"org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile",
"com.brsanthu" % "migbase64" % "2.2" % "compile",
"junit" % "junit" % "4.12" % "test",
"com.novocode" % "junit-interface" % "0.10" % "test"
)
)

View File

@ -149,19 +149,7 @@
<dependency> <dependency>
<groupId>com.fasterxml.jackson.datatype</groupId> <groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId> <artifactId>jackson-datatype-joda</artifactId>
<version>2.1.5</version> <version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${jodatime-version}</version>
</dependency>
<!-- Base64 encoding that works in both JVM and Android -->
<dependency>
<groupId>com.brsanthu</groupId>
<artifactId>migbase64</artifactId>
<version>2.2</version>
</dependency> </dependency>
<dependency> <dependency>

View File

@ -1,3 +1,5 @@
{{>licenseInfo}}
package {{invokerPackage}}; package {{invokerPackage}};
import java.io.IOException; import java.io.IOException;

View File

@ -1,3 +1,5 @@
{{>licenseInfo}}
package {{invokerPackage}}; package {{invokerPackage}};
import com.squareup.okhttp.Call; import com.squareup.okhttp.Call;
@ -120,6 +122,9 @@ public class ApiClient {
private HttpLoggingInterceptor loggingInterceptor; private HttpLoggingInterceptor loggingInterceptor;
/*
* Constructor for ApiClient
*/
public ApiClient() { public ApiClient() {
httpClient = new OkHttpClient(); httpClient = new OkHttpClient();
@ -152,33 +157,71 @@ public class ApiClient {
authentications = Collections.unmodifiableMap(authentications); authentications = Collections.unmodifiableMap(authentications);
} }
/**
* Get base path
*
* @return Baes path
*/
public String getBasePath() { public String getBasePath() {
return basePath; return basePath;
} }
/**
* Set base path
*
* @param basePath Base path of the URL (e.g {{basePath}})
* @return An instance of OkHttpClient
*/
public ApiClient setBasePath(String basePath) { public ApiClient setBasePath(String basePath) {
this.basePath = basePath; this.basePath = basePath;
return this; return this;
} }
/**
* Get HTTP client
*
* @return An instance of OkHttpClient
*/
public OkHttpClient getHttpClient() { public OkHttpClient getHttpClient() {
return httpClient; return httpClient;
} }
/**
* Set HTTP client
*
* @param httpClient An instance of OkHttpClient
* @return Api Client
*/
public ApiClient setHttpClient(OkHttpClient httpClient) { public ApiClient setHttpClient(OkHttpClient httpClient) {
this.httpClient = httpClient; this.httpClient = httpClient;
return this; return this;
} }
/**
* Get JSON
*
* @return JSON object
*/
public JSON getJSON() { public JSON getJSON() {
return json; return json;
} }
/**
* Set JSON
*
* @param json JSON object
* @return Api client
*/
public ApiClient setJSON(JSON json) { public ApiClient setJSON(JSON json) {
this.json = json; this.json = json;
return this; return this;
} }
/**
* True if isVerifyingSsl flag is on
*
* @return True if isVerifySsl flag is on
*/
public boolean isVerifyingSsl() { public boolean isVerifyingSsl() {
return verifyingSsl; return verifyingSsl;
} }
@ -187,6 +230,9 @@ public class ApiClient {
* Configure whether to verify certificate and hostname when making https requests. * Configure whether to verify certificate and hostname when making https requests.
* Default to true. * Default to true.
* NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks.
*
* @param verifyingSsl True to verify TLS/SSL connection
* @return ApiClient
*/ */
public ApiClient setVerifyingSsl(boolean verifyingSsl) { public ApiClient setVerifyingSsl(boolean verifyingSsl) {
this.verifyingSsl = verifyingSsl; this.verifyingSsl = verifyingSsl;
@ -194,6 +240,11 @@ public class ApiClient {
return this; return this;
} }
/**
* Get SSL CA cert.
*
* @return Input stream to the SSL CA cert
*/
public InputStream getSslCaCert() { public InputStream getSslCaCert() {
return sslCaCert; return sslCaCert;
} }
@ -201,6 +252,9 @@ public class ApiClient {
/** /**
* Configure the CA certificate to be trusted when making https requests. * Configure the CA certificate to be trusted when making https requests.
* Use null to reset to default. * Use null to reset to default.
*
* @param sslCaCert input stream for SSL CA cert
* @return ApiClient
*/ */
public ApiClient setSslCaCert(InputStream sslCaCert) { public ApiClient setSslCaCert(InputStream sslCaCert) {
this.sslCaCert = sslCaCert; this.sslCaCert = sslCaCert;
@ -230,6 +284,7 @@ public class ApiClient {
/** /**
* Whether to allow various ISO 8601 datetime formats when parsing a datetime string. * Whether to allow various ISO 8601 datetime formats when parsing a datetime string.
* @see #parseDatetime(String) * @see #parseDatetime(String)
* @return True if lenientDatetimeFormat flag is set to true
*/ */
public boolean isLenientDatetimeFormat() { public boolean isLenientDatetimeFormat() {
return lenientDatetimeFormat; return lenientDatetimeFormat;
@ -245,6 +300,8 @@ public class ApiClient {
* The default <code>dateFormat</code> supports these ISO 8601 date formats: * The default <code>dateFormat</code> supports these ISO 8601 date formats:
* 2015-08-16 * 2015-08-16
* 2015-8-16 * 2015-8-16
* @param str String to be parsed
* @return Date
*/ */
public Date parseDate(String str) { public Date parseDate(String str) {
if (str == null) if (str == null)
@ -258,7 +315,7 @@ public class ApiClient {
/** /**
* Parse the given datetime string into Date object. * Parse the given datetime string into Date object.
* When <code>lenientDatetimeFormat</code> is enabled, the following ISO 8601 datetime formats are supported: * When lenientDatetimeFormat is enabled, the following ISO 8601 datetime formats are supported:
* 2015-08-16T08:20:05Z * 2015-08-16T08:20:05Z
* 2015-8-16T8:20:05Z * 2015-8-16T8:20:05Z
* 2015-08-16T08:20:05+00:00 * 2015-08-16T08:20:05+00:00
@ -272,7 +329,9 @@ public class ApiClient {
* +08:00 (same with +0800) * +08:00 (same with +0800)
* -02 (same with -0200) * -02 (same with -0200)
* -0200 * -0200
* @see https://en.wikipedia.org/wiki/ISO_8601 * @see <a href="https://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a>
* @param str Date time string to be parsed
* @return Date representation of the string
*/ */
public Date parseDatetime(String str) { public Date parseDatetime(String str) {
if (str == null) if (str == null)
@ -307,6 +366,12 @@ public class ApiClient {
} }
} }
/*
* Parse date or date time in string format into Date object.
*
* @param str Date time string to be parsed
* @return Date representation of the string
*/
public Date parseDateOrDatetime(String str) { public Date parseDateOrDatetime(String str) {
if (str == null) if (str == null)
return null; return null;
@ -317,14 +382,20 @@ public class ApiClient {
} }
/** /**
* Format the given Date object into string. * Format the given Date object into string (Date format).
*
* @param date Date object
* @return Formatted date in string representation
*/ */
public String formatDate(Date date) { public String formatDate(Date date) {
return dateFormat.format(date); return dateFormat.format(date);
} }
/** /**
* Format the given Date object into string. * Format the given Date object into string (Datetime format).
*
* @param date Date object
* @return Formatted datetime in string representation
*/ */
public String formatDatetime(Date date) { public String formatDatetime(Date date) {
return datetimeFormat.format(date); return datetimeFormat.format(date);
@ -332,6 +403,8 @@ public class ApiClient {
/** /**
* Get authentications (key: authentication name, value: authentication). * Get authentications (key: authentication name, value: authentication).
*
* @return Map of authentication objects
*/ */
public Map<String, Authentication> getAuthentications() { public Map<String, Authentication> getAuthentications() {
return authentications; return authentications;
@ -349,6 +422,8 @@ public class ApiClient {
/** /**
* Helper method to set username for the first HTTP basic authentication. * Helper method to set username for the first HTTP basic authentication.
*
* @param username Username
*/ */
public void setUsername(String username) { public void setUsername(String username) {
for (Authentication auth : authentications.values()) { for (Authentication auth : authentications.values()) {
@ -362,6 +437,8 @@ public class ApiClient {
/** /**
* Helper method to set password for the first HTTP basic authentication. * Helper method to set password for the first HTTP basic authentication.
*
* @param password Password
*/ */
public void setPassword(String password) { public void setPassword(String password) {
for (Authentication auth : authentications.values()) { for (Authentication auth : authentications.values()) {
@ -375,6 +452,8 @@ public class ApiClient {
/** /**
* Helper method to set API key value for the first API key authentication. * Helper method to set API key value for the first API key authentication.
*
* @param apiKey API key
*/ */
public void setApiKey(String apiKey) { public void setApiKey(String apiKey) {
for (Authentication auth : authentications.values()) { for (Authentication auth : authentications.values()) {
@ -388,6 +467,8 @@ public class ApiClient {
/** /**
* Helper method to set API key prefix for the first API key authentication. * Helper method to set API key prefix for the first API key authentication.
*
* @param apiKeyPrefix API key prefix
*/ */
public void setApiKeyPrefix(String apiKeyPrefix) { public void setApiKeyPrefix(String apiKeyPrefix) {
for (Authentication auth : authentications.values()) { for (Authentication auth : authentications.values()) {
@ -401,6 +482,8 @@ public class ApiClient {
/** /**
* Helper method to set access token for the first OAuth2 authentication. * Helper method to set access token for the first OAuth2 authentication.
*
* @param accessToken Access token
*/ */
public void setAccessToken(String accessToken) { public void setAccessToken(String accessToken) {
for (Authentication auth : authentications.values()) { for (Authentication auth : authentications.values()) {
@ -414,6 +497,9 @@ public class ApiClient {
/** /**
* Set the User-Agent header's value (by adding to the default header map). * Set the User-Agent header's value (by adding to the default header map).
*
* @param userAgent HTTP request's user agent
* @return ApiClient
*/ */
public ApiClient setUserAgent(String userAgent) { public ApiClient setUserAgent(String userAgent) {
addDefaultHeader("User-Agent", userAgent); addDefaultHeader("User-Agent", userAgent);
@ -425,6 +511,7 @@ public class ApiClient {
* *
* @param key The header's key * @param key The header's key
* @param value The header's value * @param value The header's value
* @return ApiClient
*/ */
public ApiClient addDefaultHeader(String key, String value) { public ApiClient addDefaultHeader(String key, String value) {
defaultHeaderMap.put(key, value); defaultHeaderMap.put(key, value);
@ -432,12 +519,20 @@ public class ApiClient {
} }
/** /**
* @see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) * @see <a href="https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean)">setLenient</a>
*
* @return True if lenientOnJson is enabled, false otherwise.
*/ */
public boolean isLenientOnJson() { public boolean isLenientOnJson() {
return lenientOnJson; return lenientOnJson;
} }
/**
* Set LenientOnJson
*
* @param lenient True to enable lenientOnJson
* @return ApiClient
*/
public ApiClient setLenientOnJson(boolean lenient) { public ApiClient setLenientOnJson(boolean lenient) {
this.lenientOnJson = lenient; this.lenientOnJson = lenient;
return this; return this;
@ -445,6 +540,8 @@ public class ApiClient {
/** /**
* Check that whether debugging is enabled for this API client. * Check that whether debugging is enabled for this API client.
*
* @return True if debugging is enabled, false otherwise.
*/ */
public boolean isDebugging() { public boolean isDebugging() {
return debugging; return debugging;
@ -454,6 +551,7 @@ public class ApiClient {
* Enable/disable debugging for this API client. * Enable/disable debugging for this API client.
* *
* @param debugging To enable (true) or disable (false) debugging * @param debugging To enable (true) or disable (false) debugging
* @return ApiClient
*/ */
public ApiClient setDebugging(boolean debugging) { public ApiClient setDebugging(boolean debugging) {
if (debugging != this.debugging) { if (debugging != this.debugging) {
@ -475,19 +573,28 @@ public class ApiClient {
* with file response. The default value is <code>null</code>, i.e. using * with file response. The default value is <code>null</code>, i.e. using
* the system's default tempopary folder. * the system's default tempopary folder.
* *
* @see https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createTempFile(java.lang.String,%20java.lang.String,%20java.io.File) * @see <a href="https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createTempFile">createTempFile</a>
* @return Temporary folder path
*/ */
public String getTempFolderPath() { public String getTempFolderPath() {
return tempFolderPath; return tempFolderPath;
} }
/**
* Set the tempoaray folder path (for downloading files)
*
* @param tempFolderPath Temporary folder path
* @return ApiClient
*/
public ApiClient setTempFolderPath(String tempFolderPath) { public ApiClient setTempFolderPath(String tempFolderPath) {
this.tempFolderPath = tempFolderPath; this.tempFolderPath = tempFolderPath;
return this; return this;
} }
/** /**
* Connect timeout (in milliseconds). * Get connection timeout (in milliseconds).
*
* @return Timeout in milliseconds
*/ */
public int getConnectTimeout() { public int getConnectTimeout() {
return httpClient.getConnectTimeout(); return httpClient.getConnectTimeout();
@ -496,7 +603,9 @@ public class ApiClient {
/** /**
* Sets the connect timeout (in milliseconds). * Sets the connect timeout (in milliseconds).
* A value of 0 means no timeout, otherwise values must be between 1 and * A value of 0 means no timeout, otherwise values must be between 1 and
* {@link Integer#MAX_VALUE}. *
* @param connectionTimeout connection timeout in milliseconds
* @return Api client
*/ */
public ApiClient setConnectTimeout(int connectionTimeout) { public ApiClient setConnectTimeout(int connectionTimeout) {
httpClient.setConnectTimeout(connectionTimeout, TimeUnit.MILLISECONDS); httpClient.setConnectTimeout(connectionTimeout, TimeUnit.MILLISECONDS);
@ -505,6 +614,9 @@ public class ApiClient {
/** /**
* Format the given parameter object into string. * Format the given parameter object into string.
*
* @param param Parameter
* @return String representation of the parameter
*/ */
public String parameterToString(Object param) { public String parameterToString(Object param) {
if (param == null) { if (param == null) {
@ -525,8 +637,13 @@ public class ApiClient {
} }
} }
/* /**
Format to {@code Pair} objects. * Format to {@code Pair} objects.
*
* @param collectionFormat collection format (e.g. csv, tsv)
* @param name Name
* @param value Value
* @return A list of Pair objects
*/ */
public List<Pair> parameterToPairs(String collectionFormat, String name, Object value){ public List<Pair> parameterToPairs(String collectionFormat, String name, Object value){
List<Pair> params = new ArrayList<Pair>(); List<Pair> params = new ArrayList<Pair>();
@ -598,6 +715,9 @@ public class ApiClient {
* application/json * application/json
* application/json; charset=UTF8 * application/json; charset=UTF8
* APPLICATION/JSON * APPLICATION/JSON
*
* @param mime MIME (Multipurpose Internet Mail Extensions)
* @return True if the given MIME is JSON, false otherwise.
*/ */
public boolean isJsonMime(String mime) { public boolean isJsonMime(String mime) {
return mime != null && mime.matches("(?i)application\\/json(;.*)?"); return mime != null && mime.matches("(?i)application\\/json(;.*)?");
@ -647,6 +767,9 @@ public class ApiClient {
/** /**
* Escape the given string to be used as URL query value. * Escape the given string to be used as URL query value.
*
* @param str String to be escaped
* @return Escaped string
*/ */
public String escapeString(String str) { public String escapeString(String str) {
try { try {
@ -660,6 +783,7 @@ public class ApiClient {
* Deserialize response body to Java object, according to the return type and * Deserialize response body to Java object, according to the return type and
* the Content-Type response header. * the Content-Type response header.
* *
* @param <T> Type
* @param response HTTP response * @param response HTTP response
* @param returnType The type of the Java object * @param returnType The type of the Java object
* @return The deserialized Java object * @return The deserialized Java object
@ -747,7 +871,10 @@ public class ApiClient {
/** /**
* Download file from the given response. * Download file from the given response.
*
* @param response An instance of the Response object
* @throws ApiException If fail to read file content from response and write to disk * @throws ApiException If fail to read file content from response and write to disk
* @return Downloaded file
*/ */
public File downloadFileFromResponse(Response response) throws ApiException { public File downloadFileFromResponse(Response response) throws ApiException {
try { try {
@ -761,6 +888,13 @@ public class ApiClient {
} }
} }
/**
* Prepare file for download
*
* @param response An instance of the Response object
* @throws IOException If fail to prepare file for download
* @return Prepared file for the download
*/
public File prepareDownloadFile(Response response) throws IOException { public File prepareDownloadFile(Response response) throws IOException {
String filename = null; String filename = null;
String contentDisposition = response.header("Content-Disposition"); String contentDisposition = response.header("Content-Disposition");
@ -798,7 +932,12 @@ public class ApiClient {
} }
/** /**
* @see #execute(Call, Type) * {@link #execute(Call, Type)}
*
* @param <T> Type
* @param call An instance of the Call object
* @throws ApiException If fail to execute the call
* @return ApiResponse&lt;T&gt;
*/ */
public <T> ApiResponse<T> execute(Call call) throws ApiException { public <T> ApiResponse<T> execute(Call call) throws ApiException {
return execute(call, null); return execute(call, null);
@ -809,7 +948,8 @@ public class ApiClient {
* *
* @param returnType The return type used to deserialize HTTP response body * @param returnType The return type used to deserialize HTTP response body
* @param <T> The return type corresponding to (same with) returnType * @param <T> The return type corresponding to (same with) returnType
* @return <code>ApiResponse</code> object containing response status, headers and * @param call Call
* @return ApiResponse object containing response status, headers and
* data, which is a Java object deserialized from response body and would be null * data, which is a Java object deserialized from response body and would be null
* when returnType is null. * when returnType is null.
* @throws ApiException If fail to execute the call * @throws ApiException If fail to execute the call
@ -825,7 +965,11 @@ public class ApiClient {
} }
/** /**
* #see executeAsync(Call, Type, ApiCallback) * {@link #executeAsync(Call, Type, ApiCallback)}
*
* @param <T> Type
* @param call An instance of the Call object
* @param callback ApiCallback&lt;T&gt;
*/ */
public <T> void executeAsync(Call call, ApiCallback<T> callback) { public <T> void executeAsync(Call call, ApiCallback<T> callback) {
executeAsync(call, null, callback); executeAsync(call, null, callback);
@ -835,7 +979,10 @@ public class ApiClient {
* Execute HTTP call asynchronously. * Execute HTTP call asynchronously.
* *
* @see #execute(Call, Type) * @see #execute(Call, Type)
* @param The callback to be executed when the API call finishes * @param <T> Type
* @param call The callback to be executed when the API call finishes
* @param returnType Return type
* @param callback ApiCallback
*/ */
public <T> void executeAsync(Call call, final Type returnType, final ApiCallback<T> callback) { public <T> void executeAsync(Call call, final Type returnType, final ApiCallback<T> callback) {
call.enqueue(new Callback() { call.enqueue(new Callback() {
@ -861,8 +1008,12 @@ public class ApiClient {
/** /**
* Handle the given response, return the deserialized object when the response is successful. * Handle the given response, return the deserialized object when the response is successful.
* *
* @param <T> Type
* @param response Response
* @param returnType Return type
* @throws ApiException If the response has a unsuccessful status code or * @throws ApiException If the response has a unsuccessful status code or
* fail to deserialize the response body * fail to deserialize the response body
* @return Type
*/ */
public <T> T handleResponse(Response response, Type returnType) throws ApiException { public <T> T handleResponse(Response response, Type returnType) throws ApiException {
if (response.isSuccessful()) { if (response.isSuccessful()) {
@ -896,6 +1047,7 @@ public class ApiClient {
* @param headerParams The header parameters * @param headerParams The header parameters
* @param formParams The form parameters * @param formParams The form parameters
* @param authNames The authentications to apply * @param authNames The authentications to apply
* @param progressRequestListener Progress request listener
* @return The HTTP call * @return The HTTP call
* @throws ApiException If fail to serialize the request body object * @throws ApiException If fail to serialize the request body object
*/ */
@ -976,6 +1128,9 @@ public class ApiClient {
/** /**
* Set header parameters to the request builder, including default headers. * Set header parameters to the request builder, including default headers.
*
* @param headerParams Header parameters in the ofrm of Map
* @param reqBuilder Reqeust.Builder
*/ */
public void processHeaderParams(Map<String, String> headerParams, Request.Builder reqBuilder) { public void processHeaderParams(Map<String, String> headerParams, Request.Builder reqBuilder) {
for (Entry<String, String> param : headerParams.entrySet()) { for (Entry<String, String> param : headerParams.entrySet()) {
@ -992,6 +1147,8 @@ public class ApiClient {
* Update query and header parameters based on authentication settings. * Update query and header parameters based on authentication settings.
* *
* @param authNames The authentications to apply * @param authNames The authentications to apply
* @param queryParams List of query parameters
* @param headerParams Map of header parameters
*/ */
public void updateParamsForAuth(String[] authNames, List<Pair> queryParams, Map<String, String> headerParams) { public void updateParamsForAuth(String[] authNames, List<Pair> queryParams, Map<String, String> headerParams) {
for (String authName : authNames) { for (String authName : authNames) {
@ -1003,6 +1160,9 @@ public class ApiClient {
/** /**
* Build a form-encoding request body with the given form parameters. * Build a form-encoding request body with the given form parameters.
*
* @param formParams Form parameters in the form of Map
* @return RequestBody
*/ */
public RequestBody buildRequestBodyFormEncoding(Map<String, Object> formParams) { public RequestBody buildRequestBodyFormEncoding(Map<String, Object> formParams) {
FormEncodingBuilder formBuilder = new FormEncodingBuilder(); FormEncodingBuilder formBuilder = new FormEncodingBuilder();
@ -1015,6 +1175,9 @@ public class ApiClient {
/** /**
* Build a multipart (file uploading) request body with the given form parameters, * Build a multipart (file uploading) request body with the given form parameters,
* which could contain text fields and file fields. * which could contain text fields and file fields.
*
* @param formParams Form parameters in the form of Map
* @return RequestBody
*/ */
public RequestBody buildRequestBodyMultipart(Map<String, Object> formParams) { public RequestBody buildRequestBodyMultipart(Map<String, Object> formParams) {
MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
@ -1036,7 +1199,7 @@ public class ApiClient {
* Guess Content-Type header from the given file (defaults to "application/octet-stream"). * Guess Content-Type header from the given file (defaults to "application/octet-stream").
* *
* @param file The given file * @param file The given file
* @return The Content-Type guessed * @return The guessed Content-Type
*/ */
public String guessContentTypeFromFile(File file) { public String guessContentTypeFromFile(File file) {
String contentType = URLConnection.guessContentTypeFromName(file.getName()); String contentType = URLConnection.guessContentTypeFromName(file.getName());

View File

@ -1,3 +1,5 @@
{{>licenseInfo}}
package {{invokerPackage}}; package {{invokerPackage}};
import java.util.List; import java.util.List;

View File

@ -1,3 +1,5 @@
{{>licenseInfo}}
package {{invokerPackage}}; package {{invokerPackage}};
import com.google.gson.Gson; import com.google.gson.Gson;
@ -10,33 +12,61 @@ import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive; import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer; import com.google.gson.JsonSerializer;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.io.StringReader; import java.io.StringReader;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.util.Date; import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
public class JSON { public class JSON {
private ApiClient apiClient; private ApiClient apiClient;
private Gson gson; private Gson gson;
/**
* JSON constructor.
*
* @param apiClient An instance of ApiClient
*/
public JSON(ApiClient apiClient) { public JSON(ApiClient apiClient) {
this.apiClient = apiClient; this.apiClient = apiClient;
gson = new GsonBuilder() gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new DateAdapter(apiClient)) .registerTypeAdapter(Date.class, new DateAdapter(apiClient))
.registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter())
.registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter())
.create(); .create();
} }
/**
* Get Gson.
*
* @return Gson
*/
public Gson getGson() { public Gson getGson() {
return gson; return gson;
} }
/**
* Set Gson.
*
* @param gson Gson
*/
public void setGson(Gson gson) { public void setGson(Gson gson) {
this.gson = gson; this.gson = gson;
} }
/** /**
* Serialize the given Java object into JSON string. * Serialize the given Java object into JSON string.
*
* @param obj Object
* @return String representation of the JSON
*/ */
public String serialize(Object obj) { public String serialize(Object obj) {
return gson.toJson(obj); return gson.toJson(obj);
@ -45,6 +75,7 @@ public class JSON {
/** /**
* Deserialize the given JSON string to Java object. * Deserialize the given JSON string to Java object.
* *
* @param <T> Type
* @param body The JSON string * @param body The JSON string
* @param returnType The type to deserialize inot * @param returnType The type to deserialize inot
* @return The deserialized Java object * @return The deserialized Java object
@ -75,11 +106,24 @@ public class JSON {
class DateAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> { class DateAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
private final ApiClient apiClient; private final ApiClient apiClient;
/**
* Constructor for DateAdapter
*
* @param apiClient Api client
*/
public DateAdapter(ApiClient apiClient) { public DateAdapter(ApiClient apiClient) {
super(); super();
this.apiClient = apiClient; this.apiClient = apiClient;
} }
/**
* Serialize
*
* @param src Date
* @param typeOfSrc Type
* @param context Json Serialization Context
* @return Json Element
*/
@Override @Override
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
if (src == null) { if (src == null) {
@ -89,6 +133,16 @@ class DateAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
} }
} }
/**
* Deserialize
*
* @param json Json element
* @param date Type
* @param typeOfSrc Type
* @param context Json Serialization Context
* @return Date
* @throw JsonParseException if fail to parse
*/
@Override @Override
public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException { public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException {
String str = json.getAsJsonPrimitive().getAsString(); String str = json.getAsJsonPrimitive().getAsString();
@ -99,3 +153,62 @@ class DateAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
} }
} }
} }
/**
* Gson TypeAdapter for Joda DateTime type
*/
class DateTimeTypeAdapter extends TypeAdapter<DateTime> {
private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime();
@Override
public void write(JsonWriter out, DateTime date) throws IOException {
if (date == null) {
out.nullValue();
} else {
out.value(formatter.print(date));
}
}
@Override
public DateTime read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
return formatter.parseDateTime(date);
}
}
}
/**
* Gson TypeAdapter for Joda LocalDate type
*/
class LocalDateTypeAdapter extends TypeAdapter<LocalDate> {
private final DateTimeFormatter formatter = ISODateTimeFormat.date();
@Override
public void write(JsonWriter out, LocalDate date) throws IOException {
if (date == null) {
out.nullValue();
} else {
out.value(formatter.print(date));
}
}
@Override
public LocalDate read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
return formatter.parseLocalDate(date);
}
}
}

View File

@ -1,3 +1,5 @@
{{>licenseInfo}}
package {{invokerPackage}}; package {{invokerPackage}};
import com.squareup.okhttp.MediaType; import com.squareup.okhttp.MediaType;

View File

@ -1,3 +1,5 @@
{{>licenseInfo}}
package {{invokerPackage}}; package {{invokerPackage}};
import com.squareup.okhttp.MediaType; import com.squareup.okhttp.MediaType;

View File

@ -1,3 +1,5 @@
{{>licenseInfo}}
package {{package}}; package {{package}};
import {{invokerPackage}}.ApiCallback; import {{invokerPackage}}.ApiCallback;
@ -11,10 +13,6 @@ import {{invokerPackage}}.ProgressResponseBody;
import com.google.gson.reflect.TypeToken; import com.google.gson.reflect.TypeToken;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.Response;
import java.io.IOException; import java.io.IOException;
{{#imports}}import {{import}}; {{#imports}}import {{import}};
@ -50,7 +48,7 @@ public class {{classname}} {
{{#operation}} {{#operation}}
/* Build call for {{operationId}} */ /* Build call for {{operationId}} */
private Call {{operationId}}Call({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { private com.squareup.okhttp.Call {{operationId}}Call({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object {{localVariablePrefix}}localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; Object {{localVariablePrefix}}localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
{{#allParams}}{{#required}} {{#allParams}}{{#required}}
// verify the required parameter '{{paramName}}' is set // verify the required parameter '{{paramName}}' is set
@ -88,10 +86,10 @@ public class {{classname}} {
{{localVariablePrefix}}localVarHeaderParams.put("Content-Type", {{localVariablePrefix}}localVarContentType); {{localVariablePrefix}}localVarHeaderParams.put("Content-Type", {{localVariablePrefix}}localVarContentType);
if(progressListener != null) { if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override @Override
public Response intercept(Interceptor.Chain chain) throws IOException { public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request()); com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder() return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener)) .body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build(); .build();
@ -107,7 +105,7 @@ public class {{classname}} {
* {{summary}} * {{summary}}
* {{notes}}{{#allParams}} * {{notes}}{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}{{#returnType}} * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}{{#returnType}}
* @return {{{returnType}}}{{/returnType}} * @return {{returnType}}{{/returnType}}
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/ */
public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
@ -119,11 +117,11 @@ public class {{classname}} {
* {{summary}} * {{summary}}
* {{notes}}{{#allParams}} * {{notes}}{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}} * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
* @return ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> * @return ApiResponse&lt;{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Void{{/returnType}}&gt;
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/ */
public ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { public ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}null, null); com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}null, null);
{{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType(); {{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType();
return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType);{{/returnType}}{{^returnType}}return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call);{{/returnType}} return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType);{{/returnType}}{{^returnType}}return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call);{{/returnType}}
} }
@ -136,7 +134,7 @@ public class {{classname}} {
* @return The request call * @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object * @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/ */
public Call {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{localVariablePrefix}}callback) throws ApiException { public com.squareup.okhttp.Call {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{localVariablePrefix}}callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null; ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
@ -157,7 +155,7 @@ public class {{classname}} {
}; };
} }
Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener); com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener);
{{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType(); {{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType();
{{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType, {{localVariablePrefix}}callback);{{/returnType}}{{^returnType}}{{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}callback);{{/returnType}} {{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType, {{localVariablePrefix}}callback);{{/returnType}}{{^returnType}}{{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}callback);{{/returnType}}
return {{localVariablePrefix}}call; return {{localVariablePrefix}}call;

View File

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

View File

@ -98,5 +98,6 @@ dependencies {
compile 'com.squareup.okhttp:okhttp:2.7.5' compile 'com.squareup.okhttp:okhttp:2.7.5'
compile 'com.squareup.okhttp:logging-interceptor:2.7.5' compile 'com.squareup.okhttp:logging-interceptor:2.7.5'
compile 'com.google.code.gson:gson:2.6.2' compile 'com.google.code.gson:gson:2.6.2'
compile 'joda-time:joda-time:2.9.3'
testCompile 'junit:junit:4.12' testCompile 'junit:junit:4.12'
} }

View File

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

View File

@ -1,3 +1,5 @@
{{>licenseInfo}}
package {{package}}; package {{package}};
import java.util.Objects; import java.util.Objects;

View File

@ -3,29 +3,51 @@
*/{{#description}} */{{#description}}
@ApiModel(description = "{{{description}}}"){{/description}} @ApiModel(description = "{{{description}}}"){{/description}}
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} {
{{#vars}}{{#isEnum}} {{#vars}}
{{#isEnum}}
{{>libraries/common/modelInnerEnum}}{{/isEnum}}{{#items.isEnum}}{{#items}} {{>libraries/common/modelInnerEnum}}
{{/isEnum}}
{{>libraries/common/modelInnerEnum}}{{/items}}{{/items.isEnum}} {{#items.isEnum}}
{{#items}}
{{>libraries/common/modelInnerEnum}}
{{/items}}
{{/items.isEnum}}
@SerializedName("{{baseName}}") @SerializedName("{{baseName}}")
private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}}; private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};
{{/vars}} {{/vars}}
{{#vars}} {{#vars}}
/**{{#description}} /**
* {{{description}}}{{/description}}{{#minimum}} {{#description}}
* minimum: {{minimum}}{{/minimum}}{{#maximum}} * {{{description}}}
* maximum: {{maximum}}{{/maximum}} {{/description}}
{{^description}}
* Get {{name}}
{{/description}}
{{#minimum}}
* minimum: {{minimum}}
{{/minimum}}
{{#maximum}}
* maximum: {{maximum}}
{{/maximum}}
* @return {{name}}
**/ **/
@ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") @ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}")
public {{{datatypeWithEnum}}} {{getter}}() { public {{{datatypeWithEnum}}} {{getter}}() {
return {{name}}; return {{name}};
}{{^isReadOnly}} }
{{^isReadOnly}}
/**
* Set {{name}}
*
* @param {{name}} {{name}}
*/
public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { public void {{setter}}({{{datatypeWithEnum}}} {{name}}) {
this.{{name}} = {{name}}; this.{{name}} = {{name}};
}{{/isReadOnly}} }
{{/isReadOnly}}
{{/vars}} {{/vars}}
@Override @Override
@ -61,6 +83,8 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali
/** /**
* Convert the given object to string with each line indented by 4 spaces * Convert the given object to string with each line indented by 4 spaces
* (except the first line). * (except the first line).
*
* @param o Object to be converted to indented string
*/ */
private String toIndentedString(Object o) { private String toIndentedString(Object o) {
if (o == null) { if (o == null) {

View File

@ -105,40 +105,6 @@
<target>1.7</target> <target>1.7</target>
</configuration> </configuration>
</plugin> </plugin>
<!-- For testing build.gradle, build.sbt -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<id>gradle-test</id>
<phase>integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>gradle</executable>
<arguments>
<argument>check</argument>
</arguments>
</configuration>
</execution>
<execution>
<id>sbt-test</id>
<phase>integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>sbt</executable>
<arguments>
<argument>publishLocal</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins> </plugins>
</build> </build>
<dependencies> <dependencies>
@ -162,6 +128,11 @@
<artifactId>gson</artifactId> <artifactId>gson</artifactId>
<version>${gson-version}</version> <version>${gson-version}</version>
</dependency> </dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${jodatime-version}</version>
</dependency>
<!-- test dependencies --> <!-- test dependencies -->
<dependency> <dependency>
@ -172,9 +143,10 @@
</dependency> </dependency>
</dependencies> </dependencies>
<properties> <properties>
<swagger-core-version>1.5.8</swagger-core-version> <swagger-core-version>1.5.9</swagger-core-version>
<okhttp-version>2.7.5</okhttp-version> <okhttp-version>2.7.5</okhttp-version>
<gson-version>2.6.2</gson-version> <gson-version>2.6.2</gson-version>
<jodatime-version>2.9.3</jodatime-version>
<maven-plugin-version>1.0.0</maven-plugin-version> <maven-plugin-version>1.0.0</maven-plugin-version>
<junit-version>4.12</junit-version> <junit-version>4.12</junit-version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

View File

@ -9,6 +9,10 @@ import java.util.Map;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import retrofit.RestAdapter; import retrofit.RestAdapter;
import retrofit.client.OkClient; import retrofit.client.OkClient;
@ -22,6 +26,9 @@ import retrofit.mime.TypedOutput;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException; import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.OkHttpClient;
@ -108,6 +115,8 @@ public class ApiClient {
public void createDefaultAdapter() { public void createDefaultAdapter() {
Gson gson = new GsonBuilder() Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
.registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter())
.registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter())
.create(); .create();
okClient = new OkHttpClient(); okClient = new OkHttpClient();
@ -339,3 +348,61 @@ class GsonConverterWrapper implements Converter {
} }
} }
/**
* Gson TypeAdapter for Joda DateTime type
*/
class DateTimeTypeAdapter extends TypeAdapter<DateTime> {
private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime();
@Override
public void write(JsonWriter out, DateTime date) throws IOException {
if (date == null) {
out.nullValue();
} else {
out.value(formatter.print(date));
}
}
@Override
public DateTime read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
return formatter.parseDateTime(date);
}
}
}
/**
* Gson TypeAdapter for Joda DateTime type
*/
class LocalDateTypeAdapter extends TypeAdapter<LocalDate> {
private final DateTimeFormatter formatter = ISODateTimeFormat.date();
@Override
public void write(JsonWriter out, LocalDate date) throws IOException {
if (date == null) {
out.nullValue();
} else {
out.value(formatter.print(date));
}
}
@Override
public LocalDate read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
return formatter.parseLocalDate(date);
}
}
}

View File

@ -99,6 +99,7 @@ ext {
retrofit_version = "1.9.0" retrofit_version = "1.9.0"
swagger_annotations_version = "1.5.8" swagger_annotations_version = "1.5.8"
junit_version = "4.12" junit_version = "4.12"
jodatime_version = "2.9.3"
} }
dependencies { dependencies {
@ -106,5 +107,6 @@ dependencies {
compile "com.squareup.retrofit:retrofit:$retrofit_version" compile "com.squareup.retrofit:retrofit:$retrofit_version"
compile "io.swagger:swagger-annotations:$swagger_annotations_version" compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version" compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version"
compile "joda-time:joda-time:$jodatime_version"
testCompile "junit:junit:$junit_version" testCompile "junit:junit:$junit_version"
} }

View File

@ -0,0 +1,20 @@
lazy val root = (project in file(".")).
settings(
organization := "{{groupId}}",
name := "{{artifactId}}",
version := "{{artifactVersion}}",
scalaVersion := "2.11.4",
scalacOptions ++= Seq("-feature"),
javacOptions in compile ++= Seq("-Xlint:deprecation"),
publishArtifact in (Compile, packageDoc) := false,
resolvers += Resolver.mavenLocal,
libraryDependencies ++= Seq(
"com.squareup.okhttp" % "okhttp" % "2.7.5" % "compile",
"com.squareup.retrofit" % "retrofit" % "1.9.0" % "compile",
"io.swagger" % "swagger-annotations" % "1.5.8" % "compile",
"org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile",
"joda-time" % "joda-time" % "2.9.3" % "compile",
"junit" % "junit" % "4.12" % "test",
"com.novocode" % "junit-interface" % "0.10" % "test"
)
)

View File

@ -127,6 +127,11 @@
<artifactId>okhttp</artifactId> <artifactId>okhttp</artifactId>
<version>${okhttp-version}</version> <version>${okhttp-version}</version>
</dependency> </dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${jodatime-version}</version>
</dependency>
<!-- test dependencies --> <!-- test dependencies -->
<dependency> <dependency>
@ -140,6 +145,7 @@
<swagger-core-version>1.5.8</swagger-core-version> <swagger-core-version>1.5.8</swagger-core-version>
<retrofit-version>1.9.0</retrofit-version> <retrofit-version>1.9.0</retrofit-version>
<okhttp-version>2.7.5</okhttp-version> <okhttp-version>2.7.5</okhttp-version>
<jodatime-version>2.9.3</jodatime-version>
<oltu-version>1.0.1</oltu-version> <oltu-version>1.0.1</oltu-version>
<maven-plugin-version>1.0.0</maven-plugin-version> <maven-plugin-version>1.0.0</maven-plugin-version>
<junit-version>4.12</junit-version> <junit-version>4.12</junit-version>

View File

@ -9,6 +9,10 @@ import java.util.Map;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import retrofit2.Converter; import retrofit2.Converter;
import retrofit2.Retrofit; import retrofit2.Retrofit;
@ -19,6 +23,9 @@ import retrofit2.converter.scalars.ScalarsConverterFactory;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException; import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import okhttp3.Interceptor; import okhttp3.Interceptor;
import okhttp3.OkHttpClient; import okhttp3.OkHttpClient;
import okhttp3.RequestBody; import okhttp3.RequestBody;
@ -108,6 +115,8 @@ public class ApiClient {
public void createDefaultAdapter() { public void createDefaultAdapter() {
Gson gson = new GsonBuilder() Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
.registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter())
.registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter())
.create(); .create();
okClient = new OkHttpClient(); okClient = new OkHttpClient();
@ -346,3 +355,58 @@ class GsonCustomConverterFactory extends Converter.Factory
} }
} }
/**
* Gson TypeAdapter for Joda DateTime type
*/
class DateTimeTypeAdapter extends TypeAdapter<DateTime> {
private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime();
@Override
public void write(JsonWriter out, DateTime date) throws IOException {
if (date == null) {
out.nullValue();
} else {
out.value(formatter.print(date));
}
}
@Override
public DateTime read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
return formatter.parseDateTime(date);
}
}
}
class LocalDateTypeAdapter extends TypeAdapter<LocalDate> {
private final DateTimeFormatter formatter = ISODateTimeFormat.date();
@Override
public void write(JsonWriter out, LocalDate date) throws IOException {
if (date == null) {
out.nullValue();
} else {
out.value(formatter.print(date));
}
}
@Override
public LocalDate read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
return formatter.parseLocalDate(date);
}
}
}

View File

@ -97,25 +97,20 @@ ext {
oltu_version = "1.0.1" oltu_version = "1.0.1"
retrofit_version = "2.0.2" retrofit_version = "2.0.2"
swagger_annotations_version = "1.5.8" swagger_annotations_version = "1.5.8"
junit_version = "4.12" junit_version = "4.12"{{#useRxJava}}
{{#useRxJava}} rx_java_version = "1.1.3"{{/useRxJava}}
rx_java_version = "1.1.3" jodatime_version = "2.9.3"
{{/useRxJava}}
{{^useRxJava}}{{/useRxJava}}
} }
dependencies { dependencies {
compile "com.squareup.retrofit2:retrofit:$retrofit_version" compile "com.squareup.retrofit2:retrofit:$retrofit_version"
compile "com.squareup.retrofit2:converter-scalars:$retrofit_version" compile "com.squareup.retrofit2:converter-scalars:$retrofit_version"
compile "com.squareup.retrofit2:converter-gson:$retrofit_version" compile "com.squareup.retrofit2:converter-gson:$retrofit_version"{{#useRxJava}}
{{#useRxJava}}
compile "com.squareup.retrofit2:adapter-rxjava:$retrofit_version" compile "com.squareup.retrofit2:adapter-rxjava:$retrofit_version"
compile "io.reactivex:rxjava:$rx_java_version" compile "io.reactivex:rxjava:$rx_java_version"{{/useRxJava}}
{{/useRxJava}}
{{^useRxJava}}{{/useRxJava}}
compile "io.swagger:swagger-annotations:$swagger_annotations_version" compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version" compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version"
compile "joda-time:joda-time:$jodatime_version"
testCompile "junit:junit:$junit_version" testCompile "junit:junit:$junit_version"
} }

View File

@ -0,0 +1,23 @@
lazy val root = (project in file(".")).
settings(
organization := "{{groupId}}",
name := "{{artifactId}}",
version := "{{artifactVersion}}",
scalaVersion := "2.11.4",
scalacOptions ++= Seq("-feature"),
javacOptions in compile ++= Seq("-Xlint:deprecation"),
publishArtifact in (Compile, packageDoc) := false,
resolvers += Resolver.mavenLocal,
libraryDependencies ++= Seq(
"com.squareup.retrofit2" % "retrofit" % "2.0.2" % "compile",
"com.squareup.retrofit2" % "converter-scalars" % "2.0.2" % "compile",
"com.squareup.retrofit2" % "converter-gson" % "2.0.2" % "compile",{{#useRxJava}}
"com.squareup.retrofit2" % "adapter-rxjava" % "2.0.2" % "compile",
"io.reactivex" % "rxjava" % "1.1.3" % "compile",{{/useRxJava}}
"io.swagger" % "swagger-annotations" % "1.5.8" % "compile",
"org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile",
"joda-time" % "joda-time" % "2.9.3" % "compile",
"junit" % "junit" % "4.12" % "test",
"com.novocode" % "junit-interface" % "0.10" % "test"
)
)

View File

@ -131,6 +131,11 @@
<groupId>org.apache.oltu.oauth2</groupId> <groupId>org.apache.oltu.oauth2</groupId>
<artifactId>org.apache.oltu.oauth2.client</artifactId> <artifactId>org.apache.oltu.oauth2.client</artifactId>
<version>${oltu-version}</version> <version>${oltu-version}</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${jodatime-version}</version>
</dependency>{{#useRxJava}} </dependency>{{#useRxJava}}
<dependency> <dependency>
<groupId>io.reactivex</groupId> <groupId>io.reactivex</groupId>
@ -153,9 +158,9 @@
</dependencies> </dependencies>
<properties> <properties>
<swagger-core-version>1.5.8</swagger-core-version> <swagger-core-version>1.5.8</swagger-core-version>
<retrofit-version>2.0.2</retrofit-version> <retrofit-version>2.0.2</retrofit-version>{{#useRxJava}}
{{#useRxJava}}<rxjava-version>1.1.3</rxjava-version>{{/useRxJava}} <rxjava-version>1.1.3</rxjava-version>{{/useRxJava}}
<okhttp-version>3.2.0</okhttp-version> <jodatime-version>2.9.3</jodatime-version>
<oltu-version>1.0.1</oltu-version> <oltu-version>1.0.1</oltu-version>
<maven-plugin-version>1.0.0</maven-plugin-version> <maven-plugin-version>1.0.0</maven-plugin-version>
<junit-version>4.12</junit-version> <junit-version>4.12</junit-version>

View File

@ -0,0 +1,23 @@
/**
* {{{appName}}}
* {{{appDescription}}}
*
* {{#version}}OpenAPI spec version: {{{version}}}{{/version}}
* {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}}
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

View File

@ -1,4 +1,4 @@
# Swagger generated server {{^interfaceOnly}}# Swagger generated server
Spring Boot Server Spring Boot Server
@ -15,4 +15,31 @@ Start your server as an simple java application
You can view the api documentation in swagger-ui by pointing to You can view the api documentation in swagger-ui by pointing to
http://localhost:8080/ http://localhost:8080/
Change default port value in application.properties Change default port value in application.properties{{/interfaceOnly}}{{#interfaceOnly}}
# Swagger generated API stub
Spring Framework stub
## Overview
This code was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project.
By using the [OpenAPI-Spec](https://github.com/swagger-api/swagger-core), you can easily generate an API stub.
This is an example of building API stub interfaces in Java using the Spring framework.
The stubs generated can be used in your existing Spring-MVC or Spring-Boot application to create controller endpoints
by adding ```@Controller``` classes that implement the interface. Eg:
```java
@Controller
public class PetController implements PetApi {
// implement all PetApi methods
}
```
You can also use the interface to create [Spring-Cloud Feign clients](http://projects.spring.io/spring-cloud/spring-cloud.html#spring-cloud-feign-inheritance).Eg:
```java
@FeignClient(name="pet", url="http://petstore.swagger.io/v2")
public interface PetClient extends PetApi {
}
```
{{/interfaceOnly}}

View File

@ -7,9 +7,7 @@ import {{modelPackage}}.*;
import io.swagger.annotations.*; import io.swagger.annotations.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestHeader;
@ -23,12 +21,10 @@ import java.util.List;
import static org.springframework.http.MediaType.*; import static org.springframework.http.MediaType.*;
@Controller @Api(value = "{{{baseName}}}", description = "the {{{baseName}}} API")
@RequestMapping(value = "/{{{baseName}}}", produces = {APPLICATION_JSON_VALUE})
@Api(value = "/{{{baseName}}}", description = "the {{{baseName}}} API")
{{>generatedAnnotation}} {{>generatedAnnotation}}
{{#operations}} {{#operations}}
public class {{classname}} { public interface {{classname}} {
{{#operation}} {{#operation}}
@ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}{{#hasAuthMethods}}, authorizations = { @ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}{{#hasAuthMethods}}, authorizations = {
@ -40,16 +36,14 @@ public class {{classname}} {
}{{/hasAuthMethods}}) }{{/hasAuthMethods}})
@ApiResponses(value = { {{#responses}} @ApiResponses(value = { {{#responses}}
@ApiResponse(code = {{{code}}}, message = "{{{message}}}", response = {{{returnType}}}.class){{#hasMore}},{{/hasMore}}{{/responses}} }) @ApiResponse(code = {{{code}}}, message = "{{{message}}}", response = {{{returnType}}}.class){{#hasMore}},{{/hasMore}}{{/responses}} })
@RequestMapping(value = "{{{path}}}", @RequestMapping(value = "{{{path}}}",{{#singleContentTypes}}
{{#hasProduces}}produces = { {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }, {{/hasProduces}} produces = "{{{vendorExtensions.x-accepts}}}",
{{#hasConsumes}}consumes = { {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} },{{/hasConsumes}} consumes = "{{{vendorExtensions.x-contentType}}}",{{/singleContentTypes}}{{^singleContentTypes}}{{#hasProduces}}
produces = { {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }, {{/hasProduces}}{{#hasConsumes}}
consumes = { {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} },{{/hasConsumes}}{{/singleContentTypes}}
method = RequestMethod.{{httpMethod}}) method = RequestMethod.{{httpMethod}})
public ResponseEntity<{{>returnTypes}}> {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, ResponseEntity<{{>returnTypes}}> {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},
{{/hasMore}}{{/allParams}}) {{/hasMore}}{{/allParams}});
throws NotFoundException {
// do some magic!
return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK);
}
{{/operation}} {{/operation}}
} }

View File

@ -0,0 +1,35 @@
package {{apiPackage}};
import {{modelPackage}}.*;
{{#imports}}import {{import}};
{{/imports}}
import io.swagger.annotations.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
@Controller
{{>generatedAnnotation}}
{{#operations}}
public class {{classname}}Controller implements {{classname}} {
{{#operation}}
public ResponseEntity<{{>returnTypes}}> {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},
{{/hasMore}}{{/allParams}}) {
// do some magic!
return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK);
}
{{/operation}}
}
{{/operations}}

View File

@ -1,2 +1 @@
{{#isFormParam}}{{#notFile}} {{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestPart(value="{{paramName}}"{{#required}}, required=true{{/required}}{{^required}}, required=false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}@ApiParam(value = "file detail") @RequestPart("file") MultipartFile {{baseName}}{{/isFile}}{{/isFormParam}}
@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestPart(value="{{paramName}}"{{#required}}, required=true{{/required}}{{^required}}, required=false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}@ApiParam(value = "file detail") @RequestPart("file") MultipartFile {{baseName}}{{/isFile}}{{/isFormParam}}

View File

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

View File

@ -14,7 +14,7 @@
<version>1.3.3.RELEASE</version> <version>1.3.3.RELEASE</version>
</parent> </parent>
<build> <build>
<sourceDirectory>src/main/java</sourceDirectory> <sourceDirectory>src/main/java</sourceDirectory>{{^interfaceOnly}}
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
@ -27,7 +27,7 @@
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
</plugins> </plugins>{{/interfaceOnly}}
</build> </build>
<dependencies> <dependencies>
<dependency> <dependency>
@ -50,5 +50,14 @@
<artifactId>springfox-swagger-ui</artifactId> <artifactId>springfox-swagger-ui</artifactId>
<version>${springfox-version}</version> <version>${springfox-version}</version>
</dependency> </dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -34,6 +34,8 @@ public class SwaggerDocumentationConfig {
.select() .select()
.apis(RequestHandlerSelectors.basePackage("{{apiPackage}}")) .apis(RequestHandlerSelectors.basePackage("{{apiPackage}}"))
.build() .build()
.directModelSubstitute(org.joda.time.LocalDate.class, java.sql.Date.class)
.directModelSubstitute(org.joda.time.DateTime.class, java.util.Date.class)
.apiInfo(apiInfo()); .apiInfo(apiInfo());
} }

View File

@ -0,0 +1,61 @@
package {{apiPackage}};
import {{modelPackage}}.*;
{{#imports}}import {{import}};
{{/imports}}
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.Authorization;
import io.swagger.annotations.AuthorizationScope;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import static org.springframework.http.MediaType.*;
@Controller
@RequestMapping(value = "/{{{baseName}}}", produces = {APPLICATION_JSON_VALUE})
@Api(value = "/{{{baseName}}}", description = "the {{{baseName}}} API")
{{>generatedAnnotation}}
{{#operations}}
public class {{classname}} {
{{#operation}}
@ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}{{#hasAuthMethods}}, authorizations = {
{{#authMethods}}@Authorization(value = "{{name}}"{{#isOAuth}}, scopes = {
{{#scopes}}@AuthorizationScope(scope = "{{scope}}", description = "{{description}}"){{#hasMore}},
{{/hasMore}}{{/scopes}}
}{{/isOAuth}}){{#hasMore}},
{{/hasMore}}{{/authMethods}}
}{{/hasAuthMethods}})
@io.swagger.annotations.ApiResponses(value = { {{#responses}}
@io.swagger.annotations.ApiResponse(code = {{{code}}}, message = "{{{message}}}", response = {{{returnType}}}.class){{#hasMore}},{{/hasMore}}{{/responses}} })
@RequestMapping(value = "{{{path}}}",
{{#hasProduces}}produces = { {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }, {{/hasProduces}}
{{#hasConsumes}}consumes = { {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} },{{/hasConsumes}}
method = RequestMethod.{{httpMethod}})
public ResponseEntity<{{>returnTypes}}> {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},
{{/hasMore}}{{/allParams}})
throws NotFoundException {
// do some magic!
return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK);
}
{{/operation}}
}
{{/operations}}

View File

@ -17,15 +17,28 @@ using RestSharp;
namespace {{packageName}}.Client namespace {{packageName}}.Client
{ {
/// <summary> /// <summary>
/// API client is mainly responible for making the HTTP call to the API backend. /// API client is mainly responsible for making the HTTP call to the API backend.
/// </summary> /// </summary>
public class ApiClient public partial class ApiClient
{ {
private JsonSerializerSettings serializerSettings = new JsonSerializerSettings private JsonSerializerSettings serializerSettings = new JsonSerializerSettings
{ {
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
}; };
/// <summary>
/// Allows for extending request processing for <see cref="ApiClient"/> generated code.
/// </summary>
/// <param name="request">The RestSharp request object</param>
partial void InterceptRequest(IRestRequest request);
/// <summary>
/// Allows for extending response processing for <see cref="ApiClient"/> generated code.
/// </summary>
/// <param name="request">The RestSharp request object</param>
/// <param name="response">The RestSharp response object</param>
partial void InterceptResponse(IRestRequest request, IRestResponse response);
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="ApiClient" /> class /// Initializes a new instance of the <see cref="ApiClient" /> class
/// with default configuration and base path ({{basePath}}). /// with default configuration and base path ({{basePath}}).
@ -165,6 +178,7 @@ namespace {{packageName}}.Client
// set user agent // set user agent
RestClient.UserAgent = Configuration.UserAgent; RestClient.UserAgent = Configuration.UserAgent;
InterceptRequest(request);
{{^supportsUWP}} {{^supportsUWP}}
var response = RestClient.Execute(request); var response = RestClient.Execute(request);
{{/supportsUWP}} {{/supportsUWP}}
@ -172,6 +186,8 @@ namespace {{packageName}}.Client
// Using async method to perform sync call (uwp-only) // Using async method to perform sync call (uwp-only)
var response = RestClient.ExecuteTaskAsync(request).Result; var response = RestClient.ExecuteTaskAsync(request).Result;
{{/supportsUWP}} {{/supportsUWP}}
InterceptResponse(request, response);
return (Object) response; return (Object) response;
} }
{{#supportsAsync}} {{#supportsAsync}}
@ -197,7 +213,9 @@ namespace {{packageName}}.Client
var request = PrepareRequest( var request = PrepareRequest(
path, method, queryParams, postBody, headerParams, formParams, fileParams, path, method, queryParams, postBody, headerParams, formParams, fileParams,
pathParams, contentType); pathParams, contentType);
InterceptRequest(request);
var response = await RestClient.ExecuteTaskAsync(request); var response = await RestClient.ExecuteTaskAsync(request);
InterceptResponse(request, response);
return (Object)response; return (Object)response;
}{{/supportsAsync}} }{{/supportsAsync}}

View File

@ -80,6 +80,17 @@ namespace {{packageName}}.Client
/// <value>Configuration.</value> /// <value>Configuration.</value>
public static Configuration Default = new Configuration(); public static Configuration Default = new Configuration();
/// <summary>
/// Default creation of exceptions for a given method name and response object
/// </summary>
public static readonly ExceptionFactory DefaultExceptionFactory = (methodName, response) =>
{
int status = (int) response.StatusCode;
if (status >= 400) return new ApiException(status, String.Format("Error calling {0}: {1}", methodName, response.Content), response.Content);
if (status == 0) return new ApiException(status, String.Format("Error calling {0}: {1}", methodName, response.ErrorMessage), response.ErrorMessage);
return null;
};
/// <summary> /// <summary>
/// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds. /// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds.
/// </summary> /// </summary>

View File

@ -0,0 +1,15 @@
{{>partial_header}}
using System;
using RestSharp;
namespace {{packageName}}.Client
{
/// <summary>
/// A delegate to ExceptionFactory method
/// </summary>
/// <param name="methodName">Method name</param>
/// <param name="response">Response</param>
/// <returns>Exceptions</returns>
public delegate Exception ExceptionFactory(string methodName, IRestResponse response);
}

View File

@ -24,5 +24,10 @@ namespace {{packageName}}.Client
/// </summary> /// </summary>
/// <value>The base path</value> /// <value>The base path</value>
String GetBasePath(); String GetBasePath();
/// <summary>
/// Provides a factory method hook for the creation of exceptions.
/// </summary>
ExceptionFactory ExceptionFactory { get; set; }
} }
} }

View File

@ -71,10 +71,10 @@ limitations under the License.
<Reference Include="System.Runtime.Serialization" /> <Reference Include="System.Runtime.Serialization" />
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
<Reference Include="Newtonsoft.Json"> <Reference Include="Newtonsoft.Json">
<HintPath Condition="Exists('$(SolutionDir)\packages')">$(SolutionDir)\packages\Newtonsoft.Json.8.0.2\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll</HintPath> <HintPath Condition="Exists('$(SolutionDir)\packages')">$(SolutionDir)\packages\Newtonsoft.Json.8.0.3\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll</HintPath>
<HintPath Condition="Exists('..\packages')">..\packages\Newtonsoft.Json.8.0.2\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll</HintPath> <HintPath Condition="Exists('..\packages')">..\packages\Newtonsoft.Json.8.0.3\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll</HintPath>
<HintPath Condition="Exists('..\..\packages')">..\..\packages\Newtonsoft.Json.8.0.2\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll</HintPath> <HintPath Condition="Exists('..\..\packages')">..\..\packages\Newtonsoft.Json.8.0.3\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll</HintPath>
<HintPath Condition="Exists('{{binRelativePath}}')">{{binRelativePath}}\Newtonsoft.Json.8.0.2\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll</HintPath> <HintPath Condition="Exists('{{binRelativePath}}')">{{binRelativePath}}\Newtonsoft.Json.8.0.3\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll</HintPath>
</Reference> </Reference>
<Reference Include="RestSharp"> <Reference Include="RestSharp">
<HintPath Condition="Exists('$(SolutionDir)\packages')">$(SolutionDir)\packages\RestSharp.105.1.0\lib\{{targetFrameworkNuget}}\RestSharp.dll</HintPath> <HintPath Condition="Exists('$(SolutionDir)\packages')">$(SolutionDir)\packages\RestSharp.105.1.0\lib\{{targetFrameworkNuget}}\RestSharp.dll</HintPath>

View File

@ -71,10 +71,10 @@ limitations under the License.
<Reference Include="System.Runtime.Serialization" /> <Reference Include="System.Runtime.Serialization" />
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
<Reference Include="Newtonsoft.Json"> <Reference Include="Newtonsoft.Json">
<HintPath Condition="Exists('$(SolutionDir)\packages')">$(SolutionDir)\packages\Newtonsoft.Json.8.0.2\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll</HintPath> <HintPath Condition="Exists('$(SolutionDir)\packages')">$(SolutionDir)\packages\Newtonsoft.Json.8.0.3\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll</HintPath>
<HintPath Condition="Exists('..\packages')">..\packages\Newtonsoft.Json.8.0.2\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll</HintPath> <HintPath Condition="Exists('..\packages')">..\packages\Newtonsoft.Json.8.0.3\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll</HintPath>
<HintPath Condition="Exists('..\..\packages')">..\..\packages\Newtonsoft.Json.8.0.2\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll</HintPath> <HintPath Condition="Exists('..\..\packages')">..\..\packages\Newtonsoft.Json.8.0.3\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll</HintPath>
<HintPath Condition="Exists('{{binRelativePath}}')">{{binRelativePath}}\Newtonsoft.Json.8.0.2\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll</HintPath> <HintPath Condition="Exists('{{binRelativePath}}')">{{binRelativePath}}\Newtonsoft.Json.8.0.3\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll</HintPath>
</Reference> </Reference>
<Reference Include="RestSharp"> <Reference Include="RestSharp">
<HintPath Condition="Exists('$(SolutionDir)\packages')">$(SolutionDir)\packages\RestSharp.105.1.0\lib\{{targetFrameworkNuget}}\RestSharp.dll</HintPath> <HintPath Condition="Exists('$(SolutionDir)\packages')">$(SolutionDir)\packages\RestSharp.105.1.0\lib\{{targetFrameworkNuget}}\RestSharp.dll</HintPath>
@ -83,10 +83,10 @@ limitations under the License.
<HintPath Condition="Exists('{{binRelativePath}}')">{{binRelativePath}}\RestSharp.105.1.0\lib\{{targetFrameworkNuget}}\RestSharp.dll</HintPath> <HintPath Condition="Exists('{{binRelativePath}}')">{{binRelativePath}}\RestSharp.105.1.0\lib\{{targetFrameworkNuget}}\RestSharp.dll</HintPath>
</Reference> </Reference>
<Reference Include="nunit.framework"> <Reference Include="nunit.framework">
<HintPath Condition="Exists('$(SolutionDir)\packages')">$(SolutionDir)\packages\NUnit.2.6.3\lib\nunit.framework.dll</HintPath> <HintPath Condition="Exists('$(SolutionDir)\packages')">$(SolutionDir)\packages\NUnit.3.2.1\lib\nunit.framework.dll</HintPath>
<HintPath Condition="Exists('..\packages')">..\packages\NUnit.2.6.3\lib\nunit.framework.dll</HintPath> <HintPath Condition="Exists('..\packages')">..\packages\NUnit.3.2.1\lib\nunit.framework.dll</HintPath>
<HintPath Condition="Exists('..\..\packages')">..\..\packages\NUnit.2.6.3\lib\nunit.framework.dll</HintPath> <HintPath Condition="Exists('..\..\packages')">..\..\packages\NUnit.3.2.1\lib\nunit.framework.dll</HintPath>
<HintPath Condition="Exists('{{binRelativePath}}')">{{binRelativePath}}\NUnit.2.6.3\lib\nunit.framework.dll</HintPath> <HintPath Condition="Exists('{{binRelativePath}}')">{{binRelativePath}}\NUnit.3.2.1\lib\nunit.framework.dll</HintPath>
</Reference> </Reference>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@ -75,6 +75,8 @@ namespace {{packageName}}.Api
/// </summary> /// </summary>
public partial class {{classname}} : I{{classname}} public partial class {{classname}} : I{{classname}}
{ {
private {{packageName}}.Client.ExceptionFactory _exceptionFactory = (name, response) => null;
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="{{classname}}"/> class. /// Initializes a new instance of the <see cref="{{classname}}"/> class.
/// </summary> /// </summary>
@ -83,6 +85,8 @@ namespace {{packageName}}.Api
{ {
this.Configuration = new Configuration(new ApiClient(basePath)); this.Configuration = new Configuration(new ApiClient(basePath));
ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready // ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null) if (Configuration.ApiClient.Configuration == null)
{ {
@ -103,6 +107,8 @@ namespace {{packageName}}.Api
else else
this.Configuration = configuration; this.Configuration = configuration;
ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready // ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null) if (Configuration.ApiClient.Configuration == null)
{ {
@ -135,6 +141,22 @@ namespace {{packageName}}.Api
/// <value>An instance of the Configuration</value> /// <value>An instance of the Configuration</value>
public Configuration Configuration {get; set;} public Configuration Configuration {get; set;}
/// <summary>
/// Provides a factory method hook for the creation of exceptions.
/// </summary>
public {{packageName}}.Client.ExceptionFactory ExceptionFactory
{
get
{
if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1)
{
throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported.");
}
return _exceptionFactory;
}
set { _exceptionFactory = value; }
}
/// <summary> /// <summary>
/// Gets the default header. /// Gets the default header.
/// </summary> /// </summary>
@ -276,10 +298,11 @@ namespace {{packageName}}.Api
int localVarStatusCode = (int) localVarResponse.StatusCode; int localVarStatusCode = (int) localVarResponse.StatusCode;
if (localVarStatusCode >= 400) if (ExceptionFactory != null)
throw new ApiException (localVarStatusCode, "Error calling {{operationId}}: " + localVarResponse.Content, localVarResponse.Content); {
else if (localVarStatusCode == 0) Exception exception = ExceptionFactory("{{operationId}}", localVarResponse);
throw new ApiException (localVarStatusCode, "Error calling {{operationId}}: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); if (exception != null) throw exception;
}
{{#returnType}}return new ApiResponse<{{{returnType}}}>(localVarStatusCode, {{#returnType}}return new ApiResponse<{{{returnType}}}>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
@ -410,10 +433,11 @@ namespace {{packageName}}.Api
int localVarStatusCode = (int) localVarResponse.StatusCode; int localVarStatusCode = (int) localVarResponse.StatusCode;
if (localVarStatusCode >= 400) if (ExceptionFactory != null)
throw new ApiException (localVarStatusCode, "Error calling {{operationId}}: " + localVarResponse.Content, localVarResponse.Content); {
else if (localVarStatusCode == 0) Exception exception = ExceptionFactory("{{operationId}}", localVarResponse);
throw new ApiException (localVarStatusCode, "Error calling {{operationId}}: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); if (exception != null) throw exception;
}
{{#returnType}}return new ApiResponse<{{{returnType}}}>(localVarStatusCode, {{#returnType}}return new ApiResponse<{{{returnType}}}>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),

View File

@ -51,7 +51,8 @@ namespace {{packageName}}.Test
[Test] [Test]
public void {{operationId}}InstanceTest() public void {{operationId}}InstanceTest()
{ {
Assert.IsInstanceOf<{{classname}}> (instance, "instance is a {{classname}}"); // test 'IsInstanceOfType' {{classname}}
Assert.IsInstanceOfType(typeof({{classname}}), instance, "instance is a {{classname}}");
} }
{{#operations}}{{#operation}} {{#operations}}{{#operation}}
@ -61,12 +62,12 @@ namespace {{packageName}}.Test
[Test] [Test]
public void {{operationId}}Test() public void {{operationId}}Test()
{ {
// TODO: add unit test for the method '{{operationId}}' // TODO uncomment below to test the method and replace null with proper value
{{#allParams}} {{#allParams}}
{{{dataType}}} {{paramName}} = null; // TODO: replace null with proper value //{{{dataType}}} {{paramName}} = null;
{{/allParams}} {{/allParams}}
{{#returnType}}var response = {{/returnType}}instance.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); //{{#returnType}}var response = {{/returnType}}instance.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
{{#returnType}}Assert.IsInstanceOf<{{{returnType}}}> (response, "response is {{{returnType}}}");{{/returnType}} {{#returnType}}//Assert.IsInstanceOf<{{{returnType}}}> (response, "response is {{{returnType}}}");{{/returnType}}
} }
{{/operation}}{{/operations}} {{/operation}}{{/operations}}
} }

View File

@ -1,15 +1,35 @@
#!/usr/bin/env bash #!/usr/bin/env bash
#
# Generated by: https://github.com/swagger-api/swagger-codegen.git
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
frameworkVersion={{targetFrameworkNuget}} frameworkVersion={{targetFrameworkNuget}}
netfx=${frameworkVersion#net} netfx=${frameworkVersion#net}
echo "[INFO] Target framework: ${frameworkVersion}"
echo "[INFO] Download nuget and packages"
wget -nc https://nuget.org/nuget.exe; wget -nc https://nuget.org/nuget.exe;
mozroots --import --sync mozroots --import --sync
mono nuget.exe install src/{{packageName}}/packages.config -o packages; mono nuget.exe install src/{{packageName}}/packages.config -o packages;
mkdir -p bin;
cp packages/Newtonsoft.Json.8.0.2/lib/{{targetFrameworkNuget}}/Newtonsoft.Json.dll bin/Newtonsoft.Json.dll; echo "[INFO] Copy DLLs to the 'bin' folder"
mkdir -p bin;
cp packages/Newtonsoft.Json.8.0.3/lib/{{targetFrameworkNuget}}/Newtonsoft.Json.dll bin/Newtonsoft.Json.dll;
cp packages/RestSharp.105.1.0/lib/{{targetFrameworkNuget}}/RestSharp.dll bin/RestSharp.dll; cp packages/RestSharp.105.1.0/lib/{{targetFrameworkNuget}}/RestSharp.dll bin/RestSharp.dll;
echo "[INFO] Run 'mcs' to build bin/{{{packageName}}}.dll"
mcs -sdk:${netfx} -r:bin/Newtonsoft.Json.dll,\ mcs -sdk:${netfx} -r:bin/Newtonsoft.Json.dll,\
bin/RestSharp.dll,\ bin/RestSharp.dll,\
System.Runtime.Serialization.dll \ System.Runtime.Serialization.dll \
@ -18,3 +38,11 @@ System.Runtime.Serialization.dll \
-recurse:'src/{{packageName}}/*.cs' \ -recurse:'src/{{packageName}}/*.cs' \
-doc:bin/{{packageName}}.xml \ -doc:bin/{{packageName}}.xml \
-platform:anycpu -platform:anycpu
if [ $? -ne 0 ]
then
echo "[ERROR] Compilation failed with exit code $?"
exit 1
else
echo "[INFO] bin/{{{packageName}}}.dll was created successfully"
fi

View File

@ -1,3 +1,17 @@
:: Generated by: https://github.com/swagger-api/swagger-codegen.git
::
:: Licensed under the Apache License, Version 2.0 (the "License");
:: you may not use this file except in compliance with the License.
:: You may obtain a copy of the License at
::
:: http://www.apache.org/licenses/LICENSE-2.0
::
:: Unless required by applicable law or agreed to in writing, software
:: distributed under the License is distributed on an "AS IS" BASIS,
:: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
:: See the License for the specific language governing permissions and
:: limitations under the License.
@echo off @echo off
{{#supportsAsync}}SET CSCPATH=%SYSTEMROOT%\Microsoft.NET\Framework\v4.0.30319{{/supportsAsync}} {{#supportsAsync}}SET CSCPATH=%SYSTEMROOT%\Microsoft.NET\Framework\v4.0.30319{{/supportsAsync}}
@ -8,7 +22,7 @@ if not exist ".\nuget.exe" powershell -Command "(new-object System.Net.WebClient
if not exist ".\bin" mkdir bin if not exist ".\bin" mkdir bin
copy packages\Newtonsoft.Json.8.0.2\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll bin\Newtonsoft.Json.dll copy packages\Newtonsoft.Json.8.0.3\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll bin\Newtonsoft.Json.dll
copy packages\RestSharp.105.1.0\lib\{{targetFrameworkNuget}}\RestSharp.dll bin\RestSharp.dll copy packages\RestSharp.105.1.0\lib\{{targetFrameworkNuget}}\RestSharp.dll bin\RestSharp.dll
%CSCPATH%\csc /reference:bin\Newtonsoft.Json.dll;bin\RestSharp.dll /target:library /out:bin\{{packageName}}.dll /recurse:src\{{packageName}}\*.cs /doc:bin\{{packageName}}.xml %CSCPATH%\csc /reference:bin\Newtonsoft.Json.dll;bin\RestSharp.dll /target:library /out:bin\{{packageName}}.dll /recurse:src\{{packageName}}\*.cs /doc:bin\{{packageName}}.xml

View File

@ -25,7 +25,8 @@ namespace {{packageName}}.Test
[TestFixture] [TestFixture]
public class {{classname}}Tests public class {{classname}}Tests
{ {
private {{classname}} instance; // TODO uncomment below to declare an instance variable for {{classname}}
//private {{classname}} instance;
/// <summary> /// <summary>
/// Setup before each test /// Setup before each test
@ -33,7 +34,8 @@ namespace {{packageName}}.Test
[SetUp] [SetUp]
public void Init() public void Init()
{ {
instance = new {{classname}}(); // TODO uncomment below to create an instance of {{classname}}
//instance = new {{classname}}();
} }
/// <summary> /// <summary>
@ -51,7 +53,8 @@ namespace {{packageName}}.Test
[Test] [Test]
public void {{classname}}InstanceTest() public void {{classname}}InstanceTest()
{ {
Assert.IsInstanceOf<{{classname}}> (instance, "instance is a {{classname}}"); // TODO uncomment below to test "IsInstanceOfType" {{classname}}
//Assert.IsInstanceOfType<{{classname}}> (instance, "variable 'instance' is a {{classname}}");
} }
{{#vars}} {{#vars}}
@ -61,7 +64,7 @@ namespace {{packageName}}.Test
[Test] [Test]
public void {{name}}Test() public void {{name}}Test()
{ {
// TODO: unit test for the property '{{name}}' // TODO unit test for the property '{{name}}'
} }
{{/vars}} {{/vars}}

View File

@ -0,0 +1,33 @@
#!/usr/bin/env bash
#
# Generated by: https://github.com/swagger-api/swagger-codegen.git
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
wget -nc https://nuget.org/nuget.exe
mozroots --import --sync
echo "[INFO] remove bin/Debug/SwaggerClientTest.dll"
rm src/IO.Swagger.Test/bin/Debug/{{{packageName}}}.Test.dll 2> /dev/null
echo "[INFO] install NUnit runners via NuGet"
wget -nc https://nuget.org/nuget.exe
mozroots --import --sync
mono nuget.exe install src/{{{packageName}}}.Test/packages.config -o packages
echo "[INFO] Install NUnit runners via NuGet"
mono nuget.exe install NUnit.Runners -Version 3.2.1 -OutputDirectory packages
echo "[INFO] Build the solution and run the unit test"
xbuild {{{packageName}}}.sln && \
mono ./packages/NUnit.ConsoleRunner.3.2.1/tools/nunit3-console.exe src/{{{packageName}}}.Test/bin/Debug/{{{packageName}}}.Test.dll

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<packages> <packages>
<package id="RestSharp" version="105.1.0" targetFramework="{{targetFrameworkNuget}}" developmentDependency="true" /> <package id="RestSharp" version="105.1.0" targetFramework="{{targetFrameworkNuget}}" developmentDependency="true" />
<package id="Newtonsoft.Json" version="8.0.2" targetFramework="{{targetFrameworkNuget}}" developmentDependency="true" /> <package id="Newtonsoft.Json" version="8.0.3" targetFramework="{{targetFrameworkNuget}}" developmentDependency="true" />
</packages> </packages>

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<packages> <packages>
<package id="NUnit" version="2.6.3" targetFramework="{{targetFrameworkNuget}}" /> <package id="NUnit" version="3.2.1" targetFramework="{{targetFrameworkNuget}}" />
<package id="RestSharp" version="105.1.0" targetFramework="{{targetFrameworkNuget}}" developmentDependency="true" /> <package id="RestSharp" version="105.1.0" targetFramework="{{targetFrameworkNuget}}" developmentDependency="true" />
<package id="Newtonsoft.Json" version="8.0.2" targetFramework="{{targetFrameworkNuget}}" developmentDependency="true" /> <package id="Newtonsoft.Json" version="8.0.3" targetFramework="{{targetFrameworkNuget}}" developmentDependency="true" />
</packages> </packages>

View File

@ -0,0 +1,21 @@
#
# Generated by: https://github.com/swagger-api/swagger-codegen.git
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
language: csharp
mono:
- latest
solution: {{{packageName}}}.sln
script:
- /bin/sh ./mono_nunit_test.sh

View File

@ -265,6 +265,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
self.requestSerializer = [AFHTTPRequestSerializer serializer]; self.requestSerializer = [AFHTTPRequestSerializer serializer];
} }
else { else {
self.requestSerializer = [AFHTTPRequestSerializer serializer];
NSAssert(NO, @"Unsupported request type %@", requestContentType); NSAssert(NO, @"Unsupported request type %@", requestContentType);
} }
@ -280,7 +281,9 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
queryParams = [self.sanitizer sanitizeForSerialization:queryParams]; queryParams = [self.sanitizer sanitizeForSerialization:queryParams];
headerParams = [self.sanitizer sanitizeForSerialization:headerParams]; headerParams = [self.sanitizer sanitizeForSerialization:headerParams];
formParams = [self.sanitizer sanitizeForSerialization:formParams]; formParams = [self.sanitizer sanitizeForSerialization:formParams];
if(![body isKindOfClass:[NSData class]]) {
body = [self.sanitizer sanitizeForSerialization:body]; body = [self.sanitizer sanitizeForSerialization:body];
}
// auth setting // auth setting
[self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings]; [self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings];

View File

@ -17,19 +17,21 @@
withParameters:(id)parameters withParameters:(id)parameters
error:(NSError *__autoreleasing *)error error:(NSError *__autoreleasing *)error
{ {
if (!parameters) {
return request;
}
// If the body data which will be serialized isn't NSArray or NSDictionary // If the body data which will be serialized isn't NSArray or NSDictionary
// then put the data in the http request body directly. // then put the data in the http request body directly.
if ([parameters isKindOfClass:[NSArray class]] || [parameters isKindOfClass:[NSDictionary class]]) { if ([parameters isKindOfClass:[NSArray class]] || [parameters isKindOfClass:[NSDictionary class]]) {
return [super requestBySerializingRequest:request withParameters:parameters error:error]; return [super requestBySerializingRequest:request withParameters:parameters error:error];
} else { }
NSMutableURLRequest *mutableRequest = [request mutableCopy]; NSMutableURLRequest *mutableRequest = [request mutableCopy];
if([parameters isKindOfClass:[NSData class]]) {
if (parameters) { [mutableRequest setHTTPBody:parameters];
} else {
[mutableRequest setHTTPBody:[parameters dataUsingEncoding:self.stringEncoding]]; [mutableRequest setHTTPBody:[parameters dataUsingEncoding:self.stringEncoding]];
} }
return mutableRequest; return mutableRequest;
}
} }
@end @end

View File

@ -1,3 +1,9 @@
{{>partial_license}}
#
# NOTE: This class is auto generated by the swagger code generator program.
# Do not edit the class manually.
# Ref: https://github.com/swagger-api/swagger-codegen
#
package {{moduleName}}::ApiClient; package {{moduleName}}::ApiClient;
use strict; use strict;

View File

@ -1,3 +1,9 @@
{{>partial_license}}
#
# NOTE: This class is auto generated by the swagger code generator program.
# Do not edit the class manually.
# Ref: https://github.com/swagger-api/swagger-codegen
#
package {{moduleName}}::ApiFactory; package {{moduleName}}::ApiFactory;
use strict; use strict;

View File

@ -1,3 +1,9 @@
{{>partial_license}}
#
# NOTE: This class is auto generated by the swagger code generator program.
# Do not edit the class manually.
# Ref: https://github.com/swagger-api/swagger-codegen
#
package {{moduleName}}::Role::AutoDoc; package {{moduleName}}::Role::AutoDoc;
use List::MoreUtils qw(uniq); use List::MoreUtils qw(uniq);

View File

@ -1,3 +1,9 @@
{{>partial_license}}
#
# NOTE: This class is auto generated by the swagger code generator program.
# Do not edit the class manually.
# Ref: https://github.com/swagger-api/swagger-codegen
#
__PACKAGE__->mk_classdata('attribute_map' => {}); __PACKAGE__->mk_classdata('attribute_map' => {});
__PACKAGE__->mk_classdata('swagger_types' => {}); __PACKAGE__->mk_classdata('swagger_types' => {});
__PACKAGE__->mk_classdata('method_documentation' => {}); __PACKAGE__->mk_classdata('method_documentation' => {});

View File

@ -1,3 +1,9 @@
{{>partial_license}}
#
# NOTE: This class is auto generated by the swagger code generator program.
# Do not edit the class manually.
# Ref: https://github.com/swagger-api/swagger-codegen
#
package {{moduleName}}::Configuration; package {{moduleName}}::Configuration;
use strict; use strict;

View File

@ -1,3 +1,9 @@
{{>partial_license}}
#
# NOTE: This class is auto generated by the swagger code generator program.
# Do not edit the class manually.
# Ref: https://github.com/swagger-api/swagger-codegen
#
package {{moduleName}}::Role; package {{moduleName}}::Role;
use utf8; use utf8;

View File

@ -1,21 +1,8 @@
# {{>partial_license}}
# Copyright 2016 SmartBear Software
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# #
# NOTE: This class is auto generated by the swagger code generator program. # NOTE: This class is auto generated by the swagger code generator program.
# Do not edit the class manually. # Do not edit the class manually.
# Ref: https://github.com/swagger-api/swagger-codegen
# #
package {{moduleName}}::{{classname}}; package {{moduleName}}::{{classname}};

View File

@ -1,21 +1,8 @@
# {{>partial_license}}
# Copyright 2016 SmartBear Software
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# #
# NOTE: This class is auto generated by Swagger Codegen # NOTE: This class is auto generated by Swagger Codegen
# Please update the test case below to test the API endpoints. # Please update the test cases below to test the API endpoints.
# Ref: https://github.com/swagger-api/swagger-codegen
# #
use Test::More tests => 1; #TODO update number of test cases use Test::More tests => 1; #TODO update number of test cases
use Test::Exception; use Test::Exception;

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