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,28 +72,20 @@ 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 library = config.getLibrary();
if (library != null && !"".equals(library)) {
String libTemplateFile = config.templateDir() + File.separator +
"libraries" + File.separator + library + File.separator +
templateFile;
if (new File(libTemplateFile).exists()) {
return libTemplateFile;
}
libTemplateFile = config.embeddedTemplateDir() + File.separator +
"libraries" + File.separator + library + File.separator +
templateFile;
if (embeddedTemplateExists(libTemplateFile)) {
// Fall back to the template file embedded/packaged in the JAR file...
return libTemplateFile;
}
}
String template = config.templateDir() + File.separator + templateFile; String template = config.templateDir() + File.separator + templateFile;
if (new File(template).exists()) { if (new File(template).exists()) {
return template; return template;
} else { } else {
String library = config.getLibrary();
if (library != null && !"".equals(library)) {
String libTemplateFile = config.embeddedTemplateDir() + File.separator +
"libraries" + File.separator + library + File.separator +
templateFile;
if (embeddedTemplateExists(libTemplateFile)) {
// Fall back to the template file embedded/packaged in the JAR file...
return libTemplateFile;
}
}
// Fall back to the template file embedded/packaged in the JAR file... // 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,30 +84,37 @@ 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"));
supportingFiles.add(new SupportingFile("apiException.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java"));
supportingFiles.add(new SupportingFile("apiOriginFilter.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiOriginFilter.java"));
supportingFiles.add(new SupportingFile("apiResponseMessage.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java"));
supportingFiles.add(new SupportingFile("notFoundException.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java"));
supportingFiles.add(new SupportingFile("swaggerDocumentationConfig.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerDocumentationConfig.java"));
supportingFiles.add(new SupportingFile("homeController.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "HomeController.java"));
supportingFiles.add(new SupportingFile("swagger2SpringBoot.mustache",
(sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator), "Swagger2SpringBoot.java"));
supportingFiles.add(new SupportingFile("application.properties",
("src.main.resources").replace(".", java.io.File.separator), "application.properties"));
if(!this.interfaceOnly) {
apiTemplateFiles.put("apiController.mustache", "Controller.java");
supportingFiles.add(new SupportingFile("apiException.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java"));
supportingFiles.add(new SupportingFile("apiOriginFilter.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiOriginFilter.java"));
supportingFiles.add(new SupportingFile("apiResponseMessage.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java"));
supportingFiles.add(new SupportingFile("notFoundException.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java"));
supportingFiles.add(new SupportingFile("swaggerDocumentationConfig.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerDocumentationConfig.java"));
supportingFiles.add(new SupportingFile("homeController.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "HomeController.java"));
supportingFiles.add(new SupportingFile("swagger2SpringBoot.mustache",
(sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator), "Swagger2SpringBoot.java"));
supportingFiles.add(new SupportingFile("application.properties",
("src.main.resources").replace(".", java.io.File.separator), "application.properties"));
}
} }
@Override @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,22 +1,28 @@
{{>licenseInfo}}
package {{invokerPackage}}; package {{invokerPackage}};
{{>generatedAnnotation}} {{>generatedAnnotation}}
public class Configuration { public class Configuration {
private static ApiClient defaultApiClient = new ApiClient(); private static ApiClient defaultApiClient = new ApiClient();
/** /**
* Get the default API client, which would be used when creating API * Get the default API client, which would be used when creating API
* instances without providing an API client. * instances without providing an API client.
*/ *
public static ApiClient getDefaultApiClient() { * @return Default API client
return defaultApiClient; */
} public static ApiClient getDefaultApiClient() {
return defaultApiClient;
}
/** /**
* 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.
*/ *
public static void setDefaultApiClient(ApiClient apiClient) { * @param apiClient API client
defaultApiClient = apiClient; */
} public static void setDefaultApiClient(ApiClient 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;
@ -5,65 +7,74 @@ import java.util.List;
{{>generatedAnnotation}} {{>generatedAnnotation}}
public class ApiException extends Exception { public class ApiException extends Exception {
private int code = 0; private int code = 0;
private Map<String, List<String>> responseHeaders = null; private Map<String, List<String>> responseHeaders = null;
private String responseBody = null; private String responseBody = null;
public ApiException() {} public ApiException() {}
public ApiException(Throwable throwable) { public ApiException(Throwable throwable) {
super(throwable); super(throwable);
} }
public ApiException(String message) { public ApiException(String message) {
super(message); super(message);
} }
public ApiException(String message, Throwable throwable, int code, Map<String, List<String>> responseHeaders, String responseBody) { public ApiException(String message, Throwable throwable, int code, Map<String, List<String>> responseHeaders, String responseBody) {
super(message, throwable); super(message, throwable);
this.code = code; this.code = code;
this.responseHeaders = responseHeaders; this.responseHeaders = responseHeaders;
this.responseBody = responseBody; this.responseBody = responseBody;
} }
public ApiException(String message, int code, Map<String, List<String>> responseHeaders, String responseBody) { public ApiException(String message, int code, Map<String, List<String>> responseHeaders, String responseBody) {
this(message, (Throwable) null, code, responseHeaders, responseBody); this(message, (Throwable) null, code, responseHeaders, responseBody);
} }
public ApiException(String message, Throwable throwable, int code, Map<String, List<String>> responseHeaders) { public ApiException(String message, Throwable throwable, int code, Map<String, List<String>> responseHeaders) {
this(message, throwable, code, responseHeaders, null); this(message, throwable, code, responseHeaders, null);
} }
public ApiException(int code, Map<String, List<String>> responseHeaders, String responseBody) { public ApiException(int code, Map<String, List<String>> responseHeaders, String responseBody) {
this((String) null, (Throwable) null, code, responseHeaders, responseBody); this((String) null, (Throwable) null, code, responseHeaders, responseBody);
} }
public ApiException(int code, String message) { public ApiException(int code, String message) {
super(message); super(message);
this.code = code; this.code = code;
} }
public ApiException(int code, String message, Map<String, List<String>> responseHeaders, String responseBody) { public ApiException(int code, String message, Map<String, List<String>> responseHeaders, String responseBody) {
this(code, message); this(code, message);
this.responseHeaders = responseHeaders; this.responseHeaders = responseHeaders;
this.responseBody = responseBody; this.responseBody = responseBody;
} }
public int getCode() { /**
return code; * Get the HTTP status code.
} *
* @return HTTP status code
*/
public int getCode() {
return code;
}
/** /**
* Get the HTTP response headers. * Get the HTTP response headers.
*/ *
public Map<String, List<String>> getResponseHeaders() { * @return A map of list of string
return responseHeaders; */
} public Map<String, List<String>> getResponseHeaders() {
return responseHeaders;
}
/** /**
* Get the HTTP response body. * Get the HTTP response body.
*/ *
public String getResponseBody() { * @return Response body in the form of string
return responseBody; */
} public String getResponseBody() {
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. */ /**
void applyToParams(List<Pair> queryParams, Map<String, String> headerParams); * Apply authentication settings to header and query params.
*
* @param queryParams List of query parameters
* @param headerParams Map of header parameters
*/
void applyToParams(List<Pair> queryParams, Map<String, String> headerParams);
} }

View File

@ -1,3 +1,5 @@
{{>licenseInfo}}
package {{invokerPackage}}.auth; 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;
@ -11,39 +13,39 @@ import java.util.List;
* @param <T> The return type * @param <T> The return type
*/ */
public interface ApiCallback<T> { public interface ApiCallback<T> {
/** /**
* This is called when the API call fails. * This is called when the API call fails.
* *
* @param e The exception causing the failure * @param e The exception causing the failure
* @param statusCode Status code of the response if available, otherwise it would be 0 * @param statusCode Status code of the response if available, otherwise it would be 0
* @param responseHeaders Headers of the response if available, otherwise it would be null * @param responseHeaders Headers of the response if available, otherwise it would be null
*/ */
void onFailure(ApiException e, int statusCode, Map<String, List<String>> responseHeaders); void onFailure(ApiException e, int statusCode, Map<String, List<String>> responseHeaders);
/** /**
* This is called when the API call succeeded. * This is called when the API call succeeded.
* *
* @param result The result deserialized from response * @param result The result deserialized from response
* @param statusCode Status code of the response * @param statusCode Status code of the response
* @param responseHeaders Headers of the response * @param responseHeaders Headers of the response
*/ */
void onSuccess(T result, int statusCode, Map<String, List<String>> responseHeaders); void onSuccess(T result, int statusCode, Map<String, List<String>> responseHeaders);
/** /**
* This is called when the API upload processing. * This is called when the API upload processing.
* *
* @param bytesWritten bytes Written * @param bytesWritten bytes Written
* @param contentLength content length of request body * @param contentLength content length of request body
* @param done write end * @param done write end
*/ */
void onUploadProgress(long bytesWritten, long contentLength, boolean done); void onUploadProgress(long bytesWritten, long contentLength, boolean done);
/** /**
* This is called when the API downlond processing. * This is called when the API downlond processing.
* *
* @param bytesRead bytes Read * @param bytesRead bytes Read
* @param contentLength content lenngth of the response * @param contentLength content lenngth of the response
* @param done Read end * @param done Read end
*/ */
void onDownloadProgress(long bytesRead, long contentLength, boolean done); void onDownloadProgress(long bytesRead, long contentLength, boolean done);
} }

View File

@ -1,3 +1,5 @@
{{>licenseInfo}}
package {{invokerPackage}}; package {{invokerPackage}};
import java.util.List; import java.util.List;
@ -9,38 +11,38 @@ import java.util.Map;
* @param T The type of data that is deserialized from response body * @param T The type of data that is deserialized from response body
*/ */
public class ApiResponse<T> { public class ApiResponse<T> {
final private int statusCode; final private int statusCode;
final private Map<String, List<String>> headers; final private Map<String, List<String>> headers;
final private T data; final private T data;
/** /**
* @param statusCode The status code of HTTP response * @param statusCode The status code of HTTP response
* @param headers The headers of HTTP response * @param headers The headers of HTTP response
*/ */
public ApiResponse(int statusCode, Map<String, List<String>> headers) { public ApiResponse(int statusCode, Map<String, List<String>> headers) {
this(statusCode, headers, null); this(statusCode, headers, null);
} }
/** /**
* @param statusCode The status code of HTTP response * @param statusCode The status code of HTTP response
* @param headers The headers of HTTP response * @param headers The headers of HTTP response
* @param data The object deserialized from response bod * @param data The object deserialized from response bod
*/ */
public ApiResponse(int statusCode, Map<String, List<String>> headers, T data) { public ApiResponse(int statusCode, Map<String, List<String>> headers, T data) {
this.statusCode = statusCode; this.statusCode = statusCode;
this.headers = headers; this.headers = headers;
this.data = data; this.data = data;
} }
public int getStatusCode() { public int getStatusCode() {
return statusCode; return statusCode;
} }
public Map<String, List<String>> getHeaders() { public Map<String, List<String>> getHeaders() {
return headers; return headers;
} }
public T getData() { public T getData() {
return data; return data;
} }
} }

View File

@ -1,3 +1,5 @@
{{>licenseInfo}}
package {{invokerPackage}}; package {{invokerPackage}};
import com.google.gson.Gson; import com.google.gson.Gson;
@ -10,76 +12,118 @@ 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;
public JSON(ApiClient apiClient) { /**
this.apiClient = apiClient; * JSON constructor.
gson = new GsonBuilder() *
.registerTypeAdapter(Date.class, new DateAdapter(apiClient)) * @param apiClient An instance of ApiClient
.create(); */
} public JSON(ApiClient apiClient) {
this.apiClient = apiClient;
public Gson getGson() { gson = new GsonBuilder()
return gson; .registerTypeAdapter(Date.class, new DateAdapter(apiClient))
} .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter())
.registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter())
public void setGson(Gson gson) { .create();
this.gson = gson; }
}
/**
/** * Get Gson.
* Serialize the given Java object into JSON string. *
*/ * @return Gson
public String serialize(Object obj) { */
return gson.toJson(obj); public Gson getGson() {
} return gson;
}
/**
* Deserialize the given JSON string to Java object. /**
* * Set Gson.
* @param body The JSON string *
* @param returnType The type to deserialize inot * @param gson Gson
* @return The deserialized Java object */
*/ public void setGson(Gson gson) {
public <T> T deserialize(String body, Type returnType) { this.gson = gson;
try { }
if (apiClient.isLenientOnJson()) {
JsonReader jsonReader = new JsonReader(new StringReader(body)); /**
// see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) * Serialize the given Java object into JSON string.
jsonReader.setLenient(true); *
return gson.fromJson(jsonReader, returnType); * @param obj Object
} else { * @return String representation of the JSON
return gson.fromJson(body, returnType); */
} public String serialize(Object obj) {
} catch (JsonParseException e) { return gson.toJson(obj);
// Fallback processing when failed to parse JSON form response body: }
// return the response body string directly for the String return type;
// parse response body into date or datetime for the Date return type. /**
if (returnType.equals(String.class)) * Deserialize the given JSON string to Java object.
return (T) body; *
else if (returnType.equals(Date.class)) * @param <T> Type
return (T) apiClient.parseDateOrDatetime(body); * @param body The JSON string
else throw(e); * @param returnType The type to deserialize inot
* @return The deserialized Java object
*/
public <T> T deserialize(String body, Type returnType) {
try {
if (apiClient.isLenientOnJson()) {
JsonReader jsonReader = new JsonReader(new StringReader(body));
// see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean)
jsonReader.setLenient(true);
return gson.fromJson(jsonReader, returnType);
} else {
return gson.fromJson(body, returnType);
}
} catch (JsonParseException e) {
// Fallback processing when failed to parse JSON form response body:
// return the response body string directly for the String return type;
// parse response body into date or datetime for the Date return type.
if (returnType.equals(String.class))
return (T) body;
else if (returnType.equals(Date.class))
return (T) apiClient.parseDateOrDatetime(body);
else throw(e);
}
} }
}
} }
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}};
@ -30,138 +28,138 @@ import java.util.Map;
{{#operations}} {{#operations}}
public class {{classname}} { public class {{classname}} {
private ApiClient {{localVariablePrefix}}apiClient; private ApiClient {{localVariablePrefix}}apiClient;
public {{classname}}() { public {{classname}}() {
this(Configuration.getDefaultApiClient()); this(Configuration.getDefaultApiClient());
}
public {{classname}}(ApiClient apiClient) {
this.{{localVariablePrefix}}apiClient = apiClient;
}
public ApiClient getApiClient() {
return {{localVariablePrefix}}apiClient;
}
public void setApiClient(ApiClient apiClient) {
this.{{localVariablePrefix}}apiClient = apiClient;
}
{{#operation}}
/* Build call for {{operationId}} */
private 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}};
{{#allParams}}{{#required}}
// verify the required parameter '{{paramName}}' is set
if ({{paramName}} == null) {
throw new ApiException("Missing the required parameter '{{paramName}}' when calling {{operationId}}(Async)");
}
{{/required}}{{/allParams}}
// create path and map variables
String {{localVariablePrefix}}localVarPath = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}
.replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}};
{{javaUtilPrefix}}List<Pair> {{localVariablePrefix}}localVarQueryParams = new {{javaUtilPrefix}}ArrayList<Pair>();{{#queryParams}}
if ({{paramName}} != null)
{{localVariablePrefix}}localVarQueryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));{{/queryParams}}
{{javaUtilPrefix}}Map<String, String> {{localVariablePrefix}}localVarHeaderParams = new {{javaUtilPrefix}}HashMap<String, String>();{{#headerParams}}
if ({{paramName}} != null)
{{localVariablePrefix}}localVarHeaderParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}}));{{/headerParams}}
{{javaUtilPrefix}}Map<String, Object> {{localVariablePrefix}}localVarFormParams = new {{javaUtilPrefix}}HashMap<String, Object>();{{#formParams}}
if ({{paramName}} != null)
{{localVariablePrefix}}localVarFormParams.put("{{baseName}}", {{paramName}});{{/formParams}}
final String[] {{localVariablePrefix}}localVarAccepts = {
{{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}}
};
final String {{localVariablePrefix}}localVarAccept = {{localVariablePrefix}}apiClient.selectHeaderAccept({{localVariablePrefix}}localVarAccepts);
if ({{localVariablePrefix}}localVarAccept != null) {{localVariablePrefix}}localVarHeaderParams.put("Accept", {{localVariablePrefix}}localVarAccept);
final String[] {{localVariablePrefix}}localVarContentTypes = {
{{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}
};
final String {{localVariablePrefix}}localVarContentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}localVarContentTypes);
{{localVariablePrefix}}localVarHeaderParams.put("Content-Type", {{localVariablePrefix}}localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
} }
String[] {{localVariablePrefix}}localVarAuthNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; public {{classname}}(ApiClient apiClient) {
return {{localVariablePrefix}}apiClient.buildCall({{localVariablePrefix}}localVarPath, "{{httpMethod}}", {{localVariablePrefix}}localVarQueryParams, {{localVariablePrefix}}localVarPostBody, {{localVariablePrefix}}localVarHeaderParams, {{localVariablePrefix}}localVarFormParams, {{localVariablePrefix}}localVarAuthNames, progressRequestListener); this.{{localVariablePrefix}}apiClient = apiClient;
}
/**
* {{summary}}
* {{notes}}{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}{{#returnType}}
* @return {{{returnType}}}{{/returnType}}
* @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 {
{{#returnType}}ApiResponse<{{{returnType}}}> {{localVariablePrefix}}resp = {{/returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}}
return {{localVariablePrefix}}resp.getData();{{/returnType}}
}
/**
* {{summary}}
* {{notes}}{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
* @return ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
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);
{{#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}}
}
/**
* {{summary}} (asynchronously)
* {{notes}}{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @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 {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
} }
Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener); public ApiClient getApiClient() {
{{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType(); return {{localVariablePrefix}}apiClient;
{{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType, {{localVariablePrefix}}callback);{{/returnType}}{{^returnType}}{{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}callback);{{/returnType}} }
return {{localVariablePrefix}}call;
} public void setApiClient(ApiClient apiClient) {
{{/operation}} this.{{localVariablePrefix}}apiClient = apiClient;
}
{{#operation}}
/* Build call for {{operationId}} */
private com.squareup.okhttp.Call {{operationId}}Call({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object {{localVariablePrefix}}localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
{{#allParams}}{{#required}}
// verify the required parameter '{{paramName}}' is set
if ({{paramName}} == null) {
throw new ApiException("Missing the required parameter '{{paramName}}' when calling {{operationId}}(Async)");
}
{{/required}}{{/allParams}}
// create path and map variables
String {{localVariablePrefix}}localVarPath = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}
.replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}};
{{javaUtilPrefix}}List<Pair> {{localVariablePrefix}}localVarQueryParams = new {{javaUtilPrefix}}ArrayList<Pair>();{{#queryParams}}
if ({{paramName}} != null)
{{localVariablePrefix}}localVarQueryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));{{/queryParams}}
{{javaUtilPrefix}}Map<String, String> {{localVariablePrefix}}localVarHeaderParams = new {{javaUtilPrefix}}HashMap<String, String>();{{#headerParams}}
if ({{paramName}} != null)
{{localVariablePrefix}}localVarHeaderParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}}));{{/headerParams}}
{{javaUtilPrefix}}Map<String, Object> {{localVariablePrefix}}localVarFormParams = new {{javaUtilPrefix}}HashMap<String, Object>();{{#formParams}}
if ({{paramName}} != null)
{{localVariablePrefix}}localVarFormParams.put("{{baseName}}", {{paramName}});{{/formParams}}
final String[] {{localVariablePrefix}}localVarAccepts = {
{{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}}
};
final String {{localVariablePrefix}}localVarAccept = {{localVariablePrefix}}apiClient.selectHeaderAccept({{localVariablePrefix}}localVarAccepts);
if ({{localVariablePrefix}}localVarAccept != null) {{localVariablePrefix}}localVarHeaderParams.put("Accept", {{localVariablePrefix}}localVarAccept);
final String[] {{localVariablePrefix}}localVarContentTypes = {
{{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}
};
final String {{localVariablePrefix}}localVarContentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}localVarContentTypes);
{{localVariablePrefix}}localVarHeaderParams.put("Content-Type", {{localVariablePrefix}}localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] {{localVariablePrefix}}localVarAuthNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} };
return {{localVariablePrefix}}apiClient.buildCall({{localVariablePrefix}}localVarPath, "{{httpMethod}}", {{localVariablePrefix}}localVarQueryParams, {{localVariablePrefix}}localVarPostBody, {{localVariablePrefix}}localVarHeaderParams, {{localVariablePrefix}}localVarFormParams, {{localVariablePrefix}}localVarAuthNames, progressRequestListener);
}
/**
* {{summary}}
* {{notes}}{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}{{#returnType}}
* @return {{returnType}}{{/returnType}}
* @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 {
{{#returnType}}ApiResponse<{{{returnType}}}> {{localVariablePrefix}}resp = {{/returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}}
return {{localVariablePrefix}}resp.getData();{{/returnType}}
}
/**
* {{summary}}
* {{notes}}{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
* @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
*/
public ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}null, null);
{{#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}}
}
/**
* {{summary}} (asynchronously)
* {{notes}}{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
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;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener);
{{#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}}
return {{localVariablePrefix}}call;
}
{{/operation}}
} }
{{/operations}} {{/operations}}

View File

@ -1,3 +1,5 @@
{{>licenseInfo}}
package {{invokerPackage}}.auth; package {{invokerPackage}}.auth;
import {{invokerPackage}}.Pair; import {{invokerPackage}}.Pair;
@ -10,32 +12,32 @@ import java.util.List;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
public class HttpBasicAuth implements Authentication { public class HttpBasicAuth implements Authentication {
private String username; private String username;
private String password; private String password;
public String getUsername() { public String getUsername() {
return username; return username;
} }
public void setUsername(String username) { public void setUsername(String username) {
this.username = username; this.username = username;
} }
public String getPassword() { public String getPassword() {
return password; return password;
} }
public void setPassword(String password) { public void setPassword(String password) {
this.password = password; this.password = password;
} }
@Override @Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) { public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) {
if (username == null && password == null) { if (username == null && password == null) {
return; return;
}
headerParams.put("Authorization", Credentials.basic(
username == null ? "" : username,
password == null ? "" : password));
} }
headerParams.put("Authorization", Credentials.basic(
username == null ? "" : username,
password == null ? "" : password));
}
} }

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

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

View File

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

View File

@ -3,69 +3,93 @@
*/{{#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}}
{{/items}}
{{/items.isEnum}}
@SerializedName("{{baseName}}")
private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};
{{/vars}}
{{>libraries/common/modelInnerEnum}}{{/isEnum}}{{#items.isEnum}}{{#items}} {{#vars}}
/**
{{>libraries/common/modelInnerEnum}}{{/items}}{{/items.isEnum}} {{#description}}
@SerializedName("{{baseName}}") * {{{description}}}
private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}}; {{/description}}
{{/vars}} {{^description}}
* Get {{name}}
{{#vars}} {{/description}}
/**{{#description}} {{#minimum}}
* {{{description}}}{{/description}}{{#minimum}} * minimum: {{minimum}}
* minimum: {{minimum}}{{/minimum}}{{#maximum}} {{/minimum}}
* maximum: {{maximum}}{{/maximum}} {{#maximum}}
**/ * maximum: {{maximum}}
@ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") {{/maximum}}
public {{{datatypeWithEnum}}} {{getter}}() { * @return {{name}}
return {{name}}; **/
}{{^isReadOnly}} @ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}")
public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { public {{{datatypeWithEnum}}} {{getter}}() {
this.{{name}} = {{name}}; return {{name}};
}{{/isReadOnly}}
{{/vars}}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
} }
if (o == null || getClass() != o.getClass()) {
return false; {{^isReadOnly}}
}{{#hasVars}} /**
{{classname}} {{classVarName}} = ({{classname}}) o; * Set {{name}}
return {{#vars}}Objects.equals(this.{{name}}, {{classVarName}}.{{name}}){{#hasMore}} && *
* @param {{name}} {{name}}
*/
public void {{setter}}({{{datatypeWithEnum}}} {{name}}) {
this.{{name}} = {{name}};
}
{{/isReadOnly}}
{{/vars}}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}{{#hasVars}}
{{classname}} {{classVarName}} = ({{classname}}) o;
return {{#vars}}Objects.equals(this.{{name}}, {{classVarName}}.{{name}}){{#hasMore}} &&
{{/hasMore}}{{/vars}}{{#parent}} && {{/hasMore}}{{/vars}}{{#parent}} &&
super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}} super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}}
return true;{{/hasVars}} return true;{{/hasVars}}
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}); return Objects.hash({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}});
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("class {{classname}} {\n"); sb.append("class {{classname}} {\n");
{{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}}
{{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n");
{{/vars}}sb.append("}"); {{/vars}}sb.append("}");
return sb.toString(); return sb.toString();
} }
/** /**
* 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).
*/ *
private String toIndentedString(Object o) { * @param o Object to be converted to indented string
if (o == null) { */
return "null"; private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
} }
return o.toString().replace("\n", "\n ");
}
} }

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];
body = [self.sanitizer sanitizeForSerialization:body]; if(![body isKindOfClass:[NSData class]]) {
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];
if (parameters) {
[mutableRequest setHTTPBody:[parameters dataUsingEncoding:self.stringEncoding]];
}
return mutableRequest;
} }
NSMutableURLRequest *mutableRequest = [request mutableCopy];
if([parameters isKindOfClass:[NSData class]]) {
[mutableRequest setHTTPBody:parameters];
} else {
[mutableRequest setHTTPBody:[parameters dataUsingEncoding:self.stringEncoding]];
}
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;

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