From ecd80a3d703bab68c8b091ac0e5401ee833c9963 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 14 Jun 2016 16:33:50 +0800 Subject: [PATCH] add cpprest and samples --- bin/cpprest-petstore.sh | 31 + .../languages/CppRestClientCodegen.java | 382 +++++++ .../services/io.swagger.codegen.CodegenConfig | 1 + .../resources/cpprest/api-header.mustache | 48 + .../resources/cpprest/api-source.mustache | 269 +++++ .../cpprest/apiclient-header.mustache | 75 ++ .../cpprest/apiclient-source.mustache | 131 +++ .../cpprest/apiconfiguration-header.mustache | 51 + .../cpprest/apiconfiguration-source.mustache | 67 ++ .../cpprest/apiexception-header.mustache | 48 + .../cpprest/apiexception-source.mustache | 40 + .../resources/cpprest/git_push.sh.mustache | 51 + .../main/resources/cpprest/gitignore.mustache | 29 + .../cpprest/httpcontent-header.mustache | 56 + .../cpprest/httpcontent-source.mustache | 73 ++ .../cpprest/ihttpbody-header.mustache | 29 + .../cpprest/jsonbody-header.mustache | 36 + .../cpprest/jsonbody-source.mustache | 23 + .../resources/cpprest/model-header.mustache | 69 ++ .../resources/cpprest/model-source.mustache | 254 +++++ .../cpprest/modelbase-header.mustache | 76 ++ .../cpprest/modelbase-source.mustache | 337 ++++++ .../cpprest/multipart-header.mustache | 49 + .../cpprest/multipart-source.mustache | 99 ++ samples/client/petstore/cpprest/.gitignore | 29 + .../petstore/cpprest/.swagger-codegen-ignore | 23 + samples/client/petstore/cpprest/ApiClient.cpp | 133 +++ samples/client/petstore/cpprest/ApiClient.h | 77 ++ .../petstore/cpprest/ApiConfiguration.cpp | 69 ++ .../petstore/cpprest/ApiConfiguration.h | 53 + .../client/petstore/cpprest/ApiException.cpp | 42 + .../client/petstore/cpprest/ApiException.h | 50 + .../client/petstore/cpprest/HttpContent.cpp | 75 ++ samples/client/petstore/cpprest/HttpContent.h | 58 + samples/client/petstore/cpprest/IHttpBody.h | 31 + samples/client/petstore/cpprest/JsonBody.cpp | 25 + samples/client/petstore/cpprest/JsonBody.h | 38 + samples/client/petstore/cpprest/LICENSE | 201 ++++ samples/client/petstore/cpprest/ModelBase.cpp | 339 ++++++ samples/client/petstore/cpprest/ModelBase.h | 78 ++ .../petstore/cpprest/MultipartFormData.cpp | 101 ++ .../petstore/cpprest/MultipartFormData.h | 51 + .../client/petstore/cpprest/api/PetApi.cpp | 1000 +++++++++++++++++ samples/client/petstore/cpprest/api/PetApi.h | 105 ++ .../client/petstore/cpprest/api/StoreApi.cpp | 508 +++++++++ .../client/petstore/cpprest/api/StoreApi.h | 72 ++ .../client/petstore/cpprest/api/UserApi.cpp | 954 ++++++++++++++++ samples/client/petstore/cpprest/api/UserApi.h | 104 ++ samples/client/petstore/cpprest/git_push.sh | 51 + .../petstore/cpprest/model/ApiResponse.cpp | 177 +++ .../petstore/cpprest/model/ApiResponse.h | 80 ++ .../petstore/cpprest/model/Category.cpp | 139 +++ .../client/petstore/cpprest/model/Category.h | 71 ++ .../client/petstore/cpprest/model/Order.cpp | 282 +++++ samples/client/petstore/cpprest/model/Order.h | 107 ++ samples/client/petstore/cpprest/model/Pet.cpp | 324 ++++++ samples/client/petstore/cpprest/model/Pet.h | 102 ++ samples/client/petstore/cpprest/model/Tag.cpp | 139 +++ samples/client/petstore/cpprest/model/Tag.h | 71 ++ .../client/petstore/cpprest/model/User.cpp | 364 ++++++ samples/client/petstore/cpprest/model/User.h | 125 +++ .../ruby/lib/petstore/models/array_test.rb | 39 +- 62 files changed, 8609 insertions(+), 2 deletions(-) create mode 100755 bin/cpprest-petstore.sh create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CppRestClientCodegen.java create mode 100644 modules/swagger-codegen/src/main/resources/cpprest/api-header.mustache create mode 100644 modules/swagger-codegen/src/main/resources/cpprest/api-source.mustache create mode 100644 modules/swagger-codegen/src/main/resources/cpprest/apiclient-header.mustache create mode 100644 modules/swagger-codegen/src/main/resources/cpprest/apiclient-source.mustache create mode 100644 modules/swagger-codegen/src/main/resources/cpprest/apiconfiguration-header.mustache create mode 100644 modules/swagger-codegen/src/main/resources/cpprest/apiconfiguration-source.mustache create mode 100644 modules/swagger-codegen/src/main/resources/cpprest/apiexception-header.mustache create mode 100644 modules/swagger-codegen/src/main/resources/cpprest/apiexception-source.mustache create mode 100644 modules/swagger-codegen/src/main/resources/cpprest/git_push.sh.mustache create mode 100644 modules/swagger-codegen/src/main/resources/cpprest/gitignore.mustache create mode 100644 modules/swagger-codegen/src/main/resources/cpprest/httpcontent-header.mustache create mode 100644 modules/swagger-codegen/src/main/resources/cpprest/httpcontent-source.mustache create mode 100644 modules/swagger-codegen/src/main/resources/cpprest/ihttpbody-header.mustache create mode 100644 modules/swagger-codegen/src/main/resources/cpprest/jsonbody-header.mustache create mode 100644 modules/swagger-codegen/src/main/resources/cpprest/jsonbody-source.mustache create mode 100644 modules/swagger-codegen/src/main/resources/cpprest/model-header.mustache create mode 100644 modules/swagger-codegen/src/main/resources/cpprest/model-source.mustache create mode 100644 modules/swagger-codegen/src/main/resources/cpprest/modelbase-header.mustache create mode 100644 modules/swagger-codegen/src/main/resources/cpprest/modelbase-source.mustache create mode 100644 modules/swagger-codegen/src/main/resources/cpprest/multipart-header.mustache create mode 100644 modules/swagger-codegen/src/main/resources/cpprest/multipart-source.mustache create mode 100644 samples/client/petstore/cpprest/.gitignore create mode 100644 samples/client/petstore/cpprest/.swagger-codegen-ignore create mode 100644 samples/client/petstore/cpprest/ApiClient.cpp create mode 100644 samples/client/petstore/cpprest/ApiClient.h create mode 100644 samples/client/petstore/cpprest/ApiConfiguration.cpp create mode 100644 samples/client/petstore/cpprest/ApiConfiguration.h create mode 100644 samples/client/petstore/cpprest/ApiException.cpp create mode 100644 samples/client/petstore/cpprest/ApiException.h create mode 100644 samples/client/petstore/cpprest/HttpContent.cpp create mode 100644 samples/client/petstore/cpprest/HttpContent.h create mode 100644 samples/client/petstore/cpprest/IHttpBody.h create mode 100644 samples/client/petstore/cpprest/JsonBody.cpp create mode 100644 samples/client/petstore/cpprest/JsonBody.h create mode 100644 samples/client/petstore/cpprest/LICENSE create mode 100644 samples/client/petstore/cpprest/ModelBase.cpp create mode 100644 samples/client/petstore/cpprest/ModelBase.h create mode 100644 samples/client/petstore/cpprest/MultipartFormData.cpp create mode 100644 samples/client/petstore/cpprest/MultipartFormData.h create mode 100644 samples/client/petstore/cpprest/api/PetApi.cpp create mode 100644 samples/client/petstore/cpprest/api/PetApi.h create mode 100644 samples/client/petstore/cpprest/api/StoreApi.cpp create mode 100644 samples/client/petstore/cpprest/api/StoreApi.h create mode 100644 samples/client/petstore/cpprest/api/UserApi.cpp create mode 100644 samples/client/petstore/cpprest/api/UserApi.h create mode 100644 samples/client/petstore/cpprest/git_push.sh create mode 100644 samples/client/petstore/cpprest/model/ApiResponse.cpp create mode 100644 samples/client/petstore/cpprest/model/ApiResponse.h create mode 100644 samples/client/petstore/cpprest/model/Category.cpp create mode 100644 samples/client/petstore/cpprest/model/Category.h create mode 100644 samples/client/petstore/cpprest/model/Order.cpp create mode 100644 samples/client/petstore/cpprest/model/Order.h create mode 100644 samples/client/petstore/cpprest/model/Pet.cpp create mode 100644 samples/client/petstore/cpprest/model/Pet.h create mode 100644 samples/client/petstore/cpprest/model/Tag.cpp create mode 100644 samples/client/petstore/cpprest/model/Tag.h create mode 100644 samples/client/petstore/cpprest/model/User.cpp create mode 100644 samples/client/petstore/cpprest/model/User.h diff --git a/bin/cpprest-petstore.sh b/bin/cpprest-petstore.sh new file mode 100755 index 00000000000..93f7ad609cc --- /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/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 00000000000..e3e9e47e191 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CppRestClientCodegen.java @@ -0,0 +1,382 @@ +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("apibase-header.mustache", "", "ApiBase.h")); + //supportingFiles.add(new SupportingFile("apibase-source.mustache", "", "ApiBase.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/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig index f0d0fde5e57..e4822bdcd88 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 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 00000000000..a93709b1fd5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/api-header.mustache @@ -0,0 +1,48 @@ +{{#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 00000000000..6ecbdb1a0f5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/api-source.mustache @@ -0,0 +1,269 @@ +{{#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 00000000000..97bd2f823e1 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/apiclient-header.mustache @@ -0,0 +1,75 @@ +/* + * 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_ */ \ No newline at end of file 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 00000000000..cdb62a507b4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/apiclient-source.mustache @@ -0,0 +1,131 @@ +#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}} \ No newline at end of file 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 00000000000..0463650572b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/apiconfiguration-header.mustache @@ -0,0 +1,51 @@ +/* + * 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_ */ \ No newline at end of file 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 00000000000..7585bc10924 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/apiconfiguration-source.mustache @@ -0,0 +1,67 @@ +#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}} \ No newline at end of file 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 00000000000..94a46402858 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/apiexception-header.mustache @@ -0,0 +1,48 @@ +/* + * 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_ */ \ No newline at end of file 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 00000000000..c6276211b61 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/apiexception-source.mustache @@ -0,0 +1,40 @@ +#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}} \ No newline at end of file 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 00000000000..2619d82f14d --- /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 00000000000..4581ef2eeef --- /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 00000000000..93130031118 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/httpcontent-header.mustache @@ -0,0 +1,56 @@ +/* + * 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_ */ \ No newline at end of file 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 00000000000..c6d9c6da608 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/httpcontent-source.mustache @@ -0,0 +1,73 @@ +#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}} \ No newline at end of file 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 00000000000..50ccf4a4d63 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/ihttpbody-header.mustache @@ -0,0 +1,29 @@ +/* + * 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_ */ \ No newline at end of file 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 00000000000..3dfcba1458e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/jsonbody-header.mustache @@ -0,0 +1,36 @@ +/* + * 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_ */ \ No newline at end of file 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 00000000000..c787471e5d4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/jsonbody-source.mustache @@ -0,0 +1,23 @@ +#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}} \ No newline at end of file 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 00000000000..615a00f57e2 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/model-header.mustache @@ -0,0 +1,69 @@ +{{#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}} \ No newline at end of file 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 00000000000..c784bb4eb47 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/model-source.mustache @@ -0,0 +1,254 @@ +{{#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}} \ No newline at end of file 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 00000000000..9505286ec97 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/modelbase-header.mustache @@ -0,0 +1,76 @@ +/* + * 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_ */ \ No newline at end of file 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 00000000000..dce2c3eb3b4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/modelbase-source.mustache @@ -0,0 +1,337 @@ +#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}} \ No newline at end of file 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 00000000000..f6e1b774379 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/multipart-header.mustache @@ -0,0 +1,49 @@ +/* + * 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_ */ \ No newline at end of file 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 00000000000..64b59113050 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/cpprest/multipart-source.mustache @@ -0,0 +1,99 @@ +#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}} \ No newline at end of file diff --git a/samples/client/petstore/cpprest/.gitignore b/samples/client/petstore/cpprest/.gitignore new file mode 100644 index 00000000000..4581ef2eeef --- /dev/null +++ b/samples/client/petstore/cpprest/.gitignore @@ -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/samples/client/petstore/cpprest/.swagger-codegen-ignore b/samples/client/petstore/cpprest/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/client/petstore/cpprest/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# 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 + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/cpprest/ApiClient.cpp b/samples/client/petstore/cpprest/ApiClient.cpp new file mode 100644 index 00000000000..b04707e54c9 --- /dev/null +++ b/samples/client/petstore/cpprest/ApiClient.cpp @@ -0,0 +1,133 @@ +#include "ApiClient.h" +#include "MultipartFormData.h" +#include "ModelBase.h" + +namespace io { +namespace swagger { +namespace client { +namespace api { + +using namespace io::swagger::client::model; + +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); +} + +} +} +} +} diff --git a/samples/client/petstore/cpprest/ApiClient.h b/samples/client/petstore/cpprest/ApiClient.h new file mode 100644 index 00000000000..cbbb91ce7db --- /dev/null +++ b/samples/client/petstore/cpprest/ApiClient.h @@ -0,0 +1,77 @@ +/* + * ApiClient.h + * + * This is an API client responsible for stating the HTTP calls + */ + +#ifndef ApiClient_H_ +#define ApiClient_H_ + + +#include "ApiConfiguration.h" +#include "ApiException.h" +#include "IHttpBody.h" +#include "HttpContent.h" + +#include +#include + +#include +#include + +namespace io { +namespace swagger { +namespace client { +namespace api { + +using namespace io::swagger::client::model; + +class 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; +}; + +} +} +} +} + +#endif /* ApiClient_H_ */ \ No newline at end of file diff --git a/samples/client/petstore/cpprest/ApiConfiguration.cpp b/samples/client/petstore/cpprest/ApiConfiguration.cpp new file mode 100644 index 00000000000..e66ce50a209 --- /dev/null +++ b/samples/client/petstore/cpprest/ApiConfiguration.cpp @@ -0,0 +1,69 @@ +#include "ApiConfiguration.h" + +namespace io { +namespace swagger { +namespace client { +namespace api { + +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; +} + +} +} +} +} diff --git a/samples/client/petstore/cpprest/ApiConfiguration.h b/samples/client/petstore/cpprest/ApiConfiguration.h new file mode 100644 index 00000000000..d0011a82c9e --- /dev/null +++ b/samples/client/petstore/cpprest/ApiConfiguration.h @@ -0,0 +1,53 @@ +/* + * ApiConfiguration.h + * + * This class represents a single item of a multipart-formdata request. + */ + +#ifndef ApiConfiguration_H_ +#define ApiConfiguration_H_ + + + +#include + +#include +#include +namespace io { +namespace swagger { +namespace client { +namespace api { + +class 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; +}; + +} +} +} +} +#endif /* ApiConfiguration_H_ */ \ No newline at end of file diff --git a/samples/client/petstore/cpprest/ApiException.cpp b/samples/client/petstore/cpprest/ApiException.cpp new file mode 100644 index 00000000000..a2d5ba18da2 --- /dev/null +++ b/samples/client/petstore/cpprest/ApiException.cpp @@ -0,0 +1,42 @@ +#include "ApiException.h" + +namespace io { +namespace swagger { +namespace client { +namespace api { + +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; +} + +} +} +} +} diff --git a/samples/client/petstore/cpprest/ApiException.h b/samples/client/petstore/cpprest/ApiException.h new file mode 100644 index 00000000000..1c16a5c2d3b --- /dev/null +++ b/samples/client/petstore/cpprest/ApiException.h @@ -0,0 +1,50 @@ +/* + * ApiException.h + * + * This is the exception being thrown in case the api call was not successful + */ + +#ifndef ApiException_H_ +#define ApiException_H_ + + + +#include +#include + +#include +#include + + +namespace io { +namespace swagger { +namespace client { +namespace api { + +class 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; +}; + +} +} +} +} + +#endif /* ApiBase_H_ */ \ No newline at end of file diff --git a/samples/client/petstore/cpprest/HttpContent.cpp b/samples/client/petstore/cpprest/HttpContent.cpp new file mode 100644 index 00000000000..c6697f6e0d2 --- /dev/null +++ b/samples/client/petstore/cpprest/HttpContent.cpp @@ -0,0 +1,75 @@ +#include "HttpContent.h" + +namespace io { +namespace swagger { +namespace client { +namespace model { + +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(); +} + +} +} +} +} diff --git a/samples/client/petstore/cpprest/HttpContent.h b/samples/client/petstore/cpprest/HttpContent.h new file mode 100644 index 00000000000..d8ec4ba51db --- /dev/null +++ b/samples/client/petstore/cpprest/HttpContent.h @@ -0,0 +1,58 @@ +/* + * HttpContent.h + * + * This class represents a single item of a multipart-formdata request. + */ + +#ifndef HttpContent_H_ +#define HttpContent_H_ + + + +#include + +#include + +namespace io { +namespace swagger { +namespace client { +namespace model { + +class 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; +}; + +} +} +} +} + +#endif /* HttpContent_H_ */ \ No newline at end of file diff --git a/samples/client/petstore/cpprest/IHttpBody.h b/samples/client/petstore/cpprest/IHttpBody.h new file mode 100644 index 00000000000..a4e34b6e76a --- /dev/null +++ b/samples/client/petstore/cpprest/IHttpBody.h @@ -0,0 +1,31 @@ +/* + * IHttpBody.h + * + * This is the interface for contents that can be sent to a remote HTTP server. + */ + +#ifndef IHttpBody_H_ +#define IHttpBody_H_ + + +#include + +namespace io { +namespace swagger { +namespace client { +namespace model { + +class IHttpBody +{ +public: + virtual ~IHttpBody() { } + + virtual void writeTo( std::ostream& stream ) = 0; +}; + +} +} +} +} + +#endif /* IHttpBody_H_ */ \ No newline at end of file diff --git a/samples/client/petstore/cpprest/JsonBody.cpp b/samples/client/petstore/cpprest/JsonBody.cpp new file mode 100644 index 00000000000..43970e03f25 --- /dev/null +++ b/samples/client/petstore/cpprest/JsonBody.cpp @@ -0,0 +1,25 @@ +#include "JsonBody.h" + +namespace io { +namespace swagger { +namespace client { +namespace model { + +JsonBody::JsonBody( const web::json::value& json) + : m_Json(json) +{ +} + +JsonBody::~JsonBody() +{ +} + +void JsonBody::writeTo( std::ostream& target ) +{ + m_Json.serialize(target); +} + +} +} +} +} diff --git a/samples/client/petstore/cpprest/JsonBody.h b/samples/client/petstore/cpprest/JsonBody.h new file mode 100644 index 00000000000..a86d9a5177a --- /dev/null +++ b/samples/client/petstore/cpprest/JsonBody.h @@ -0,0 +1,38 @@ +/* + * JsonBody.h + * + * This is a JSON http body which can be submitted via http + */ + +#ifndef JsonBody_H_ +#define JsonBody_H_ + + +#include "IHttpBody.h" + +#include + +namespace io { +namespace swagger { +namespace client { +namespace model { + +class JsonBody + : public IHttpBody +{ +public: + JsonBody( const web::json::value& value ); + virtual ~JsonBody(); + + void writeTo( std::ostream& target ) override; + +protected: + web::json::value m_Json; +}; + +} +} +} +} + +#endif /* JsonBody_H_ */ \ No newline at end of file diff --git a/samples/client/petstore/cpprest/LICENSE b/samples/client/petstore/cpprest/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/cpprest/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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/samples/client/petstore/cpprest/ModelBase.cpp b/samples/client/petstore/cpprest/ModelBase.cpp new file mode 100644 index 00000000000..d8abe304fa5 --- /dev/null +++ b/samples/client/petstore/cpprest/ModelBase.cpp @@ -0,0 +1,339 @@ +#include "ModelBase.h" + +namespace io { +namespace swagger { +namespace client { +namespace model { + +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; +} + +} +} +} +} diff --git a/samples/client/petstore/cpprest/ModelBase.h b/samples/client/petstore/cpprest/ModelBase.h new file mode 100644 index 00000000000..a3dccce65da --- /dev/null +++ b/samples/client/petstore/cpprest/ModelBase.h @@ -0,0 +1,78 @@ +/* + * ModelBase.h + * + * This is the base class for all model classes + */ + +#ifndef ModelBase_H_ +#define ModelBase_H_ + + +#include "HttpContent.h" +#include "MultipartFormData.h" + +#include +#include + +namespace io { +namespace swagger { +namespace client { +namespace model { + +class 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 ); +}; + +} +} +} +} + +#endif /* ModelBase_H_ */ \ No newline at end of file diff --git a/samples/client/petstore/cpprest/MultipartFormData.cpp b/samples/client/petstore/cpprest/MultipartFormData.cpp new file mode 100644 index 00000000000..2637af6ed2e --- /dev/null +++ b/samples/client/petstore/cpprest/MultipartFormData.cpp @@ -0,0 +1,101 @@ +#include "MultipartFormData.h" +#include "ModelBase.h" + +#include +#include + +namespace io { +namespace swagger { +namespace client { +namespace model { + +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"; +} + +} +} +} +} diff --git a/samples/client/petstore/cpprest/MultipartFormData.h b/samples/client/petstore/cpprest/MultipartFormData.h new file mode 100644 index 00000000000..aab22d7467f --- /dev/null +++ b/samples/client/petstore/cpprest/MultipartFormData.h @@ -0,0 +1,51 @@ +/* + * MultipartFormData.h + * + * This class represents a container for building a application/x-multipart-formdata requests. + */ + +#ifndef MultipartFormData_H_ +#define MultipartFormData_H_ + + +#include "IHttpBody.h" +#include "HttpContent.h" + +#include +#include +#include + +#include + + +namespace io { +namespace swagger { +namespace client { +namespace model { + +class 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; +}; + +} +} +} +} + +#endif /* MultipartFormData_H_ */ \ No newline at end of file diff --git a/samples/client/petstore/cpprest/api/PetApi.cpp b/samples/client/petstore/cpprest/api/PetApi.cpp new file mode 100644 index 00000000000..fe197a14b10 --- /dev/null +++ b/samples/client/petstore/cpprest/api/PetApi.cpp @@ -0,0 +1,1000 @@ + +#include "PetApi.h" +#include "IHttpBody.h" +#include "JsonBody.h" +#include "MultipartFormData.h" + +#include + +#include + +namespace io { +namespace swagger { +namespace client { +namespace api { + +using namespace io::swagger::client::model; + +PetApi::PetApi( std::shared_ptr apiClient ) + : m_ApiClient(apiClient) +{ +} + +PetApi::~PetApi() +{ +} + +pplx::task PetApi::addPet(std::shared_ptr body) +{ + + // verify the required parameter 'body' is set + if (body == nullptr) + { + throw ApiException(400, U("Missing required parameter 'body' when calling PetApi->addPet")); + } + + + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); + utility::string_t path = U("/pet"); + + std::map queryParams; + std::map headerParams( apiConfiguration->getDefaultHeaders() ); + std::map formParams; + std::map> fileParams; + + std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); +responseHttpContentTypes.insert( U("application/json") ); + + 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("PetApi->addPet does not produce any supported media type")); + } + + headerParams[U("Accept")] = responseHttpContentType; + + std::unordered_set consumeHttpContentTypes; + consumeHttpContentTypes.insert( U("application/json") ); +consumeHttpContentTypes.insert( U("application/xml") ); + + + + 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"); + + web::json::value json; + + json = ModelBase::toJson(body); + + + httpBody = std::shared_ptr( new JsonBody( json ) ); + + } + // multipart formdata + else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + { + requestHttpContentType = U("multipart/form-data"); + + std::shared_ptr multipart(new MultipartFormData); + + if(body.get()) + { + body->toMultipart(multipart, U("body")); + } + + + httpBody = multipart; + requestHttpContentType += U("; boundary=") + multipart->getBoundary(); + } + else + { + throw ApiException(415, U("PetApi->addPet does not consume any supported media type")); + } + + // authentication (petstore_auth) required + // oauth2 authentication is added automatically as part of the http_client_config + + return m_ApiClient->callApi(path, U("POST"), 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 addPet: ") + 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 addPet: unexpected response type: ") + contentType + , std::make_shared(response.extract_utf8string(true).get())); + } + } + + return response.extract_string(); + }) + .then([=](utility::string_t response) + { + return void(); + }); +} +pplx::task PetApi::deletePet(int64_t petId, utility::string_t apiKey) +{ + + + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); + utility::string_t path = U("/pet/{petId}"); + boost::replace_all(path, U("{") U("petId") U("}"), ApiClient::parameterToString(petId)); + + std::map queryParams; + std::map headerParams( apiConfiguration->getDefaultHeaders() ); + std::map formParams; + std::map> fileParams; + + std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); +responseHttpContentTypes.insert( U("application/json") ); + + 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("PetApi->deletePet does not produce any supported media type")); + } + + headerParams[U("Accept")] = responseHttpContentType; + + std::unordered_set consumeHttpContentTypes; + + + { + + } + + { + headerParams[U("api_key")] = ApiClient::parameterToString(apiKey); + + } + + + 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"); + + } + // multipart formdata + else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + { + requestHttpContentType = U("multipart/form-data"); + + } + else + { + throw ApiException(415, U("PetApi->deletePet does not consume any supported media type")); + } + + // authentication (petstore_auth) required + // oauth2 authentication is added automatically as part of the http_client_config + + return m_ApiClient->callApi(path, U("DELETE"), 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 deletePet: ") + 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 deletePet: unexpected response type: ") + contentType + , std::make_shared(response.extract_utf8string(true).get())); + } + } + + return response.extract_string(); + }) + .then([=](utility::string_t response) + { + return void(); + }); +} +pplx::task>> PetApi::findPetsByStatus(std::vector status) +{ + + + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); + utility::string_t path = U("/pet/findByStatus"); + + std::map queryParams; + std::map headerParams( apiConfiguration->getDefaultHeaders() ); + std::map formParams; + std::map> fileParams; + + std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); +responseHttpContentTypes.insert( U("application/json") ); + + 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("PetApi->findPetsByStatus does not produce any supported media type")); + } + + headerParams[U("Accept")] = responseHttpContentType; + + std::unordered_set consumeHttpContentTypes; + + + { + queryParams[U("status")] = ApiClient::parameterToArrayString(status); + + } + + + 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"); + + } + // multipart formdata + else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + { + requestHttpContentType = U("multipart/form-data"); + + } + else + { + throw ApiException(415, U("PetApi->findPetsByStatus does not consume any supported media type")); + } + + // authentication (petstore_auth) required + // oauth2 authentication is added automatically as part of the http_client_config + + return m_ApiClient->callApi(path, U("GET"), 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 findPetsByStatus: ") + 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 findPetsByStatus: unexpected response type: ") + contentType + , std::make_shared(response.extract_utf8string(true).get())); + } + } + + return response.extract_string(); + }) + .then([=](utility::string_t response) + { + std::vector> result; + + + if(responseHttpContentType == U("application/json")) + { + web::json::value json = web::json::value::parse(response); + + for( auto& item : json.as_array() ) + { + std::shared_ptr itemObj(new Pet()); + itemObj->fromJson(item); + result.push_back(itemObj); + + } + + } + // else if(responseHttpContentType == U("multipart/form-data")) + // { + // TODO multipart response parsing + // } + else + { + throw ApiException(500 + , U("error calling findPetsByStatus: unsupported response type")); + } + + return result; + }); +} +pplx::task>> PetApi::findPetsByTags(std::vector tags) +{ + + + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); + utility::string_t path = U("/pet/findByTags"); + + std::map queryParams; + std::map headerParams( apiConfiguration->getDefaultHeaders() ); + std::map formParams; + std::map> fileParams; + + std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); +responseHttpContentTypes.insert( U("application/json") ); + + 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("PetApi->findPetsByTags does not produce any supported media type")); + } + + headerParams[U("Accept")] = responseHttpContentType; + + std::unordered_set consumeHttpContentTypes; + + + { + queryParams[U("tags")] = ApiClient::parameterToArrayString<>(tags); + + } + + + 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"); + + } + // multipart formdata + else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + { + requestHttpContentType = U("multipart/form-data"); + + } + else + { + throw ApiException(415, U("PetApi->findPetsByTags does not consume any supported media type")); + } + + // authentication (petstore_auth) required + // oauth2 authentication is added automatically as part of the http_client_config + + return m_ApiClient->callApi(path, U("GET"), 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 findPetsByTags: ") + 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 findPetsByTags: unexpected response type: ") + contentType + , std::make_shared(response.extract_utf8string(true).get())); + } + } + + return response.extract_string(); + }) + .then([=](utility::string_t response) + { + std::vector> result; + + + if(responseHttpContentType == U("application/json")) + { + web::json::value json = web::json::value::parse(response); + + for( auto& item : json.as_array() ) + { + std::shared_ptr itemObj(new Pet()); + itemObj->fromJson(item); + result.push_back(itemObj); + + } + + } + // else if(responseHttpContentType == U("multipart/form-data")) + // { + // TODO multipart response parsing + // } + else + { + throw ApiException(500 + , U("error calling findPetsByStatus: unsupported response type")); + } + + return result; + }); +} +pplx::task> PetApi::getPetById(int64_t petId) +{ + + + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); + utility::string_t path = U("/pet/{petId}"); + boost::replace_all(path, U("{") U("petId") U("}"), ApiClient::parameterToString(petId)); + + std::map queryParams; + std::map headerParams( apiConfiguration->getDefaultHeaders() ); + std::map formParams; + std::map> fileParams; + + std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); +responseHttpContentTypes.insert( U("application/json") ); + + 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("PetApi->getPetById does not produce any supported media type")); + } + + headerParams[U("Accept")] = responseHttpContentType; + + std::unordered_set consumeHttpContentTypes; + + + { + + } + + + 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"); + + } + // multipart formdata + else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + { + requestHttpContentType = U("multipart/form-data"); + + } + else + { + throw ApiException(415, U("PetApi->getPetById does not consume any supported media type")); + } + + // authentication (api_key) required + { + utility::string_t apiKey = apiConfiguration->getApiKey(U("api_key")); + if ( apiKey.size() > 0 ) + { + headerParams[U("api_key")] = apiKey; + } + } + + return m_ApiClient->callApi(path, U("GET"), 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 getPetById: ") + 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 getPetById: unexpected response type: ") + contentType + , std::make_shared(response.extract_utf8string(true).get())); + } + } + + return response.extract_string(); + }) + .then([=](utility::string_t response) + { + std::shared_ptr result(new Pet()); + + if(responseHttpContentType == U("application/json")) + { + web::json::value json = web::json::value::parse(response); + + result->fromJson(json); + } + // else if(responseHttpContentType == U("multipart/form-data")) + // { + // TODO multipart response parsing + // } + else + { + throw ApiException(500 + , U("error calling findPetsByStatus: unsupported response type")); + } + + return result; + }); +} +pplx::task PetApi::updatePet(std::shared_ptr body) +{ + + // verify the required parameter 'body' is set + if (body == nullptr) + { + throw ApiException(400, U("Missing required parameter 'body' when calling PetApi->updatePet")); + } + + + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); + utility::string_t path = U("/pet"); + + std::map queryParams; + std::map headerParams( apiConfiguration->getDefaultHeaders() ); + std::map formParams; + std::map> fileParams; + + std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); +responseHttpContentTypes.insert( U("application/json") ); + + 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("PetApi->updatePet does not produce any supported media type")); + } + + headerParams[U("Accept")] = responseHttpContentType; + + std::unordered_set consumeHttpContentTypes; + consumeHttpContentTypes.insert( U("application/json") ); +consumeHttpContentTypes.insert( U("application/xml") ); + + + + 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"); + + web::json::value json; + + json = ModelBase::toJson(body); + + + httpBody = std::shared_ptr( new JsonBody( json ) ); + + } + // multipart formdata + else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + { + requestHttpContentType = U("multipart/form-data"); + + std::shared_ptr multipart(new MultipartFormData); + + if(body.get()) + { + body->toMultipart(multipart, U("body")); + } + + + httpBody = multipart; + requestHttpContentType += U("; boundary=") + multipart->getBoundary(); + } + else + { + throw ApiException(415, U("PetApi->updatePet does not consume any supported media type")); + } + + // authentication (petstore_auth) required + // oauth2 authentication is added automatically as part of the http_client_config + + return m_ApiClient->callApi(path, U("PUT"), 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 updatePet: ") + 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 updatePet: unexpected response type: ") + contentType + , std::make_shared(response.extract_utf8string(true).get())); + } + } + + return response.extract_string(); + }) + .then([=](utility::string_t response) + { + return void(); + }); +} +pplx::task PetApi::updatePetWithForm(int64_t petId, utility::string_t name, utility::string_t status) +{ + + + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); + utility::string_t path = U("/pet/{petId}"); + boost::replace_all(path, U("{") U("petId") U("}"), ApiClient::parameterToString(petId)); + + std::map queryParams; + std::map headerParams( apiConfiguration->getDefaultHeaders() ); + std::map formParams; + std::map> fileParams; + + std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); +responseHttpContentTypes.insert( U("application/json") ); + + 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("PetApi->updatePetWithForm does not produce any supported media type")); + } + + headerParams[U("Accept")] = responseHttpContentType; + + std::unordered_set consumeHttpContentTypes; + consumeHttpContentTypes.insert( U("application/x-www-form-urlencoded") ); + + + { + + } + + { + formParams[ U("name") ] = ApiClient::parameterToString(name); + + } + + { + formParams[ U("status") ] = ApiClient::parameterToString(status); + + } + + + 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"); + + } + // multipart formdata + else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + { + requestHttpContentType = U("multipart/form-data"); + + } + else + { + throw ApiException(415, U("PetApi->updatePetWithForm does not consume any supported media type")); + } + + // authentication (petstore_auth) required + // oauth2 authentication is added automatically as part of the http_client_config + + return m_ApiClient->callApi(path, U("POST"), 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 updatePetWithForm: ") + 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 updatePetWithForm: unexpected response type: ") + contentType + , std::make_shared(response.extract_utf8string(true).get())); + } + } + + return response.extract_string(); + }) + .then([=](utility::string_t response) + { + return void(); + }); +} +pplx::task> PetApi::uploadFile(int64_t petId, utility::string_t additionalMetadata, std::shared_ptr file) +{ + + + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); + utility::string_t path = U("/pet/{petId}/uploadImage"); + boost::replace_all(path, U("{") U("petId") U("}"), ApiClient::parameterToString(petId)); + + std::map queryParams; + std::map headerParams( apiConfiguration->getDefaultHeaders() ); + std::map formParams; + std::map> fileParams; + + std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/json") ); + + 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("PetApi->uploadFile does not produce any supported media type")); + } + + headerParams[U("Accept")] = responseHttpContentType; + + std::unordered_set consumeHttpContentTypes; + consumeHttpContentTypes.insert( U("multipart/form-data") ); + + + { + + } + + { + formParams[ U("additionalMetadata") ] = ApiClient::parameterToString(additionalMetadata); + + } + if (file != nullptr) + { + fileParams[ U("file") ] = file; + + } + + + 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"); + + } + // multipart formdata + else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + { + requestHttpContentType = U("multipart/form-data"); + + } + else + { + throw ApiException(415, U("PetApi->uploadFile does not consume any supported media type")); + } + + // authentication (petstore_auth) required + // oauth2 authentication is added automatically as part of the http_client_config + + return m_ApiClient->callApi(path, U("POST"), 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 uploadFile: ") + 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 uploadFile: unexpected response type: ") + contentType + , std::make_shared(response.extract_utf8string(true).get())); + } + } + + return response.extract_string(); + }) + .then([=](utility::string_t response) + { + std::shared_ptr result(new ApiResponse()); + + if(responseHttpContentType == U("application/json")) + { + web::json::value json = web::json::value::parse(response); + + result->fromJson(json); + } + // else if(responseHttpContentType == U("multipart/form-data")) + // { + // TODO multipart response parsing + // } + else + { + throw ApiException(500 + , U("error calling findPetsByStatus: unsupported response type")); + } + + return result; + }); +} + +} +} +} +} + diff --git a/samples/client/petstore/cpprest/api/PetApi.h b/samples/client/petstore/cpprest/api/PetApi.h new file mode 100644 index 00000000000..7aa37d09701 --- /dev/null +++ b/samples/client/petstore/cpprest/api/PetApi.h @@ -0,0 +1,105 @@ +/* + * PetApi.h + * + * + */ + +#ifndef PetApi_H_ +#define PetApi_H_ + + +#include "ApiClient.h" + +#include "Pet.h" +#include +#include "ApiResponse.h" +#include "HttpContent.h" + +namespace io { +namespace swagger { +namespace client { +namespace api { + +using namespace io::swagger::client::model; + +class PetApi +{ +public: + PetApi( std::shared_ptr apiClient ); + virtual ~PetApi(); + /// + /// Add a new pet to the store + /// + /// + /// + /// + /// Pet object that needs to be added to the store + pplx::task addPet(std::shared_ptr body); + /// + /// Deletes a pet + /// + /// + /// + /// + /// Pet id to delete/// (optional) + pplx::task deletePet(int64_t petId, utility::string_t apiKey); + /// + /// Finds Pets by status + /// + /// + /// Multiple status values can be provided with comma separated strings + /// + /// Status values that need to be considered for filter + pplx::task>> findPetsByStatus(std::vector status); + /// + /// Finds Pets by tags + /// + /// + /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// + /// Tags to filter by + pplx::task>> findPetsByTags(std::vector tags); + /// + /// Find pet by ID + /// + /// + /// Returns a single pet + /// + /// ID of pet to return + pplx::task> getPetById(int64_t petId); + /// + /// Update an existing pet + /// + /// + /// + /// + /// Pet object that needs to be added to the store + pplx::task updatePet(std::shared_ptr body); + /// + /// Updates a pet in the store with form data + /// + /// + /// + /// + /// ID of pet that needs to be updated/// Updated name of the pet (optional)/// Updated status of the pet (optional) + pplx::task updatePetWithForm(int64_t petId, utility::string_t name, utility::string_t status); + /// + /// uploads an image + /// + /// + /// + /// + /// ID of pet to update/// Additional data to pass to server (optional)/// file to upload (optional) + pplx::task> uploadFile(int64_t petId, utility::string_t additionalMetadata, std::shared_ptr file); + +protected: + std::shared_ptr m_ApiClient; +}; + +} +} +} +} + +#endif /* PetApi_H_ */ + diff --git a/samples/client/petstore/cpprest/api/StoreApi.cpp b/samples/client/petstore/cpprest/api/StoreApi.cpp new file mode 100644 index 00000000000..ddb7e5b0067 --- /dev/null +++ b/samples/client/petstore/cpprest/api/StoreApi.cpp @@ -0,0 +1,508 @@ + +#include "StoreApi.h" +#include "IHttpBody.h" +#include "JsonBody.h" +#include "MultipartFormData.h" + +#include + +#include + +namespace io { +namespace swagger { +namespace client { +namespace api { + +using namespace io::swagger::client::model; + +StoreApi::StoreApi( std::shared_ptr apiClient ) + : m_ApiClient(apiClient) +{ +} + +StoreApi::~StoreApi() +{ +} + +pplx::task StoreApi::deleteOrder(utility::string_t orderId) +{ + + + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); + utility::string_t path = U("/store/order/{orderId}"); + boost::replace_all(path, U("{") U("orderId") U("}"), ApiClient::parameterToString(orderId)); + + std::map queryParams; + std::map headerParams( apiConfiguration->getDefaultHeaders() ); + std::map formParams; + std::map> fileParams; + + std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); +responseHttpContentTypes.insert( U("application/json") ); + + 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("StoreApi->deleteOrder does not produce any supported media type")); + } + + headerParams[U("Accept")] = responseHttpContentType; + + std::unordered_set consumeHttpContentTypes; + + + { + + } + + + 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"); + + } + // multipart formdata + else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + { + requestHttpContentType = U("multipart/form-data"); + + } + else + { + throw ApiException(415, U("StoreApi->deleteOrder does not consume any supported media type")); + } + + + return m_ApiClient->callApi(path, U("DELETE"), 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 deleteOrder: ") + 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 deleteOrder: unexpected response type: ") + contentType + , std::make_shared(response.extract_utf8string(true).get())); + } + } + + return response.extract_string(); + }) + .then([=](utility::string_t response) + { + return void(); + }); +} +pplx::task> StoreApi::getInventory() +{ + + + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); + utility::string_t path = U("/store/inventory"); + + std::map queryParams; + std::map headerParams( apiConfiguration->getDefaultHeaders() ); + std::map formParams; + std::map> fileParams; + + std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/json") ); + + 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("StoreApi->getInventory does not produce any supported media type")); + } + + headerParams[U("Accept")] = responseHttpContentType; + + std::unordered_set consumeHttpContentTypes; + + + + 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"); + + } + // multipart formdata + else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + { + requestHttpContentType = U("multipart/form-data"); + + } + else + { + throw ApiException(415, U("StoreApi->getInventory does not consume any supported media type")); + } + + // authentication (api_key) required + { + utility::string_t apiKey = apiConfiguration->getApiKey(U("api_key")); + if ( apiKey.size() > 0 ) + { + headerParams[U("api_key")] = apiKey; + } + } + + return m_ApiClient->callApi(path, U("GET"), 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 getInventory: ") + 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 getInventory: unexpected response type: ") + contentType + , std::make_shared(response.extract_utf8string(true).get())); + } + } + + return response.extract_string(); + }) + .then([=](utility::string_t response) + { + std::map result; + + + if(responseHttpContentType == U("application/json")) + { + web::json::value json = web::json::value::parse(response); + + for( auto& item : json.as_object() ) + { + result[item.first] = ModelBase::int32_tFromJson(item.second); + + } + + } + // else if(responseHttpContentType == U("multipart/form-data")) + // { + // TODO multipart response parsing + // } + else + { + throw ApiException(500 + , U("error calling findPetsByStatus: unsupported response type")); + } + + return result; + }); +} +pplx::task> StoreApi::getOrderById(int64_t orderId) +{ + + + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); + utility::string_t path = U("/store/order/{orderId}"); + boost::replace_all(path, U("{") U("orderId") U("}"), ApiClient::parameterToString(orderId)); + + std::map queryParams; + std::map headerParams( apiConfiguration->getDefaultHeaders() ); + std::map formParams; + std::map> fileParams; + + std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); +responseHttpContentTypes.insert( U("application/json") ); + + 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("StoreApi->getOrderById does not produce any supported media type")); + } + + headerParams[U("Accept")] = responseHttpContentType; + + std::unordered_set consumeHttpContentTypes; + + + { + + } + + + 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"); + + } + // multipart formdata + else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + { + requestHttpContentType = U("multipart/form-data"); + + } + else + { + throw ApiException(415, U("StoreApi->getOrderById does not consume any supported media type")); + } + + + return m_ApiClient->callApi(path, U("GET"), 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 getOrderById: ") + 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 getOrderById: unexpected response type: ") + contentType + , std::make_shared(response.extract_utf8string(true).get())); + } + } + + return response.extract_string(); + }) + .then([=](utility::string_t response) + { + std::shared_ptr result(new Order()); + + if(responseHttpContentType == U("application/json")) + { + web::json::value json = web::json::value::parse(response); + + result->fromJson(json); + } + // else if(responseHttpContentType == U("multipart/form-data")) + // { + // TODO multipart response parsing + // } + else + { + throw ApiException(500 + , U("error calling findPetsByStatus: unsupported response type")); + } + + return result; + }); +} +pplx::task> StoreApi::placeOrder(std::shared_ptr body) +{ + + // verify the required parameter 'body' is set + if (body == nullptr) + { + throw ApiException(400, U("Missing required parameter 'body' when calling StoreApi->placeOrder")); + } + + + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); + utility::string_t path = U("/store/order"); + + std::map queryParams; + std::map headerParams( apiConfiguration->getDefaultHeaders() ); + std::map formParams; + std::map> fileParams; + + std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); +responseHttpContentTypes.insert( U("application/json") ); + + 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("StoreApi->placeOrder does not produce any supported media type")); + } + + headerParams[U("Accept")] = responseHttpContentType; + + std::unordered_set consumeHttpContentTypes; + + + + 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"); + + web::json::value json; + + json = ModelBase::toJson(body); + + + httpBody = std::shared_ptr( new JsonBody( json ) ); + + } + // multipart formdata + else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + { + requestHttpContentType = U("multipart/form-data"); + + std::shared_ptr multipart(new MultipartFormData); + + if(body.get()) + { + body->toMultipart(multipart, U("body")); + } + + + httpBody = multipart; + requestHttpContentType += U("; boundary=") + multipart->getBoundary(); + } + else + { + throw ApiException(415, U("StoreApi->placeOrder does not consume any supported media type")); + } + + + return m_ApiClient->callApi(path, U("POST"), 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 placeOrder: ") + 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 placeOrder: unexpected response type: ") + contentType + , std::make_shared(response.extract_utf8string(true).get())); + } + } + + return response.extract_string(); + }) + .then([=](utility::string_t response) + { + std::shared_ptr result(new Order()); + + if(responseHttpContentType == U("application/json")) + { + web::json::value json = web::json::value::parse(response); + + result->fromJson(json); + } + // else if(responseHttpContentType == U("multipart/form-data")) + // { + // TODO multipart response parsing + // } + else + { + throw ApiException(500 + , U("error calling findPetsByStatus: unsupported response type")); + } + + return result; + }); +} + +} +} +} +} + diff --git a/samples/client/petstore/cpprest/api/StoreApi.h b/samples/client/petstore/cpprest/api/StoreApi.h new file mode 100644 index 00000000000..c076a255359 --- /dev/null +++ b/samples/client/petstore/cpprest/api/StoreApi.h @@ -0,0 +1,72 @@ +/* + * StoreApi.h + * + * + */ + +#ifndef StoreApi_H_ +#define StoreApi_H_ + + +#include "ApiClient.h" + +#include +#include +#include "Order.h" + +namespace io { +namespace swagger { +namespace client { +namespace api { + +using namespace io::swagger::client::model; + +class StoreApi +{ +public: + StoreApi( std::shared_ptr apiClient ); + virtual ~StoreApi(); + /// + /// Delete purchase order by ID + /// + /// + /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// ID of the order that needs to be deleted + pplx::task deleteOrder(utility::string_t orderId); + /// + /// Returns pet inventories by status + /// + /// + /// Returns a map of status codes to quantities + /// + + pplx::task> getInventory(); + /// + /// Find purchase order by ID + /// + /// + /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// ID of pet that needs to be fetched + pplx::task> getOrderById(int64_t orderId); + /// + /// Place an order for a pet + /// + /// + /// + /// + /// order placed for purchasing the pet + pplx::task> placeOrder(std::shared_ptr body); + +protected: + std::shared_ptr m_ApiClient; +}; + +} +} +} +} + +#endif /* StoreApi_H_ */ + diff --git a/samples/client/petstore/cpprest/api/UserApi.cpp b/samples/client/petstore/cpprest/api/UserApi.cpp new file mode 100644 index 00000000000..e17a1acf42b --- /dev/null +++ b/samples/client/petstore/cpprest/api/UserApi.cpp @@ -0,0 +1,954 @@ + +#include "UserApi.h" +#include "IHttpBody.h" +#include "JsonBody.h" +#include "MultipartFormData.h" + +#include + +#include + +namespace io { +namespace swagger { +namespace client { +namespace api { + +using namespace io::swagger::client::model; + +UserApi::UserApi( std::shared_ptr apiClient ) + : m_ApiClient(apiClient) +{ +} + +UserApi::~UserApi() +{ +} + +pplx::task UserApi::createUser(std::shared_ptr body) +{ + + // verify the required parameter 'body' is set + if (body == nullptr) + { + throw ApiException(400, U("Missing required parameter 'body' when calling UserApi->createUser")); + } + + + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); + utility::string_t path = U("/user"); + + std::map queryParams; + std::map headerParams( apiConfiguration->getDefaultHeaders() ); + std::map formParams; + std::map> fileParams; + + std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); +responseHttpContentTypes.insert( U("application/json") ); + + 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("UserApi->createUser does not produce any supported media type")); + } + + headerParams[U("Accept")] = responseHttpContentType; + + std::unordered_set consumeHttpContentTypes; + + + + 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"); + + web::json::value json; + + json = ModelBase::toJson(body); + + + httpBody = std::shared_ptr( new JsonBody( json ) ); + + } + // multipart formdata + else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + { + requestHttpContentType = U("multipart/form-data"); + + std::shared_ptr multipart(new MultipartFormData); + + if(body.get()) + { + body->toMultipart(multipart, U("body")); + } + + + httpBody = multipart; + requestHttpContentType += U("; boundary=") + multipart->getBoundary(); + } + else + { + throw ApiException(415, U("UserApi->createUser does not consume any supported media type")); + } + + + return m_ApiClient->callApi(path, U("POST"), 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 createUser: ") + 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 createUser: unexpected response type: ") + contentType + , std::make_shared(response.extract_utf8string(true).get())); + } + } + + return response.extract_string(); + }) + .then([=](utility::string_t response) + { + return void(); + }); +} +pplx::task UserApi::createUsersWithArrayInput(std::vector> body) +{ + + + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); + utility::string_t path = U("/user/createWithArray"); + + std::map queryParams; + std::map headerParams( apiConfiguration->getDefaultHeaders() ); + std::map formParams; + std::map> fileParams; + + std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); +responseHttpContentTypes.insert( U("application/json") ); + + 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("UserApi->createUsersWithArrayInput does not produce any supported media type")); + } + + headerParams[U("Accept")] = responseHttpContentType; + + std::unordered_set consumeHttpContentTypes; + + + + 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"); + + web::json::value json; + + + { + std::vector jsonArray; + for( auto& item : body ) + { + jsonArray.push_back( item.get() ? item->toJson() : web::json::value::null() ); + + } + json = web::json::value::array(jsonArray); + } + + + httpBody = std::shared_ptr( new JsonBody( json ) ); + + } + // multipart formdata + else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + { + requestHttpContentType = U("multipart/form-data"); + + std::shared_ptr multipart(new MultipartFormData); + + { + std::vector jsonArray; + for( auto& item : body ) + { + jsonArray.push_back( item.get() ? item->toJson() : web::json::value::null() ); + + } + multipart->add(ModelBase::toHttpContent(U("body"), web::json::value::array(jsonArray), U("application/json"))); + } + + + httpBody = multipart; + requestHttpContentType += U("; boundary=") + multipart->getBoundary(); + } + else + { + throw ApiException(415, U("UserApi->createUsersWithArrayInput does not consume any supported media type")); + } + + + return m_ApiClient->callApi(path, U("POST"), 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 createUsersWithArrayInput: ") + 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 createUsersWithArrayInput: unexpected response type: ") + contentType + , std::make_shared(response.extract_utf8string(true).get())); + } + } + + return response.extract_string(); + }) + .then([=](utility::string_t response) + { + return void(); + }); +} +pplx::task UserApi::createUsersWithListInput(std::vector> body) +{ + + + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); + utility::string_t path = U("/user/createWithList"); + + std::map queryParams; + std::map headerParams( apiConfiguration->getDefaultHeaders() ); + std::map formParams; + std::map> fileParams; + + std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); +responseHttpContentTypes.insert( U("application/json") ); + + 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("UserApi->createUsersWithListInput does not produce any supported media type")); + } + + headerParams[U("Accept")] = responseHttpContentType; + + std::unordered_set consumeHttpContentTypes; + + + + 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"); + + web::json::value json; + + + { + std::vector jsonArray; + for( auto& item : body ) + { + jsonArray.push_back( item.get() ? item->toJson() : web::json::value::null() ); + + } + json = web::json::value::array(jsonArray); + } + + + httpBody = std::shared_ptr( new JsonBody( json ) ); + + } + // multipart formdata + else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + { + requestHttpContentType = U("multipart/form-data"); + + std::shared_ptr multipart(new MultipartFormData); + + { + std::vector jsonArray; + for( auto& item : body ) + { + jsonArray.push_back( item.get() ? item->toJson() : web::json::value::null() ); + + } + multipart->add(ModelBase::toHttpContent(U("body"), web::json::value::array(jsonArray), U("application/json"))); + } + + + httpBody = multipart; + requestHttpContentType += U("; boundary=") + multipart->getBoundary(); + } + else + { + throw ApiException(415, U("UserApi->createUsersWithListInput does not consume any supported media type")); + } + + + return m_ApiClient->callApi(path, U("POST"), 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 createUsersWithListInput: ") + 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 createUsersWithListInput: unexpected response type: ") + contentType + , std::make_shared(response.extract_utf8string(true).get())); + } + } + + return response.extract_string(); + }) + .then([=](utility::string_t response) + { + return void(); + }); +} +pplx::task UserApi::deleteUser(utility::string_t username) +{ + + + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); + utility::string_t path = U("/user/{username}"); + boost::replace_all(path, U("{") U("username") U("}"), ApiClient::parameterToString(username)); + + std::map queryParams; + std::map headerParams( apiConfiguration->getDefaultHeaders() ); + std::map formParams; + std::map> fileParams; + + std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); +responseHttpContentTypes.insert( U("application/json") ); + + 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("UserApi->deleteUser does not produce any supported media type")); + } + + headerParams[U("Accept")] = responseHttpContentType; + + std::unordered_set consumeHttpContentTypes; + + + { + + } + + + 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"); + + } + // multipart formdata + else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + { + requestHttpContentType = U("multipart/form-data"); + + } + else + { + throw ApiException(415, U("UserApi->deleteUser does not consume any supported media type")); + } + + + return m_ApiClient->callApi(path, U("DELETE"), 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 deleteUser: ") + 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 deleteUser: unexpected response type: ") + contentType + , std::make_shared(response.extract_utf8string(true).get())); + } + } + + return response.extract_string(); + }) + .then([=](utility::string_t response) + { + return void(); + }); +} +pplx::task> UserApi::getUserByName(utility::string_t username) +{ + + + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); + utility::string_t path = U("/user/{username}"); + boost::replace_all(path, U("{") U("username") U("}"), ApiClient::parameterToString(username)); + + std::map queryParams; + std::map headerParams( apiConfiguration->getDefaultHeaders() ); + std::map formParams; + std::map> fileParams; + + std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); +responseHttpContentTypes.insert( U("application/json") ); + + 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("UserApi->getUserByName does not produce any supported media type")); + } + + headerParams[U("Accept")] = responseHttpContentType; + + std::unordered_set consumeHttpContentTypes; + + + { + + } + + + 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"); + + } + // multipart formdata + else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + { + requestHttpContentType = U("multipart/form-data"); + + } + else + { + throw ApiException(415, U("UserApi->getUserByName does not consume any supported media type")); + } + + + return m_ApiClient->callApi(path, U("GET"), 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 getUserByName: ") + 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 getUserByName: unexpected response type: ") + contentType + , std::make_shared(response.extract_utf8string(true).get())); + } + } + + return response.extract_string(); + }) + .then([=](utility::string_t response) + { + std::shared_ptr result(new User()); + + if(responseHttpContentType == U("application/json")) + { + web::json::value json = web::json::value::parse(response); + + result->fromJson(json); + } + // else if(responseHttpContentType == U("multipart/form-data")) + // { + // TODO multipart response parsing + // } + else + { + throw ApiException(500 + , U("error calling findPetsByStatus: unsupported response type")); + } + + return result; + }); +} +pplx::task UserApi::loginUser(utility::string_t username, utility::string_t password) +{ + + + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); + utility::string_t path = U("/user/login"); + + std::map queryParams; + std::map headerParams( apiConfiguration->getDefaultHeaders() ); + std::map formParams; + std::map> fileParams; + + std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); +responseHttpContentTypes.insert( U("application/json") ); + + 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("UserApi->loginUser does not produce any supported media type")); + } + + headerParams[U("Accept")] = responseHttpContentType; + + std::unordered_set consumeHttpContentTypes; + + + { + queryParams[U("username")] = ApiClient::parameterToString(username); + + } + + { + queryParams[U("password")] = ApiClient::parameterToString(password); + + } + + + 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"); + + } + // multipart formdata + else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + { + requestHttpContentType = U("multipart/form-data"); + + } + else + { + throw ApiException(415, U("UserApi->loginUser does not consume any supported media type")); + } + + + return m_ApiClient->callApi(path, U("GET"), 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 loginUser: ") + 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 loginUser: unexpected response type: ") + contentType + , std::make_shared(response.extract_utf8string(true).get())); + } + } + + return response.extract_string(); + }) + .then([=](utility::string_t response) + { + utility::string_t result(U("")); + + if(responseHttpContentType == U("application/json")) + { + web::json::value json = web::json::value::parse(response); + + result = ModelBase::stringFromJson(json); + + } + // else if(responseHttpContentType == U("multipart/form-data")) + // { + // TODO multipart response parsing + // } + else + { + throw ApiException(500 + , U("error calling findPetsByStatus: unsupported response type")); + } + + return result; + }); +} +pplx::task UserApi::logoutUser() +{ + + + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); + utility::string_t path = U("/user/logout"); + + std::map queryParams; + std::map headerParams( apiConfiguration->getDefaultHeaders() ); + std::map formParams; + std::map> fileParams; + + std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); +responseHttpContentTypes.insert( U("application/json") ); + + 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("UserApi->logoutUser does not produce any supported media type")); + } + + headerParams[U("Accept")] = responseHttpContentType; + + std::unordered_set consumeHttpContentTypes; + + + + 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"); + + } + // multipart formdata + else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + { + requestHttpContentType = U("multipart/form-data"); + + } + else + { + throw ApiException(415, U("UserApi->logoutUser does not consume any supported media type")); + } + + + return m_ApiClient->callApi(path, U("GET"), 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 logoutUser: ") + 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 logoutUser: unexpected response type: ") + contentType + , std::make_shared(response.extract_utf8string(true).get())); + } + } + + return response.extract_string(); + }) + .then([=](utility::string_t response) + { + return void(); + }); +} +pplx::task UserApi::updateUser(utility::string_t username, std::shared_ptr body) +{ + + // verify the required parameter 'body' is set + if (body == nullptr) + { + throw ApiException(400, U("Missing required parameter 'body' when calling UserApi->updateUser")); + } + + + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); + utility::string_t path = U("/user/{username}"); + boost::replace_all(path, U("{") U("username") U("}"), ApiClient::parameterToString(username)); + + std::map queryParams; + std::map headerParams( apiConfiguration->getDefaultHeaders() ); + std::map formParams; + std::map> fileParams; + + std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); +responseHttpContentTypes.insert( U("application/json") ); + + 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("UserApi->updateUser does not produce any supported media type")); + } + + headerParams[U("Accept")] = responseHttpContentType; + + std::unordered_set consumeHttpContentTypes; + + + { + + } + + + 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"); + + web::json::value json; + + json = ModelBase::toJson(body); + + + httpBody = std::shared_ptr( new JsonBody( json ) ); + + } + // multipart formdata + else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) + { + requestHttpContentType = U("multipart/form-data"); + + std::shared_ptr multipart(new MultipartFormData); + + if(body.get()) + { + body->toMultipart(multipart, U("body")); + } + + + httpBody = multipart; + requestHttpContentType += U("; boundary=") + multipart->getBoundary(); + } + else + { + throw ApiException(415, U("UserApi->updateUser does not consume any supported media type")); + } + + + return m_ApiClient->callApi(path, U("PUT"), 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 updateUser: ") + 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 updateUser: unexpected response type: ") + contentType + , std::make_shared(response.extract_utf8string(true).get())); + } + } + + return response.extract_string(); + }) + .then([=](utility::string_t response) + { + return void(); + }); +} + +} +} +} +} + diff --git a/samples/client/petstore/cpprest/api/UserApi.h b/samples/client/petstore/cpprest/api/UserApi.h new file mode 100644 index 00000000000..217ad44a12e --- /dev/null +++ b/samples/client/petstore/cpprest/api/UserApi.h @@ -0,0 +1,104 @@ +/* + * UserApi.h + * + * + */ + +#ifndef UserApi_H_ +#define UserApi_H_ + + +#include "ApiClient.h" + +#include "User.h" +#include +#include + +namespace io { +namespace swagger { +namespace client { +namespace api { + +using namespace io::swagger::client::model; + +class UserApi +{ +public: + UserApi( std::shared_ptr apiClient ); + virtual ~UserApi(); + /// + /// Create user + /// + /// + /// This can only be done by the logged in user. + /// + /// Created user object + pplx::task createUser(std::shared_ptr body); + /// + /// Creates list of users with given input array + /// + /// + /// + /// + /// List of user object + pplx::task createUsersWithArrayInput(std::vector> body); + /// + /// Creates list of users with given input array + /// + /// + /// + /// + /// List of user object + pplx::task createUsersWithListInput(std::vector> body); + /// + /// Delete user + /// + /// + /// This can only be done by the logged in user. + /// + /// The name that needs to be deleted + pplx::task deleteUser(utility::string_t username); + /// + /// Get user by user name + /// + /// + /// + /// + /// The name that needs to be fetched. Use user1 for testing. + pplx::task> getUserByName(utility::string_t username); + /// + /// Logs user into the system + /// + /// + /// + /// + /// The user name for login/// The password for login in clear text + pplx::task loginUser(utility::string_t username, utility::string_t password); + /// + /// Logs out current logged in user session + /// + /// + /// + /// + + pplx::task logoutUser(); + /// + /// Updated user + /// + /// + /// This can only be done by the logged in user. + /// + /// name that need to be deleted/// Updated user object + pplx::task updateUser(utility::string_t username, std::shared_ptr body); + +protected: + std::shared_ptr m_ApiClient; +}; + +} +} +} +} + +#endif /* UserApi_H_ */ + diff --git a/samples/client/petstore/cpprest/git_push.sh b/samples/client/petstore/cpprest/git_push.sh new file mode 100644 index 00000000000..970522bca1f --- /dev/null +++ b/samples/client/petstore/cpprest/git_push.sh @@ -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="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + 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/samples/client/petstore/cpprest/model/ApiResponse.cpp b/samples/client/petstore/cpprest/model/ApiResponse.cpp new file mode 100644 index 00000000000..66ee88ef464 --- /dev/null +++ b/samples/client/petstore/cpprest/model/ApiResponse.cpp @@ -0,0 +1,177 @@ + + +#include "ApiResponse.h" + +namespace io { +namespace swagger { +namespace client { +namespace model { + +ApiResponse::ApiResponse() +{ + m_Code = 0; + m_CodeIsSet = false; + m_Type = U(""); + m_TypeIsSet = false; + m_Message = U(""); + m_MessageIsSet = false; + +} + +ApiResponse::~ApiResponse() +{ +} + +void ApiResponse::validate() +{ + // TODO: implement validation +} + +web::json::value ApiResponse::toJson() const +{ + web::json::value val = web::json::value::object(); + + if(m_CodeIsSet) + { + val[U("code")] = ModelBase::toJson(m_Code); + } + if(m_TypeIsSet) + { + val[U("type")] = ModelBase::toJson(m_Type); + } + if(m_MessageIsSet) + { + val[U("message")] = ModelBase::toJson(m_Message); + } + + + return val; +} + +void ApiResponse::fromJson(web::json::value& val) +{ + if(val.has_field(U("code"))) + { + setCode(ModelBase::int32_tFromJson(val[U("code")])); + } + if(val.has_field(U("type"))) + { + setType(ModelBase::stringFromJson(val[U("type")])); + + } + if(val.has_field(U("message"))) + { + setMessage(ModelBase::stringFromJson(val[U("message")])); + + } + +} + +void ApiResponse::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("."); + } + + if(m_CodeIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + U("code"), m_Code)); + } + if(m_TypeIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + U("type"), m_Type)); + + } + if(m_MessageIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + U("message"), m_Message)); + + } + +} + +void ApiResponse::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("."); + } + + if(multipart->hasContent(U("code"))) + { + setCode(ModelBase::int32_tFromHttpContent(multipart->getContent(U("code")))); + } + if(multipart->hasContent(U("type"))) + { + setType(ModelBase::stringFromHttpContent(multipart->getContent(U("type")))); + + } + if(multipart->hasContent(U("message"))) + { + setMessage(ModelBase::stringFromHttpContent(multipart->getContent(U("message")))); + + } + +} + + +int32_t ApiResponse::getCode() const +{ + return m_Code; +} +void ApiResponse::setCode(int32_t value) +{ + m_Code = value; + m_CodeIsSet = true; +} +bool ApiResponse::codeIsSet() const +{ + return m_CodeIsSet; +} +void ApiResponse::unsetCode() +{ + m_CodeIsSet = false; +} +utility::string_t ApiResponse::getType() const +{ + return m_Type; +} +void ApiResponse::setType(utility::string_t value) +{ + m_Type = value; + m_TypeIsSet = true; +} +bool ApiResponse::typeIsSet() const +{ + return m_TypeIsSet; +} +void ApiResponse::unsetType() +{ + m_TypeIsSet = false; +} +utility::string_t ApiResponse::getMessage() const +{ + return m_Message; +} +void ApiResponse::setMessage(utility::string_t value) +{ + m_Message = value; + m_MessageIsSet = true; +} +bool ApiResponse::messageIsSet() const +{ + return m_MessageIsSet; +} +void ApiResponse::unsetMessage() +{ + m_MessageIsSet = false; +} + +} +} +} +} + diff --git a/samples/client/petstore/cpprest/model/ApiResponse.h b/samples/client/petstore/cpprest/model/ApiResponse.h new file mode 100644 index 00000000000..ca9e137b6b2 --- /dev/null +++ b/samples/client/petstore/cpprest/model/ApiResponse.h @@ -0,0 +1,80 @@ +/* + * ApiResponse.h + * + * + */ + +#ifndef ApiResponse_H_ +#define ApiResponse_H_ + + +#include "ModelBase.h" + +#include + +namespace io { +namespace swagger { +namespace client { +namespace model { + +/// +/// +/// +class ApiResponse + : public ModelBase +{ +public: + ApiResponse(); + virtual ~ApiResponse(); + + ///////////////////////////////////////////// + /// 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; + + ///////////////////////////////////////////// + /// ApiResponse members + + /// + /// + /// + int32_t getCode() const; + void setCode(int32_t value); + bool codeIsSet() const; + void unsetCode(); + /// + /// + /// + utility::string_t getType() const; + void setType(utility::string_t value); + bool typeIsSet() const; + void unsetType(); + /// + /// + /// + utility::string_t getMessage() const; + void setMessage(utility::string_t value); + bool messageIsSet() const; + void unsetMessage(); + +protected: + int32_t m_Code; + bool m_CodeIsSet; +utility::string_t m_Type; + bool m_TypeIsSet; +utility::string_t m_Message; + bool m_MessageIsSet; +}; + +} +} +} +} + +#endif /* ApiResponse_H_ */ diff --git a/samples/client/petstore/cpprest/model/Category.cpp b/samples/client/petstore/cpprest/model/Category.cpp new file mode 100644 index 00000000000..3420df3392c --- /dev/null +++ b/samples/client/petstore/cpprest/model/Category.cpp @@ -0,0 +1,139 @@ + + +#include "Category.h" + +namespace io { +namespace swagger { +namespace client { +namespace model { + +Category::Category() +{ + m_Id = 0L; + m_IdIsSet = false; + m_Name = U(""); + m_NameIsSet = false; + +} + +Category::~Category() +{ +} + +void Category::validate() +{ + // TODO: implement validation +} + +web::json::value Category::toJson() const +{ + web::json::value val = web::json::value::object(); + + if(m_IdIsSet) + { + val[U("id")] = ModelBase::toJson(m_Id); + } + if(m_NameIsSet) + { + val[U("name")] = ModelBase::toJson(m_Name); + } + + + return val; +} + +void Category::fromJson(web::json::value& val) +{ + if(val.has_field(U("id"))) + { + setId(ModelBase::int64_tFromJson(val[U("id")])); + } + if(val.has_field(U("name"))) + { + setName(ModelBase::stringFromJson(val[U("name")])); + + } + +} + +void Category::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("."); + } + + if(m_IdIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + U("id"), m_Id)); + } + if(m_NameIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + U("name"), m_Name)); + + } + +} + +void Category::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("."); + } + + if(multipart->hasContent(U("id"))) + { + setId(ModelBase::int64_tFromHttpContent(multipart->getContent(U("id")))); + } + if(multipart->hasContent(U("name"))) + { + setName(ModelBase::stringFromHttpContent(multipart->getContent(U("name")))); + + } + +} + + +int64_t Category::getId() const +{ + return m_Id; +} +void Category::setId(int64_t value) +{ + m_Id = value; + m_IdIsSet = true; +} +bool Category::idIsSet() const +{ + return m_IdIsSet; +} +void Category::unsetId() +{ + m_IdIsSet = false; +} +utility::string_t Category::getName() const +{ + return m_Name; +} +void Category::setName(utility::string_t value) +{ + m_Name = value; + m_NameIsSet = true; +} +bool Category::nameIsSet() const +{ + return m_NameIsSet; +} +void Category::unsetName() +{ + m_NameIsSet = false; +} + +} +} +} +} + diff --git a/samples/client/petstore/cpprest/model/Category.h b/samples/client/petstore/cpprest/model/Category.h new file mode 100644 index 00000000000..d472fb13927 --- /dev/null +++ b/samples/client/petstore/cpprest/model/Category.h @@ -0,0 +1,71 @@ +/* + * Category.h + * + * + */ + +#ifndef Category_H_ +#define Category_H_ + + +#include "ModelBase.h" + +#include + +namespace io { +namespace swagger { +namespace client { +namespace model { + +/// +/// +/// +class Category + : public ModelBase +{ +public: + Category(); + virtual ~Category(); + + ///////////////////////////////////////////// + /// 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; + + ///////////////////////////////////////////// + /// Category members + + /// + /// + /// + int64_t getId() const; + void setId(int64_t value); + bool idIsSet() const; + void unsetId(); + /// + /// + /// + utility::string_t getName() const; + void setName(utility::string_t value); + bool nameIsSet() const; + void unsetName(); + +protected: + int64_t m_Id; + bool m_IdIsSet; +utility::string_t m_Name; + bool m_NameIsSet; +}; + +} +} +} +} + +#endif /* Category_H_ */ diff --git a/samples/client/petstore/cpprest/model/Order.cpp b/samples/client/petstore/cpprest/model/Order.cpp new file mode 100644 index 00000000000..ca0ecf8f93b --- /dev/null +++ b/samples/client/petstore/cpprest/model/Order.cpp @@ -0,0 +1,282 @@ + + +#include "Order.h" + +namespace io { +namespace swagger { +namespace client { +namespace model { + +Order::Order() +{ + m_Id = 0L; + m_IdIsSet = false; + m_PetId = 0L; + m_PetIdIsSet = false; + m_Quantity = 0; + m_QuantityIsSet = false; + m_ShipDate = utility::datetime(); + m_ShipDateIsSet = false; + m_Status = U(""); + m_StatusIsSet = false; + m_Complete = false; + m_CompleteIsSet = false; + +} + +Order::~Order() +{ +} + +void Order::validate() +{ + // TODO: implement validation +} + +web::json::value Order::toJson() const +{ + web::json::value val = web::json::value::object(); + + if(m_IdIsSet) + { + val[U("id")] = ModelBase::toJson(m_Id); + } + if(m_PetIdIsSet) + { + val[U("petId")] = ModelBase::toJson(m_PetId); + } + if(m_QuantityIsSet) + { + val[U("quantity")] = ModelBase::toJson(m_Quantity); + } + if(m_ShipDateIsSet) + { + val[U("shipDate")] = ModelBase::toJson(m_ShipDate); + } + if(m_StatusIsSet) + { + val[U("status")] = ModelBase::toJson(m_Status); + } + if(m_CompleteIsSet) + { + val[U("complete")] = ModelBase::toJson(m_Complete); + } + + + return val; +} + +void Order::fromJson(web::json::value& val) +{ + if(val.has_field(U("id"))) + { + setId(ModelBase::int64_tFromJson(val[U("id")])); + } + if(val.has_field(U("petId"))) + { + setPetId(ModelBase::int64_tFromJson(val[U("petId")])); + } + if(val.has_field(U("quantity"))) + { + setQuantity(ModelBase::int32_tFromJson(val[U("quantity")])); + } + if(val.has_field(U("shipDate"))) + { + setShipDate(ModelBase::dateFromJson(val[U("shipDate")])); + + } + if(val.has_field(U("status"))) + { + setStatus(ModelBase::stringFromJson(val[U("status")])); + + } + if(val.has_field(U("complete"))) + { + setComplete(ModelBase::boolFromJson(val[U("complete")])); + } + +} + +void Order::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("."); + } + + if(m_IdIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + U("id"), m_Id)); + } + if(m_PetIdIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + U("petId"), m_PetId)); + } + if(m_QuantityIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + U("quantity"), m_Quantity)); + } + if(m_ShipDateIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + U("shipDate"), m_ShipDate)); + + } + if(m_StatusIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + U("status"), m_Status)); + + } + if(m_CompleteIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + U("complete"), m_Complete)); + } + +} + +void Order::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("."); + } + + if(multipart->hasContent(U("id"))) + { + setId(ModelBase::int64_tFromHttpContent(multipart->getContent(U("id")))); + } + if(multipart->hasContent(U("petId"))) + { + setPetId(ModelBase::int64_tFromHttpContent(multipart->getContent(U("petId")))); + } + if(multipart->hasContent(U("quantity"))) + { + setQuantity(ModelBase::int32_tFromHttpContent(multipart->getContent(U("quantity")))); + } + if(multipart->hasContent(U("shipDate"))) + { + setShipDate(ModelBase::dateFromHttpContent(multipart->getContent(U("shipDate")))); + + } + if(multipart->hasContent(U("status"))) + { + setStatus(ModelBase::stringFromHttpContent(multipart->getContent(U("status")))); + + } + if(multipart->hasContent(U("complete"))) + { + setComplete(ModelBase::boolFromHttpContent(multipart->getContent(U("complete")))); + } + +} + + +int64_t Order::getId() const +{ + return m_Id; +} +void Order::setId(int64_t value) +{ + m_Id = value; + m_IdIsSet = true; +} +bool Order::idIsSet() const +{ + return m_IdIsSet; +} +void Order::unsetId() +{ + m_IdIsSet = false; +} +int64_t Order::getPetId() const +{ + return m_PetId; +} +void Order::setPetId(int64_t value) +{ + m_PetId = value; + m_PetIdIsSet = true; +} +bool Order::petIdIsSet() const +{ + return m_PetIdIsSet; +} +void Order::unsetPetId() +{ + m_PetIdIsSet = false; +} +int32_t Order::getQuantity() const +{ + return m_Quantity; +} +void Order::setQuantity(int32_t value) +{ + m_Quantity = value; + m_QuantityIsSet = true; +} +bool Order::quantityIsSet() const +{ + return m_QuantityIsSet; +} +void Order::unsetQuantity() +{ + m_QuantityIsSet = false; +} +utility::datetime Order::getShipDate() const +{ + return m_ShipDate; +} +void Order::setShipDate(utility::datetime value) +{ + m_ShipDate = value; + m_ShipDateIsSet = true; +} +bool Order::shipDateIsSet() const +{ + return m_ShipDateIsSet; +} +void Order::unsetShipDate() +{ + m_ShipDateIsSet = false; +} +utility::string_t Order::getStatus() const +{ + return m_Status; +} +void Order::setStatus(utility::string_t value) +{ + m_Status = value; + m_StatusIsSet = true; +} +bool Order::statusIsSet() const +{ + return m_StatusIsSet; +} +void Order::unsetStatus() +{ + m_StatusIsSet = false; +} +bool Order::getComplete() const +{ + return m_Complete; +} +void Order::setComplete(bool value) +{ + m_Complete = value; + m_CompleteIsSet = true; +} +bool Order::completeIsSet() const +{ + return m_CompleteIsSet; +} +void Order::unsetComplete() +{ + m_CompleteIsSet = false; +} + +} +} +} +} + diff --git a/samples/client/petstore/cpprest/model/Order.h b/samples/client/petstore/cpprest/model/Order.h new file mode 100644 index 00000000000..8fe54141d10 --- /dev/null +++ b/samples/client/petstore/cpprest/model/Order.h @@ -0,0 +1,107 @@ +/* + * Order.h + * + * + */ + +#ifndef Order_H_ +#define Order_H_ + + +#include "ModelBase.h" + +#include + +namespace io { +namespace swagger { +namespace client { +namespace model { + +/// +/// +/// +class Order + : public ModelBase +{ +public: + Order(); + virtual ~Order(); + + ///////////////////////////////////////////// + /// 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; + + ///////////////////////////////////////////// + /// Order members + + /// + /// + /// + int64_t getId() const; + void setId(int64_t value); + bool idIsSet() const; + void unsetId(); + /// + /// + /// + int64_t getPetId() const; + void setPetId(int64_t value); + bool petIdIsSet() const; + void unsetPetId(); + /// + /// + /// + int32_t getQuantity() const; + void setQuantity(int32_t value); + bool quantityIsSet() const; + void unsetQuantity(); + /// + /// + /// + utility::datetime getShipDate() const; + void setShipDate(utility::datetime value); + bool shipDateIsSet() const; + void unsetShipDate(); + /// + /// Order Status + /// + utility::string_t getStatus() const; + void setStatus(utility::string_t value); + bool statusIsSet() const; + void unsetStatus(); + /// + /// + /// + bool getComplete() const; + void setComplete(bool value); + bool completeIsSet() const; + void unsetComplete(); + +protected: + int64_t m_Id; + bool m_IdIsSet; +int64_t m_PetId; + bool m_PetIdIsSet; +int32_t m_Quantity; + bool m_QuantityIsSet; +utility::datetime m_ShipDate; + bool m_ShipDateIsSet; +utility::string_t m_Status; + bool m_StatusIsSet; +bool m_Complete; + bool m_CompleteIsSet; +}; + +} +} +} +} + +#endif /* Order_H_ */ diff --git a/samples/client/petstore/cpprest/model/Pet.cpp b/samples/client/petstore/cpprest/model/Pet.cpp new file mode 100644 index 00000000000..4589b73d871 --- /dev/null +++ b/samples/client/petstore/cpprest/model/Pet.cpp @@ -0,0 +1,324 @@ + + +#include "Pet.h" + +namespace io { +namespace swagger { +namespace client { +namespace model { + +Pet::Pet() +{ + m_Id = 0L; + m_IdIsSet = false; + m_CategoryIsSet = false; + m_Name = U(""); + m_TagsIsSet = false; + m_Status = U(""); + m_StatusIsSet = false; + +} + +Pet::~Pet() +{ +} + +void Pet::validate() +{ + // TODO: implement validation +} + +web::json::value Pet::toJson() const +{ + web::json::value val = web::json::value::object(); + + if(m_IdIsSet) + { + val[U("id")] = ModelBase::toJson(m_Id); + } + if(m_CategoryIsSet) + { + val[U("category")] = ModelBase::toJson(m_Category); + } + val[U("name")] = ModelBase::toJson(m_Name); + { + std::vector jsonArray; + for( auto& item : m_PhotoUrls ) + { + jsonArray.push_back(ModelBase::toJson(item)); + } + val[U("photoUrls")] = web::json::value::array(jsonArray); + } + { + std::vector jsonArray; + for( auto& item : m_Tags ) + { + jsonArray.push_back(ModelBase::toJson(item)); + } + + if(jsonArray.size() > 0) + { + val[U("tags")] = web::json::value::array(jsonArray); + } + } + if(m_StatusIsSet) + { + val[U("status")] = ModelBase::toJson(m_Status); + } + + + return val; +} + +void Pet::fromJson(web::json::value& val) +{ + if(val.has_field(U("id"))) + { + setId(ModelBase::int64_tFromJson(val[U("id")])); + } + if(val.has_field(U("category"))) + { + if(!val[U("category")].is_null()) + { + std::shared_ptr newItem(new Category()); + newItem->fromJson(val[U("category")]); + setCategory( newItem ); + } + + } + setName(ModelBase::stringFromJson(val[U("name")])); + { + m_PhotoUrls.clear(); + std::vector jsonArray; + for( auto& item : val[U("photoUrls")].as_array() ) + { + m_PhotoUrls.push_back(ModelBase::stringFromJson(item)); + + } + } + { + m_Tags.clear(); + std::vector jsonArray; + if(val.has_field(U("tags"))) + { + for( auto& item : val[U("tags")].as_array() ) + { + + if(item.is_null()) + { + m_Tags.push_back( std::shared_ptr(nullptr) ); + } + else + { + std::shared_ptr newItem(new Tag()); + newItem->fromJson(item); + m_Tags.push_back( newItem ); + } + + } + } + } + if(val.has_field(U("status"))) + { + setStatus(ModelBase::stringFromJson(val[U("status")])); + + } + +} + +void Pet::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("."); + } + + if(m_IdIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + U("id"), m_Id)); + } + if(m_CategoryIsSet) + { + if (m_Category.get()) + { + m_Category->toMultipart(multipart, U("category.")); + } + + } + multipart->add(ModelBase::toHttpContent(namePrefix + U("name"), m_Name)); + { + std::vector jsonArray; + for( auto& item : m_PhotoUrls ) + { + jsonArray.push_back(ModelBase::toJson(item)); + } + multipart->add(ModelBase::toHttpContent(namePrefix + U("photoUrls"), web::json::value::array(jsonArray), U("application/json"))); + } + { + std::vector jsonArray; + for( auto& item : m_Tags ) + { + jsonArray.push_back(ModelBase::toJson(item)); + } + + if(jsonArray.size() > 0) + { + multipart->add(ModelBase::toHttpContent(namePrefix + U("tags"), web::json::value::array(jsonArray), U("application/json"))); + } + } + if(m_StatusIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + U("status"), m_Status)); + + } + +} + +void Pet::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("."); + } + + if(multipart->hasContent(U("id"))) + { + setId(ModelBase::int64_tFromHttpContent(multipart->getContent(U("id")))); + } + if(multipart->hasContent(U("category"))) + { + if(multipart->hasContent(U("category"))) + { + std::shared_ptr newItem(new Category()); + newItem->fromMultiPart(multipart, U("category.")); + setCategory( newItem ); + } + + } + setName(ModelBase::stringFromHttpContent(multipart->getContent(U("name")))); + { + m_PhotoUrls.clear(); + + web::json::value jsonArray = web::json::value::parse(ModelBase::stringFromHttpContent(multipart->getContent(U("photoUrls")))); + for( auto& item : jsonArray.as_array() ) + { + m_PhotoUrls.push_back(ModelBase::stringFromJson(item)); + + } + } + { + m_Tags.clear(); + if(multipart->hasContent(U("tags"))) + { + + web::json::value jsonArray = web::json::value::parse(ModelBase::stringFromHttpContent(multipart->getContent(U("tags")))); + for( auto& item : jsonArray.as_array() ) + { + + if(item.is_null()) + { + m_Tags.push_back( std::shared_ptr(nullptr) ); + } + else + { + std::shared_ptr newItem(new Tag()); + newItem->fromJson(item); + m_Tags.push_back( newItem ); + } + + } + } + } + if(multipart->hasContent(U("status"))) + { + setStatus(ModelBase::stringFromHttpContent(multipart->getContent(U("status")))); + + } + +} + + +int64_t Pet::getId() const +{ + return m_Id; +} +void Pet::setId(int64_t value) +{ + m_Id = value; + m_IdIsSet = true; +} +bool Pet::idIsSet() const +{ + return m_IdIsSet; +} +void Pet::unsetId() +{ + m_IdIsSet = false; +} +std::shared_ptr Pet::getCategory() const +{ + return m_Category; +} +void Pet::setCategory(std::shared_ptr value) +{ + m_Category = value; + m_CategoryIsSet = true; +} +bool Pet::categoryIsSet() const +{ + return m_CategoryIsSet; +} +void Pet::unsetCategory() +{ + m_CategoryIsSet = false; +} +utility::string_t Pet::getName() const +{ + return m_Name; +} +void Pet::setName(utility::string_t value) +{ + m_Name = value; + +} +std::vector& Pet::getPhotoUrls() +{ + return m_PhotoUrls; +} +std::vector>& Pet::getTags() +{ + return m_Tags; +} +bool Pet::tagsIsSet() const +{ + return m_TagsIsSet; +} +void Pet::unsetTags() +{ + m_TagsIsSet = false; +} +utility::string_t Pet::getStatus() const +{ + return m_Status; +} +void Pet::setStatus(utility::string_t value) +{ + m_Status = value; + m_StatusIsSet = true; +} +bool Pet::statusIsSet() const +{ + return m_StatusIsSet; +} +void Pet::unsetStatus() +{ + m_StatusIsSet = false; +} + +} +} +} +} + diff --git a/samples/client/petstore/cpprest/model/Pet.h b/samples/client/petstore/cpprest/model/Pet.h new file mode 100644 index 00000000000..3152cd580f7 --- /dev/null +++ b/samples/client/petstore/cpprest/model/Pet.h @@ -0,0 +1,102 @@ +/* + * Pet.h + * + * + */ + +#ifndef Pet_H_ +#define Pet_H_ + + +#include "ModelBase.h" + +#include "Category.h" +#include +#include +#include "Tag.h" + +namespace io { +namespace swagger { +namespace client { +namespace model { + +/// +/// +/// +class Pet + : public ModelBase +{ +public: + Pet(); + virtual ~Pet(); + + ///////////////////////////////////////////// + /// 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; + + ///////////////////////////////////////////// + /// Pet members + + /// + /// + /// + int64_t getId() const; + void setId(int64_t value); + bool idIsSet() const; + void unsetId(); + /// + /// + /// + std::shared_ptr getCategory() const; + void setCategory(std::shared_ptr value); + bool categoryIsSet() const; + void unsetCategory(); + /// + /// + /// + utility::string_t getName() const; + void setName(utility::string_t value); + /// + /// + /// + std::vector& getPhotoUrls(); + /// + /// + /// + std::vector>& getTags(); + bool tagsIsSet() const; + void unsetTags(); + /// + /// pet status in the store + /// + utility::string_t getStatus() const; + void setStatus(utility::string_t value); + bool statusIsSet() const; + void unsetStatus(); + +protected: + int64_t m_Id; + bool m_IdIsSet; +std::shared_ptr m_Category; + bool m_CategoryIsSet; +utility::string_t m_Name; + std::vector m_PhotoUrls; + std::vector> m_Tags; + bool m_TagsIsSet; +utility::string_t m_Status; + bool m_StatusIsSet; +}; + +} +} +} +} + +#endif /* Pet_H_ */ diff --git a/samples/client/petstore/cpprest/model/Tag.cpp b/samples/client/petstore/cpprest/model/Tag.cpp new file mode 100644 index 00000000000..115cc6bb899 --- /dev/null +++ b/samples/client/petstore/cpprest/model/Tag.cpp @@ -0,0 +1,139 @@ + + +#include "Tag.h" + +namespace io { +namespace swagger { +namespace client { +namespace model { + +Tag::Tag() +{ + m_Id = 0L; + m_IdIsSet = false; + m_Name = U(""); + m_NameIsSet = false; + +} + +Tag::~Tag() +{ +} + +void Tag::validate() +{ + // TODO: implement validation +} + +web::json::value Tag::toJson() const +{ + web::json::value val = web::json::value::object(); + + if(m_IdIsSet) + { + val[U("id")] = ModelBase::toJson(m_Id); + } + if(m_NameIsSet) + { + val[U("name")] = ModelBase::toJson(m_Name); + } + + + return val; +} + +void Tag::fromJson(web::json::value& val) +{ + if(val.has_field(U("id"))) + { + setId(ModelBase::int64_tFromJson(val[U("id")])); + } + if(val.has_field(U("name"))) + { + setName(ModelBase::stringFromJson(val[U("name")])); + + } + +} + +void Tag::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("."); + } + + if(m_IdIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + U("id"), m_Id)); + } + if(m_NameIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + U("name"), m_Name)); + + } + +} + +void Tag::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("."); + } + + if(multipart->hasContent(U("id"))) + { + setId(ModelBase::int64_tFromHttpContent(multipart->getContent(U("id")))); + } + if(multipart->hasContent(U("name"))) + { + setName(ModelBase::stringFromHttpContent(multipart->getContent(U("name")))); + + } + +} + + +int64_t Tag::getId() const +{ + return m_Id; +} +void Tag::setId(int64_t value) +{ + m_Id = value; + m_IdIsSet = true; +} +bool Tag::idIsSet() const +{ + return m_IdIsSet; +} +void Tag::unsetId() +{ + m_IdIsSet = false; +} +utility::string_t Tag::getName() const +{ + return m_Name; +} +void Tag::setName(utility::string_t value) +{ + m_Name = value; + m_NameIsSet = true; +} +bool Tag::nameIsSet() const +{ + return m_NameIsSet; +} +void Tag::unsetName() +{ + m_NameIsSet = false; +} + +} +} +} +} + diff --git a/samples/client/petstore/cpprest/model/Tag.h b/samples/client/petstore/cpprest/model/Tag.h new file mode 100644 index 00000000000..e657692ea35 --- /dev/null +++ b/samples/client/petstore/cpprest/model/Tag.h @@ -0,0 +1,71 @@ +/* + * Tag.h + * + * + */ + +#ifndef Tag_H_ +#define Tag_H_ + + +#include "ModelBase.h" + +#include + +namespace io { +namespace swagger { +namespace client { +namespace model { + +/// +/// +/// +class Tag + : public ModelBase +{ +public: + Tag(); + virtual ~Tag(); + + ///////////////////////////////////////////// + /// 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; + + ///////////////////////////////////////////// + /// Tag members + + /// + /// + /// + int64_t getId() const; + void setId(int64_t value); + bool idIsSet() const; + void unsetId(); + /// + /// + /// + utility::string_t getName() const; + void setName(utility::string_t value); + bool nameIsSet() const; + void unsetName(); + +protected: + int64_t m_Id; + bool m_IdIsSet; +utility::string_t m_Name; + bool m_NameIsSet; +}; + +} +} +} +} + +#endif /* Tag_H_ */ diff --git a/samples/client/petstore/cpprest/model/User.cpp b/samples/client/petstore/cpprest/model/User.cpp new file mode 100644 index 00000000000..39c17dfd964 --- /dev/null +++ b/samples/client/petstore/cpprest/model/User.cpp @@ -0,0 +1,364 @@ + + +#include "User.h" + +namespace io { +namespace swagger { +namespace client { +namespace model { + +User::User() +{ + m_Id = 0L; + m_IdIsSet = false; + m_Username = U(""); + m_UsernameIsSet = false; + m_FirstName = U(""); + m_FirstNameIsSet = false; + m_LastName = U(""); + m_LastNameIsSet = false; + m_Email = U(""); + m_EmailIsSet = false; + m_Password = U(""); + m_PasswordIsSet = false; + m_Phone = U(""); + m_PhoneIsSet = false; + m_UserStatus = 0; + m_UserStatusIsSet = false; + +} + +User::~User() +{ +} + +void User::validate() +{ + // TODO: implement validation +} + +web::json::value User::toJson() const +{ + web::json::value val = web::json::value::object(); + + if(m_IdIsSet) + { + val[U("id")] = ModelBase::toJson(m_Id); + } + if(m_UsernameIsSet) + { + val[U("username")] = ModelBase::toJson(m_Username); + } + if(m_FirstNameIsSet) + { + val[U("firstName")] = ModelBase::toJson(m_FirstName); + } + if(m_LastNameIsSet) + { + val[U("lastName")] = ModelBase::toJson(m_LastName); + } + if(m_EmailIsSet) + { + val[U("email")] = ModelBase::toJson(m_Email); + } + if(m_PasswordIsSet) + { + val[U("password")] = ModelBase::toJson(m_Password); + } + if(m_PhoneIsSet) + { + val[U("phone")] = ModelBase::toJson(m_Phone); + } + if(m_UserStatusIsSet) + { + val[U("userStatus")] = ModelBase::toJson(m_UserStatus); + } + + + return val; +} + +void User::fromJson(web::json::value& val) +{ + if(val.has_field(U("id"))) + { + setId(ModelBase::int64_tFromJson(val[U("id")])); + } + if(val.has_field(U("username"))) + { + setUsername(ModelBase::stringFromJson(val[U("username")])); + + } + if(val.has_field(U("firstName"))) + { + setFirstName(ModelBase::stringFromJson(val[U("firstName")])); + + } + if(val.has_field(U("lastName"))) + { + setLastName(ModelBase::stringFromJson(val[U("lastName")])); + + } + if(val.has_field(U("email"))) + { + setEmail(ModelBase::stringFromJson(val[U("email")])); + + } + if(val.has_field(U("password"))) + { + setPassword(ModelBase::stringFromJson(val[U("password")])); + + } + if(val.has_field(U("phone"))) + { + setPhone(ModelBase::stringFromJson(val[U("phone")])); + + } + if(val.has_field(U("userStatus"))) + { + setUserStatus(ModelBase::int32_tFromJson(val[U("userStatus")])); + } + +} + +void User::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("."); + } + + if(m_IdIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + U("id"), m_Id)); + } + if(m_UsernameIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + U("username"), m_Username)); + + } + if(m_FirstNameIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + U("firstName"), m_FirstName)); + + } + if(m_LastNameIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + U("lastName"), m_LastName)); + + } + if(m_EmailIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + U("email"), m_Email)); + + } + if(m_PasswordIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + U("password"), m_Password)); + + } + if(m_PhoneIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + U("phone"), m_Phone)); + + } + if(m_UserStatusIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + U("userStatus"), m_UserStatus)); + } + +} + +void User::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("."); + } + + if(multipart->hasContent(U("id"))) + { + setId(ModelBase::int64_tFromHttpContent(multipart->getContent(U("id")))); + } + if(multipart->hasContent(U("username"))) + { + setUsername(ModelBase::stringFromHttpContent(multipart->getContent(U("username")))); + + } + if(multipart->hasContent(U("firstName"))) + { + setFirstName(ModelBase::stringFromHttpContent(multipart->getContent(U("firstName")))); + + } + if(multipart->hasContent(U("lastName"))) + { + setLastName(ModelBase::stringFromHttpContent(multipart->getContent(U("lastName")))); + + } + if(multipart->hasContent(U("email"))) + { + setEmail(ModelBase::stringFromHttpContent(multipart->getContent(U("email")))); + + } + if(multipart->hasContent(U("password"))) + { + setPassword(ModelBase::stringFromHttpContent(multipart->getContent(U("password")))); + + } + if(multipart->hasContent(U("phone"))) + { + setPhone(ModelBase::stringFromHttpContent(multipart->getContent(U("phone")))); + + } + if(multipart->hasContent(U("userStatus"))) + { + setUserStatus(ModelBase::int32_tFromHttpContent(multipart->getContent(U("userStatus")))); + } + +} + + +int64_t User::getId() const +{ + return m_Id; +} +void User::setId(int64_t value) +{ + m_Id = value; + m_IdIsSet = true; +} +bool User::idIsSet() const +{ + return m_IdIsSet; +} +void User::unsetId() +{ + m_IdIsSet = false; +} +utility::string_t User::getUsername() const +{ + return m_Username; +} +void User::setUsername(utility::string_t value) +{ + m_Username = value; + m_UsernameIsSet = true; +} +bool User::usernameIsSet() const +{ + return m_UsernameIsSet; +} +void User::unsetUsername() +{ + m_UsernameIsSet = false; +} +utility::string_t User::getFirstName() const +{ + return m_FirstName; +} +void User::setFirstName(utility::string_t value) +{ + m_FirstName = value; + m_FirstNameIsSet = true; +} +bool User::firstNameIsSet() const +{ + return m_FirstNameIsSet; +} +void User::unsetFirstName() +{ + m_FirstNameIsSet = false; +} +utility::string_t User::getLastName() const +{ + return m_LastName; +} +void User::setLastName(utility::string_t value) +{ + m_LastName = value; + m_LastNameIsSet = true; +} +bool User::lastNameIsSet() const +{ + return m_LastNameIsSet; +} +void User::unsetLastName() +{ + m_LastNameIsSet = false; +} +utility::string_t User::getEmail() const +{ + return m_Email; +} +void User::setEmail(utility::string_t value) +{ + m_Email = value; + m_EmailIsSet = true; +} +bool User::emailIsSet() const +{ + return m_EmailIsSet; +} +void User::unsetEmail() +{ + m_EmailIsSet = false; +} +utility::string_t User::getPassword() const +{ + return m_Password; +} +void User::setPassword(utility::string_t value) +{ + m_Password = value; + m_PasswordIsSet = true; +} +bool User::passwordIsSet() const +{ + return m_PasswordIsSet; +} +void User::unsetPassword() +{ + m_PasswordIsSet = false; +} +utility::string_t User::getPhone() const +{ + return m_Phone; +} +void User::setPhone(utility::string_t value) +{ + m_Phone = value; + m_PhoneIsSet = true; +} +bool User::phoneIsSet() const +{ + return m_PhoneIsSet; +} +void User::unsetPhone() +{ + m_PhoneIsSet = false; +} +int32_t User::getUserStatus() const +{ + return m_UserStatus; +} +void User::setUserStatus(int32_t value) +{ + m_UserStatus = value; + m_UserStatusIsSet = true; +} +bool User::userStatusIsSet() const +{ + return m_UserStatusIsSet; +} +void User::unsetUserStatus() +{ + m_UserStatusIsSet = false; +} + +} +} +} +} + diff --git a/samples/client/petstore/cpprest/model/User.h b/samples/client/petstore/cpprest/model/User.h new file mode 100644 index 00000000000..ba90e464cca --- /dev/null +++ b/samples/client/petstore/cpprest/model/User.h @@ -0,0 +1,125 @@ +/* + * User.h + * + * + */ + +#ifndef User_H_ +#define User_H_ + + +#include "ModelBase.h" + +#include + +namespace io { +namespace swagger { +namespace client { +namespace model { + +/// +/// +/// +class User + : public ModelBase +{ +public: + User(); + virtual ~User(); + + ///////////////////////////////////////////// + /// 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; + + ///////////////////////////////////////////// + /// User members + + /// + /// + /// + int64_t getId() const; + void setId(int64_t value); + bool idIsSet() const; + void unsetId(); + /// + /// + /// + utility::string_t getUsername() const; + void setUsername(utility::string_t value); + bool usernameIsSet() const; + void unsetUsername(); + /// + /// + /// + utility::string_t getFirstName() const; + void setFirstName(utility::string_t value); + bool firstNameIsSet() const; + void unsetFirstName(); + /// + /// + /// + utility::string_t getLastName() const; + void setLastName(utility::string_t value); + bool lastNameIsSet() const; + void unsetLastName(); + /// + /// + /// + utility::string_t getEmail() const; + void setEmail(utility::string_t value); + bool emailIsSet() const; + void unsetEmail(); + /// + /// + /// + utility::string_t getPassword() const; + void setPassword(utility::string_t value); + bool passwordIsSet() const; + void unsetPassword(); + /// + /// + /// + utility::string_t getPhone() const; + void setPhone(utility::string_t value); + bool phoneIsSet() const; + void unsetPhone(); + /// + /// User Status + /// + int32_t getUserStatus() const; + void setUserStatus(int32_t value); + bool userStatusIsSet() const; + void unsetUserStatus(); + +protected: + int64_t m_Id; + bool m_IdIsSet; +utility::string_t m_Username; + bool m_UsernameIsSet; +utility::string_t m_FirstName; + bool m_FirstNameIsSet; +utility::string_t m_LastName; + bool m_LastNameIsSet; +utility::string_t m_Email; + bool m_EmailIsSet; +utility::string_t m_Password; + bool m_PasswordIsSet; +utility::string_t m_Phone; + bool m_PhoneIsSet; +int32_t m_UserStatus; + bool m_UserStatusIsSet; +}; + +} +} +} +} + +#endif /* User_H_ */ diff --git a/samples/client/petstore/ruby/lib/petstore/models/array_test.rb b/samples/client/petstore/ruby/lib/petstore/models/array_test.rb index 35d498fc9af..58bc4b1ae28 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/array_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/array_test.rb @@ -26,15 +26,28 @@ require 'date' module Petstore class ArrayTest + attr_accessor :array_of_string + + attr_accessor :array_array_of_integer + + attr_accessor :array_array_of_model + + # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { + :'array_of_string' => :'array_of_string', + :'array_array_of_integer' => :'array_array_of_integer', + :'array_array_of_model' => :'array_array_of_model' } end # Attribute type mapping. def self.swagger_types { + :'array_of_string' => :'Array', + :'array_array_of_integer' => :'Array>', + :'array_array_of_model' => :'Array>' } end @@ -46,6 +59,24 @@ module Petstore # convert string to symbol for hash key attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} + if attributes.has_key?(:'array_of_string') + if (value = attributes[:'array_of_string']).is_a?(Array) + self.array_of_string = value + end + end + + if attributes.has_key?(:'array_array_of_integer') + if (value = attributes[:'array_array_of_integer']).is_a?(Array) + self.array_array_of_integer = value + end + end + + if attributes.has_key?(:'array_array_of_model') + if (value = attributes[:'array_array_of_model']).is_a?(Array) + self.array_array_of_model = value + end + end + end # Show invalid properties with the reasons. Usually used together with valid? @@ -58,13 +89,17 @@ module Petstore # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? + return true end # Checks equality by comparing each attribute. # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) - self.class == o.class + self.class == o.class && + array_of_string == o.array_of_string && + array_array_of_integer == o.array_array_of_integer && + array_array_of_model == o.array_array_of_model end # @see the `==` method @@ -76,7 +111,7 @@ module Petstore # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash - [].hash + [array_of_string, array_array_of_integer, array_array_of_model].hash end # Builds the object from hash