diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a40a96f7b389..d7d241c1040f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -28,15 +28,19 @@ For a list of variables available in the template, please refer to this [page](h ### Style guide Code change should conform to the programming style guide of the respective langauages: +- Android: https://source.android.com/source/code-style.html - C#: https://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx +- Haskell: https://github.com/tibbe/haskell-style-guide/blob/master/haskell-style.md - Java: https://google.github.io/styleguide/javaguide.html - JavaScript: https://github.com/airbnb/javascript/tree/master/es5 +- Groovy: http://groovy-lang.org/style-guide.html - Go: https://github.com/golang/go/wiki/CodeReviewComments - ObjC: https://github.com/NYTimes/objective-c-style-guide - Perl: http://perldoc.perl.org/perlstyle.html - PHP: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md - Python: https://www.python.org/dev/peps/pep-0008/ - Ruby: https://github.com/bbatsov/ruby-style-guide +- Scala: http://docs.scala-lang.org/style/ - 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 diff --git a/README.md b/README.md index ece108666e16..fb1d85012873 100644 --- a/README.md +++ b/README.md @@ -641,155 +641,7 @@ open index.html ### To build a server stub -You can also use the codegen to generate a server for a couple different frameworks. Take a look here: - -### Node.js - -``` -java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ - -i http://petstore.swagger.io/v2/swagger.json \ - -l nodejs-server \ - -o samples/server/petstore/nodejs -``` - -### PHP Slim - -``` -java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ - -i http://petstore.swagger.io/v2/swagger.json \ - -l slim \ - -o samples/server/petstore/slim -``` - -### PHP Silex - -``` -java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ - -i http://petstore.swagger.io/v2/swagger.json \ - -l silex-PHP \ - -o samples/server/petstore/silex -``` - -### Python Flask (Connexion) - -``` -java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ - -i http://petstore.swagger.io/v2/swagger.json \ - -l python-flask \ - -o samples/server/petstore/flaskConnexion -``` - -### Ruby Sinatra - -``` -java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ - -i http://petstore.swagger.io/v2/swagger.json \ - -l sinatra \ - -o samples/server/petstore/sinatra -``` - -### Scala Scalatra -``` -java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ - -i http://petstore.swagger.io/v2/swagger.json \ - -l scalatra \ - -o samples/server/petstore/scalatra -``` - -### Java JAX-RS (Jersey v1.18) - -``` -java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ - -i http://petstore.swagger.io/v2/swagger.json \ - -l jaxrs \ - -o samples/server/petstore/jaxrs-jersey -``` - -### Java JAX-RS (Apache CXF 2 / 3) - -``` -java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ - -i http://petstore.swagger.io/v2/swagger.json \ - -l jaxrs-cxf \ - -o samples/server/petstore/jaxrs-cxf -``` - -This Codegen only generate a minimalist server stub. You must add the CXF dependency to your classpath (eg: with Maven) -If you are using CXF v2.x, you must provided a custom ```ResourceComparator``` class. This class will help CXF to choose the good resource interface for mapping an incomming request. The default behavior of CXF v2.x is not correct when many resources interface have the same global path. -See: See http://cxf.apache.org/docs/jax-rs-basics.html#JAX-RSBasics-Customselectionbetweenmultipleresources - -You can found this class here: https://github.com/hiveship/CXF2-resource-comparator/blob/master/src/main/java/CXFInterfaceComparator.java -TODO: This class could be directly generated by the Codegen. - -You must register this class into your JAX-RS configuration file: -```xml - - - -``` - -This is no longer necessary if you are using CXF >=v3.x - -### Java JAX-RS (Resteasy) - -``` -java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ - -i http://petstore.swagger.io/v2/swagger.json \ - -l jaxrs-resteasy \ - -o samples/server/petstore/jaxrs-resteasy -``` - -### Java Spring MVC - -``` -java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ - -i http://petstore.swagger.io/v2/swagger.json \ - -l spring-mvc \ - -o samples/server/petstore/spring-mvc -``` - -### Java SpringBoot - -``` -java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ - -i http://petstore.swagger.io/v2/swagger.json \ - -l springboot \ - -o samples/server/petstore/springboot -``` - -You can also set a Json file with basePackage & configPackage properties : -Example : -``` -{ -"basePackage":"io.swagger", -"configPackage":"io.swagger.config" -} -``` -For use it add option ```-c myOptions.json``` to the generation command - -To Use-it : -in the generated folder try ``` mvn package ``` for build jar. -Start your server ``` java -jar target/swagger-springboot-server-1.0.0.jar ``` -SpringBoot listening on default port 8080 - - -### Haskell Servant - -``` -java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ - -i http://petstore.swagger.io/v2/swagger.json \ - -l haskell-servant \ - -o samples/server/petstore/haskell-servant -``` - -### ASP.NET 5 Web API - -``` -java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ - -i http://petstore.swagger.io/v2/swagger.json \ - -l aspnet5 \ - -o samples/server/petstore/aspnet5 -``` +Please refer to https://github.com/swagger-api/swagger-codegen/wiki/Server-stub-generator-HOWTO for more information. ### To build the codegen library @@ -864,6 +716,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [IMS Health](http://www.imshealth.com/en/solution-areas/technology-and-applications) - [Interactive Intelligence](http://developer.mypurecloud.com/) - [LANDR Audio](https://www.landr.com/) +- [Lascaux](http://www.lascaux.it/) - [LiveAgent](https://www.ladesk.com/) - [Kabuku](http://www.kabuku.co.jp/en) - [Kuary](https://kuary.com/) @@ -935,6 +788,7 @@ Swaagger Codegen core team members are contributors who have been making signfic Here is a list of template creators: * API Clients: * Akka-Scala: @cchafer + * C++ REST: @Danielku15 * C# (.NET 2.0): @who * Clojure: @xhh * Dart: @yissachar diff --git a/bin/cpprest-petstore.sh b/bin/cpprest-petstore.sh new file mode 100755 index 000000000000..93f7ad609cc5 --- /dev/null +++ b/bin/cpprest-petstore.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/cpprest -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l cpprest -o samples/client/petstore/cpprest" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/go-petstore-server.sh b/bin/go-petstore-server.sh new file mode 100755 index 000000000000..a668a1cfbdd7 --- /dev/null +++ b/bin/go-petstore-server.sh @@ -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 go-server -o samples/server/petstore/go-api-server -DpackageName=petstoreserver " + +java $JAVA_OPTS -Dservice -jar $executable $ags diff --git a/bin/lumen-petstore-server.sh b/bin/lumen-petstore-server.sh index 15acb2fe2bd3..a4a5df0f817d 100755 --- a/bin/lumen-petstore-server.sh +++ b/bin/lumen-petstore-server.sh @@ -26,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -t modules/swagger-codegen/src/main/resources/lumen -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l lumen -o samples/server/petstore/lumen" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/lumen -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l lumen -o samples/server/petstore/lumen" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/swift-petstore-all.sh b/bin/swift-petstore-all.sh new file mode 100755 index 000000000000..e74eba377047 --- /dev/null +++ b/bin/swift-petstore-all.sh @@ -0,0 +1,36 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/swift -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l swift -c ./bin/swift-petstore.json -o samples/client/petstore/swift/default" + +echo "#### Petstore Swift API client (default) ####" +java $JAVA_OPTS -jar $executable $ags + +ags="$@ generate -t modules/swagger-codegen/src/main/resources/swift -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l swift -c ./bin/swift-petstore-promisekit.json -o samples/client/petstore/swift/promisekit" +echo "#### Petstore Swift API client (promisekit) ####" +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/typescript-angular2-petstore-all.sh b/bin/typescript-angular2-petstore-all.sh new file mode 100755 index 000000000000..b3fc0df2126f --- /dev/null +++ b/bin/typescript-angular2-petstore-all.sh @@ -0,0 +1,36 @@ +#!/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" + +echo "Typescript Petstore API client (default)" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-angular2 -o samples/client/petstore/typescript-angular2/default" +java $JAVA_OPTS -jar $executable $ags + +echo "Typescript Petstore API client (npm setting)" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-angular2 -c bin/typescript-petstore-npm.json -o samples/client/petstore/typescript-angular2/npm" +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/typescript-node-petstore-all.sh b/bin/typescript-node-petstore-all.sh new file mode 100755 index 000000000000..65f25060725d --- /dev/null +++ b/bin/typescript-node-petstore-all.sh @@ -0,0 +1,36 @@ +#!/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" + +echo "Typescript node Petstore API client (default setting)" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-node -o samples/client/petstore/typescript-node/default" +java $JAVA_OPTS -jar $executable $ags + +echo "Typescript node Petstore API client with npm setting" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-node -c bin/typescript-petstore-npm.json -o samples/client/petstore/typescript-node/npm" +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/windows/cpprest-petstore.bat b/bin/windows/cpprest-petstore.bat new file mode 100755 index 000000000000..433126698407 --- /dev/null +++ b/bin/windows/cpprest-petstore.bat @@ -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\cpprest -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l cpprest -o samples\client\petstore\cpprest + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java index c11f444437b5..3752f69dca5c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java @@ -22,6 +22,7 @@ public class CodegenModel { public String unescapedDescription; public String discriminator; public String defaultValue; + public String arrayModelType; public List vars = new ArrayList(); public List requiredVars = new ArrayList(); // a list of required properties public List optionalVars = new ArrayList(); // a list of optional properties @@ -35,7 +36,7 @@ public class CodegenModel { public Set allMandatory; public Set imports = new TreeSet(); - public Boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum, hasRequired; + public Boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum, hasRequired, isArrayModel; public ExternalDocs externalDocs; public Map vendorExtensions; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 8304849a14c4..0bd0c08cccc2 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -1198,6 +1198,8 @@ public class DefaultCodegen { ArrayModel am = (ArrayModel) model; ArrayProperty arrayProperty = new ArrayProperty(am.getItems()); m.hasEnums = false; // Otherwise there will be a NullPointerException in JavaClientCodegen.fromModel + m.isArrayModel = true; + m.arrayModelType = fromProperty(name, arrayProperty).complexType; addParentContainer(m, name, arrayProperty); } else if (model instanceof RefModel) { // TODO @@ -1465,7 +1467,9 @@ public class DefaultCodegen { if (p instanceof BinaryProperty) { property.isBinary = true; } - + if (p instanceof UUIDProperty) { + property.isString = true; + } if (p instanceof ByteArrayProperty) { property.isByteArray = true; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CppRestClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CppRestClientCodegen.java new file mode 100644 index 000000000000..f8299fc60cd8 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CppRestClientCodegen.java @@ -0,0 +1,380 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.codegen.examples.ExampleGenerator; +import io.swagger.models.Model; +import io.swagger.models.Operation; +import io.swagger.models.Response; +import io.swagger.models.Swagger; +import io.swagger.models.properties.*; + +import java.util.*; +import java.io.File; + +public class CppRestClientCodegen extends DefaultCodegen implements CodegenConfig { + + public static final String DECLSPEC = "declspec"; + public static final String DEFAULT_INCLUDE = "defaultInclude"; + + protected String packageVersion = "1.0.0"; + protected String declspec = ""; + protected String defaultInclude = ""; + + /** + * Configures the type of generator. + * + * @return the CodegenType for this generator + * @see io.swagger.codegen.CodegenType + */ + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + /** + * Configures a friendly name for the generator. This will be used by the + * generator to select the library with the -l flag. + * + * @return the friendly name for the generator + */ + public String getName() { + return "cpprest"; + } + + /** + * Returns human-friendly help for the generator. Provide the consumer with + * help tips, parameters here + * + * @return A string value for the help message + */ + public String getHelp() { + return "Generates a C++ API client with C++ REST SDK (https://github.com/Microsoft/cpprestsdk)."; + } + + public CppRestClientCodegen() { + super(); + + apiPackage = "io.swagger.client.api"; + modelPackage = "io.swagger.client.model"; + + modelTemplateFiles.put("model-header.mustache", ".h"); + modelTemplateFiles.put("model-source.mustache", ".cpp"); + + apiTemplateFiles.put("api-header.mustache", ".h"); + apiTemplateFiles.put("api-source.mustache", ".cpp"); + + templateDir = "cpprest"; + + cliOptions.clear(); + + // CLI options + addOption(CodegenConstants.MODEL_PACKAGE, "C++ namespace for models (convention: name.space.model).", + this.modelPackage); + addOption(CodegenConstants.API_PACKAGE, "C++ namespace for apis (convention: name.space.api).", + this.apiPackage); + addOption(CodegenConstants.PACKAGE_VERSION, "C++ package version.", this.packageVersion); + addOption(DECLSPEC, "C++ preprocessor to place before the class name for handling dllexport/dllimport.", + this.declspec); + addOption(DEFAULT_INCLUDE, + "The default include statement that should be placed in all headers for including things like the declspec (convention: #include \"Commons.h\" ", + this.defaultInclude); + + reservedWords = new HashSet(); + + supportingFiles.add(new SupportingFile("modelbase-header.mustache", "", "ModelBase.h")); + supportingFiles.add(new SupportingFile("modelbase-source.mustache", "", "ModelBase.cpp")); + supportingFiles.add(new SupportingFile("apiclient-header.mustache", "", "ApiClient.h")); + supportingFiles.add(new SupportingFile("apiclient-source.mustache", "", "ApiClient.cpp")); + supportingFiles.add(new SupportingFile("apiconfiguration-header.mustache", "", "ApiConfiguration.h")); + supportingFiles.add(new SupportingFile("apiconfiguration-source.mustache", "", "ApiConfiguration.cpp")); + supportingFiles.add(new SupportingFile("apiexception-header.mustache", "", "ApiException.h")); + supportingFiles.add(new SupportingFile("apiexception-source.mustache", "", "ApiException.cpp")); + supportingFiles.add(new SupportingFile("ihttpbody-header.mustache", "", "IHttpBody.h")); + supportingFiles.add(new SupportingFile("jsonbody-header.mustache", "", "JsonBody.h")); + supportingFiles.add(new SupportingFile("jsonbody-source.mustache", "", "JsonBody.cpp")); + supportingFiles.add(new SupportingFile("httpcontent-header.mustache", "", "HttpContent.h")); + supportingFiles.add(new SupportingFile("httpcontent-source.mustache", "", "HttpContent.cpp")); + supportingFiles.add(new SupportingFile("multipart-header.mustache", "", "MultipartFormData.h")); + supportingFiles.add(new SupportingFile("multipart-source.mustache", "", "MultipartFormData.cpp")); + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + + languageSpecificPrimitives = new HashSet( + Arrays.asList("int", "char", "bool", "long", "float", "double", "int32_t", "int64_t")); + + typeMapping = new HashMap(); + typeMapping.put("date", "utility::datetime"); + typeMapping.put("DateTime", "utility::datetime"); + typeMapping.put("string", "utility::string_t"); + typeMapping.put("integer", "int32_t"); + typeMapping.put("long", "int64_t"); + typeMapping.put("boolean", "bool"); + typeMapping.put("array", "std::vector"); + typeMapping.put("map", "std::map"); + typeMapping.put("file", "HttpContent"); + typeMapping.put("object", "Object"); + typeMapping.put("binary", "std::string"); + + super.importMapping = new HashMap(); + importMapping.put("std::vector", "#include "); + importMapping.put("std::map", "#include "); + importMapping.put("std::string", "#include "); + importMapping.put("HttpContent", "#include \"HttpContent.h\""); + importMapping.put("Object", "#include \"Object.h\""); + importMapping.put("utility::string_t", "#include "); + importMapping.put("utility::datetime", "#include "); + } + + protected void addOption(String key, String description, String defaultValue) { + CliOption option = new CliOption(key, description); + if (defaultValue != null) + option.defaultValue(defaultValue); + cliOptions.add(option); + } + + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey(DECLSPEC)) { + declspec = additionalProperties.get(DECLSPEC).toString(); + } + + if (additionalProperties.containsKey(DEFAULT_INCLUDE)) { + defaultInclude = additionalProperties.get(DEFAULT_INCLUDE).toString(); + } + + additionalProperties.put("modelNamespaceDeclarations", modelPackage.split("\\.")); + additionalProperties.put("modelNamespace", modelPackage.replaceAll("\\.", "::")); + additionalProperties.put("apiNamespaceDeclarations", apiPackage.split("\\.")); + additionalProperties.put("apiNamespace", apiPackage.replaceAll("\\.", "::")); + additionalProperties.put("declspec", declspec); + additionalProperties.put("defaultInclude", defaultInclude); + } + + /** + * Escapes a reserved word as defined in the `reservedWords` array. Handle + * escaping those terms here. This logic is only called if a variable + * matches the reseved words + * + * @return the escaped term + */ + @Override + public String escapeReservedWord(String name) { + return "_" + name; // add an underscore to the name + } + + /** + * Location to write model files. You can use the modelPackage() as defined + * when the class is instantiated + */ + public String modelFileFolder() { + return outputFolder + "/model"; + } + + /** + * Location to write api files. You can use the apiPackage() as defined when + * the class is instantiated + */ + @Override + public String apiFileFolder() { + return outputFolder + "/api"; + } + + @Override + public String toModelImport(String name) { + if (importMapping.containsKey(name)) { + return importMapping.get(name); + } else { + return "#include \"" + name + ".h\""; + } + } + + @Override + public CodegenModel fromModel(String name, Model model, Map allDefinitions) { + CodegenModel codegenModel = super.fromModel(name, model, allDefinitions); + + Set oldImports = codegenModel.imports; + codegenModel.imports = new HashSet(); + for (String imp : oldImports) { + String newImp = toModelImport(imp); + if (!newImp.isEmpty()) { + codegenModel.imports.add(newImp); + } + } + + return codegenModel; + } + + @Override + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, + Map definitions, Swagger swagger) { + CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger); + + if (operation.getResponses() != null && !operation.getResponses().isEmpty()) { + Response methodResponse = findMethodResponse(operation.getResponses()); + + if (methodResponse != null) { + if (methodResponse.getSchema() != null) { + CodegenProperty cm = fromProperty("response", methodResponse.getSchema()); + op.vendorExtensions.put("x-codegen-response", cm); + } + } + } + + return op; + } + + @Override + public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { + if (isFileProperty(property)) { + property.vendorExtensions.put("x-codegen-file", true); + } + } + + protected boolean isFileProperty(CodegenProperty property) { + return property.baseType.equals("HttpContent"); + } + + @Override + public String toModelFilename(String name) { + return initialCaps(name); + } + + @Override + public String toApiFilename(String name) { + return initialCaps(name) + "Api"; + } + + /** + * Optional - type declaration. This is a String which is used by the + * templates to instantiate your types. There is typically special handling + * for different property types + * + * @return a string value used as the `dataType` field for model templates, + * `returnType` for api templates + */ + @Override + public String getTypeDeclaration(Property p) { + String swaggerType = getSwaggerType(p); + + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; + } + if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + return getSwaggerType(p) + ""; + } + if (p instanceof StringProperty || p instanceof DateProperty || p instanceof DateTimeProperty + || languageSpecificPrimitives.contains(swaggerType)) { + return toModelName(swaggerType); + } + + return "std::shared_ptr<" + swaggerType + ">"; + } + + @Override + public String toDefaultValue(Property p) { + if (p instanceof StringProperty) { + return "U(\"\")"; + } else if (p instanceof BooleanProperty) { + return "false"; + } else if (p instanceof DateProperty) { + return "utility::datetime()"; + } else if (p instanceof DateTimeProperty) { + return "utility::datetime()"; + } else if (p instanceof DoubleProperty) { + return "0.0"; + } else if (p instanceof FloatProperty) { + return "0.0f"; + } else if (p instanceof IntegerProperty) { + return "0"; + } else if (p instanceof LongProperty) { + return "0L"; + } else if (p instanceof DecimalProperty) { + return "0.0"; + } else if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return "std::map()"; + } else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + if (!languageSpecificPrimitives.contains(inner)) { + inner = "std::shared_ptr<" + inner + ">"; + } + return "std::vector<" + inner + ">()"; + } else if (p instanceof RefProperty) { + RefProperty rp = (RefProperty) p; + return "new " + toModelName(rp.getSimpleRef()) + "()"; + } + return "nullptr"; + } + + @Override + public void postProcessParameter(CodegenParameter parameter) { + super.postProcessParameter(parameter); + + boolean isPrimitiveType = parameter.isPrimitiveType == Boolean.TRUE; + boolean isListContainer = parameter.isListContainer == Boolean.TRUE; + boolean isString = parameter.isString == Boolean.TRUE; + + if (!isPrimitiveType && !isListContainer && !isString && !parameter.dataType.startsWith("std::shared_ptr")) { + parameter.dataType = "std::shared_ptr<" + parameter.dataType + ">"; + } + } + + /** + * Optional - swagger type conversion. This is used to map swagger types in + * a `Property` into either language specific types via `typeMapping` or + * into complex models if there is not a mapping. + * + * @return a string value of the type or complex model for this property + * @see io.swagger.models.properties.Property + */ + @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 toModelName(type); + } else + type = swaggerType; + return toModelName(type); + } + + @Override + public String toModelName(String type) { + if (typeMapping.keySet().contains(type) || typeMapping.values().contains(type) + || importMapping.values().contains(type) || defaultIncludes.contains(type) + || languageSpecificPrimitives.contains(type)) { + return type; + } else { + return Character.toUpperCase(type.charAt(0)) + type.substring(1); + } + } + + @Override + public String toVarName(String name) { + if (typeMapping.keySet().contains(name) || typeMapping.values().contains(name) + || importMapping.values().contains(name) || defaultIncludes.contains(name) + || languageSpecificPrimitives.contains(name)) { + return name; + } + + if (name.length() > 1) { + return Character.toUpperCase(name.charAt(0)) + name.substring(1); + } + + return name; + } + + @Override + public String toApiName(String type) { + return Character.toUpperCase(type.charAt(0)) + type.substring(1) + "Api"; + } +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoServerCodegen.java new file mode 100644 index 000000000000..43c48cc64f7d --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoServerCodegen.java @@ -0,0 +1,266 @@ +package io.swagger.codegen.languages; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.module.SimpleModule; +import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.Lists; +import com.google.common.collect.Multimap; +import io.swagger.codegen.*; +import io.swagger.models.*; +import io.swagger.util.Yaml; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.*; +import java.util.Map.Entry; +import org.apache.commons.lang3.StringUtils; + +public class GoServerCodegen extends DefaultCodegen implements CodegenConfig { + + private static final Logger LOGGER = LoggerFactory.getLogger(GoServerCodegen.class); + + protected String apiVersion = "1.0.0"; + protected int serverPort = 8080; + protected String projectName = "swagger-server"; + protected String apiPath = "go"; + + public GoServerCodegen() { + super(); + + // set the output folder here + outputFolder = "generated-code/go"; + + /** + * Models. You can write model files using the modelTemplateFiles map. + * if you want to create one template for file, you can do so here. + * for multiple files for model, just put another entry in the `modelTemplateFiles` with + * a different extension + */ + modelTemplateFiles.clear(); + + /** + * Api classes. You can write classes for each Api file with the apiTemplateFiles map. + * as with models, add multiple entries with different extensions for multiple files per + * class + */ + apiTemplateFiles.put( + "controller.mustache", // the template to use + ".go"); // the extension for each file to write + + /** + * Template Location. This is the location which templates will be read from. The generator + * will use the resource stream to attempt to read the templates. + */ + embeddedTemplateDir = templateDir = "go-server"; + + /** + * Reserved words. Override this with reserved words specific to your language + */ + setReservedWordsLowerCase( + Arrays.asList( + "break", "default", "func", "interface", "select", + "case", "defer", "go", "map", "struct", + "chan", "else", "goto", "package", "switch", + "const", "fallthrough", "if", "range", "type", + "continue", "for", "import", "return", "var", "error", "ApiResponse") + // Added "error" as it's used so frequently that it may as well be a keyword + ); + + defaultIncludes = new HashSet( + Arrays.asList( + "map", + "array") + ); + + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "string", + "bool", + "uint", + "uint32", + "uint64", + "int", + "int32", + "int64", + "float32", + "float64", + "complex64", + "complex128", + "rune", + "byte") + ); + + instantiationTypes.clear(); + /*instantiationTypes.put("array", "GoArray"); + instantiationTypes.put("map", "GoMap");*/ + + typeMapping.clear(); + typeMapping.put("integer", "int32"); + typeMapping.put("long", "int64"); + typeMapping.put("number", "float32"); + typeMapping.put("float", "float32"); + typeMapping.put("double", "float64"); + typeMapping.put("boolean", "bool"); + typeMapping.put("string", "string"); + typeMapping.put("date", "time.Time"); + typeMapping.put("DateTime", "time.Time"); + typeMapping.put("password", "string"); + typeMapping.put("File", "*os.File"); + typeMapping.put("file", "*os.File"); + // map binary to string as a workaround + // the correct solution is to use []byte + typeMapping.put("binary", "string"); + typeMapping.put("ByteArray", "string"); + + importMapping = new HashMap(); + importMapping.put("time.Time", "time"); + importMapping.put("*os.File", "os"); + importMapping.put("os", "io/ioutil"); + + cliOptions.clear(); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Go package name (convention: lowercase).") + .defaultValue("swagger")); + /** + * Additional Properties. These values can be passed to the templates and + * are available in models, apis, and supporting files + */ + additionalProperties.put("apiVersion", apiVersion); + additionalProperties.put("serverPort", serverPort); + additionalProperties.put("apiPath", apiPath); + /** + * Supporting Files. You can write single files for the generator with the + * entire object tree available. If the input file has a suffix of `.mustache + * it will be processed by the template engine. Otherwise, it will be copied + */ + supportingFiles.add(new SupportingFile("swagger.mustache", + "api", + "swagger.yaml") + ); + supportingFiles.add(new SupportingFile("main.mustache", "", "main.go")); + supportingFiles.add(new SupportingFile("routers.mustache", apiPath, "routers.go")); + supportingFiles.add(new SupportingFile("logger.mustache", apiPath, "logger.go")); + supportingFiles.add(new SupportingFile("app.mustache", apiPath, "app.yaml")); + writeOptional(outputFolder, new SupportingFile("README.mustache", apiPath, "README.md")); + } + + @Override + public String apiPackage() { + return apiPath; + } + + /** + * Configures the type of generator. + * + * @return the CodegenType for this generator + * @see io.swagger.codegen.CodegenType + */ + @Override + public CodegenType getTag() { + return CodegenType.SERVER; + } + + /** + * Configures a friendly name for the generator. This will be used by the generator + * to select the library with the -l flag. + * + * @return the friendly name for the generator + */ + @Override + public String getName() { + return "go-server"; + } + + /** + * Returns human-friendly help for the generator. Provide the consumer with help + * tips, parameters here + * + * @return A string value for the help message + */ + @Override + public String getHelp() { + return "Generates a Go server library using the swagger-tools project. By default, " + + "it will also generate service classes--which you can disable with the `-Dnoservice` environment variable."; + } + + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return "DefaultController"; + } + return initialCaps(name); + } + + /** + * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping + * those terms here. This logic is only called if a variable matches the reseved words + * + * @return the escaped term + */ + @Override + public String escapeReservedWord(String name) { + return "_" + name; // add an underscore to the name + } + + /** + * Location to write api files. You can use the apiPackage() as defined when the class is + * instantiated + */ + @Override + public String apiFileFolder() { + return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar); + } + + @Override + public String toModelName(String name) { + // camelize the model name + // phone_number => PhoneNumber + return camelize(toModelFilename(name)); + } + + @Override + public String toOperationId(String operationId) { + // method name cannot use reserved keyword, e.g. return + if (isReservedWord(operationId)) { + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId))); + operationId = "call_" + operationId; + } + + return camelize(operationId); + } + + @Override + public String toModelFilename(String name) { + if (!StringUtils.isEmpty(modelNamePrefix)) { + name = modelNamePrefix + "_" + name; + } + + if (!StringUtils.isEmpty(modelNameSuffix)) { + name = name + "_" + modelNameSuffix; + } + + name = sanitizeName(name); + + // model name cannot use reserved keyword, e.g. return + if (isReservedWord(name)) { + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name)); + name = "model_" + name; // e.g. return => ModelReturn (after camelize) + } + + return underscore(name); + } + + @Override + public String toApiFilename(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + + // e.g. PetApi.go => pet_api.go + return underscore(name); + } +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java index c80bb0ed23fd..ad4750cf8ce5 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java @@ -127,6 +127,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { CliOption dateLibrary = new CliOption(DATE_LIBRARY, "Option. Date library to use"); Map dateOptions = new HashMap(); dateOptions.put("java8", "Java 8 native"); + dateOptions.put("java8-localdatetime", "Java 8 using LocalDateTime (for legacy app only)"); dateOptions.put("joda", "Joda"); dateOptions.put("legacy", "Legacy java.util.Date"); dateLibrary.setEnum(dateOptions); @@ -262,6 +263,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { writeOptional(outputFolder, new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); writeOptional(outputFolder, new SupportingFile("gradle.properties.mustache", "", "gradle.properties")); writeOptional(outputFolder, new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml")); + supportingFiles.add(new SupportingFile("travis.mustache", "", ".travis.yml")); supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java")); supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java")); @@ -362,7 +364,8 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { } if(additionalProperties.containsKey(DATE_LIBRARY)) { - this.dateLibrary = additionalProperties.get(DATE_LIBRARY).toString(); + setDateLibrary(additionalProperties.get(DATE_LIBRARY).toString()); + additionalProperties.put(dateLibrary, "true"); } if("joda".equals(dateLibrary)) { @@ -372,13 +375,17 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { importMapping.put("LocalDate", "org.joda.time.LocalDate"); importMapping.put("DateTime", "org.joda.time.DateTime"); } - else if ("java8".equals(dateLibrary)) { + else if (dateLibrary.startsWith("java8")) { additionalProperties.put("java8", "true"); - additionalProperties.put("javaVersion", "1.8"); typeMapping.put("date", "LocalDate"); - typeMapping.put("DateTime", "LocalDateTime"); importMapping.put("LocalDate", "java.time.LocalDate"); - importMapping.put("LocalDateTime", "java.time.LocalDateTime"); + if ("java8-localdatetime".equals(dateLibrary)) { + typeMapping.put("DateTime", "LocalDateTime"); + importMapping.put("LocalDateTime", "java.time.LocalDateTime"); + } else { + typeMapping.put("DateTime", "OffsetDateTime"); + importMapping.put("OffsetDateTime", "java.time.OffsetDateTime"); + } } supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); @@ -1031,7 +1038,5 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { this.useRxJava = useRxJava; } - public void setDateLibrary(String library) { - this.dateLibrary = library; - } + public void setDateLibrary(String library) { this.dateLibrary = library; } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java index 72f969403bf5..f6c3f861e492 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java @@ -89,16 +89,11 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen { implFolder = (String) additionalProperties.get(CodegenConstants.IMPL_FOLDER); } - if (additionalProperties.containsKey("dateLibrary")) { - setDateLibrary(additionalProperties.get("dateLibrary").toString()); - additionalProperties.put(dateLibrary, "true"); - } - if ("joda".equals(dateLibrary)) { supportingFiles.add(new SupportingFile("JodaDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaDateTimeProvider.java")); supportingFiles.add(new SupportingFile("JodaLocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaLocalDateProvider.java")); - } else if ( "java8".equals(dateLibrary) ) { - supportingFiles.add(new SupportingFile("LocalDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateTimeProvider.java")); + } else if ( dateLibrary.startsWith("java8") ) { + supportingFiles.add(new SupportingFile("OffsetDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "OffsetDateTimeProvider.java")); supportingFiles.add(new SupportingFile("LocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateProvider.java")); } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java index 4c13fd50f0b7..33803b087b86 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java @@ -47,14 +47,6 @@ public class JavaResteasyServerCodegen extends JavaClientCodegen implements Code } } - CliOption dateLibrary = new CliOption(DATE_LIBRARY, "Option. Date library to use"); - Map dateOptions = new HashMap(); - dateOptions.put("java8", "Java 8 native"); - dateOptions.put("joda", "Joda"); - dateLibrary.setEnum(dateOptions); - - cliOptions.add(dateLibrary); - CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); library.setDefault(DEFAULT_LIBRARY); @@ -117,35 +109,16 @@ public class JavaResteasyServerCodegen extends JavaClientCodegen implements Code supportingFiles.add(new SupportingFile("StringUtil.mustache", (sourceFolder + '/' + invokerPackage).replace(".", "/"), "StringUtil.java")); - if (additionalProperties.containsKey("dateLibrary")) { - setDateLibrary(additionalProperties.get("dateLibrary").toString()); - additionalProperties.put(dateLibrary, "true"); - } - if ("joda".equals(dateLibrary)) { - typeMapping.put("date", "LocalDate"); - typeMapping.put("DateTime", "DateTime"); - - importMapping.put("LocalDate", "org.joda.time.LocalDate"); - importMapping.put("DateTime", "org.joda.time.DateTime"); - supportingFiles.add(new SupportingFile("JacksonConfig.mustache", (sourceFolder + '/' + invokerPackage).replace(".", "/"), "JacksonConfig.java")); - supportingFiles.add(new SupportingFile("JodaDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaDateTimeProvider.java")); supportingFiles.add(new SupportingFile("JodaLocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaLocalDateProvider.java")); - } else if ("java8".equals(dateLibrary)) { - additionalProperties.put("java8", "true"); - additionalProperties.put("javaVersion", "1.8"); - typeMapping.put("date", "LocalDate"); - typeMapping.put("DateTime", "LocalDateTime"); - importMapping.put("LocalDate", "java.time.LocalDate"); - importMapping.put("LocalDateTime", "java.time.LocalDateTime"); - - supportingFiles.add(new SupportingFile("LocalDateTimeProvider.mustache", - (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateTimeProvider.java")); + } else if (dateLibrary.startsWith("java8")) { + supportingFiles.add(new SupportingFile("OffsetDateTimeProvider.mustache", + (sourceFolder + '/' + apiPackage).replace(".", "/"), "OffsetDateTimeProvider.java")); supportingFiles.add(new SupportingFile("LocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateProvider.java")); } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java index d937842a128d..6ecf9a89c0eb 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java @@ -74,12 +74,16 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo protected boolean emitJSDoc = true; protected String apiDocPath = "docs/"; protected String modelDocPath = "docs/"; + protected String apiTestPath = "api/"; + protected String modelTestPath = "model/"; public JavascriptClientCodegen() { super(); outputFolder = "generated-code/js"; modelTemplateFiles.put("model.mustache", ".js"); + modelTestTemplateFiles.put("model_test.mustache", ".js"); apiTemplateFiles.put("api.mustache", ".js"); + apiTestTemplateFiles.put("api_test.mustache", ".js"); templateDir = "Javascript"; apiPackage = "api"; modelPackage = "model"; @@ -292,6 +296,8 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo supportingFiles.add(new SupportingFile("ApiClient.mustache", createPath(sourceFolder, invokerPackage), "ApiClient.js")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("mocha.opts", "", "mocha.opts")); + supportingFiles.add(new SupportingFile("travis.yml", "", ".travis.yml")); } @Override @@ -322,6 +328,16 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo return buf.toString(); } + @Override + public String apiTestFileFolder() { + return (outputFolder + "/test/" + apiTestPath).replace('/', File.separatorChar); + } + + @Override + public String modelTestFileFolder() { + return (outputFolder + "/test/" + modelTestPath).replace('/', File.separatorChar); + } + @Override public String apiFileFolder() { return createPath(outputFolder, sourceFolder, invokerPackage, apiPackage()); @@ -400,6 +416,16 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo return toModelName(name); } + @Override + public String toApiTestFilename(String name) { + return toApiName(name) + ".spec"; + } + + @Override + public String toModelTestFilename(String name) { + return toModelName(name) + ".spec"; + } + @Override public String toVarName(String name) { // sanitize name diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/LumenServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/LumenServerCodegen.java index fbd98c034df0..abc747435bf8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/LumenServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/LumenServerCodegen.java @@ -9,9 +9,20 @@ import java.io.File; public class LumenServerCodegen extends DefaultCodegen implements CodegenConfig { // source folder where to write the files - protected String sourceFolder = "src"; - protected String apiVersion = "1.0.0"; + protected String sourceFolder = ""; + public static final String SRC_BASE_PATH = "srcBasePath"; + public static final String COMPOSER_VENDOR_NAME = "composerVendorName"; + public static final String COMPOSER_PROJECT_NAME = "composerProjectName"; + protected String invokerPackage = "Swagger\\Client"; + protected String composerVendorName = null; + protected String composerProjectName = null; + protected String packagePath = "SwaggerClient-php"; + protected String artifactVersion = null; + protected String srcBasePath = "lib"; + protected String apiVersion = "1.0.0"; + protected String apiDirName = "Api"; + /** * Configures the type of generator. * @@ -46,13 +57,8 @@ public class LumenServerCodegen extends DefaultCodegen implements CodegenConfig super(); // set the output folder here - outputFolder = "generated-code/lumen"; - String packagePath = "lumen"; - - // modelPackage = packagePath + "\\lib\\Models"; - // apiPackage = packagePath + "\\lib"; - // // outputFolder = "generated-code" + File.separator + "slim"; - // modelTemplateFiles.put("model.mustache", ".php"); + outputFolder = "lumen"; + String packagePath = ""; /** * Models. You can write model files using the modelTemplateFiles map. @@ -75,7 +81,8 @@ public class LumenServerCodegen extends DefaultCodegen implements CodegenConfig // no api files - apiTemplateFiles.clear(); + // apiTemplateFiles.clear(); + apiTemplateFiles.put("api.mustache", ".php"); // embeddedTemplateDir = templateDir = "slim"; @@ -115,43 +122,18 @@ public class LumenServerCodegen extends DefaultCodegen implements CodegenConfig * entire object tree available. If the input file has a suffix of `.mustache * it will be processed by the template engine. Otherwise, it will be copied */ - // supportingFiles.add(new SupportingFile("index.mustache", packagePath, "index.php")); - // supportingFiles.add(new SupportingFile("routes.mustache", packagePath, "routes.php")); - - supportingFiles.add(new SupportingFile("composer.json", packagePath, "composer.json")); + supportingFiles.add(new SupportingFile("composer.mustache", packagePath, "composer.json")); supportingFiles.add(new SupportingFile("readme.md", packagePath, "readme.md")); - supportingFiles.add(new SupportingFile("artisan", packagePath, "artisan")); - // supportingFiles.add(new SupportingFile("server.php", packagePath, "server.php")); - - supportingFiles.add(new SupportingFile("bootstrap" + File.separator + "app.php", packagePath + File.separator + "bootstrap", "app.php")); - - supportingFiles.add(new SupportingFile("public" + File.separator + "index.php", packagePath + File.separator + "public", "index.php")); - - supportingFiles.add(new SupportingFile("app" + File.separator + "User.php", packagePath + File.separator + "app", "User.php")); - supportingFiles.add(new SupportingFile("app" + File.separator + "Console" + File.separator + "Kernel.php", packagePath + File.separator + "app" + File.separator + "Console", "Kernel.php")); - supportingFiles.add(new SupportingFile("app" + File.separator + "Exceptions" + File.separator + "Handler.php", packagePath + File.separator + "app" + File.separator + "Exceptions", "Handler.php")); - // supportingFiles.add(new SupportingFile("app" + File.separator + "Http" + File.separator + "Kernel.php", packagePath + File.separator + "app" + File.separator + "Http", "Kernel.php")); - supportingFiles.add(new SupportingFile("app" + File.separator + "Http" + File.separator + "routes.mustache", packagePath + File.separator + "app" + File.separator + "Http", "routes.php")); + supportingFiles.add(new SupportingFile("app.php", packagePath + File.separator + "bootstrap", "app.php")); + supportingFiles.add(new SupportingFile("index.php", packagePath + File.separator + "public", "index.php")); + supportingFiles.add(new SupportingFile("User.php", packagePath + File.separator + "app", "User.php")); + supportingFiles.add(new SupportingFile("Kernel.php", packagePath + File.separator + "app" + File.separator + "Console", "Kernel.php")); + supportingFiles.add(new SupportingFile("Handler.php", packagePath + File.separator + "app" + File.separator + "Exceptions", "Handler.php")); + supportingFiles.add(new SupportingFile("routes.mustache", packagePath + File.separator + "app" + File.separator + "Http", "routes.php")); - supportingFiles.add(new SupportingFile("app" + File.separator + "Http" + File.separator + "Controllers" + File.separator + "Controller.php", packagePath + File.separator + "app" + File.separator + "Http" + File.separator + "Controllers" + File.separator, "Controller.php")); - supportingFiles.add(new SupportingFile("app" + File.separator + "Http" + File.separator + "Controllers" + File.separator + "ExampleController.php", packagePath + File.separator + "app" + File.separator + "Http" + File.separator + "Controllers" + File.separator, "ExampleController.php")); - // supportingFiles.add(new SupportingFile("app" + File.separator + "Http" + File.separator + "Controllers" + File.separator + "Auth" + File.separator + "AuthController.php", packagePath + File.separator + "app" + File.separator + "Http" + File.separator + "Controllers" + File.separator + "Auth" + File.separator, "AuthController.php")); - // supportingFiles.add(new SupportingFile("app" + File.separator + "Http" + File.separator + "Controllers" + File.separator + "Auth" + File.separator + "PasswordController.php", packagePath + File.separator + "app" + File.separator + "Http" + File.separator + "Controllers" + File.separator + "Auth" + File.separator, "PasswordController.php")); + supportingFiles.add(new SupportingFile("Controller.php", packagePath + File.separator + "app" + File.separator + "Http" + File.separator + "Controllers" + File.separator, "Controller.php")); + supportingFiles.add(new SupportingFile("Authenticate.php", packagePath + File.separator + "app" + File.separator + "Http" + File.separator + "Middleware" + File.separator, "Authenticate.php")); - supportingFiles.add(new SupportingFile("app" + File.separator + "Http" + File.separator + "Middleware" + File.separator + "Authenticate.php", packagePath + File.separator + "app" + File.separator + "Http" + File.separator + "Middleware" + File.separator, "Authenticate.php")); - supportingFiles.add(new SupportingFile("app" + File.separator + "Http" + File.separator + "Middleware" + File.separator + "ExampleMiddleware.php", packagePath + File.separator + "app" + File.separator + "Http" + File.separator + "Middleware" + File.separator, "ExampleMiddleware.php")); - // supportingFiles.add(new SupportingFile("app" + File.separator + "Http" + File.separator + "Middleware" + File.separator + "RedirectIfAuthenticated.php", packagePath + File.separator + "app" + File.separator + "Http" + File.separator + "Middleware" + File.separator, "RedirectIfAuthenticated.php")); - // supportingFiles.add(new SupportingFile("app" + File.separator + "Http" + File.separator + "Middleware" + File.separator + "VerifyCsrfToken.php", packagePath + File.separator + "app" + File.separator + "Http" + File.separator + "Middleware" + File.separator, "VerifyCsrfToken.php")); - - // supportingFiles.add(new SupportingFile("app" + File.separator + "Http" + File.separator + "Requests" + File.separator + "Request.php", packagePath + File.separator + "app" + File.separator + "Http" + File.separator + "Requests" + File.separator, "Request.php")); - - supportingFiles.add(new SupportingFile("app" + File.separator + "Providers" + File.separator + "AppServiceProvider.php", packagePath + File.separator + "app" + File.separator + "Providers", "AppServiceProvider.php")); - supportingFiles.add(new SupportingFile("app" + File.separator + "Providers" + File.separator + "AuthServiceProvider.php", packagePath + File.separator + "app" + File.separator + "Providers", "AuthServiceProvider.php")); - supportingFiles.add(new SupportingFile("app" + File.separator + "Providers" + File.separator + "EventServiceProvider.php", packagePath + File.separator + "app" + File.separator + "Providers", "EventServiceProvider.php")); - // supportingFiles.add(new SupportingFile("app" + File.separator + "Providers" + File.separator + "RouteServiceProvider.php", packagePath + File.separator + "app" + File.separator + "Providers", "RouteServiceProvider.php")); - - // supportingFiles.add(new SupportingFile("config" + File.separator + "app.php", packagePath + File.separator + "config" + File.separator, "app.php")); - /** * Language Specific Primitives. These types will not trigger imports by * the client generator @@ -188,7 +170,8 @@ public class LumenServerCodegen extends DefaultCodegen implements CodegenConfig */ @Override public String apiFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); + return outputFolder + "/app/Http/controllers"; + // return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); } /** diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java index cc1e77649e58..4344d90c7ae8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java @@ -1,6 +1,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.*; +import io.swagger.models.ArrayModel; import io.swagger.models.Model; import io.swagger.models.properties.*; @@ -94,7 +95,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.clear(); typeMapping.put("enum", "NSString"); typeMapping.put("date", "NSDate"); - typeMapping.put("DateTime", "NSDate"); + typeMapping.put("datetime", "NSDate"); typeMapping.put("boolean", "NSNumber"); typeMapping.put("string", "NSString"); typeMapping.put("integer", "NSNumber"); @@ -105,12 +106,15 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("array", "NSArray"); typeMapping.put("map", "NSDictionary"); typeMapping.put("number", "NSNumber"); + typeMapping.put("bigdecimal", "NSNumber"); typeMapping.put("List", "NSArray"); typeMapping.put("object", "NSObject"); typeMapping.put("file", "NSURL"); typeMapping.put("binary", "NSData"); - typeMapping.put("ByteArray", "NSData"); + typeMapping.put("bytearray", "NSData"); typeMapping.put("byte", "NSData"); + typeMapping.put("uuid", "NSString"); + typeMapping.put("password", "NSString"); // ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm setReservedWordsLowerCase( @@ -293,8 +297,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { public String getSwaggerType(Property p) { String swaggerType = super.getSwaggerType(p); String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); + if (typeMapping.containsKey(swaggerType.toLowerCase())) { + type = typeMapping.get(swaggerType.toLowerCase()); if (languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type)) { return toModelNameWithoutReservedWordCheck(type); } @@ -304,15 +308,6 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { return toModelNameWithoutReservedWordCheck(type); } - public CodegenProperty coreDatafromProperty(String name, Property p) { - CodegenProperty property = fromProperty(name, p); - if(!generateCoreData) { - return property; - } - property.baseType = getTypeCoreDataDeclaration(p); - return property; - } - @Override public String getTypeDeclaration(Property p) { if (p instanceof ArrayProperty) { @@ -377,73 +372,6 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { } } - - public String getTypeCoreDataDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - String innerType = getSwaggerType(inner); - - String innerTypeDeclaration = getTypeDeclaration(inner); - if (innerTypeDeclaration.endsWith("*")) { - innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); - } - // In this codition, type of property p is array of primitive, - // return container type with pointer, e.g. `NSArray**' - if (languageSpecificPrimitives.contains(innerTypeDeclaration)) { - return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*"; - } - // In this codition, type of property p is array of model, - // return container type combine inner type with pointer, e.g. `NSArray*' - else { - for (String sd : advancedMapingTypes) { - if(innerTypeDeclaration.startsWith(sd)) { - return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*"; - } - } - return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*"; - } - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - - String innerTypeDeclaration = getTypeDeclaration(inner); - - if (innerTypeDeclaration.endsWith("*")) { - innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); - } - if (languageSpecificPrimitives.contains(innerTypeDeclaration)) { - return getSwaggerType(p) + "*"; - } else { - for (String s : advancedMapingTypes) { - if(innerTypeDeclaration.startsWith(s)) { - return getSwaggerType(p) + "*"; - } - } - return getSwaggerType(p) + "*"; - } - } else { - String swaggerType = getSwaggerType(p); - - // In this codition, type of p is objective-c primitive type, e.g. `NSSNumber', - // return type of p with pointer, e.g. `NSNumber*' - if (languageSpecificPrimitives.contains(swaggerType) && - foundationClasses.contains(swaggerType)) { - return swaggerType + "*"; - } - // In this codition, type of p is c primitive type, e.g. `bool', - // return type of p, e.g. `bool' - else if (languageSpecificPrimitives.contains(swaggerType)) { - return swaggerType; - } - // In this codition, type of p is objective-c object type, e.g. `SWGPet', - // return type of p with pointer, e.g. `SWGPet*' - else { - return swaggerType + "*"; - } - } - } - @Override public boolean isDataTypeBinary(String dataType) { return dataType.toLowerCase().startsWith("nsdata"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java index 51bd143ba8ff..ba9dfa2ab60f 100755 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java @@ -167,6 +167,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig } supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + supportingFiles.add(new SupportingFile("travis.mustache", "", ".travis.yml")); } private static String dropDots(String str) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java index aa32eb4e5100..2b8e35232874 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java @@ -104,8 +104,8 @@ public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("helpers-header.mustache", sourceFolder, PREFIX + "Helpers.h")); supportingFiles.add(new SupportingFile("helpers-body.mustache", sourceFolder, PREFIX + "Helpers.cpp")); - supportingFiles.add(new SupportingFile("HttpRequest.h", sourceFolder, PREFIX + "HttpRequest.h")); - supportingFiles.add(new SupportingFile("HttpRequest.cpp", sourceFolder, PREFIX + "HttpRequest.cpp")); + supportingFiles.add(new SupportingFile("HttpRequest.h.mustache", sourceFolder, PREFIX + "HttpRequest.h")); + supportingFiles.add(new SupportingFile("HttpRequest.cpp.mustache", sourceFolder, PREFIX + "HttpRequest.cpp")); supportingFiles.add(new SupportingFile("modelFactory.mustache", sourceFolder, PREFIX + "ModelFactory.h")); supportingFiles.add(new SupportingFile("object.mustache", sourceFolder, PREFIX + "Object.h")); @@ -135,6 +135,9 @@ public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig { systemIncludes.add("QString"); systemIncludes.add("QList"); + systemIncludes.add("QMap"); + systemIncludes.add("QDate"); + systemIncludes.add("QDateTime"); } /** diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java index 12467f12efef..b740ba552a1e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java @@ -87,6 +87,8 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig supportingFiles.add(new SupportingFile( "gradle-wrapper.jar", gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.jar") ); + supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); + importMapping.remove("List"); importMapping.remove("Set"); importMapping.remove("Map"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java index d3fb0bf1881d..46a3af763243 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java @@ -86,7 +86,7 @@ public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConf supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("build.sbt", "", "build.sbt")); supportingFiles.add(new SupportingFile("web.xml", "/src/main/webapp/WEB-INF", "web.xml")); - supportingFiles.add(new SupportingFile("JettyMain.scala", sourceFolder, "JettyMain.scala")); + supportingFiles.add(new SupportingFile("JettyMain.mustache", sourceFolder, "JettyMain.scala")); supportingFiles.add(new SupportingFile("Bootstrap.mustache", sourceFolder, "ScalatraBootstrap.scala")); supportingFiles.add(new SupportingFile("ServletApp.mustache", sourceFolder, "ServletApp.scala")); supportingFiles.add(new SupportingFile("project/build.properties", "project", "build.properties")); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringBootServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringBootServerCodegen.java index dbed6bc98c47..4b30062d7999 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringBootServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringBootServerCodegen.java @@ -12,11 +12,15 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege public static final String BASE_PACKAGE = "basePackage"; public static final String INTERFACE_ONLY = "interfaceOnly"; public static final String SINGLE_CONTENT_TYPES = "singleContentTypes"; + public static final String JAVA_8 = "java8"; + public static final String ASYNC = "async"; protected String title = "Petstore Server"; protected String configPackage = ""; protected String basePackage = ""; protected boolean interfaceOnly = false; protected boolean singleContentTypes = false; + protected boolean java8 = false; + protected boolean async = false; protected String templateFileName = "api.mustache"; public SpringBootServerCodegen() { @@ -45,11 +49,14 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege 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.")); + cliOptions.add(CliOption.newBoolean(JAVA_8, "use java8 default interface")); + cliOptions.add(CliOption.newBoolean(ASYNC, "use async Callable controllers")); supportedLibraries.clear(); supportedLibraries.put(DEFAULT_LIBRARY, "Default Spring Boot server stub."); supportedLibraries.put("j8-async", "Use async servlet feature and Java 8's default interface. Generating interface with service " + - "declaration is useful when using Maven plugin. Just provide a implementation with @Controller to instantiate service."); + "declaration is useful when using Maven plugin. Just provide a implementation with @Controller to instantiate service." + + "(DEPRECATED: use -Djava8=true,async=true instead)"); } @Override @@ -92,11 +99,19 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege this.setSingleContentTypes(Boolean.valueOf(additionalProperties.get(SINGLE_CONTENT_TYPES).toString())); } + if (additionalProperties.containsKey(JAVA_8)) { + this.setJava8(Boolean.valueOf(additionalProperties.get(JAVA_8).toString())); + } + + if (additionalProperties.containsKey(ASYNC)) { + this.setAsync(Boolean.valueOf(additionalProperties.get(ASYNC).toString())); + } + supportingFiles.clear(); supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - if(!this.interfaceOnly) { + 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")); @@ -115,6 +130,19 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege supportingFiles.add(new SupportingFile("application.properties", ("src.main.resources").replace(".", java.io.File.separator), "application.properties")); } + + if ("j8-async".equals(getLibrary())) { + setJava8(true); + setAsync(true); + } + + if (this.java8) { + additionalProperties.put("javaVersion", "1.8"); + typeMapping.put("date", "LocalDate"); + typeMapping.put("DateTime", "OffsetDateTime"); + importMapping.put("LocalDate", "java.time.LocalDate"); + importMapping.put("OffsetDateTime", "java.time.OffsetDateTime"); + } } @Override @@ -228,23 +256,6 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege } } } - if("j8-async".equals(getLibrary())) { - apiTemplateFiles.remove(this.templateFileName); - this.templateFileName = "api-j8-async.mustache"; - apiTemplateFiles.put(this.templateFileName, ".java"); - - int originalPomFileIdx = -1; - for (int i = 0; i < supportingFiles.size(); i++) { - if ("pom.xml".equals(supportingFiles.get(i).destinationFilename)) { - originalPomFileIdx = i; - break; - } - } - if (originalPomFileIdx > -1) { - supportingFiles.remove(originalPomFileIdx); - } - supportingFiles.add(new SupportingFile("pom-j8-async.mustache", "", "pom.xml")); - } return objs; } @@ -266,13 +277,15 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege this.basePackage = configPackage; } - public void setInterfaceOnly(boolean interfaceOnly) { - this.interfaceOnly = interfaceOnly; - } + public void setInterfaceOnly(boolean interfaceOnly) { this.interfaceOnly = interfaceOnly; } public void setSingleContentTypes(boolean singleContentTypes) { this.singleContentTypes = singleContentTypes; } + + public void setJava8(boolean java8) { this.java8 = java8; } + + public void setAsync(boolean async) { this.async = async; } @Override public Map postProcessModels(Map objs) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngular2ClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngular2ClientCodegen.java index 6a945249af6c..c9dd10b2a58e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngular2ClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngular2ClientCodegen.java @@ -68,6 +68,8 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod supportingFiles.add(new SupportingFile("models.mustache", modelPackage().replace('.', File.separatorChar), "models.ts")); supportingFiles.add(new SupportingFile("apis.mustache", apiPackage().replace('.', File.separatorChar), "api.ts")); supportingFiles.add(new SupportingFile("index.mustache", getIndexDirectory(), "index.ts")); + supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); if(additionalProperties.containsKey(NPM_NAME)) { addNpmPackageGeneration(); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java index 242293fc258c..2853c1b379bf 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java @@ -21,7 +21,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode super.processOpts(); supportingFiles.add(new SupportingFile("api.d.mustache", apiPackage().replace('.', File.separatorChar), "api.d.ts")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); - //supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore")); } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java index 90f778eae8e8..cf25259e61c8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java @@ -30,6 +30,7 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege supportingFiles.add(new SupportingFile("package.json.mustache", "", "package.json")); supportingFiles.add(new SupportingFile("typings.json.mustache", "", "typings.json")); supportingFiles.add(new SupportingFile("tsconfig.json.mustache", "", "tsconfig.json")); + supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore")); if(additionalProperties.containsKey(NPM_NAME)) { this.setNpmName(additionalProperties.get(NPM_NAME).toString()); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java index 516d34b9810b..db9e2fcf2ad6 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java @@ -41,6 +41,7 @@ public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen super.processOpts(); supportingFiles.add(new SupportingFile("api.mustache", null, "api.ts")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore")); if(additionalProperties.containsKey(NPM_NAME)) { addNpmPackageGeneration(); diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index 4c79216bc557..eb402d9f8dab 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -1,8 +1,9 @@ package {{invokerPackage}}; import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.*; -import com.fasterxml.jackson.datatype.joda.*; +import com.fasterxml.jackson.databind.*;{{#java8}} +import com.fasterxml.jackson.datatype.jsr310.*;{{/java8}}{{^java8}} +import com.fasterxml.jackson.datatype.joda.*;{{/java8}} import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; import com.sun.jersey.api.client.Client; @@ -64,8 +65,9 @@ public class ApiClient { objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); - objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); - objectMapper.registerModule(new JodaModule()); + objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);{{#java8}} + objectMapper.registerModule(new JavaTimeModule());{{/java8}}{{^java8}} + objectMapper.registerModule(new JodaModule());{{/java8}} objectMapper.setDateFormat(ApiClient.buildDefaultDateFormat()); dateFormat = ApiClient.buildDefaultDateFormat(); diff --git a/modules/swagger-codegen/src/main/resources/Java/gitignore.mustache b/modules/swagger-codegen/src/main/resources/Java/gitignore.mustache index 7cf39af816c9..a530464afa1b 100644 --- a/modules/swagger-codegen/src/main/resources/Java/gitignore.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/gitignore.mustache @@ -13,3 +13,9 @@ # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* + +# build files +**/target +target +.gradle +build diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache index 58bab66e13d6..14d1c224c1ef 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache @@ -98,6 +98,15 @@ public class ApiClient { return json; } + public Client getHttpClient() { + return httpClient; + } + + public ApiClient setHttpClient(Client httpClient) { + this.httpClient = httpClient; + return this; + } + public String getBasePath() { return basePath; } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/JSON.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/JSON.mustache index cc3f1baba140..5de3af16f595 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/JSON.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/JSON.mustache @@ -1,8 +1,9 @@ package {{invokerPackage}}; import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.*; -import com.fasterxml.jackson.datatype.joda.*; +import com.fasterxml.jackson.databind.*;{{#java8}} +import com.fasterxml.jackson.datatype.jsr310.*;{{/java8}}{{^java8}} +import com.fasterxml.jackson.datatype.joda.*;{{/java8}} import java.text.DateFormat; @@ -18,8 +19,9 @@ public class JSON implements ContextResolver { mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); - mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); - mapper.registerModule(new JodaModule()); + mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);{{#java8}} + mapper.registerModule(new JavaTimeModule());{{/java8}}{{^java8}} + mapper.registerModule(new JodaModule());{{/java8}} } /** diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.gradle.mustache index aa0e6da3fb06..42af6834251c 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.gradle.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.gradle.mustache @@ -31,9 +31,11 @@ if(hasProperty('target') && target == 'android') { minSdkVersion 14 targetSdkVersion 23 } - compileOptions { + compileOptions { {{#java8}} + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8{{/java8}}{{^java8}} sourceCompatibility JavaVersion.VERSION_1_7 - targetCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7{{/java8}} } // Rename the aar correctly @@ -77,9 +79,11 @@ if(hasProperty('target') && target == 'android') { apply plugin: 'java' apply plugin: 'maven' - + {{#java8}} + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8{{/java8}}{{^java8}} sourceCompatibility = JavaVersion.VERSION_1_7 - targetCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7{{/java8}} install { repositories.mavenInstaller { @@ -96,8 +100,8 @@ if(hasProperty('target') && target == 'android') { ext { swagger_annotations_version = "1.5.8" jackson_version = "2.7.0" - jersey_version = "2.22.2" - jodatime_version = "2.9.3" + jersey_version = "2.22.2"{{^java8}} + jodatime_version = "2.9.3"{{/java8}} junit_version = "4.12" } @@ -108,9 +112,10 @@ dependencies { compile "org.glassfish.jersey.media:jersey-media-json-jackson:2.22.1" compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" - compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version"{{#java8}} + compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version"{{/java8}}{{^java8}} compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:2.1.5" - compile "joda-time:joda-time:$jodatime_version" + compile "joda-time:joda-time:$jodatime_version"{{/java8}} compile "com.brsanthu:migbase64:2.2" testCompile "junit:junit:$junit_version" } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.sbt.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.sbt.mustache index 0a297497d9db..21e7dbceaa6f 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.sbt.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.sbt.mustache @@ -15,9 +15,10 @@ lazy val root = (project in file(".")). "org.glassfish.jersey.media" % "jersey-media-json-jackson" % "2.22.1", "com.fasterxml.jackson.core" % "jackson-core" % "2.7.0", "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.0", - "com.fasterxml.jackson.core" % "jackson-databind" % "2.7.0", + "com.fasterxml.jackson.core" % "jackson-databind" % "2.7.0",{{#java8}} + "com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % "2.7.0",{{/java8}}{{^java8}} "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.1.5", - "joda-time" % "joda-time" % "2.9.3", + "joda-time" % "joda-time" % "2.9.3",{{/java8}} "com.brsanthu" % "migbase64" % "2.2", "junit" % "junit" % "4.12" % "test", "com.novocode" % "junit-interface" % "0.10" % "test" diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/pom.mustache index 472bbf9b9b8e..2e2a38daee5a 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/pom.mustache @@ -99,32 +99,13 @@ org.apache.maven.plugins maven-compiler-plugin 2.3.2 - + {{#java8}} + 1.8 + 1.8{{/java8}}{{^java8}} 1.7 - 1.7 + 1.7{{/java8}} - - - org.codehaus.mojo - exec-maven-plugin - 1.2.1 - - - gradle-test - integration-test - - exec - - - gradle - - check - - - - - @@ -166,7 +147,12 @@ com.fasterxml.jackson.core jackson-databind ${jackson-version} - + {{#java8}} + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson-version} + {{/java8}}{{^java8}} com.fasterxml.jackson.datatype jackson-datatype-joda @@ -176,7 +162,7 @@ joda-time joda-time ${jodatime-version} - + {{/java8}} @@ -196,8 +182,8 @@ 1.5.8 2.22.2 - 2.7.0 - 2.9.3 + 2.7.0{{^java8}} + 2.9.3{{/java8}} 1.0.0 4.12 diff --git a/modules/swagger-codegen/src/main/resources/Java/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/pom.mustache index 8521b54bad0c..a43cb3c1c196 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pom.mustache @@ -96,9 +96,11 @@ org.apache.maven.plugins maven-compiler-plugin 2.3.2 - + {{#java8}} + 1.8 + 1.8{{/java8}}{{^java8}} 1.7 - 1.7 + 1.7{{/java8}} @@ -142,7 +144,12 @@ com.fasterxml.jackson.jaxrs jackson-jaxrs-json-provider ${jackson-version} - + {{#java8}} + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson-version} + {{/java8}}{{^java8}} com.fasterxml.jackson.datatype jackson-datatype-joda @@ -152,7 +159,7 @@ joda-time joda-time ${jodatime-version} - + {{/java8}} @@ -173,8 +180,8 @@ UTF-8 1.5.8 1.19.1 - 2.7.0 - 2.9.3 + 2.7.0{{^java8}} + 2.9.3{{/java8}} 1.0.0 4.12 diff --git a/modules/swagger-codegen/src/main/resources/Java/travis.mustache b/modules/swagger-codegen/src/main/resources/Java/travis.mustache new file mode 100644 index 000000000000..33e79472abd8 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/travis.mustache @@ -0,0 +1,29 @@ +# +# 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: java +jdk: + - oraclejdk8 + - oraclejdk7 +before_install: + # ensure gradlew has proper permission + - chmod a+x ./gradlew +script: + # test using maven + - mvn test + # uncomment below to test using gradle + # - gradle test + # uncomment below to test using sbt + # - sbt test diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache index f17abb0d2220..c214ae2ae84d 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache @@ -18,6 +18,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{>enumClass}}{{/items}}{{/items.isEnum}} + @XmlElement(name="{{baseName}}") private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}} {{#vars}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/LocalDateTimeProvider.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/OffsetDateTimeProvider.mustache similarity index 67% rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/LocalDateTimeProvider.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/OffsetDateTimeProvider.mustache index 93bb6f19d506..876aeb327be7 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/LocalDateTimeProvider.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/OffsetDateTimeProvider.mustache @@ -11,23 +11,23 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriInfo; import javax.ws.rs.ext.Provider; -import java.time.LocalDateTime; +import java.time.OffsetDateTime; import java.util.List; @Provider -public class LocalDateTimeProvider extends PerRequestTypeInjectableProvider { +public class OffsetDateTimeProvider extends PerRequestTypeInjectableProvider { private final UriInfo uriInfo; - public LocalDateTimeProvider(@Context UriInfo uriInfo) { - super(LocalDateTime.class); + public OffsetDateTimeProvider(@Context UriInfo uriInfo) { + super(OffsetDateTime.class); this.uriInfo = uriInfo; } @Override - public Injectable getInjectable(final ComponentContext cc, final QueryParam a) { - return new Injectable() { + public Injectable getInjectable(final ComponentContext cc, final QueryParam a) { + return new Injectable() { @Override - public LocalDateTime getValue() { + public OffsetDateTime getValue() { final List values = uriInfo.getQueryParameters().get(a.value()); if (values == null || values.isEmpty()) @@ -37,7 +37,7 @@ public class LocalDateTimeProvider extends PerRequestTypeInjectableProvider { +public class OffsetDateTimeProvider extends PerRequestTypeInjectableProvider { private final UriInfo uriInfo; - public LocalDateTimeProvider(@Context UriInfo uriInfo) { - super(LocalDateTime.class); + public OffsetDateTimeProvider(@Context UriInfo uriInfo) { + super(OffsetDateTime.class); this.uriInfo = uriInfo; } @Override - public Injectable getInjectable(final ComponentContext cc, final QueryParam a) { - return new Injectable() { + public Injectable getInjectable(final ComponentContext cc, final QueryParam a) { + return new Injectable() { @Override - public LocalDateTime getValue() { + public OffsetDateTime getValue() { final List values = uriInfo.getQueryParameters().get(a.value()); if (values == null || values.isEmpty()) @@ -37,7 +37,7 @@ public class LocalDateTimeProvider extends PerRequestTypeInjectableProvider { - - @Override - public LocalDateTime fromString(String string) { - LocalDateTime localDateTime = LocalDateTime.parse(string); - return localDateTime; - } - - @Override - public String toString(LocalDateTime t) { - return t.toString(); - } - } - - @Override - public ParamConverter getConverter(Class type, Type type1, Annotation[] antns) { - if (LocalDateTime.class.equals(type)) { - return (ParamConverter) new LocalDateTimeConverter(); - } - return null; - } -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/OffsetDateTimeProvider.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/OffsetDateTimeProvider.mustache new file mode 100644 index 000000000000..f24dabbe2834 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/OffsetDateTimeProvider.mustache @@ -0,0 +1,34 @@ +package {{apiPackage}}; + +import java.time.OffsetDateTime; +import javax.ws.rs.ext.ParamConverter; +import javax.ws.rs.ext.ParamConverterProvider; +import javax.ws.rs.ext.Provider; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; + +@Provider +public class OffsetDateTimeProvider implements ParamConverterProvider { + + public static class OffsetDateTimeConverter implements ParamConverter { + + @Override + public OffsetDateTime fromString(String string) { + OffsetDateTime OffsetDateTime = OffsetDateTime.parse(string); + return OffsetDateTime; + } + + @Override + public String toString(OffsetDateTime t) { + return t.toString(); + } + } + + @Override + public ParamConverter getConverter(Class type, Type type1, Annotation[] antns) { + if (OffsetDateTime.class.equals(type)) { + return (ParamConverter) new OffsetDateTimeConverter(); + } + return null; + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/api.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/api.mustache index bd0d71805296..c3b3bb669083 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/api.mustache @@ -1,12 +1,12 @@ package {{apiPackage}}; -import {{modelPackage}}.*; - {{#imports}}import {{import}}; {{/imports}} import io.swagger.annotations.*; - +{{#java8}} +import org.springframework.http.HttpStatus; +{{/java8}} import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; @@ -18,33 +18,37 @@ import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.multipart.MultipartFile; import java.util.List; +{{#async}} +import java.util.concurrent.Callable; +{{/async}} -import static org.springframework.http.MediaType.*; - -@Api(value = "{{{baseName}}}", description = "the {{{baseName}}} API") {{>generatedAnnotation}} +@Api(value = "{{{baseName}}}", description = "the {{{baseName}}} API") {{#operations}} public interface {{classname}} { - {{#operation}} +{{#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}}) - @ApiResponses(value = { {{#responses}} - @ApiResponse(code = {{{code}}}, message = "{{{message}}}", response = {{{returnType}}}.class){{#hasMore}},{{/hasMore}}{{/responses}} }) - @RequestMapping(value = "{{{path}}}",{{#singleContentTypes}} - produces = "{{{vendorExtensions.x-accepts}}}", - 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}}) - ResponseEntity<{{>returnTypes}}> {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, - {{/hasMore}}{{/allParams}}); + @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}}) + @ApiResponses(value = { {{#responses}} + @ApiResponse(code = {{{code}}}, message = "{{{message}}}", response = {{{returnType}}}.class){{#hasMore}},{{/hasMore}}{{/responses}} }) + @RequestMapping(value = "{{{path}}}",{{#singleContentTypes}} + produces = "{{{vendorExtensions.x-accepts}}}", + 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}}) + {{#java8}}default {{/java8}}{{#async}}Callable<{{/async}}ResponseEntity<{{>returnTypes}}>{{#async}}>{{/async}} {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, + {{/hasMore}}{{/allParams}}){{^java8}};{{/java8}}{{#java8}} { + // do some magic! + return {{#async}}() -> {{/async}}new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK); + }{{/java8}} - {{/operation}} +{{/operation}} } {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/apiController.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/apiController.mustache index 0cde913d6602..f9c03faafc12 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/apiController.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/apiController.mustache @@ -1,7 +1,6 @@ package {{apiPackage}}; -import {{modelPackage}}.*; - +{{^java8}} {{#imports}}import {{import}}; {{/imports}} @@ -9,7 +8,9 @@ import io.swagger.annotations.*; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +{{/java8}} import org.springframework.stereotype.Controller; +{{^java8}} import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -18,18 +19,26 @@ import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.multipart.MultipartFile; import java.util.List; +{{#async}} +import java.util.concurrent.Callable; +{{/async}}{{/java8}} -@Controller {{>generatedAnnotation}} +@Controller {{#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}} +{{^java8}}{{#operation}} + public {{#async}}Callable<{{/async}}ResponseEntity<{{>returnTypes}}>{{#async}}>{{/async}} {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, + {{/hasMore}}{{/allParams}}) { + // do some magic!{{^async}} + return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK);{{/async}}{{#async}} + return new CallablereturnTypes}}>>() { + @Override + public ResponseEntity<{{>returnTypes}}> call() throws Exception { + return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK); + } + };{{/async}} + } +{{/operation}}{{/java8}} } {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/pom.mustache index 53c3652cb45b..d3b0cbfd467a 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/pom.mustache @@ -1,63 +1,78 @@ - 4.0.0 - {{groupId}} - {{artifactId}} - jar - {{artifactId}} - {{artifactVersion}} - - 2.4.0 - - - org.springframework.boot - spring-boot-starter-parent - 1.3.3.RELEASE - - - src/main/java{{^interfaceOnly}} - - - org.springframework.boot - spring-boot-maven-plugin - - - - repackage - - - - - {{/interfaceOnly}} - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - provided - - - - io.springfox - springfox-swagger2 - ${springfox-version} - - - io.springfox - springfox-swagger-ui - ${springfox-version} - + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + + 2.4.0 + {{#java8}} + 1.8 + 1.8 + {{/java8}} + + + org.springframework.boot + spring-boot-starter-parent + 1.3.3.RELEASE + + + src/main/java + {{^interfaceOnly}} + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + {{/interfaceOnly}} + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + io.springfox + springfox-swagger2 + ${springfox-version} + + + io.springfox + springfox-swagger-ui + ${springfox-version} + + {{#java8}} - - com.fasterxml.jackson.datatype - jackson-datatype-joda - - - joda-time - joda-time - - + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + {{/java8}} + {{^java8}} + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + + + joda-time + joda-time + + {{/java8}} + \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/swaggerDocumentationConfig.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/swaggerDocumentationConfig.mustache index 970739e1b979..fc4af3892c66 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/swaggerDocumentationConfig.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/swaggerDocumentationConfig.mustache @@ -30,13 +30,15 @@ public class SwaggerDocumentationConfig { @Bean public Docket customImplementation(){ - return new Docket(DocumentationType.SWAGGER_2) - .select() - .apis(RequestHandlerSelectors.basePackage("{{apiPackage}}")) - .build() - .directModelSubstitute(org.joda.time.LocalDate.class, java.sql.Date.class) - .directModelSubstitute(org.joda.time.DateTime.class, java.util.Date.class) - .apiInfo(apiInfo()); + return new Docket(DocumentationType.SWAGGER_2) + .select() + .apis(RequestHandlerSelectors.basePackage("{{apiPackage}}")) + .build(){{#java8}} + .directModelSubstitute(java.time.LocalDate.class, java.sql.Date.class) + .directModelSubstitute(java.time.OffsetDateTime.class, java.util.Date.class){{/java8}}{{^java8}} + .directModelSubstitute(org.joda.time.LocalDate.class, java.sql.Date.class) + .directModelSubstitute(org.joda.time.DateTime.class, java.util.Date.class){{/java8}} + .apiInfo(apiInfo()); } } diff --git a/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache index 25a0e5155aaf..36a484258ec0 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. @@ -488,7 +489,7 @@ } else { for (var k in data) { if (data.hasOwnProperty(k)) - result[k] = exports.convertToType(data[k], itemType); + obj[k] = exports.convertToType(data[k], itemType); } } }; diff --git a/modules/swagger-codegen/src/main/resources/Javascript/api.mustache b/modules/swagger-codegen/src/main/resources/Javascript/api.mustache index 14abda4751cf..375acd90ac72 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/api.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} {{=< >=}}(function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. diff --git a/modules/swagger-codegen/src/main/resources/Javascript/api_test.mustache b/modules/swagger-codegen/src/main/resources/Javascript/api_test.mustache new file mode 100644 index 000000000000..181c114ca965 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Javascript/api_test.mustache @@ -0,0 +1,55 @@ +{{>licenseInfo}} +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', '../../src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require('../../src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.{{moduleName}}); + } +}(this, function(expect, {{moduleName}}) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new {{moduleName}}.{{classname}}(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('{{classname}}', function() { +{{#operations}} +{{#operation}} + describe('{{operationId}}', function() { + it('should call {{operationId}} successfully', function(done) { + //uncomment below and update the code to test {{operationId}} + //instance.{{operationId}}(pet, function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); +{{/operation}} +{{/operations}} + }); + +})); diff --git a/modules/swagger-codegen/src/main/resources/Javascript/index.mustache b/modules/swagger-codegen/src/main/resources/Javascript/index.mustache index 1561763af0ea..d6ca3cff7042 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/index.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/index.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} (function(factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. diff --git a/modules/swagger-codegen/src/main/resources/Javascript/licenseInfo.mustache b/modules/swagger-codegen/src/main/resources/Javascript/licenseInfo.mustache new file mode 100644 index 000000000000..861d97234cfa --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Javascript/licenseInfo.mustache @@ -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. + */ diff --git a/modules/swagger-codegen/src/main/resources/Javascript/mocha.opts b/modules/swagger-codegen/src/main/resources/Javascript/mocha.opts new file mode 100644 index 000000000000..907011807d68 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Javascript/mocha.opts @@ -0,0 +1 @@ +--timeout 10000 diff --git a/modules/swagger-codegen/src/main/resources/Javascript/model.mustache b/modules/swagger-codegen/src/main/resources/Javascript/model.mustache index db480f05b1d1..95f2b2df81dd 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/model.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/model.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. diff --git a/modules/swagger-codegen/src/main/resources/Javascript/model_test.mustache b/modules/swagger-codegen/src/main/resources/Javascript/model_test.mustache new file mode 100644 index 000000000000..2b43b3388126 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Javascript/model_test.mustache @@ -0,0 +1,65 @@ +{{>licenseInfo}} +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', '../../src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require('../../src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.{{moduleName}}); + } +}(this, function(expect, {{moduleName}}) { + 'use strict'; + + var instance; + + beforeEach(function() { +{{#models}} +{{#model}} +{{^isEnum}} + instance = new {{moduleName}}.{{classname}}(); +{{/isEnum}} +{{/model}} +{{/models}} + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('{{classname}}', function() { + it('should create an instance of {{classname}}', function() { + // uncomment below and update the code to test {{classname}} + //var instane = new {{moduleName}}.{{classname}}(); + //expect(instance).to.be.a({{moduleName}}.{{classname}}); + }); + +{{#models}} +{{#model}} +{{#vars}} + it('should have the property {{name}} (base name: "{{baseName}}")', function() { + // uncomment below and update the code to test the property {{name}} + //var instane = new {{moduleName}}.{{classname}}(); + //expect(instance).to.be(); + }); + +{{/vars}} +{{/model}} +{{/models}} + }); + +})); diff --git a/modules/swagger-codegen/src/main/resources/Javascript/travis.yml b/modules/swagger-codegen/src/main/resources/Javascript/travis.yml new file mode 100644 index 000000000000..e49f4692f7c8 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Javascript/travis.yml @@ -0,0 +1,7 @@ +language: node_js +node_js: + - "6" + - "6.1" + - "5" + - "5.11" + diff --git a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig index f0d0fde5e576..c75af63df840 100644 --- a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig +++ b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig @@ -2,6 +2,7 @@ io.swagger.codegen.languages.AndroidClientCodegen io.swagger.codegen.languages.AspNet5ServerCodegen io.swagger.codegen.languages.AsyncScalaClientCodegen io.swagger.codegen.languages.CSharpClientCodegen +io.swagger.codegen.languages.CppRestClientCodegen io.swagger.codegen.languages.DartClientCodegen io.swagger.codegen.languages.FlashClientCodegen io.swagger.codegen.languages.FlaskConnexionCodegen @@ -46,3 +47,4 @@ io.swagger.codegen.languages.CsharpDotNet2ClientCodegen io.swagger.codegen.languages.ClojureClientCodegen io.swagger.codegen.languages.HaskellServantCodegen io.swagger.codegen.languages.LumenServerCodegen +io.swagger.codegen.languages.GoServerCodegen \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache index 20c303e40eb1..df1b5e05acec 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} import * as querystring from "querystring"; import * as url from "url"; diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/gitignore b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/gitignore new file mode 100644 index 000000000000..35e2fb2b02ed --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/gitignore @@ -0,0 +1,3 @@ +wwwroot/*.js +node_modules +typings diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/licenseInfo.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/licenseInfo.mustache new file mode 100644 index 000000000000..861d97234cfa --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/licenseInfo.mustache @@ -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. + */ diff --git a/modules/swagger-codegen/src/main/resources/_common/.swagger-codegen-ignore b/modules/swagger-codegen/src/main/resources/_common/.swagger-codegen-ignore index 19d3377182e2..c5fa491b4c55 100644 --- a/modules/swagger-codegen/src/main/resources/_common/.swagger-codegen-ignore +++ b/modules/swagger-codegen/src/main/resources/_common/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/deleterequest.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/deleterequest.mustache index 6b0600e77b95..b5def5f589f7 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/deleterequest.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/deleterequest.mustache @@ -34,11 +34,17 @@ public class DeleteRequest extends Request { @Override public String getBodyContentType() { + if(entity == null) { + return null; + } return entity.getContentType().getValue(); } @Override public byte[] getBody() throws AuthFailureError { + if(entity == null) { + return null; + } ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { entity.writeTo(bos); diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/patchrequest.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/patchrequest.mustache index 188fc5edb416..3607a03eeabd 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/patchrequest.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/patchrequest.mustache @@ -34,11 +34,17 @@ public class PatchRequest extends Request { @Override public String getBodyContentType() { + if(entity == null) { + return null; + } return entity.getContentType().getValue(); } @Override public byte[] getBody() throws AuthFailureError { + if(entity == null) { + return null; + } ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { entity.writeTo(bos); diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/postrequest.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/postrequest.mustache index 02c7fdfb119d..7d0d1fe1c14e 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/postrequest.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/postrequest.mustache @@ -34,11 +34,17 @@ public class PostRequest extends Request { @Override public String getBodyContentType() { + if(entity == null) { + return null; + } return entity.getContentType().getValue(); } @Override public byte[] getBody() throws AuthFailureError { + if(entity == null) { + return null; + } ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { entity.writeTo(bos); diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/putrequest.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/putrequest.mustache index 571a921e56ad..a9dd14b0a7b0 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/putrequest.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/putrequest.mustache @@ -34,11 +34,17 @@ public class PutRequest extends Request { @Override public String getBodyContentType() { + if(entity == null) { + return null; + } return entity.getContentType().getValue(); } @Override public byte[] getBody() throws AuthFailureError { + if(entity == null) { + return null; + } ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { entity.writeTo(bos); diff --git a/modules/swagger-codegen/src/main/resources/cpprest/api-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/api-header.mustache new file mode 100644 index 000000000000..02880a18859f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/api-header.mustache @@ -0,0 +1,49 @@ +{{>licenseInfo}} +{{#operations}}/* + * {{classname}}.h + * + * {{description}} + */ + +#ifndef {{classname}}_H_ +#define {{classname}}_H_ + +{{{defaultInclude}}} +#include "ApiClient.h" + +{{#imports}}{{{import}}} +{{/imports}} + +{{#apiNamespaceDeclarations}} +namespace {{this}} { +{{/apiNamespaceDeclarations}} + +using namespace {{modelNamespace}}; + +class {{declspec}} {{classname}} +{ +public: + {{classname}}( std::shared_ptr apiClient ); + virtual ~{{classname}}(); + {{#operation}} + /// + /// {{summary}} + /// + /// + /// {{notes}} + /// + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{/allParams}} + pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}> {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{/operation}} + +protected: + std::shared_ptr m_ApiClient; +}; + +{{#apiNamespaceDeclarations}} +} +{{/apiNamespaceDeclarations}} + +#endif /* {{classname}}_H_ */ + +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/cpprest/api-source.mustache b/modules/swagger-codegen/src/main/resources/cpprest/api-source.mustache new file mode 100644 index 000000000000..b6312e37a7fd --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/api-source.mustache @@ -0,0 +1,270 @@ +{{>licenseInfo}} +{{#operations}} + +#include "{{classname}}.h" +#include "IHttpBody.h" +#include "JsonBody.h" +#include "MultipartFormData.h" + +#include + +#include + +{{#apiNamespaceDeclarations}} +namespace {{this}} { +{{/apiNamespaceDeclarations}} + +using namespace {{modelNamespace}}; + +{{classname}}::{{classname}}( std::shared_ptr apiClient ) + : m_ApiClient(apiClient) +{ +} + +{{classname}}::~{{classname}}() +{ +} + +{{#operation}} +pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}> {{classname}}::{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) +{ + {{#allParams}}{{#required}}{{^isPrimitiveType}}{{^isContainer}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == nullptr) + { + throw ApiException(400, U("Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}")); + } + {{/isContainer}}{{/isPrimitiveType}}{{/required}}{{/allParams}} + + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); + utility::string_t path = U("{{path}}"); + {{#pathParams}}boost::replace_all(path, U("{") U("{{baseName}}") U("}"), ApiClient::parameterToString({{{paramName}}})); + {{/pathParams}} + + std::map queryParams; + std::map headerParams( apiConfiguration->getDefaultHeaders() ); + std::map formParams; + std::map> fileParams; + + std::unordered_set responseHttpContentTypes; + {{#produces}}responseHttpContentTypes.insert( U("{{mediaType}}") ); + {{/produces}} + + utility::string_t responseHttpContentType; + + // use JSON if possible + if ( responseHttpContentTypes.size() == 0 || responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + { + responseHttpContentType = U("application/json"); + } + // multipart formdata + else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) + { + responseHttpContentType = U("multipart/form-data"); + } + else + { + throw ApiException(400, U("{{classname}}->{{operationId}} does not produce any supported media type")); + } + + headerParams[U("Accept")] = responseHttpContentType; + + std::unordered_set consumeHttpContentTypes; + {{#consumes}}consumeHttpContentTypes.insert( U("{{mediaType}}") ); + {{/consumes}} + + {{#allParams}}{{^isBodyParam}}{{^isPrimitiveType}}{{^isContainer}}if ({{paramName}} != nullptr){{/isContainer}}{{/isPrimitiveType}} + { + {{#isContainer}}{{#isQueryParam}}queryParams[U("{{baseName}}")] = ApiClient::parameterToArrayString<{{items.datatype}}>({{paramName}}); + {{/isQueryParam}}{{#isHeaderParam}}headerParams[U("{{baseName}}")] = ApiClient::parameterToArrayString<{{items.datatype}}>({{paramName}}); + {{/isHeaderParam}}{{#isFormParam}}{{^isFile}}formParams[ U("{{baseName}}") ] = ApiClient::parameterToArrayString<{{items.datatype}}>({{paramName}}); + {{/isFile}}{{/isFormParam}}{{/isContainer}}{{^isContainer}}{{#isQueryParam}}queryParams[U("{{baseName}}")] = ApiClient::parameterToString({{paramName}}); + {{/isQueryParam}}{{#isHeaderParam}}headerParams[U("{{baseName}}")] = ApiClient::parameterToString({{paramName}}); + {{/isHeaderParam}}{{#isFormParam}}{{#isFile}}fileParams[ U("{{baseName}}") ] = {{paramName}}; + {{/isFile}}{{^isFile}}formParams[ U("{{baseName}}") ] = ApiClient::parameterToString({{paramName}}); + {{/isFile}}{{/isFormParam}}{{/isContainer}} + } + {{/isBodyParam}}{{/allParams}} + + std::shared_ptr httpBody; + utility::string_t requestHttpContentType; + + // use JSON if possible + if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) + { + requestHttpContentType = U("application/json"); + + {{#bodyParam}} + web::json::value json; + + {{#isPrimitiveType}} json = ModelBase::toJson({{paramName}}); + {{/isPrimitiveType}}{{^isPrimitiveType}}{{#isListContainer}} + { + std::vector jsonArray; + for( auto& item : {{paramName}} ) + { + {{#items.isPrimitiveType}}jsonArray.push_back(ModelBase::toJson(item)); + {{/items.isPrimitiveType}}{{^items.isPrimitiveType}}{{#items.isString}}jsonArray.push_back(ModelBase::toJson(item)); + {{/items.isString}}{{^items.isString}}{{#items.isDateTime}}jsonArray.push_back(ModelBase::toJson(item)); + {{/items.isDateTime}}{{^items.isDateTime}}jsonArray.push_back( item.get() ? item->toJson() : web::json::value::null() ); + {{/items.isDateTime}}{{/items.isString}}{{/items.isPrimitiveType}} + } + json = web::json::value::array(jsonArray); + } + {{/isListContainer}}{{^isListContainer}}json = ModelBase::toJson({{paramName}}); + {{/isListContainer}}{{/isPrimitiveType}} + + httpBody = std::shared_ptr( new JsonBody( json ) ); + + {{/bodyParam}} + } + // multipart formdata + else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + { + requestHttpContentType = U("multipart/form-data"); + + {{#bodyParam}} + std::shared_ptr multipart(new MultipartFormData); + {{#isPrimitiveType}} multipart->add(ModelBase::toHttpContent("{{paramName}}", {{paramName}})); + {{/isPrimitiveType}}{{^isPrimitiveType}}{{#isListContainer}} + { + std::vector jsonArray; + for( auto& item : {{paramName}} ) + { + {{#items.isPrimitiveType}}jsonArray.push_back(ModelBase::toJson(item)); + {{/items.isPrimitiveType}}{{^items.isPrimitiveType}}{{#items.isString}}jsonArray.push_back(ModelBase::toJson(item)); + {{/items.isString}}{{^items.isString}}{{#items.isDateTime}}jsonArray.push_back(ModelBase::toJson(item)); + {{/items.isDateTime}}{{^items.isDateTime}}jsonArray.push_back( item.get() ? item->toJson() : web::json::value::null() ); + {{/items.isDateTime}}{{/items.isString}}{{/items.isPrimitiveType}} + } + multipart->add(ModelBase::toHttpContent(U("{{paramName}}"), web::json::value::array(jsonArray), U("application/json"))); + } + {{/isListContainer}}{{^isListContainer}}{{#isString}}multipart->add(ModelBase::toHttpContent(U("{{paramName}}"), {{paramName}})); + {{/isString}}{{^isString}} + if({{paramName}}.get()) + { + {{paramName}}->toMultipart(multipart, U("{{paramName}}")); + } + {{/isString}}{{/isListContainer}}{{/isPrimitiveType}} + + httpBody = multipart; + requestHttpContentType += U("; boundary=") + multipart->getBoundary(); + {{/bodyParam}} + } + else + { + throw ApiException(415, U("{{classname}}->{{operationId}} does not consume any supported media type")); + } + + {{#authMethods}} + // authentication ({{name}}) required + {{#isApiKey}} + {{#isKeyInHeader}} + { + utility::string_t apiKey = apiConfiguration->getApiKey(U("{{keyParamName}}")); + if ( apiKey.size() > 0 ) + { + headerParams[U("{{keyParamName}}")] = apiKey; + } + } + {{/isKeyInHeader}} + {{#isKeyInQuery}} + { + utility::string_t apiKey = apiConfiguration->getApiKey(U("{{keyParamName}}")); + if ( apiKey.size() > 0 ) + { + queryParams[U("{{keyParamName}}")] = apiKey; + } + } + {{/isKeyInQuery}} + {{/isApiKey}} + {{#isBasic}} + // Basic authentication is added automatically as part of the http_client_config + {{/isBasic}} + {{#isOAuth}} + // oauth2 authentication is added automatically as part of the http_client_config + {{/isOAuth}} + {{/authMethods}} + + return m_ApiClient->callApi(path, U("{{httpMethod}}"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) + .then([=](web::http::http_response response) + { + // 1xx - informational : OK + // 2xx - successful : OK + // 3xx - redirection : OK + // 4xx - client error : not OK + // 5xx - client error : not OK + if (response.status_code() >= 400) + { + throw ApiException(response.status_code() + , U("error calling {{operationId}}: ") + response.reason_phrase() + , std::make_shared(response.extract_utf8string(true).get())); + } + + // check response content type + if(response.headers().has(U("Content-Type"))) + { + utility::string_t contentType = response.headers()[U("Content-Type")]; + if( contentType.find(responseHttpContentType) == std::string::npos ) + { + throw ApiException(500 + , U("error calling {{operationId}}: unexpected response type: ") + contentType + , std::make_shared(response.extract_utf8string(true).get())); + } + } + + return response.extract_string(); + }) + .then([=](utility::string_t response) + { + {{^returnType}}return void(); + {{/returnType}}{{#returnType}}{{#returnContainer}}{{{returnType}}} result; + {{/returnContainer}}{{^returnContainer}}{{{returnType}}} result({{{defaultResponse}}});{{/returnContainer}} + + if(responseHttpContentType == U("application/json")) + { + web::json::value json = web::json::value::parse(response); + + {{#isListContainer}}for( auto& item : json.as_array() ) + { + {{#vendorExtensions.x-codegen-response.items.isPrimitiveType}}result.push_back(ModelBase::{{vendorExtensions.x-codegen-response.items.datatype}}FromJson(item)); + {{/vendorExtensions.x-codegen-response.items.isPrimitiveType}}{{^vendorExtensions.x-codegen-response.items.isPrimitiveType}}{{#vendorExtensions.x-codegen-response.items.isString}}result.push_back(ModelBase::stringFromJson(item)); + {{/vendorExtensions.x-codegen-response.items.isString}}{{^vendorExtensions.x-codegen-response.items.isString}}{{{vendorExtensions.x-codegen-response.items.datatype}}} itemObj({{{vendorExtensions.x-codegen-response.items.defaultValue}}}); + itemObj->fromJson(item); + result.push_back(itemObj); + {{/vendorExtensions.x-codegen-response.items.isString}}{{/vendorExtensions.x-codegen-response.items.isPrimitiveType}} + } + {{/isListContainer}}{{^isListContainer}}{{#isMapContainer}}for( auto& item : json.as_object() ) + { + {{#vendorExtensions.x-codegen-response.items.isPrimitiveType}}result[item.first] = ModelBase::{{vendorExtensions.x-codegen-response.items.datatype}}FromJson(item.second); + {{/vendorExtensions.x-codegen-response.items.isPrimitiveType}}{{^vendorExtensions.x-codegen-response.items.isPrimitiveType}}{{#vendorExtensions.x-codegen-response.items.isString}}result[item.first] = ModelBase::stringFromJson(item.second); + {{/vendorExtensions.x-codegen-response.items.isString}}{{^vendorExtensions.x-codegen-response.items.isString}}{{{vendorExtensions.x-codegen-response.items.datatype}}} itemObj({{{vendorExtensions.x-codegen-response.items.defaultValue}}}); + itemObj->fromJson(item); + result[item.first] = itemObj; + {{/vendorExtensions.x-codegen-response.items.isString}}{{/vendorExtensions.x-codegen-response.items.isPrimitiveType}} + } + {{/isMapContainer}}{{^isMapContainer}}{{#vendorExtensions.x-codegen-response.isPrimitiveType}}result = ModelBase::{{vendorExtensions.x-codegen-response.items.datatype}}FromJson(json); + {{/vendorExtensions.x-codegen-response.isPrimitiveType}}{{^vendorExtensions.x-codegen-response.isPrimitiveType}}{{#vendorExtensions.x-codegen-response.isString}}result = ModelBase::stringFromJson(json); + {{/vendorExtensions.x-codegen-response.isString}}{{^vendorExtensions.x-codegen-response.isString}}result->fromJson(json);{{/vendorExtensions.x-codegen-response.isString}}{{/vendorExtensions.x-codegen-response.isPrimitiveType}}{{/isMapContainer}}{{/isListContainer}} + } + // else if(responseHttpContentType == U("multipart/form-data")) + // { + // TODO multipart response parsing + // } + else + { + throw ApiException(500 + , U("error calling findPetsByStatus: unsupported response type")); + } + + return result; + {{/returnType}} + }); +} +{{/operation}} + +{{#apiNamespaceDeclarations}} +} +{{/apiNamespaceDeclarations}} + +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/cpprest/apiclient-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/apiclient-header.mustache new file mode 100644 index 000000000000..ba975f011556 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/apiclient-header.mustache @@ -0,0 +1,76 @@ +{{>licenseInfo}} +/* + * ApiClient.h + * + * This is an API client responsible for stating the HTTP calls + */ + +#ifndef ApiClient_H_ +#define ApiClient_H_ + +{{{defaultInclude}}} +#include "ApiConfiguration.h" +#include "ApiException.h" +#include "IHttpBody.h" +#include "HttpContent.h" + +#include +#include + +#include +#include + +{{#apiNamespaceDeclarations}} +namespace {{this}} { +{{/apiNamespaceDeclarations}} + +using namespace {{modelNamespace}}; + +class {{declspec}} ApiClient +{ +public: + ApiClient( std::shared_ptr configuration = nullptr ); + virtual ~ApiClient(); + + std::shared_ptr getConfiguration() const; + void setConfiguration(std::shared_ptr configuration); + + static utility::string_t parameterToString(utility::string_t value); + static utility::string_t parameterToString(int32_t value); + static utility::string_t parameterToString(int64_t value); + + template + static utility::string_t parameterToArrayString(std::vector value) + { + utility::stringstream_t ss; + + for( size_t i = 0; i < value.size(); i++) + { + if( i > 0) ss << U(", "); + ss << ApiClient::parameterToString(value[i]); + } + + return ss.str(); + } + + pplx::task callApi( + const utility::string_t& path, + const utility::string_t& method, + const std::map& queryParams, + const std::shared_ptr postBody, + const std::map& headerParams, + const std::map& formParams, + const std::map>& fileParams, + const utility::string_t& contentType + ) const; + +protected: + + std::shared_ptr m_Configuration; +}; + +{{#apiNamespaceDeclarations}} +} +{{/apiNamespaceDeclarations}} + +#endif /* ApiClient_H_ */ diff --git a/modules/swagger-codegen/src/main/resources/cpprest/apiclient-source.mustache b/modules/swagger-codegen/src/main/resources/cpprest/apiclient-source.mustache new file mode 100644 index 000000000000..541125433167 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/apiclient-source.mustache @@ -0,0 +1,132 @@ +{{>licenseInfo}} +#include "ApiClient.h" +#include "MultipartFormData.h" +#include "ModelBase.h" + +{{#apiNamespaceDeclarations}} +namespace {{this}} { +{{/apiNamespaceDeclarations}} + +using namespace {{modelNamespace}}; + +ApiClient::ApiClient(std::shared_ptr configuration ) + : m_Configuration(configuration) +{ +} +ApiClient::~ApiClient() +{ +} + +std::shared_ptr ApiClient::getConfiguration() const +{ + return m_Configuration; +} +void ApiClient::setConfiguration(std::shared_ptr configuration) +{ + m_Configuration = configuration; +} + + +utility::string_t ApiClient::parameterToString(utility::string_t value) +{ + return value; +} +utility::string_t ApiClient::parameterToString(int64_t value) +{ + return std::to_wstring(value); +} +utility::string_t ApiClient::parameterToString(int32_t value) +{ + return std::to_wstring(value); +} + +pplx::task ApiClient::callApi( + const utility::string_t& path, + const utility::string_t& method, + const std::map& queryParams, + const std::shared_ptr postBody, + const std::map& headerParams, + const std::map& formParams, + const std::map>& fileParams, + const utility::string_t& contentType +) const +{ + if (postBody != nullptr && formParams.size() != 0) + { + throw ApiException(400, U("Cannot have body and form params")); + } + + if (postBody != nullptr && fileParams.size() != 0) + { + throw ApiException(400, U("Cannot have body and file params")); + } + + if (fileParams.size() > 0 && contentType != U("multipart/form-data")) + { + throw ApiException(400, U("Operations with file parameters must be called with multipart/form-data")); + } + + web::http::client::http_client client(m_Configuration->getBaseUrl(), m_Configuration->getHttpConfig()); + + web::http::http_request request; + for ( auto& kvp : headerParams ) + { + request.headers().add(kvp.first, kvp.second); + } + + if (fileParams.size() > 0) + { + MultipartFormData uploadData; + for (auto& kvp : formParams) + { + uploadData.add(ModelBase::toHttpContent(kvp.first, kvp.second)); + } + for (auto& kvp : fileParams) + { + uploadData.add(ModelBase::toHttpContent(kvp.first, kvp.second)); + } + std::stringstream data; + postBody->writeTo(data); + auto bodyString = data.str(); + auto length = bodyString.size(); + request.set_body(concurrency::streams::bytestream::open_istream(std::move(bodyString)), length, contentType); + } + else + { + if (postBody != nullptr) + { + std::stringstream data; + postBody->writeTo(data); + auto bodyString = data.str(); + auto length = bodyString.size(); + request.set_body(concurrency::streams::bytestream::open_istream(std::move(bodyString)), length, contentType); + } + else + { + web::http::uri_builder formData; + for (auto& kvp : formParams) + { + formData.append_query(kvp.first, kvp.second); + } + request.set_body(formData.query(), U("application/x-www-form-urlencoded")); + } + } + + web::http::uri_builder builder(path); + for (auto& kvp : queryParams) + { + builder.append_query(kvp.first, kvp.second); + } + request.set_request_uri(builder.to_uri()); + request.set_method(method); + if ( !request.headers().has( web::http::header_names::user_agent ) ) + { + request.headers().add( web::http::header_names::user_agent, m_Configuration->getUserAgent() ); + } + + return client.request(request); +} + +{{#apiNamespaceDeclarations}} +} +{{/apiNamespaceDeclarations}} diff --git a/modules/swagger-codegen/src/main/resources/cpprest/apiconfiguration-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/apiconfiguration-header.mustache new file mode 100644 index 000000000000..32411f411805 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/apiconfiguration-header.mustache @@ -0,0 +1,52 @@ +{{>licenseInfo}} +/* + * ApiConfiguration.h + * + * This class represents a single item of a multipart-formdata request. + */ + +#ifndef ApiConfiguration_H_ +#define ApiConfiguration_H_ + +{{{defaultInclude}}} + +#include + +#include +#include +{{#apiNamespaceDeclarations}} +namespace {{this}} { +{{/apiNamespaceDeclarations}} + +class {{declspec}} ApiConfiguration +{ +public: + ApiConfiguration(); + virtual ~ApiConfiguration(); + + web::http::client::http_client_config& getHttpConfig(); + void setHttpConfig( web::http::client::http_client_config& value ); + + utility::string_t getBaseUrl() const; + void setBaseUrl( const utility::string_t value ); + + utility::string_t getUserAgent() const; + void setUserAgent( const utility::string_t value ); + + std::map& getDefaultHeaders(); + + utility::string_t getApiKey( const utility::string_t& prefix) const; + void setApiKey( const utility::string_t& prefix, const utility::string_t& apiKey ); + +protected: + utility::string_t m_BaseUrl; + std::map m_DefaultHeaders; + std::map m_ApiKeys; + web::http::client::http_client_config m_HttpConfig; + utility::string_t m_UserAgent; +}; + +{{#apiNamespaceDeclarations}} +} +{{/apiNamespaceDeclarations}} +#endif /* ApiConfiguration_H_ */ diff --git a/modules/swagger-codegen/src/main/resources/cpprest/apiconfiguration-source.mustache b/modules/swagger-codegen/src/main/resources/cpprest/apiconfiguration-source.mustache new file mode 100644 index 000000000000..6e0d4e9147e3 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/apiconfiguration-source.mustache @@ -0,0 +1,68 @@ +{{>licenseInfo}} +#include "ApiConfiguration.h" + +{{#apiNamespaceDeclarations}} +namespace {{this}} { +{{/apiNamespaceDeclarations}} + +ApiConfiguration::ApiConfiguration() +{ +} + +ApiConfiguration::~ApiConfiguration() +{ +} + +web::http::client::http_client_config& ApiConfiguration::getHttpConfig() +{ + return m_HttpConfig; +} + +void ApiConfiguration::setHttpConfig( web::http::client::http_client_config& value ) +{ + m_HttpConfig = value; +} + +utility::string_t ApiConfiguration::getBaseUrl() const +{ + return m_BaseUrl; +} + +void ApiConfiguration::setBaseUrl( const utility::string_t value ) +{ + m_BaseUrl = value; +} + +utility::string_t ApiConfiguration::getUserAgent() const +{ + return m_UserAgent; +} + +void ApiConfiguration::setUserAgent( const utility::string_t value ) +{ + m_UserAgent = value; +} + +std::map& ApiConfiguration::getDefaultHeaders() +{ + return m_DefaultHeaders; +} + +utility::string_t ApiConfiguration::getApiKey( const utility::string_t& prefix) const +{ + auto result = m_ApiKeys.find(prefix); + if( result != m_ApiKeys.end() ) + { + return result->second; + } + return U(""); +} + +void ApiConfiguration::setApiKey( const utility::string_t& prefix, const utility::string_t& apiKey ) +{ + m_ApiKeys[prefix] = apiKey; +} + +{{#apiNamespaceDeclarations}} +} +{{/apiNamespaceDeclarations}} diff --git a/modules/swagger-codegen/src/main/resources/cpprest/apiexception-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/apiexception-header.mustache new file mode 100644 index 000000000000..483d7dab4235 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/apiexception-header.mustache @@ -0,0 +1,49 @@ +{{>licenseInfo}} +/* + * ApiException.h + * + * This is the exception being thrown in case the api call was not successful + */ + +#ifndef ApiException_H_ +#define ApiException_H_ + +{{{defaultInclude}}} + +#include +#include + +#include +#include + + +{{#apiNamespaceDeclarations}} +namespace {{this}} { +{{/apiNamespaceDeclarations}} + +class {{declspec}} ApiException + : public web::http::http_exception +{ +public: + ApiException( int errorCode + , const utility::string_t& message + , std::shared_ptr content = nullptr ); + ApiException( int errorCode + , const utility::string_t& message + , std::map& headers + , std::shared_ptr content = nullptr ); + virtual ~ApiException(); + + std::map& getHeaders(); + std::shared_ptr getContent() const; + +protected: + std::shared_ptr m_Content; + std::map m_Headers; +}; + +{{#apiNamespaceDeclarations}} +} +{{/apiNamespaceDeclarations}} + +#endif /* ApiBase_H_ */ diff --git a/modules/swagger-codegen/src/main/resources/cpprest/apiexception-source.mustache b/modules/swagger-codegen/src/main/resources/cpprest/apiexception-source.mustache new file mode 100644 index 000000000000..5da062ddbfef --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/apiexception-source.mustache @@ -0,0 +1,41 @@ +{{>licenseInfo}} +#include "ApiException.h" + +{{#apiNamespaceDeclarations}} +namespace {{this}} { +{{/apiNamespaceDeclarations}} + +ApiException::ApiException( int errorCode + , const utility::string_t& message + , std::shared_ptr content /*= nullptr*/ ) + : web::http::http_exception( errorCode, message ) + , m_Content(content) +{ +} +ApiException::ApiException( int errorCode + , const utility::string_t& message + , std::map& headers + , std::shared_ptr content /*= nullptr*/ ) + : web::http::http_exception( errorCode, message ) + , m_Content(content) + , m_Headers(headers) +{ +} + +ApiException::~ApiException() +{ +} + +std::shared_ptr ApiException::getContent() const +{ + return m_Content; +} + +std::map& ApiException::getHeaders() +{ + return m_Headers; +} + +{{#apiNamespaceDeclarations}} +} +{{/apiNamespaceDeclarations}} diff --git a/modules/swagger-codegen/src/main/resources/cpprest/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/cpprest/git_push.sh.mustache new file mode 100644 index 000000000000..2619d82f14d3 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/git_push.sh.mustache @@ -0,0 +1,51 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-cpprest "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/modules/swagger-codegen/src/main/resources/cpprest/gitignore.mustache b/modules/swagger-codegen/src/main/resources/cpprest/gitignore.mustache new file mode 100644 index 000000000000..4581ef2eeefc --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/gitignore.mustache @@ -0,0 +1,29 @@ +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai +*.la +*.a +*.lib + +# Executables +*.exe +*.out +*.app diff --git a/modules/swagger-codegen/src/main/resources/cpprest/httpcontent-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/httpcontent-header.mustache new file mode 100644 index 000000000000..e79f575061f6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/httpcontent-header.mustache @@ -0,0 +1,57 @@ +{{>licenseInfo}} +/* + * HttpContent.h + * + * This class represents a single item of a multipart-formdata request. + */ + +#ifndef HttpContent_H_ +#define HttpContent_H_ + +{{{defaultInclude}}} + +#include + +#include + +{{#modelNamespaceDeclarations}} +namespace {{this}} { +{{/modelNamespaceDeclarations}} + +class {{declspec}} HttpContent +{ +public: + HttpContent(); + virtual ~HttpContent(); + + virtual utility::string_t getContentDisposition(); + virtual void setContentDisposition( const utility::string_t& value ); + + virtual utility::string_t getName(); + virtual void setName( const utility::string_t& value ); + + virtual utility::string_t getFileName(); + virtual void setFileName( const utility::string_t& value ); + + virtual utility::string_t getContentType(); + virtual void setContentType( const utility::string_t& value ); + + virtual std::shared_ptr getData(); + virtual void setData( std::shared_ptr value ); + + virtual void writeTo( std::ostream& stream ); + +protected: + // NOTE: no utility::string_t here because those strings can only contain ascii + utility::string_t m_ContentDisposition; + utility::string_t m_Name; + utility::string_t m_FileName; + utility::string_t m_ContentType; + std::shared_ptr m_Data; +}; + +{{#modelNamespaceDeclarations}} +} +{{/modelNamespaceDeclarations}} + +#endif /* HttpContent_H_ */ diff --git a/modules/swagger-codegen/src/main/resources/cpprest/httpcontent-source.mustache b/modules/swagger-codegen/src/main/resources/cpprest/httpcontent-source.mustache new file mode 100644 index 000000000000..791515a205da --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/httpcontent-source.mustache @@ -0,0 +1,74 @@ +{{>licenseInfo}} +#include "HttpContent.h" + +{{#modelNamespaceDeclarations}} +namespace {{this}} { +{{/modelNamespaceDeclarations}} + +HttpContent::HttpContent() +{ +} + +HttpContent::~HttpContent() +{ +} + +utility::string_t HttpContent::getContentDisposition() +{ + return m_ContentDisposition; +} + +void HttpContent::setContentDisposition( const utility::string_t & value ) +{ + m_ContentDisposition = value; +} + +utility::string_t HttpContent::getName() +{ + return m_Name; +} + +void HttpContent::setName( const utility::string_t & value ) +{ + m_Name = value; +} + +utility::string_t HttpContent::getFileName() +{ + return m_FileName; +} + +void HttpContent::setFileName( const utility::string_t & value ) +{ + m_FileName = value; +} + +utility::string_t HttpContent::getContentType() +{ + return m_ContentType; +} + +void HttpContent::setContentType( const utility::string_t & value ) +{ + m_ContentType = value; +} + +std::shared_ptr HttpContent::getData() +{ + return m_Data; +} + +void HttpContent::setData( std::shared_ptr value ) +{ + m_Data = value; +} + +void HttpContent::writeTo( std::ostream& stream ) +{ + m_Data->seekg( 0, m_Data->beg ); + stream << m_Data->rdbuf(); +} + +{{#modelNamespaceDeclarations}} +} +{{/modelNamespaceDeclarations}} diff --git a/modules/swagger-codegen/src/main/resources/cpprest/ihttpbody-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/ihttpbody-header.mustache new file mode 100644 index 000000000000..34604e0048e9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/ihttpbody-header.mustache @@ -0,0 +1,30 @@ +{{>licenseInfo}} +/* + * IHttpBody.h + * + * This is the interface for contents that can be sent to a remote HTTP server. + */ + +#ifndef IHttpBody_H_ +#define IHttpBody_H_ + +{{{defaultInclude}}} +#include + +{{#modelNamespaceDeclarations}} +namespace {{this}} { +{{/modelNamespaceDeclarations}} + +class {{declspec}} IHttpBody +{ +public: + virtual ~IHttpBody() { } + + virtual void writeTo( std::ostream& stream ) = 0; +}; + +{{#modelNamespaceDeclarations}} +} +{{/modelNamespaceDeclarations}} + +#endif /* IHttpBody_H_ */ diff --git a/modules/swagger-codegen/src/main/resources/cpprest/jsonbody-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/jsonbody-header.mustache new file mode 100644 index 000000000000..4a146c5373d7 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/jsonbody-header.mustache @@ -0,0 +1,37 @@ +{{>licenseInfo}} +/* + * JsonBody.h + * + * This is a JSON http body which can be submitted via http + */ + +#ifndef JsonBody_H_ +#define JsonBody_H_ + +{{{defaultInclude}}} +#include "IHttpBody.h" + +#include + +{{#modelNamespaceDeclarations}} +namespace {{this}} { +{{/modelNamespaceDeclarations}} + +class {{declspec}} JsonBody + : public IHttpBody +{ +public: + JsonBody( const web::json::value& value ); + virtual ~JsonBody(); + + void writeTo( std::ostream& target ) override; + +protected: + web::json::value m_Json; +}; + +{{#modelNamespaceDeclarations}} +} +{{/modelNamespaceDeclarations}} + +#endif /* JsonBody_H_ */ diff --git a/modules/swagger-codegen/src/main/resources/cpprest/jsonbody-source.mustache b/modules/swagger-codegen/src/main/resources/cpprest/jsonbody-source.mustache new file mode 100644 index 000000000000..05074527b286 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/jsonbody-source.mustache @@ -0,0 +1,24 @@ +{{>licenseInfo}} +#include "JsonBody.h" + +{{#modelNamespaceDeclarations}} +namespace {{this}} { +{{/modelNamespaceDeclarations}} + +JsonBody::JsonBody( const web::json::value& json) + : m_Json(json) +{ +} + +JsonBody::~JsonBody() +{ +} + +void JsonBody::writeTo( std::ostream& target ) +{ + m_Json.serialize(target); +} + +{{#modelNamespaceDeclarations}} +} +{{/modelNamespaceDeclarations}} diff --git a/modules/swagger-codegen/src/main/resources/cpprest/licenseInfo.mustache b/modules/swagger-codegen/src/main/resources/cpprest/licenseInfo.mustache new file mode 100644 index 000000000000..861d97234cfa --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/licenseInfo.mustache @@ -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. + */ diff --git a/modules/swagger-codegen/src/main/resources/cpprest/model-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/model-header.mustache new file mode 100644 index 000000000000..9515743a8ffe --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/model-header.mustache @@ -0,0 +1,70 @@ +{{>licenseInfo}} +{{#models}}{{#model}}/* + * {{classname}}.h + * + * {{description}} + */ + +#ifndef {{classname}}_H_ +#define {{classname}}_H_ + +{{{defaultInclude}}} +#include "ModelBase.h" + +{{#imports}}{{{this}}} +{{/imports}} + +{{#modelNamespaceDeclarations}} +namespace {{this}} { +{{/modelNamespaceDeclarations}} + +/// +/// {{description}} +/// +class {{declspec}} {{classname}} + : public ModelBase +{ +public: + {{classname}}(); + virtual ~{{classname}}(); + + ///////////////////////////////////////////// + /// ModelBase overrides + + void validate() override; + + web::json::value toJson() const override; + void fromJson(web::json::value& json) override; + + void toMultipart(std::shared_ptr multipart, const utility::string_t& namePrefix) const override; + void fromMultiPart(std::shared_ptr multipart, const utility::string_t& namePrefix) override; + + ///////////////////////////////////////////// + /// {{classname}} members + + {{#vars}} + /// + /// {{description}} + /// + {{^isNotContainer}}{{{datatype}}}& {{getter}}(); + {{/isNotContainer}}{{#isNotContainer}}{{{datatype}}} {{getter}}() const; + void {{setter}}({{{datatype}}} value); + {{/isNotContainer}}{{^required}}bool {{baseName}}IsSet() const; + void unset{{name}}(); + {{/required}} + {{/vars}} + +protected: + {{#vars}}{{{datatype}}} m_{{name}}; + {{^required}}bool m_{{name}}IsSet; + {{/required}} + {{/vars}} +}; + +{{#modelNamespaceDeclarations}} +} +{{/modelNamespaceDeclarations}} + +#endif /* {{classname}}_H_ */ +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/cpprest/model-source.mustache b/modules/swagger-codegen/src/main/resources/cpprest/model-source.mustache new file mode 100644 index 000000000000..a1985735d4a7 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/model-source.mustache @@ -0,0 +1,255 @@ +{{>licenseInfo}} +{{#models}}{{#model}} + +#include "{{classname}}.h" + +{{#modelNamespaceDeclarations}} +namespace {{this}} { +{{/modelNamespaceDeclarations}} + +{{classname}}::{{classname}}() +{ + {{#vars}}{{#isNotContainer}}{{#isPrimitiveType}}m_{{name}} = {{{defaultValue}}}; + {{/isPrimitiveType}}{{^isPrimitiveType}}{{#isString}}m_{{name}} = {{{defaultValue}}}; + {{/isString}}{{#isDateTime}}m_{{name}} = {{{defaultValue}}}; + {{/isDateTime}}{{/isPrimitiveType}}{{/isNotContainer}}{{^required}}m_{{name}}IsSet = false; + {{/required}}{{/vars}} +} + +{{classname}}::~{{classname}}() +{ +} + +void {{classname}}::validate() +{ + // TODO: implement validation +} + +web::json::value {{classname}}::toJson() const +{ + web::json::value val = web::json::value::object(); + + {{#vars}}{{#isPrimitiveType}}{{^required}}if(m_{{name}}IsSet) + { + val[U("{{baseName}}")] = ModelBase::toJson(m_{{name}}); + } + {{/required}}{{#required}}val[U("{{baseName}}")] = ModelBase::toJson(m_{{name}}); + {{/required}}{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isListContainer}}{ + std::vector jsonArray; + for( auto& item : m_{{name}} ) + { + jsonArray.push_back(ModelBase::toJson(item)); + } + {{#required}}val[U("{{baseName}}")] = web::json::value::array(jsonArray); + {{/required}}{{^required}} + if(jsonArray.size() > 0) + { + val[U("{{baseName}}")] = web::json::value::array(jsonArray); + } + {{/required}} + } + {{/isListContainer}}{{^isListContainer}}{{^required}}if(m_{{name}}IsSet) + { + val[U("{{baseName}}")] = ModelBase::toJson(m_{{name}}); + } + {{/required}}{{#required}}val[U("{{baseName}}")] = ModelBase::toJson(m_{{name}}); + {{/required}}{{/isListContainer}}{{/isPrimitiveType}}{{/vars}} + + return val; +} + +void {{classname}}::fromJson(web::json::value& val) +{ + {{#vars}}{{#isPrimitiveType}}{{^required}}if(val.has_field(U("{{baseName}}"))) + { + {{setter}}(ModelBase::{{baseType}}FromJson(val[U("{{baseName}}")])); + } + {{/required}}{{#required}}{{setter}}(ModelBase::{{baseType}}FromJson(val[U("{{baseName}}")])); + {{/required}}{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isListContainer}}{ + m_{{name}}.clear(); + std::vector jsonArray; + {{^required}}if(val.has_field(U("{{baseName}}"))) + { + {{/required}} + for( auto& item : val[U("{{baseName}}")].as_array() ) + { + {{#items.isPrimitiveType}}m_{{name}}.push_back(ModelBase::{{baseType}}FromJson(item)); + {{/items.isPrimitiveType}}{{^items.isPrimitiveType}}{{#items.isString}}m_{{name}}.push_back(ModelBase::stringFromJson(item)); + {{/items.isString}}{{^items.isString}}{{#items.isDateTime}}m_{{name}}.push_back(ModelBase::dateFromJson(item)); + {{/items.isDateTime}}{{^items.isDateTime}} + if(item.is_null()) + { + m_{{name}}.push_back( {{{items.datatype}}}(nullptr) ); + } + else + { + {{{items.datatype}}} newItem({{{items.defaultValue}}}); + newItem->fromJson(item); + m_{{name}}.push_back( newItem ); + } + {{/items.isDateTime}}{{/items.isString}}{{/items.isPrimitiveType}} + } + {{^required}} + } + {{/required}} + } + {{/isListContainer}}{{^isListContainer}}{{^required}}if(val.has_field(U("{{baseName}}"))) + { + {{#isString}}{{setter}}(ModelBase::stringFromJson(val[U("{{baseName}}")])); + {{/isString}}{{^isString}}{{#isDateTime}}{{setter}}(ModelBase::dateFromJson(val[U("{{baseName}}")])); + {{/isDateTime}}{{^isDateTime}}if(!val[U("{{baseName}}")].is_null()) + { + {{{datatype}}} newItem({{{defaultValue}}}); + newItem->fromJson(val[U("{{baseName}}")]); + {{setter}}( newItem ); + } + {{/isDateTime}}{{/isString}} + } + {{/required}}{{#required}}{{#isString}}{{setter}}(ModelBase::stringFromJson(val[U("{{baseName}}")])); + {{/isString}}{{^isString}}{{#isDateTime}}{{setter}}(ModelBase::dateFromJson(val[U("{{baseName}}")])); + {{/isDateTime}}{{^isDateTime}}{{#vendorExtensions.x-codegen-file}}{{setter}}(ModelBase::fileFromJson(val[U("{{baseName}}")])); + {{/vendorExtensions.x-codegen-file}}{{^vendorExtensions.x-codegen-file}}{{{datatype}}} new{{name}}({{{defaultValue}}}); + new{{name}}->fromJson(val[U("{{baseName}}")]); + {{setter}}( newItem ); + {{/vendorExtensions.x-codegen-file}}{{/isDateTime}}{{/isString}}{{/required}}{{/isListContainer}}{{/isPrimitiveType}}{{/vars}} +} + +void {{classname}}::toMultipart(std::shared_ptr multipart, const utility::string_t& prefix) const +{ + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix[namePrefix.size() - 1] != U('.')) + { + namePrefix += U("."); + } + + {{#vars}}{{#isPrimitiveType}}{{^required}}if(m_{{name}}IsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}})); + } + {{/required}}{{#required}}multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}})); + {{/required}}{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isListContainer}}{ + std::vector jsonArray; + for( auto& item : m_{{name}} ) + { + jsonArray.push_back(ModelBase::toJson(item)); + } + {{#required}}multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), web::json::value::array(jsonArray), U("application/json"))); + {{/required}}{{^required}} + if(jsonArray.size() > 0) + { + multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), web::json::value::array(jsonArray), U("application/json"))); + } + {{/required}} + } + {{/isListContainer}}{{^isListContainer}}{{^required}}if(m_{{name}}IsSet) + { + {{#isString}}multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}})); + {{/isString}}{{^isString}}{{#isDateTime}}multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}})); + {{/isDateTime}}{{^isDateTime}}if (m_{{name}}.get()) + { + m_{{name}}->toMultipart(multipart, U("{{baseName}}.")); + } + {{/isDateTime}}{{/isString}} + } + {{/required}}{{#required}}{{#isString}}multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}})); + {{/isString}}{{^isString}}{{#isDateTime}}multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}})); + {{/isDateTime}}{{^isDateTime}}{{#vendorExtensions.x-codegen-file}}multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}})); + {{/vendorExtensions.x-codegen-file}}{{^vendorExtensions.x-codegen-file}}m_{{name}}->toMultipart(multipart, U("{{baseName}}.")); + {{/vendorExtensions.x-codegen-file}}{{/isDateTime}}{{/isString}}{{/required}}{{/isListContainer}}{{/isPrimitiveType}}{{/vars}} +} + +void {{classname}}::fromMultiPart(std::shared_ptr multipart, const utility::string_t& prefix) +{ + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix[namePrefix.size() - 1] != U('.')) + { + namePrefix += U("."); + } + + {{#vars}}{{#isPrimitiveType}}{{^required}}if(multipart->hasContent(U("{{baseName}}"))) + { + {{setter}}(ModelBase::{{baseType}}FromHttpContent(multipart->getContent(U("{{baseName}}")))); + } + {{/required}}{{#required}}{{setter}}(ModelBase::{{baseType}}FromHttpContent(multipart->getContent(U("{{baseName}}")))); + {{/required}}{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isListContainer}}{ + m_{{name}}.clear(); + {{^required}}if(multipart->hasContent(U("{{baseName}}"))) + { + {{/required}} + + web::json::value jsonArray = web::json::value::parse(ModelBase::stringFromHttpContent(multipart->getContent(U("{{baseName}}")))); + for( auto& item : jsonArray.as_array() ) + { + {{#items.isPrimitiveType}}m_{{name}}.push_back(ModelBase::{{baseType}}FromJson(item)); + {{/items.isPrimitiveType}}{{^items.isPrimitiveType}}{{#items.isString}}m_{{name}}.push_back(ModelBase::stringFromJson(item)); + {{/items.isString}}{{^items.isString}}{{#items.isDateTime}}m_{{name}}.push_back(ModelBase::dateFromJson(item)); + {{/items.isDateTime}}{{^items.isDateTime}} + if(item.is_null()) + { + m_{{name}}.push_back( {{{items.datatype}}}(nullptr) ); + } + else + { + {{{items.datatype}}} newItem({{{items.defaultValue}}}); + newItem->fromJson(item); + m_{{name}}.push_back( newItem ); + } + {{/items.isDateTime}}{{/items.isString}}{{/items.isPrimitiveType}} + } + {{^required}} + } + {{/required}} + } + {{/isListContainer}}{{^isListContainer}}{{^required}}if(multipart->hasContent(U("{{baseName}}"))) + { + {{#isString}}{{setter}}(ModelBase::stringFromHttpContent(multipart->getContent(U("{{baseName}}")))); + {{/isString}}{{^isString}}{{#isDateTime}}{{setter}}(ModelBase::dateFromHttpContent(multipart->getContent(U("{{baseName}}")))); + {{/isDateTime}}{{^isDateTime}}if(multipart->hasContent(U("{{baseName}}"))) + { + {{{datatype}}} newItem({{{defaultValue}}}); + newItem->fromMultiPart(multipart, U("{{baseName}}.")); + {{setter}}( newItem ); + } + {{/isDateTime}}{{/isString}} + } + {{/required}}{{#required}}{{#isString}}{{setter}}(ModelBase::stringFromHttpContent(multipart->getContent(U("{{baseName}}")))); + {{/isString}}{{^isString}}{{#isDateTime}}{{setter}}(ModelBase::dateFromHttpContent(multipart->getContent(U("{{baseName}}")))); + {{/isDateTime}}{{^isDateTime}}{{#vendorExtensions.x-codegen-file}}{{setter}}(multipart->getContent(U("{{baseName}}"))); + {{/vendorExtensions.x-codegen-file}}{{^vendorExtensions.x-codegen-file}}{{{datatype}}} new{{name}}({{{defaultValue}}}); + new{{name}}->fromMultiPart(multipart, U("{{baseName}}.")); + {{setter}}( new{{name}} ); + {{/vendorExtensions.x-codegen-file}}{{/isDateTime}}{{/isString}}{{/required}}{{/isListContainer}}{{/isPrimitiveType}}{{/vars}} +} + + +{{#vars}}{{^isNotContainer}}{{{datatype}}}& {{classname}}::{{getter}}() +{ + return m_{{name}}; +} +{{/isNotContainer}}{{#isNotContainer}}{{{datatype}}} {{classname}}::{{getter}}() const +{ + return m_{{name}}; +} +void {{classname}}::{{setter}}({{{datatype}}} value) +{ + m_{{name}} = value; + {{^required}}m_{{name}}IsSet = true;{{/required}} +} +{{/isNotContainer}} +{{^required}}bool {{classname}}::{{baseName}}IsSet() const +{ + return m_{{name}}IsSet; +} +void {{classname}}::unset{{name}}() +{ + m_{{name}}IsSet = false; +} +{{/required}} +{{/vars}} + +{{#modelNamespaceDeclarations}} +} +{{/modelNamespaceDeclarations}} + +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/cpprest/modelbase-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/modelbase-header.mustache new file mode 100644 index 000000000000..262b154acd7b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/modelbase-header.mustache @@ -0,0 +1,77 @@ +{{>licenseInfo}} +/* + * ModelBase.h + * + * This is the base class for all model classes + */ + +#ifndef ModelBase_H_ +#define ModelBase_H_ + +{{{defaultInclude}}} +#include "HttpContent.h" +#include "MultipartFormData.h" + +#include +#include + +{{#modelNamespaceDeclarations}} +namespace {{this}} { +{{/modelNamespaceDeclarations}} + +class {{declspec}} ModelBase +{ +public: + ModelBase(); + virtual ~ModelBase(); + + virtual void validate() = 0; + + virtual web::json::value toJson() const = 0; + virtual void fromJson(web::json::value& json) = 0; + + virtual void toMultipart(std::shared_ptr multipart, const utility::string_t& namePrefix) const = 0; + virtual void fromMultiPart(std::shared_ptr multipart, const utility::string_t& namePrefix) = 0; + + static web::json::value toJson( const utility::string_t& value ); + static web::json::value toJson( const utility::datetime& value ); + static web::json::value toJson( std::shared_ptr value ); + static web::json::value toJson( std::shared_ptr value ); + static web::json::value toJson( int32_t value ); + static web::json::value toJson( int64_t value ); + static web::json::value toJson( double value ); + + static int64_t int64_tFromJson(web::json::value& val); + static int32_t int32_tFromJson(web::json::value& val); + static utility::string_t stringFromJson(web::json::value& val); + static utility::datetime dateFromJson(web::json::value& val); + static double doubleFromJson(web::json::value& val); + static bool boolFromJson(web::json::value& val); + static std::shared_ptr fileFromJson(web::json::value& val); + + static std::shared_ptr toHttpContent( const utility::string_t& name, const utility::string_t& value, const utility::string_t& contentType = U("")); + static std::shared_ptr toHttpContent( const utility::string_t& name, const utility::datetime& value, const utility::string_t& contentType = U("")); + static std::shared_ptr toHttpContent( const utility::string_t& name, std::shared_ptr value ); + static std::shared_ptr toHttpContent( const utility::string_t& name, const web::json::value& value, const utility::string_t& contentType = U("application/json") ); + static std::shared_ptr toHttpContent( const utility::string_t& name, int32_t value, const utility::string_t& contentType = U("") ); + static std::shared_ptr toHttpContent( const utility::string_t& name, int64_t value, const utility::string_t& contentType = U("") ); + static std::shared_ptr toHttpContent( const utility::string_t& name, double value, const utility::string_t& contentType = U("") ); + + static int64_t int64_tFromHttpContent(std::shared_ptr val); + static int32_t int32_tFromHttpContent(std::shared_ptr val); + static utility::string_t stringFromHttpContent(std::shared_ptr val); + static utility::datetime dateFromHttpContent(std::shared_ptr val); + static bool boolFromHttpContent(std::shared_ptr val); + static double doubleFromHttpContent(std::shared_ptr val); + + + static utility::string_t toBase64( utility::string_t value ); + static utility::string_t toBase64( std::shared_ptr value ); + static std::shared_ptr fromBase64( const utility::string_t& encoded ); +}; + +{{#modelNamespaceDeclarations}} +} +{{/modelNamespaceDeclarations}} + +#endif /* ModelBase_H_ */ diff --git a/modules/swagger-codegen/src/main/resources/cpprest/modelbase-source.mustache b/modules/swagger-codegen/src/main/resources/cpprest/modelbase-source.mustache new file mode 100644 index 000000000000..4d9ee6b40a09 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/modelbase-source.mustache @@ -0,0 +1,338 @@ +{{>licenseInfo}} +#include "ModelBase.h" + +{{#modelNamespaceDeclarations}} +namespace {{this}} { +{{/modelNamespaceDeclarations}} + +ModelBase::ModelBase() +{ +} +ModelBase::~ModelBase() +{ +} + +web::json::value ModelBase::toJson( const utility::string_t& value ) +{ + return web::json::value::string(value); +} +web::json::value ModelBase::toJson( const utility::datetime& value ) +{ + return web::json::value::string(value.to_string(utility::datetime::ISO_8601)); +} +web::json::value ModelBase::toJson( int32_t value ) +{ + return web::json::value::number(value); +} +web::json::value ModelBase::toJson( int64_t value ) +{ + return web::json::value::number(value); +} +web::json::value ModelBase::toJson( double value ) +{ + return web::json::value::number(value); +} + +web::json::value ModelBase::toJson( std::shared_ptr content ) +{ + web::json::value value; + value[U("ContentDisposition")] = ModelBase::toJson(content->getContentDisposition()); + value[U("ContentType")] = ModelBase::toJson(content->getContentType()); + value[U("FileName")] = ModelBase::toJson(content->getFileName()); + value[U("InputStream")] = web::json::value::string( ModelBase::toBase64(content->getData()) ); + return value; +} + +std::shared_ptr ModelBase::fileFromJson(web::json::value& val) +{ + std::shared_ptr content(new HttpContent); + + if(val.has_field(U("ContentDisposition"))) + { + content->setContentDisposition( ModelBase::stringFromJson(val[U("ContentDisposition")]) ); + } + if(val.has_field(U("ContentType"))) + { + content->setContentType( ModelBase::stringFromJson(val[U("ContentType")]) ); + } + if(val.has_field(U("FileName"))) + { + content->setFileName( ModelBase::stringFromJson(val[U("FileName")]) ); + } + if(val.has_field(U("InputStream"))) + { + content->setData( ModelBase::fromBase64( ModelBase::stringFromJson(val[U("InputStream")]) ) ); + } + + return content; +} + +web::json::value ModelBase::toJson( std::shared_ptr content ) +{ + return content.get() ? content->toJson() : web::json::value::null(); +} + +std::shared_ptr ModelBase::toHttpContent( const utility::string_t& name, const utility::string_t& value, const utility::string_t& contentType) +{ + std::shared_ptr content(new HttpContent); + content->setName( name ); + content->setContentDisposition( U("form-data") ); + content->setContentType( contentType ); + content->setData( std::shared_ptr( new std::stringstream( utility::conversions::to_utf8string(value) ) ) ); + return content; +} +std::shared_ptr ModelBase::toHttpContent( const utility::string_t& name, const utility::datetime& value, const utility::string_t& contentType ) +{ + std::shared_ptr content( new HttpContent ); + content->setName( name ); + content->setContentDisposition( U("form-data") ); + content->setContentType( contentType ); + content->setData( std::shared_ptr( new std::stringstream( utility::conversions::to_utf8string(value.to_string(utility::datetime::ISO_8601) ) ) ) ); + return content; +} +std::shared_ptr ModelBase::toHttpContent( const utility::string_t& name, std::shared_ptr value ) +{ + std::shared_ptr content( new HttpContent ); + content->setName( name ); + content->setContentDisposition( value->getContentDisposition() ); + content->setContentType( value->getContentType() ); + content->setData( value->getData() ); + content->setFileName( value->getFileName() ); + return content; +} +std::shared_ptr ModelBase::toHttpContent( const utility::string_t& name, const web::json::value& value, const utility::string_t& contentType ) +{ + std::shared_ptr content( new HttpContent ); + content->setName( name ); + content->setContentDisposition( U("form-data") ); + content->setContentType( contentType ); + content->setData( std::shared_ptr( new std::stringstream( utility::conversions::to_utf8string(value.serialize()) ) ) ); + return content; +} +std::shared_ptr ModelBase::toHttpContent( const utility::string_t& name, int32_t value, const utility::string_t& contentType ) +{ + std::shared_ptr content( new HttpContent ); + content->setName( name ); + content->setContentDisposition( U("form-data") ); + content->setContentType( contentType ); + content->setData( std::shared_ptr( new std::stringstream( std::to_string( value ) ) ) ); + return content; +} +std::shared_ptr ModelBase::toHttpContent( const utility::string_t& name, int64_t value, const utility::string_t& contentType ) +{ + std::shared_ptr content( new HttpContent ); + content->setName( name ); + content->setContentDisposition( U("form-data") ); + content->setContentType( contentType ); + content->setData( std::shared_ptr( new std::stringstream( std::to_string( value ) ) ) ); + return content; +} +std::shared_ptr ModelBase::toHttpContent( const utility::string_t& name, double value, const utility::string_t& contentType ) +{ + std::shared_ptr content( new HttpContent ); + content->setName( name ); + content->setContentDisposition( U("form-data") ); + content->setContentType( contentType ); + content->setData( std::shared_ptr( new std::stringstream( std::to_string( value ) ) ) ); + return content; +} + +// base64 encoding/decoding based on : https://en.wikibooks.org/wiki/Algorithm_Implementation/Miscellaneous/Base64#C.2B.2B +const static char Base64Chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +const static char Base64PadChar = '='; +utility::string_t ModelBase::toBase64( utility::string_t value ) +{ + std::shared_ptr source( new std::stringstream( utility::conversions::to_utf8string(value) ) ); + return ModelBase::toBase64(source); +} +utility::string_t ModelBase::toBase64( std::shared_ptr value ) +{ + value->seekg( 0, value->end ); + size_t length = value->tellg(); + value->seekg( 0, value->beg ); + utility::string_t base64; + base64.reserve( ((length / 3) + (length % 3 > 0)) * 4 ); + char read[3] = { 0 }; + uint32_t temp; + for ( size_t idx = 0; idx < length / 3; idx++ ) + { + value->read( read, 3 ); + temp = (read[0]) << 16; + temp += (read[1]) << 8; + temp += (read[2]); + base64.append( 1, Base64Chars[(temp & 0x00FC0000) >> 18] ); + base64.append( 1, Base64Chars[(temp & 0x0003F000) >> 12] ); + base64.append( 1, Base64Chars[(temp & 0x00000FC0) >> 6] ); + base64.append( 1, Base64Chars[(temp & 0x0000003F)] ); + } + switch ( length % 3 ) + { + case 1: + value->read( read, 1 ); + temp = read[0] << 16; + base64.append( 1, Base64Chars[(temp & 0x00FC0000) >> 18] ); + base64.append( 1, Base64Chars[(temp & 0x0003F000) >> 12] ); + base64.append( 2, Base64PadChar ); + break; + case 2: + value->read( read, 2 ); + temp = read[0] << 16; + temp += read[1] << 8; + base64.append( 1, Base64Chars[(temp & 0x00FC0000) >> 18] ); + base64.append( 1, Base64Chars[(temp & 0x0003F000) >> 12] ); + base64.append( 1, Base64Chars[(temp & 0x00000FC0) >> 6] ); + base64.append( 1, Base64PadChar ); + break; + } + return base64; +} + + +std::shared_ptr ModelBase::fromBase64( const utility::string_t& encoded ) +{ + std::shared_ptr result(new std::stringstream); + + char outBuf[3] = { 0 }; + uint32_t temp = 0; + + utility::string_t::const_iterator cursor = encoded.begin(); + while ( cursor < encoded.end() ) + { + for ( size_t quantumPosition = 0; quantumPosition < 4; quantumPosition++ ) + { + temp <<= 6; + if ( *cursor >= 0x41 && *cursor <= 0x5A ) + { + temp |= *cursor - 0x41; + } + else if ( *cursor >= 0x61 && *cursor <= 0x7A ) + { + temp |= *cursor - 0x47; + } + else if ( *cursor >= 0x30 && *cursor <= 0x39 ) + { + temp |= *cursor + 0x04; + } + else if ( *cursor == 0x2B ) + { + temp |= 0x3E; //change to 0x2D for URL alphabet + } + else if ( *cursor == 0x2F ) + { + temp |= 0x3F; //change to 0x5F for URL alphabet + } + else if ( *cursor == Base64PadChar ) //pad + { + switch ( encoded.end() - cursor ) + { + case 1: //One pad character + outBuf[0] = (temp >> 16) & 0x000000FF; + outBuf[1] = (temp >> 8) & 0x000000FF; + result->write( outBuf, 2 ); + return result; + case 2: //Two pad characters + outBuf[0] = (temp >> 10) & 0x000000FF; + result->write( outBuf, 1 ); + return result; + default: + throw web::json::json_exception( U( "Invalid Padding in Base 64!" ) ); + } + } + else + { + throw web::json::json_exception( U( "Non-Valid Character in Base 64!" ) ); + } + ++cursor; + } + + outBuf[0] = (temp >> 16) & 0x000000FF; + outBuf[1] = (temp >> 8) & 0x000000FF; + outBuf[2] = (temp) & 0x000000FF; + result->write( outBuf, 3 ); + } + + return result; +} + +int64_t ModelBase::int64_tFromJson(web::json::value& val) +{ + return val.as_number().to_int64(); +} +int32_t ModelBase::int32_tFromJson(web::json::value& val) +{ + return val.as_integer(); +} +utility::string_t ModelBase::stringFromJson(web::json::value& val) +{ + return val.is_string() ? val.as_string() : U(""); +} + +utility::datetime ModelBase::dateFromJson(web::json::value& val) +{ + return utility::datetime::from_string(val.as_string(), utility::datetime::ISO_8601); +} +bool ModelBase::boolFromJson(web::json::value& val) +{ + return val.as_bool(); +} +double ModelBase::doubleFromJson(web::json::value& val) +{ + return val.as_double(); +} + +int64_t ModelBase::int64_tFromHttpContent(std::shared_ptr val) +{ + utility::string_t str = ModelBase::stringFromHttpContent(val); + + utility::stringstream_t ss(str); + int64_t result = 0; + ss >> result; + return result; +} +int32_t ModelBase::int32_tFromHttpContent(std::shared_ptr val) +{ + utility::string_t str = ModelBase::stringFromHttpContent(val); + + utility::stringstream_t ss(str); + int32_t result = 0; + ss >> result; + return result; +} +utility::string_t ModelBase::stringFromHttpContent(std::shared_ptr val) +{ + std::shared_ptr data = val->getData(); + data->seekg( 0, data->beg ); + + std::string str((std::istreambuf_iterator(*data.get())), + std::istreambuf_iterator()); + + return utility::conversions::to_utf16string(str); +} +utility::datetime ModelBase::dateFromHttpContent(std::shared_ptr val) +{ + utility::string_t str = ModelBase::stringFromHttpContent(val); + return utility::datetime::from_string(str, utility::datetime::ISO_8601); +} + +bool ModelBase::boolFromHttpContent(std::shared_ptr val) +{ + utility::string_t str = ModelBase::stringFromHttpContent(val); + + utility::stringstream_t ss(str); + bool result = false; + ss >> result; + return result; +} +double ModelBase::doubleFromHttpContent(std::shared_ptr val) +{ + utility::string_t str = ModelBase::stringFromHttpContent(val); + + utility::stringstream_t ss(str); + double result = 0.0; + ss >> result; + return result; +} + +{{#modelNamespaceDeclarations}} +} +{{/modelNamespaceDeclarations}} diff --git a/modules/swagger-codegen/src/main/resources/cpprest/multipart-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/multipart-header.mustache new file mode 100644 index 000000000000..0835ed926676 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/multipart-header.mustache @@ -0,0 +1,50 @@ +{{>licenseInfo}} +/* + * MultipartFormData.h + * + * This class represents a container for building a application/x-multipart-formdata requests. + */ + +#ifndef MultipartFormData_H_ +#define MultipartFormData_H_ + +{{{defaultInclude}}} +#include "IHttpBody.h" +#include "HttpContent.h" + +#include +#include +#include + +#include + + +{{#modelNamespaceDeclarations}} +namespace {{this}} { +{{/modelNamespaceDeclarations}} + +class {{declspec}} MultipartFormData + : public IHttpBody +{ +public: + MultipartFormData(); + MultipartFormData(const utility::string_t& boundary); + virtual ~MultipartFormData(); + + virtual void add( std::shared_ptr content ); + virtual utility::string_t getBoundary(); + virtual std::shared_ptr getContent(const utility::string_t& name) const; + virtual bool hasContent(const utility::string_t& name) const; + virtual void writeTo( std::ostream& target ); + +protected: + std::vector> m_Contents; + utility::string_t m_Boundary; + std::map> m_ContentLookup; +}; + +{{#modelNamespaceDeclarations}} +} +{{/modelNamespaceDeclarations}} + +#endif /* MultipartFormData_H_ */ diff --git a/modules/swagger-codegen/src/main/resources/cpprest/multipart-source.mustache b/modules/swagger-codegen/src/main/resources/cpprest/multipart-source.mustache new file mode 100644 index 000000000000..507bda518397 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/multipart-source.mustache @@ -0,0 +1,100 @@ +{{>licenseInfo}} +#include "MultipartFormData.h" +#include "ModelBase.h" + +#include +#include + +{{#modelNamespaceDeclarations}} +namespace {{this}} { +{{/modelNamespaceDeclarations}} + +MultipartFormData::MultipartFormData() +{ + utility::stringstream_t uuidString; + uuidString << boost::uuids::random_generator()(); + m_Boundary = uuidString.str(); +} + +MultipartFormData::MultipartFormData(const utility::string_t& boundary) + : m_Boundary(boundary) +{ + +} + +MultipartFormData::~MultipartFormData() +{ +} + +utility::string_t MultipartFormData::getBoundary() +{ + return m_Boundary; +} + +void MultipartFormData::add( std::shared_ptr content ) +{ + m_Contents.push_back( content ); + m_ContentLookup[content->getName()] = content; +} + +bool MultipartFormData::hasContent(const utility::string_t& name) const +{ + return m_ContentLookup.find(name) != m_ContentLookup.end(); +} + +std::shared_ptr MultipartFormData::getContent(const utility::string_t& name) const +{ + auto result = m_ContentLookup.find(name); + if(result == m_ContentLookup.end()) + { + return std::shared_ptr(nullptr); + } + return result->second; +} + +void MultipartFormData::writeTo( std::ostream& target ) +{ + for ( size_t i = 0; i < m_Contents.size(); i++ ) + { + std::shared_ptr content = m_Contents[i]; + + // boundary + target << "\r\n" << "--" << utility::conversions::to_utf8string( m_Boundary ) << "\r\n"; + + // headers + target << "Content-Disposition: " << utility::conversions::to_utf8string( content->getContentDisposition() ); + if ( content->getName().size() > 0 ) + { + target << "; name=\"" << utility::conversions::to_utf8string( content->getName() ) << "\""; + } + if ( content->getFileName().size() > 0 ) + { + target << "; filename=\"" << utility::conversions::to_utf8string( content->getFileName() ) << "\""; + } + target << "\r\n"; + + if ( content->getContentType().size() > 0 ) + { + target << "Content-Type: " << utility::conversions::to_utf8string( content->getContentType() ) << "\r\n"; + } + + target << "\r\n"; + + // body + std::shared_ptr data = content->getData(); + + data->seekg( 0, data->end ); + std::vector dataBytes( data->tellg() ); + + data->seekg( 0, data->beg ); + data->read( &dataBytes[0], dataBytes.size() ); + + std::copy( dataBytes.begin(), dataBytes.end(), std::ostreambuf_iterator( target ) ); + } + + target << "\r\n--" << utility::conversions::to_utf8string( m_Boundary ) << "--\r\n"; +} + +{{#modelNamespaceDeclarations}} +} +{{/modelNamespaceDeclarations}} diff --git a/modules/swagger-codegen/src/main/resources/go-server/README.mustache b/modules/swagger-codegen/src/main/resources/go-server/README.mustache new file mode 100644 index 000000000000..8b66fe30f468 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/go-server/README.mustache @@ -0,0 +1,30 @@ +# Go API Server for {{packageName}} + +{{#appDescription}} +{{{appDescription}}} +{{/appDescription}} + +## Overview +This server was generated by the [swagger-codegen] +(https://github.com/swagger-api/swagger-codegen) project. +By using the [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate a server stub. +- + +To see how to make this your own, look here: + +[README](https://github.com/swagger-api/swagger-codegen/blob/master/README.md) + +- API version: {{appVersion}} +- Build date: {{generatedDate}} +{{#infoUrl}} +For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + + +### Running the server +To run the server, follow these simple steps: + +``` +go run main.go +``` + diff --git a/modules/swagger-codegen/src/main/resources/go-server/app.mustache b/modules/swagger-codegen/src/main/resources/go-server/app.mustache new file mode 100644 index 000000000000..18774a8cd31f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/go-server/app.mustache @@ -0,0 +1 @@ +application: {{packageName}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/go-server/controller.mustache b/modules/swagger-codegen/src/main/resources/go-server/controller.mustache new file mode 100644 index 000000000000..b8efd5f50e76 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/go-server/controller.mustache @@ -0,0 +1,19 @@ +package {{packageName}} + +{{#operations}} +import ( + "net/http" +) + +type {{classname}} struct { + +} + +{{#operation}} +func {{nickname}}(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json; charset=UTF-8") + w.WriteHeader(http.StatusOK) +} + +{{/operation}} +{{/operations}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/go-server/logger.mustache b/modules/swagger-codegen/src/main/resources/go-server/logger.mustache new file mode 100644 index 000000000000..6ccb2dafe818 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/go-server/logger.mustache @@ -0,0 +1,23 @@ +package {{packageName}} + +import ( + "log" + "net/http" + "time" +) + +func Logger(inner http.Handler, name string) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + + inner.ServeHTTP(w, r) + + log.Printf( + "%s %s %s %s", + r.Method, + r.RequestURI, + name, + time.Since(start), + ) + }) +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/go-server/main.mustache b/modules/swagger-codegen/src/main/resources/go-server/main.mustache new file mode 100644 index 000000000000..17b6072ebfb7 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/go-server/main.mustache @@ -0,0 +1,22 @@ +package main + +import ( + // WARNING! + // Change this to a fully-qualified import path + // once you place this file into your project. + // For example, + // + // sw "github.com/myname/myrepo/{{apiPath}}" + // + sw "./{{apiPath}}" + "log" + "net/http" +) + +func main() { + log.Printf("Server started") + + router := sw.NewRouter() + + log.Fatal(http.ListenAndServe(":{{serverPort}}", router)) +} diff --git a/modules/swagger-codegen/src/main/resources/go-server/routers.mustache b/modules/swagger-codegen/src/main/resources/go-server/routers.mustache new file mode 100644 index 000000000000..5999268a528e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/go-server/routers.mustache @@ -0,0 +1,54 @@ +package {{packageName}} + +import ( + "net/http" + "fmt" + "github.com/gorilla/mux" +) + +type Route struct { + Name string + Method string + Pattern string + HandlerFunc http.HandlerFunc +} + +type Routes []Route + +func NewRouter() *mux.Router { + router := mux.NewRouter().StrictSlash(true) + for _, route := range routes { + var handler http.Handler + handler = route.HandlerFunc + handler = Logger(handler, route.Name) + + router. + Methods(route.Method). + Path(route.Pattern). + Name(route.Name). + Handler(handler) + } + + return router +} + +func Index(w http.ResponseWriter, r *http.Request) { + fmt.Fprintf(w, "Hello World!") +} + +var routes = Routes{ + Route{ + "Index", + "GET", + "/", + Index, + }, +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} + Route{ + "{{operationId}}", + "{{httpMethod}}", + "{{path}}", + {{operationId}}, + }, +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/go-server/swagger.mustache b/modules/swagger-codegen/src/main/resources/go-server/swagger.mustache new file mode 100644 index 000000000000..51560926bba1 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/go-server/swagger.mustache @@ -0,0 +1 @@ +{{{swagger-yaml}}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache index 26f7f564ff57..4f2519fbef53 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache @@ -1,7 +1,5 @@ - - - + + {{{appName}}}