diff --git a/.gitignore b/.gitignore index b17bf46aa108..210834c6a855 100644 --- a/.gitignore +++ b/.gitignore @@ -28,3 +28,6 @@ target .lib atlassian-ide-plugin.xml .DS_Store + +samples/client/petstore/php/SwaggerClient-php/composer.lock +samples/client/petstore/php/SwaggerClient-php/vendor/ diff --git a/README.md b/README.md index 0687abed1ee7..cb649e07da53 100644 --- a/README.md +++ b/README.md @@ -150,8 +150,11 @@ JavaClientCodegen.java JaxRSServerCodegen.java NodeJSServerCodegen.java ObjcClientCodegen.java +PerlClientCodegen.java PhpClientCodegen.java +Python3ClientCodegen.java PythonClientCodegen.java +Qt5CPPGenerator.java RubyClientCodegen.java ScalaClientCodegen.java ScalatraServerCodegen.java diff --git a/bin/all-petstore.sh b/bin/all-petstore.sh index e1c09b901426..0f97790e75a2 100755 --- a/bin/all-petstore.sh +++ b/bin/all-petstore.sh @@ -24,6 +24,7 @@ cd $APP_DIR ./bin/html-petstore.sh ./bin/jaxrs-petstore-server.sh ./bin/java-petstore.sh +./bin/qt5-petstore.sh ./bin/php-petstore.sh ./bin/python-petstore.sh ./bin/ruby-petstore.sh diff --git a/bin/perl-petstore.sh b/bin/perl-petstore.sh new file mode 100755 index 000000000000..64d684e9ec80 --- /dev/null +++ b/bin/perl-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 -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l perl -o samples/client/petstore/perl" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/qt5-petstore.sh b/bin/qt5-petstore.sh new file mode 100755 index 000000000000..7959785de34a --- /dev/null +++ b/bin/qt5-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/qt5cpp -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l qt5cpp -o samples/client/petstore/qt5cpp" + +java $JAVA_OPTS -jar $executable $ags diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java index 7c1792a88adb..0674c08bf176 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java @@ -165,6 +165,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { operation.putAll(config.additionalProperties()); operation.put("classname", config.toApiName(tag)); operation.put("classVarName", config.toApiVarName(tag)); + operation.put("importPath", config.toApiImport(tag)); allOperations.add(new HashMap(operation)); for (int i = 0; i < allOperations.size(); i++) { @@ -427,6 +428,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { CodegenModel cm = config.fromModel(key, mm); Map mo = new HashMap(); mo.put("model", cm); + mo.put("importPath", config.toModelImport(key)); models.add(mo); allImports.addAll(cm.imports); } diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java index 54fa020922f8..b7c38c703cad 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java @@ -43,6 +43,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { defaultIncludes = new HashSet( Arrays.asList( "bool", + "BOOL", "int", "NSString", "NSObject", @@ -59,22 +60,32 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { "NSString", "NSObject", "NSDate", - "bool") + "bool", + "BOOL") ); + // ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm reservedWords = new HashSet( Arrays.asList( - "void", "char", "short", "int", "void", "char", "short", "int", - "long", "float", "double", "signed", "unsigned", "id", "const", - "volatile", "in", "out", "inout", "bycopy", "byref", "oneway", - "self", "super", "description" + "auto", "else", "long", "switch", + "break", "enum", "register", "typedef", + "case", "extern", "return", "union", + "char", "float", "short", "unsigned", + "const", "for", "signed", "void", + "continue", "goto", "sizeof", "volatile", + "default", "if", "id", "static", "while", + "do", "int", "struct", "_Packed", + "double", "protocol", "interface", "implementation", + "NSObject", "NSInteger", "NSNumber", "CGFloat", + "property", "nonatomic", "retain", "strong", + "weak", "unsafe_unretained", "readwrite", "readonly" )); typeMapping = new HashMap(); typeMapping.put("enum", "NSString"); typeMapping.put("Date", "NSDate"); typeMapping.put("DateTime", "NSDate"); - typeMapping.put("boolean", "NSNumber"); + typeMapping.put("boolean", "BOOL"); typeMapping.put("string", "NSString"); typeMapping.put("integer", "NSNumber"); typeMapping.put("int", "NSNumber"); @@ -188,7 +199,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { return swaggerType; } // In this codition, type of p is objective-c object type, e.g. `SWGPet', - // return type of p with pointer, e.g. `' + // return type of p with pointer, e.g. `SWGPet*' else { return swaggerType + "*"; } @@ -197,18 +208,28 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toModelName(String type) { + type = type.replaceAll("[^0-9a-zA-Z_]", "_"); + + // language build-in classes if(typeMapping.keySet().contains(type) || foundationClasses.contains(type) || importMapping.values().contains(type) || defaultIncludes.contains(type) || languageSpecificPrimitives.contains(type)) { - return Character.toUpperCase(type.charAt(0)) + type.substring(1); + return camelize(type); } + // custom classes else { - return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1); + return PREFIX + camelize(type); } } + @Override + public String toModelFilename(String name) { + // should be the same as the model name + return toModelName(name); + } + @Override protected void setNonArrayMapProperty(CodegenProperty property, String type) { super.setNonArrayMapProperty(property, type); @@ -243,28 +264,34 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { return outputFolder + File.separator + sourceFolder; } - @Override - public String toModelFilename(String name) { - return PREFIX + initialCaps(name); - } - @Override public String toApiName(String name) { - return PREFIX + initialCaps(name) + "Api"; + return PREFIX + camelize(name) + "Api"; } public String toApiFilename(String name) { - return PREFIX + initialCaps(name) + "Api"; + return PREFIX + camelize(name) + "Api"; } @Override public String toVarName(String name) { - String paramName = name.replaceAll("[^a-zA-Z0-9_]",""); - if(paramName.startsWith("new") || reservedWords.contains(paramName)) { - return escapeReservedWord(paramName); - } - else - return paramName; + // replace non-word characters to `_` + // e.g. `created-at` to `created_at` + name = name.replaceAll("[^a-zA-Z0-9_]","_"); + + // if it's all upper case, do noting + if (name.matches("^[A-Z_]$")) + return name; + + // camelize (lower first character) the variable name + // e.g. `pet_id` to `petId` + name = camelize(name, true); + + // for reserved word or word starting with number, prepend `_` + if (reservedWords.contains(name) || name.matches("^\\d.*")) + name = escapeReservedWord(name); + + return name; } @Override diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PerlClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PerlClientCodegen.java new file mode 100644 index 000000000000..b25e4490e856 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PerlClientCodegen.java @@ -0,0 +1,197 @@ +package com.wordnik.swagger.codegen.languages; + +import com.wordnik.swagger.codegen.*; +import com.wordnik.swagger.util.Json; +import com.wordnik.swagger.models.properties.*; + +import java.util.*; +import java.io.File; + +public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { + protected String invokerPackage = "SwaggerClient"; + protected String groupId = "com.wordnik"; + protected String artifactId = "swagger-client"; + protected String artifactVersion = "1.0.0"; + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "perl"; + } + + public String getHelp() { + return "Generates a Perl client library."; + } + + public PerlClientCodegen() { + super(); + modelPackage = "Object"; + outputFolder = "generated-code/perl"; + modelTemplateFiles.put("object.mustache", ".pm"); + apiTemplateFiles.put("api.mustache", ".pm"); + templateDir = "perl"; + + typeMapping.clear(); + languageSpecificPrimitives.clear(); + + reservedWords = new HashSet ( + Arrays.asList( + "else", "lock", "qw", + "__END__", "elsif", "lt", "qx", + "__FILE__", "eq", "m", "s", + "__LINE__", "exp", "ne", "sub", + "__PACKAGE__", "for", "no", "tr", + "and", "foreach", "or", "unless", + "cmp", "ge", "package", "until", + "continue", "gt", "q", "while", + "CORE", "if", "qq", "xor", + "do", "le", "qr", "y" + ) + ); + + additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put("groupId", groupId); + additionalProperties.put("artifactId", artifactId); + additionalProperties.put("artifactVersion", artifactVersion); + + languageSpecificPrimitives.add("int"); + languageSpecificPrimitives.add("double"); + languageSpecificPrimitives.add("string"); + languageSpecificPrimitives.add("boolean"); + languageSpecificPrimitives.add("DateTime"); + languageSpecificPrimitives.add("ARRAY"); + languageSpecificPrimitives.add("HASH"); + + typeMapping.put("integer", "int"); + typeMapping.put("long", "int"); + typeMapping.put("float", "double"); + typeMapping.put("double", "double"); + typeMapping.put("boolean", "boolean"); + typeMapping.put("string", "string"); + typeMapping.put("date", "DateTime"); + typeMapping.put("dateTime", "DateTime"); + typeMapping.put("password", "string"); + typeMapping.put("array", "ARRAY"); + typeMapping.put("map", "HASH"); + + supportingFiles.add(new SupportingFile("APIClient.mustache", "lib/WWW/" + invokerPackage, "APIClient.pm")); + supportingFiles.add(new SupportingFile("BaseObject.mustache", "lib/WWW/" + invokerPackage, "Object/BaseObject.pm")); + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + "/lib/WWW/" + invokerPackage + apiPackage().replace('.', File.separatorChar); + } + + public String modelFileFolder() { + return outputFolder + "/lib/WWW/" + invokerPackage + "/" + modelPackage().replace('.', File.separatorChar); + } + + @Override + public String getTypeDeclaration(Property p) { + if(p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } + else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if(typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if(languageSpecificPrimitives.contains(type)) { + return type; + } + } + else + type = swaggerType; + if(type == null) + return null; + return type; + } + + public String toDefaultValue(Property p) { + return "null"; + } + + + @Override + public String toVarName(String name) { + // parameter name starting with number won't compile + // need to escape it by appending _ at the beginning + if (name.matches("^[0-9]")) { + name = "_" + name; + } + + // return the name in underscore style + // PhoneNumber => phone_number + return underscore(name); + } + + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } + + @Override + public String toModelName(String name) { + // model name cannot use reserved keyword + if(reservedWords.contains(name)) + escapeReservedWord(name); // e.g. return => _return + + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); + } + + @Override + public String toModelFilename(String name) { + // should be the same as the model name + return toModelName(name); + } + + @Override + public String toApiFilename(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); + + // e.g. phone_number_api.rb => PhoneNumberApi.rb + return camelize(name) + "Api"; + } + + @Override + public String toApiName(String name) { + if(name.length() == 0) + return "DefaultApi"; + // e.g. phone_number_api => PhoneNumberApi + return camelize(name) + "Api"; + } + + @Override + public String toOperationId(String operationId) { + // method name cannot use reserved keyword, e.g. return + if(reservedWords.contains(operationId)) + throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + + return underscore(operationId); + } + + +} diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PhpClientCodegen.java index ae907423d787..48d4a86b09db 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PhpClientCodegen.java @@ -39,9 +39,6 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { apiTemplateFiles.put("api.mustache", ".php"); templateDir = "php"; - typeMapping.clear(); - languageSpecificPrimitives.clear(); - reservedWords = new HashSet ( Arrays.asList( "__halt_compiler", "abstract", "and", "array", "as", "break", "callable", "case", "catch", "class", "clone", "const", "continue", "declare", "default", "die", "do", "echo", "else", "elseif", "empty", "enddeclare", "endfor", "endforeach", "endif", "endswitch", "endwhile", "eval", "exit", "extends", "final", "for", "foreach", "function", "global", "goto", "if", "implements", "include", "include_once", "instanceof", "insteadof", "interface", "isset", "list", "namespace", "new", "or", "print", "private", "protected", "public", "require", "require_once", "return", "static", "switch", "throw", "trait", "try", "unset", "use", "var", "while", "xor") @@ -52,18 +49,39 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { additionalProperties.put("artifactId", artifactId); additionalProperties.put("artifactVersion", artifactVersion); - languageSpecificPrimitives.add("int"); - languageSpecificPrimitives.add("array"); - languageSpecificPrimitives.add("map"); - languageSpecificPrimitives.add("string"); - languageSpecificPrimitives.add("DateTime"); + // ref: http://php.net/manual/en/language.types.intro.php + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "boolean", + "int", + "integer", + "double", + "float", + "string", + "object", + "DateTime", + "mixed", + "number") + ); - typeMapping.put("long", "int"); + instantiationTypes.put("array", "array"); + instantiationTypes.put("map", "map"); + + // ref: https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#data-types + typeMapping = new HashMap(); typeMapping.put("integer", "int"); - typeMapping.put("Array", "array"); - typeMapping.put("String", "string"); - typeMapping.put("List", "array"); + typeMapping.put("long", "int"); + typeMapping.put("float", "float"); + typeMapping.put("double", "double"); + typeMapping.put("string", "string"); + typeMapping.put("byte", "int"); + typeMapping.put("boolean", "boolean"); + typeMapping.put("date", "DateTime"); + typeMapping.put("datetime", "DateTime"); + typeMapping.put("file", "string"); typeMapping.put("map", "map"); + typeMapping.put("array", "array"); + typeMapping.put("list", "array"); supportingFiles.add(new SupportingFile("composer.mustache", packagePath, "composer.json")); supportingFiles.add(new SupportingFile("APIClient.mustache", packagePath + "/lib", "APIClient.php")); @@ -109,12 +127,15 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { if(languageSpecificPrimitives.contains(type)) { return type; } + else if (instantiationTypes.containsKey(type)) { + return type; + } } else type = swaggerType; if(type == null) return null; - return type; + return toModelName(type); } public String toDefaultValue(Property p) { diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/Qt5CPPGenerator.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/Qt5CPPGenerator.java new file mode 100644 index 000000000000..35d9bf58bbb2 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/Qt5CPPGenerator.java @@ -0,0 +1,308 @@ +package com.wordnik.swagger.codegen.languages; + +import com.wordnik.swagger.codegen.*; +import com.wordnik.swagger.util.Json; +import com.wordnik.swagger.models.properties.*; + +import java.util.*; +import java.io.File; + +public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig { + protected Set foundationClasses = new HashSet(); + + // source folder where to write the files + protected String sourceFolder = "client"; + protected String apiVersion = "1.0.0"; + protected final String PREFIX = "SWG"; + protected Map namespaces = new HashMap(); + protected Set systemIncludes = new HashSet(); + + /** + * Configures the type of generator. + * + * @return the CodegenType for this generator + * @see com.wordnik.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 "qt5cpp"; + } + + /** + * 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 qt5 C++ client library."; + } + + public Qt5CPPGenerator() { + super(); + + // set the output folder here + outputFolder = "generated-code/qt5cpp"; + + /** + * Models. You can write model files using the modelTemplateFiles map. + * if you want to create one template for file, you can do so here. + * for multiple files for model, just put another entry in the `modelTemplateFiles` with + * a different extension + */ + modelTemplateFiles.put( + "model-header.mustache", + ".h"); + + modelTemplateFiles.put( + "model-body.mustache", + ".cpp"); + + /** + * Api classes. You can write classes for each Api file with the apiTemplateFiles map. + * as with models, add multiple entries with different extensions for multiple files per + * class + */ + apiTemplateFiles.put( + "api-header.mustache", // the template to use + ".h"); // the extension for each file to write + + apiTemplateFiles.put( + "api-body.mustache", // the template to use + ".cpp"); // the extension for each file to write + + /** + * Template Location. This is the location which templates will be read from. The generator + * will use the resource stream to attempt to read the templates. + */ + templateDir = "qt5cpp"; + + /** + * Reserved words. Override this with reserved words specific to your language + */ + reservedWords = new HashSet ( + Arrays.asList( + "sample1", // replace with static values + "sample2") + ); + + /** + * Additional Properties. These values can be passed to the templates and + * are available in models, apis, and supporting files + */ + additionalProperties.put("apiVersion", apiVersion); + additionalProperties().put("prefix", PREFIX); + + /** + * Language Specific Primitives. These types will not trigger imports by + * the client generator + */ + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "bool", + "qint32", + "qint64") + ); + + supportingFiles.add(new SupportingFile("helpers-header.mustache", sourceFolder, PREFIX + "Helpers.h")); + supportingFiles.add(new SupportingFile("helpers-body.mustache", sourceFolder, PREFIX + "Helpers.cpp")); + supportingFiles.add(new SupportingFile("HttpRequest.h", sourceFolder, PREFIX + "HttpRequest.h")); + supportingFiles.add(new SupportingFile("HttpRequest.cpp", sourceFolder, PREFIX + "HttpRequest.cpp")); + supportingFiles.add(new SupportingFile("modelFactory.mustache", sourceFolder, PREFIX + "ModelFactory.h")); + supportingFiles.add(new SupportingFile("object.mustache", sourceFolder, PREFIX + "Object.h")); + + super.typeMapping = new HashMap(); + + typeMapping.put("Date", "QDate"); + typeMapping.put("DateTime", "QDateTime"); + typeMapping.put("string", "QString"); + typeMapping.put("integer", "qint32"); + typeMapping.put("long", "qint64"); + typeMapping.put("boolean", "bool"); + typeMapping.put("array", "QList"); + typeMapping.put("map", "QMap"); + typeMapping.put("file", "SWGHttpRequestInputFileElement"); + typeMapping.put("object", PREFIX + "Object"); + + importMapping = new HashMap(); + + importMapping.put("SWGHttpRequestInputFileElement", "#include \"" + PREFIX + "HttpRequest.h\""); + + namespaces = new HashMap (); + + foundationClasses.add("QString"); + + systemIncludes.add("QString"); + systemIncludes.add("QList"); + } + + @Override + public String toModelImport(String name) { + if(namespaces.containsKey(name)) { + return "using " + namespaces.get(name) + ";"; + } + else if(systemIncludes.contains(name)) { + return "#include <" + name + ">"; + } + return "#include \"" + name + ".h\""; + } + + /** + * 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 + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); + } + + /** + * Location to write api files. You can use the apiPackage() as defined when the class is + * instantiated + */ + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); + } + + @Override + public String toModelFilename(String name) { + return PREFIX + initialCaps(name); + } + + @Override + public String toApiFilename(String name) { + return PREFIX + 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) + ">*"; + } + else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + return getSwaggerType(p) + "*"; + } + if(foundationClasses.contains(swaggerType)) + return swaggerType + "*"; + else if(languageSpecificPrimitives.contains(swaggerType)) + return toModelName(swaggerType); + else + return swaggerType + "*"; + } + + @Override + public String toDefaultValue(Property p) { + if(p instanceof StringProperty) + return "new QString(\"\")"; + else if (p instanceof BooleanProperty) + return "false"; + else if(p instanceof DateProperty) + return "NULL"; + else if(p instanceof DateTimeProperty) + return "NULL"; + 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 "new QMap()"; + } + else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + if(!languageSpecificPrimitives.contains(inner)) { + inner += "*"; + } + return "new QList<" + inner + ">()"; + } + // else + if(p instanceof RefProperty) { + RefProperty rp = (RefProperty) p; + return "new " + toModelName(rp.getSimpleRef()) + "()"; + } + return "NULL"; + } + + + /** + * 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 com.wordnik.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); + if(foundationClasses.contains(type)) + return 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 PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1); + } + } + + @Override + public String toApiName(String type) { + return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1) + "Api"; + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/RubyClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/RubyClientCodegen.java index 0c472a2b75d9..939c0eb0e0af 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/RubyClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/RubyClientCodegen.java @@ -8,10 +8,9 @@ import java.util.*; import java.io.File; public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String invokerPackage = "com.wordnik.client"; - protected String groupId = "com.wordnik"; - protected String artifactId = "swagger-client"; - protected String artifactVersion = "1.0.0"; + protected String gemName = "swagger_client"; + protected String moduleName = null; + protected String libFolder = "lib"; public CodegenType getTag() { return CodegenType.CLIENT; @@ -25,10 +24,18 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { return "Generates a Ruby client library."; } + /** + * Generate Ruby module name from the gem name, e.g. use "SwaggerClient" for "swagger_client". + */ + public String generateModuleName() { + return camelize(gemName.replaceAll("[^\\w]+", "_")); + } + public RubyClientCodegen() { super(); - modelPackage = "models"; - apiPackage = "lib"; + moduleName = generateModuleName(); + modelPackage = gemName + "/models"; + apiPackage = gemName + "/api"; outputFolder = "generated-code/ruby"; modelTemplateFiles.put("model.mustache", ".rb"); apiTemplateFiles.put("api.mustache", ".rb"); @@ -39,17 +46,15 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { reservedWords = new HashSet ( Arrays.asList( - "__FILE__", "and", "def", "end", "in", "or", "self", "unless", "__LINE__", + "__FILE__", "and", "def", "end", "in", "or", "self", "unless", "__LINE__", "begin", "defined?", "ensure", "module", "redo", "super", "until", "BEGIN", - "break", "do", "false", "next", "rescue", "then", "when", "END", "case", + "break", "do", "false", "next", "rescue", "then", "when", "END", "case", "else", "for", "nil", "retry", "true", "while", "alias", "class", "elsif", "if", "not", "return", "undef", "yield") ); - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); + additionalProperties.put("gemName", gemName); + additionalProperties.put("moduleName", moduleName); languageSpecificPrimitives.add("int"); languageSpecificPrimitives.add("array"); @@ -64,14 +69,18 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("List", "array"); typeMapping.put("map", "map"); - supportingFiles.add(new SupportingFile("swagger-client.gemspec.mustache", "", "swagger-client.gemspec")); - supportingFiles.add(new SupportingFile("swagger-client.mustache", "", "lib/swagger-client.rb")); - supportingFiles.add(new SupportingFile("swagger.mustache", "", "lib/swagger.rb")); - supportingFiles.add(new SupportingFile("monkey.mustache", "", "lib/monkey.rb")); - supportingFiles.add(new SupportingFile("swagger/request.mustache", "", "lib/swagger/request.rb")); - supportingFiles.add(new SupportingFile("swagger/response.mustache", "", "lib/swagger/response.rb")); - supportingFiles.add(new SupportingFile("swagger/version.mustache", "", "lib/swagger/version.rb")); - supportingFiles.add(new SupportingFile("swagger/configuration.mustache", "", "lib/swagger/configuration.rb")); + String baseFolder = "lib/" + gemName; + String swaggerFolder = baseFolder + "/swagger"; + String modelFolder = baseFolder + "/models"; + supportingFiles.add(new SupportingFile("swagger_client.gemspec.mustache", "", gemName + ".gemspec")); + supportingFiles.add(new SupportingFile("swagger_client.mustache", "lib", gemName + ".rb")); + supportingFiles.add(new SupportingFile("monkey.mustache", baseFolder, "monkey.rb")); + supportingFiles.add(new SupportingFile("swagger.mustache", baseFolder, "swagger.rb")); + supportingFiles.add(new SupportingFile("swagger/request.mustache", swaggerFolder, "request.rb")); + supportingFiles.add(new SupportingFile("swagger/response.mustache", swaggerFolder, "response.rb")); + supportingFiles.add(new SupportingFile("swagger/version.mustache", swaggerFolder, "version.rb")); + supportingFiles.add(new SupportingFile("swagger/configuration.mustache", swaggerFolder, "configuration.rb")); + supportingFiles.add(new SupportingFile("base_object.mustache", modelFolder, "base_object.rb")); } @Override @@ -81,11 +90,11 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String apiFileFolder() { - return outputFolder + "/" + apiPackage().replace('.', File.separatorChar); + return outputFolder + File.separatorChar + "lib" + File.separatorChar + gemName + File.separatorChar + "api"; } public String modelFileFolder() { - return outputFolder + "/" + modelPackage().replace('.', File.separatorChar); + return outputFolder + File.separatorChar + "lib" + File.separatorChar + gemName + File.separatorChar + "models"; } @Override @@ -149,13 +158,13 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { // should be the same as variable name return toVarName(name); } - + @Override public String toModelName(String name) { // model name cannot use reserved keyword, e.g. return if(reservedWords.contains(name)) throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); - + // camelize the model name // phone_number => PhoneNumber return camelize(name); @@ -166,11 +175,11 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { // model name cannot use reserved keyword, e.g. return if(reservedWords.contains(name)) throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); - + // underscore the model file name // PhoneNumber.rb => phone_number.rb return underscore(name); - } + } @Override public String toApiFilename(String name) { @@ -185,7 +194,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { public String toApiName(String name) { if(name.length() == 0) return "DefaultApi"; - // e.g. phone_number_api => PhoneNumberApi + // e.g. phone_number_api => PhoneNumberApi return camelize(name) + "Api"; } @@ -195,8 +204,17 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { if(reservedWords.contains(operationId)) throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); - return underscore(operationId); + return underscore(operationId); } + @Override + public String toModelImport(String name) { + return modelPackage() + "/" + toModelFilename(name); + } + + @Override + public String toApiImport(String name) { + return apiPackage() + "/" + toApiFilename(name); + } } diff --git a/modules/swagger-codegen/src/main/resources/Java/JsonUtil.mustache b/modules/swagger-codegen/src/main/resources/Java/JsonUtil.mustache index e77eb50d85b4..29d5f55eceea 100644 --- a/modules/swagger-codegen/src/main/resources/Java/JsonUtil.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/JsonUtil.mustache @@ -1,17 +1,23 @@ package {{invokerPackage}}; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.core.JsonGenerator.Feature; + +import com.fasterxml.jackson.datatype.joda.*; public class JsonUtil { - public static GsonBuilder gsonBuilder; + public static ObjectMapper mapper; static { - gsonBuilder = new GsonBuilder(); - gsonBuilder.serializeNulls(); - } + mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + mapper.registerModule(new JodaModule()); + } - public static Gson getGson() { - return gsonBuilder.create(); - } -}; \ No newline at end of file + public static ObjectMapper getJsonMapper() { + return mapper; + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/api.mustache b/modules/swagger-codegen/src/main/resources/Java/api.mustache index a1c9e05042d4..78bac41d9d6b 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api.mustache @@ -45,12 +45,12 @@ public class {{classname}} { */ public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; - {{#requiredParamCount}} - // verify required params are set - if({{/requiredParamCount}}{{#requiredParams}} {{paramName}} == null {{#hasMore}}|| {{/hasMore}}{{/requiredParams}}{{#requiredParamCount}}) { - throw new ApiException(400, "missing required params"); + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) { + throw new ApiException(400, "Missing the required parameter '{{paramName}}' when calling {{nickname}}"); } - {{/requiredParamCount}} + {{/required}}{{/allParams}} // create path and map variables String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}} diff --git a/modules/swagger-codegen/src/main/resources/META-INF/services/com.wordnik.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/com.wordnik.swagger.codegen.CodegenConfig index 54236bffc9c9..293079fbc972 100644 --- a/modules/swagger-codegen/src/main/resources/META-INF/services/com.wordnik.swagger.codegen.CodegenConfig +++ b/modules/swagger-codegen/src/main/resources/META-INF/services/com.wordnik.swagger.codegen.CodegenConfig @@ -5,9 +5,11 @@ com.wordnik.swagger.codegen.languages.JavaClientCodegen com.wordnik.swagger.codegen.languages.JaxRSServerCodegen com.wordnik.swagger.codegen.languages.NodeJSServerCodegen com.wordnik.swagger.codegen.languages.ObjcClientCodegen +com.wordnik.swagger.codegen.languages.PerlClientCodegen com.wordnik.swagger.codegen.languages.PhpClientCodegen com.wordnik.swagger.codegen.languages.PythonClientCodegen com.wordnik.swagger.codegen.languages.Python3ClientCodegen +com.wordnik.swagger.codegen.languages.Qt5CPPGenerator com.wordnik.swagger.codegen.languages.RubyClientCodegen com.wordnik.swagger.codegen.languages.ScalaClientCodegen com.wordnik.swagger.codegen.languages.ScalatraServerCodegen diff --git a/modules/swagger-codegen/src/main/resources/android-java/api.mustache b/modules/swagger-codegen/src/main/resources/android-java/api.mustache index 0f21897e6779..ed9538c15941 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/api.mustache @@ -47,13 +47,12 @@ public class {{classname}} { */ public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; - - {{#requiredParamCount}} - // verify required params are set - if({{/requiredParamCount}}{{#requiredParams}} {{paramName}} == null {{#hasMore}}|| {{/hasMore}}{{/requiredParams}}{{#requiredParamCount}}) { - throw new ApiException(400, "missing required params"); + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) { + throw new ApiException(400, "Missing the required parameter '{{paramName}}' when calling {{nickname}}"); } - {{/requiredParamCount}} + {{/required}}{{/allParams}} // create path and map variables String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}.replaceAll("\\{" + "{{paramName}}" + "\\}", apiInvoker.escapeString({{{paramName}}}.toString())){{/pathParams}}; diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache index 3f74c63de3b6..99ecb80ac1ab 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache @@ -2,7 +2,6 @@ API Reference -

{{{appName}}}

diff --git a/modules/swagger-codegen/src/main/resources/perl/APIClient.mustache b/modules/swagger-codegen/src/main/resources/perl/APIClient.mustache new file mode 100644 index 000000000000..19079a079223 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/perl/APIClient.mustache @@ -0,0 +1,291 @@ +package WWW::{{invokerPackage}}::APIClient; + +use strict; +use warnings; +use utf8; + +use LWP::UserAgent; +use HTTP::Headers; +use HTTP::Response; +use HTTP::Request::Common qw(DELETE POST GET HEAD PUT); +use HTTP::Status; +use URI::Query; +use JSON; +use URI::Escape; +use Scalar::Util; +use Log::Any qw($log); +use Carp; +use Switch; +use Module::Runtime qw(use_module); + +# class variables +my $ua = LWP::UserAgent->new; +my $http_user_agent = 'Perl-Swagger'; # HTTP user-agent +my $http_timeout; #timeout +my $base_url = "{{basePath}}"; + + +sub new +{ + my $class = shift; + my %args = @_; + + return bless \%args, $class; +} + +# Set the user agent of the API client +# +# @param string $user_agent The user agent of the API client +# +sub set_user_agent { + my $user_agent = shift; + $http_user_agent= $user_agent; +} + +# Set timeout +# +# @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] +# +sub set_timeout { + my $seconds = shift; + if (!looks_like_number($seconds)) { + croak('Timeout variable must be numeric.'); + } + $http_timeout = $seconds; +} + +# make the HTTP request +# @param string $resourcePath path to method endpoint +# @param string $method method to call +# @param array $queryParams parameters to be place in query URL +# @param array $postData parameters to be placed in POST body +# @param array $headerParams parameters to be place in request header +# @return mixed +sub call_api { + my $self = shift; + my ($resource_path, $method, $query_params, $post_params, $header_params, $body_data) = @_; + + my $headers = HTTP::Headers->new(%$header_params); + + my $_url = $base_url . $resource_path; + + # build query + if (%$query_params) { + $_url = ($_url . '?' . eval { URI::Query->new($query_params)->stringify }); + } + + # body data + $body_data = to_json($body_data->to_hash) if defined $body_data && $body_data->can('to_hash'); # model to json string + my $_body_data = %$post_params ? $post_params : $body_data; + + # Make the HTTP request + my $_request; + switch ($method) { + case 'POST' { + # multipart + my $_content_type = lc $header_params->{'Content-Type'} eq 'multipart/form' ? + 'form-data' : $header_params->{'Content-Type'}; + + $_request = POST($_url, Accept => $header_params->{Accept}, + Content_Type => $_content_type, Content => $_body_data); + } + case 'PUT' { + # multipart + my $_content_type = lc $header_params->{'Content-Type'} eq 'multipart/form' ? + 'form-data' : $header_params->{'Content-Type'}; + $_request = PUT($_url, Accept => $header_params->{Accept}, + Content_Type => $_content_type, Content => $_body_data); + } + case 'GET' { + $_request = GET($_url, Accept => $header_params->{'Accept'}, + Content_Type => $header_params->{'Content-Type'}); + } + case 'HEAD' { + $_request = HEAD($_url, Accept => $header_params->{'Accept'}, + Content_Type => $header_params->{'Content-Type'}); + } + case 'DELETE' { #TODO support form data + $_request = DELETE($_url, Accept => $header_params->{'Accept'}, + Content_Type => $header_params->{'Content-Type'}, Content => $_body_data); + } + case 'PATCH' { #TODO + } + + } + + $ua->timeout($http_timeout); + $ua->agent($http_user_agent); + + my $_response = $ua->request($_request); + + unless ($_response->is_success) { + croak("API Exception(".$_response->code."): ".$_response->message); + } + + return $_response->content; + +} + + +# Build a JSON POST object +sub sanitize_for_serialization +{ +# my $data = shift; +# if (is_scalar($data) || null === $data) { +# $sanitized = $data; +# } else if ($data instanceof \DateTime) { +# $sanitized = $data->format(\DateTime::ISO8601); +# } else if (is_array($data)) { +# foreach ($data as $property => $value) { +# $data[$property] = $this->sanitizeForSerialization($value); +# } +# $sanitized = $data; +# } else if (is_object($data)) { +# $values = array(); +# foreach (array_keys($data::$swaggerTypes) as $property) { +# $values[$data::$attributeMap[$property]] = $this->sanitizeForSerialization($data->$property); +# } +# $sanitized = $values; +# } else { +# $sanitized = (string)$data; +# } +# +# return $sanitized; +} + + +# Take value and turn it into a string suitable for inclusion in +# the path, by url-encoding. +# @param string $value a string which will be part of the path +# @return string the serialized object +sub to_path_value { + my $value = shift; + return uri_escape(to_string($value)); +} + + +# Take value and turn it into a string suitable for inclusion in +# the query, by imploding comma-separated if it's an object. +# If it's a string, pass through unchanged. It will be url-encoded +# later. +# @param object $object an object to be serialized to a string +# @return string the serialized object +sub to_query_value { + my $object = shift; + if (is_array($object)) { + return implode(',', $object); + } else { + return toString($object); + } +} + + +# Take value and turn it into a string suitable for inclusion in +# the header. If it's a string, pass through unchanged +# If it's a datetime object, format it in ISO8601 +# @param string $value a string which will be part of the header +# @return string the header string +sub to_header_value { + my $value = shift; + return to_string($value); +} + +# Take value and turn it into a string suitable for inclusion in +# the http body (form parameter). If it's a string, pass through unchanged +# If it's a datetime object, format it in ISO8601 +# @param string $value the value of the form parameter +# @return string the form string +sub to_form_value { + my $value = shift; + return to_string($value); +} + +# Take value and turn it into a string suitable for inclusion in +# the parameter. If it's a string, pass through unchanged +# If it's a datetime object, format it in ISO8601 +# @param string $value the value of the parameter +# @return string the header string +sub to_string { + my $value = shift; + if (ref($value) eq "DateTime") { # datetime in ISO8601 format + return $value->datetime(); + } + else { + return $value; + } +} + +# Deserialize a JSON string into an object +# +# @param string $class class name is passed as a string +# @param string $data data of the body +# @return object an instance of $class +sub deserialize +{ + my ($self, $class, $data) = @_; + $log->debugf("deserializing %s for %s", $data, $class); + my $_result; + + if (not defined $data) { + return undef; + } elsif ( lc(substr($class, 0, 4)) eq 'map[') { #hash + $_result = \(json_decode $data); + } elsif ( lc(substr($class, 0, 6)) eq 'array[' ) { # array of data + return $data if $data eq '[]'; # return if empty array + + my $_sub_class = substr($class, 6, -1); + my @_json_data = json_decode $data; + my @_values = (); + foreach my $_value (@_json_data) { + push @_values, $self->deserialize($_sub_class, $_value); + } + $_result = \@_values; + } elsif ($class eq 'DateTime') { + $_result = DateTime->from_epoch(epoch => str2time($data)); + } elsif (grep /^$data$/, ('string', 'int', 'float', 'bool')) { #TODO revise the primitive type + $_result= $data; + } else { # model + my $_instance = use_module("WWW::{{invokerPackage}}::Object::$class")->new; + $_result = $_instance->from_hash(decode_json $data); + } + + return $_result; + +} + +# return 'Accept' based on an array of accept provided +# @param [Array] header_accept_array Array fo 'Accept' +# @return String Accept (e.g. application/json) +sub select_header_accept +{ + my ($self, @header) = @_; + + if (@header == 0 || (@header == 1 && $header[0] eq '')) { + return undef; + } elsif (grep(/^application\/json$/i, @header)) { + return 'application/json'; + } else { + return join(',', @header); + } + +} + +# return the content type based on an array of content-type provided +# @param [Array] content_type_array Array fo content-type +# @return String Content-Type (e.g. application/json) +sub select_header_content_type +{ + my ($self, @header) = @_; + + if (@header == 0 || (@header == 1 && $header[0] eq '')) { + return 'application/json'; # default to application/json + } elsif (grep(/^application\/json$/i, @header)) { + return 'application/json'; + } else { + return join(',', @header); + } + +} + + +1; diff --git a/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache b/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache new file mode 100644 index 000000000000..b4a7885a7987 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache @@ -0,0 +1,76 @@ +package WWW::{{invokerPackage}}::Object::BaseObject; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + + +# +# +# +#NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# + + +# return json string +sub to_hash { + return decode_json(JSON->new->convert_blessed->encode( shift )); +} + +# used by JSON for serialization +sub TO_JSON { + my $self = shift; + my $_data = {}; + foreach my $_key (keys $self->get_attribute_map) { + if (defined $self->{$_key}) { + $_data->{$self->get_attribute_map->{$_key}} = $self->{$_key}; + } + } + return $_data; +} + +# from json string +sub from_hash { + my ($self, $hash) = @_; + # loop through attributes and use swagger_types to deserialize the data + while ( my ($_key, $_type) = each $self->get_swagger_types ) { + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$self->get_attribute_map->{$_key}}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif (defined $hash->{$_key}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_key}); + } else { + $log->debugf("warning: %s not defined\n", $_key); + } + } + + return $self; +} + +# deserialize non-array data +sub _deserialize { + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::{{invokerPackage}}::Object::$type->new()"; + return $_instance->from_hash($data); + } +} + +1; diff --git a/modules/swagger-codegen/src/main/resources/perl/api.mustache b/modules/swagger-codegen/src/main/resources/perl/api.mustache new file mode 100644 index 000000000000..131eb3a39347 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/perl/api.mustache @@ -0,0 +1,145 @@ +# +# Copyright 2015 Reverb Technologies, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# +package WWW::{{invokerPackage}}::{{classname}}; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use Exporter; +use Carp qw( croak ); +use Log::Any qw($log); + + +#use WWW::Swagger::Model::Category; +#use WWW::Swagger::Model::Pet; + +{{#operations}} + +use WWW::{{invokerPackage}}::APIClient; + +our @EXPORT_OK = qw( + {{#operation}}{{{nickname}}} + {{/operation}} +); + +sub new { + my $class = shift; + my $default_api_client = WWW::{{invokerPackage}}::APIClient->new; + my (%self) = ( + 'api_client' => $default_api_client, + @_ + ); + + #my $self = { + # #api_client => $options->{api_client} + # api_client => $default_api_client + #}; + + bless \%self, $class; + +} + + {{#operation}} + # + # {{{nickname}}} + # + # {{{summary}}} + # + {{#allParams}} # @param {{dataType}} ${{paramName}} {{description}} {{^optional}}(required){{/optional}}{{#optional}}(optional){{/optional}} + {{/allParams}} # @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} + # + sub {{nickname}} { + my ($self, %args) = @_; + + {{#allParams}}{{#required}} + # verify the required parameter '{{paramName}}' is set + unless (exists $args{'{{paramName}}'}) { + croak("Missing the required parameter '{{paramName}}' when calling {{nickname}}"); + } + {{/required}}{{/allParams}} + + # parse inputs + my $_resource_path = '{{path}}'; + $_resource_path =~ s/{format}/json/; # default format to json + + my $_method = '{{httpMethod}}'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept({{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type({{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}); + + {{#queryParams}} # query params + if ( exists $args{'{{paramName}}'}) { + $query_params->{'{{baseName}}'} = WWW::{{invokerPacakge}}::APIClient::to_query_value($args{'{{paramName}}'}); + }{{/queryParams}} + {{#headerParams}} # header params + if ( exists $args{'{{paramName}}'}) { + $header_params->{'{{baseName}}'} = WWW::{{invokerPackage}}::APIClient::to_header_value($args{'{{paramName}}'}); + }{{/headerParams}} + {{#pathParams}} # path params + if ( exists $args{'{{paramName}}'}) { + my $_base_variable = "{" . "{{baseName}}" . "}"; + my $_base_value = WWW::{{invokerPackage}}::APIClient::to_path_value($args{'{{paramName}}'}); + $_resource_path =~ s/$_base_variable/$_base_value/g; + }{{/pathParams}} + {{#formParams}} # form params + if ( exists $args{'{{paramName}}'} ) { + {{#isFile}}$form_params->{'{{baseName}}'} = [] unless defined $form_params->{'{{baseName}}'}; + push $form_params->{'{{baseName}}'}, $args{'{{paramName}}'}; + {{/isFile}} + {{^isFile}}$form_params->{'{{baseName}}'} = WWW::{{invokerPackage}}::APIClient::to_form_value($args{'{{paramName}}'}); + {{/isFile}} + }{{/formParams}} + my $_body_data; + {{#bodyParams}} # body params + if ( exists $args{'{{paramName}}'}) { + $_body_data = $args{'{{paramName}}'}; + }{{/bodyParams}} + + # for HTTP post (form) + #$_body_data = $_body ? undef : $form_params; + + # make the API Call + {{#returnType}}my $response = $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data); + if (!$response) { + return; + } + my $_response_object = $self->{api_client}->deserialize('{{returnType}}', $response); + return $_response_object;{{/returnType}} + {{^returnType}}$self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data); + return; + {{/returnType}} + } + {{/operation}} +{{newline}} +{{/operations}} + +1; diff --git a/modules/swagger-codegen/src/main/resources/perl/object.mustache b/modules/swagger-codegen/src/main/resources/perl/object.mustache new file mode 100644 index 000000000000..c527957a9b10 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/perl/object.mustache @@ -0,0 +1,58 @@ +{{#models}} +{{#model}} +package WWW::{{invokerPackage}}::Object::{{classname}}; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + +use base "WWW::{{invokerPackage}}::Object::BaseObject"; + +# +#{{description}} +# +#NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# + +my $swagger_types = { + {{#vars}}'{{name}}' => '{{{datatype}}}'{{#hasMore}}, + {{/hasMore}}{{/vars}} +}; + +my $attribute_map = { + {{#vars}}'{{name}}' => '{{baseName}}'{{#hasMore}}, + {{/hasMore}}{{/vars}} +}; + +# new object +sub new { + my ($class, %args) = @_; + my $self = { + {{#vars}}#{{#description}}{{{description}}}{{/description}} + '{{name}}' => $args{'{{baseName}}'}{{#hasMore}}, + {{/hasMore}}{{/vars}} + }; + + return bless $self, $class; +} + +# get swagger type of the attribute +sub get_swagger_types { + return $swagger_types; +} + +# get attribute mappping +sub get_attribute_map { + return $attribute_map; +} + +1; +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache index 5cfb953002b9..a750daff12de 100644 --- a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache @@ -94,7 +94,11 @@ class APIClient { $headers[] = $this->headerName . ": " . $this->headerValue; } - if ((isset($headerName['Content-Type']) and strpos($headerName['Content-Type'], "multipart/form-data") === FALSE) and (is_object($postData) or is_array($postData))) { + // form data + if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers)) { + $postData = http_build_query($postData); + } + else if ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers)) { // json model $postData = json_encode($this->sanitizeForSerialization($postData)); } diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index a434699f90ad..7759af5004d5 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -39,6 +39,12 @@ class {{classname}} { {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} */ public function {{nickname}}({{#allParams}}${{paramName}}{{#optional}}=null{{/optional}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + if (${{paramName}} === null) { + throw new \Exception("Missing the required parameter ${{paramName}} when calling {{nickname}}"); + } + {{/required}}{{/allParams}} // parse inputs $resourcePath = "{{path}}"; @@ -81,11 +87,9 @@ class {{classname}} { // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } - - // for HTTP post (form) - if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") !== FALSE) { - $httpBody = http_build_query($formParams); + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; } // make the API Call diff --git a/modules/swagger-codegen/src/main/resources/php/require.mustache b/modules/swagger-codegen/src/main/resources/php/require.mustache index 058aa169504c..3c02d861ef18 100644 --- a/modules/swagger-codegen/src/main/resources/php/require.mustache +++ b/modules/swagger-codegen/src/main/resources/php/require.mustache @@ -1,7 +1,4 @@ +#include +#include +#include + + +HttpRequestInput::HttpRequestInput() { + initialize(); +} + +HttpRequestInput::HttpRequestInput(QString v_url_str, QString v_http_method) { + initialize(); + url_str = v_url_str; + http_method = v_http_method; +} + +void HttpRequestInput::initialize() { + var_layout = NOT_SET; + url_str = ""; + http_method = "GET"; +} + +void HttpRequestInput::add_var(QString key, QString value) { + vars[key] = value; +} + +void HttpRequestInput::add_file(QString variable_name, QString local_filename, QString request_filename, QString mime_type) { + SWGHttpRequestInputFileElement file; + file.variable_name = variable_name; + file.local_filename = local_filename; + file.request_filename = request_filename; + file.mime_type = mime_type; + files.append(file); +} + + +HttpRequestWorker::HttpRequestWorker(QObject *parent) + : QObject(parent), manager(NULL) +{ + qsrand(QDateTime::currentDateTime().toTime_t()); + + manager = new QNetworkAccessManager(this); + connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(on_manager_finished(QNetworkReply*))); +} + +HttpRequestWorker::~HttpRequestWorker() { +} + +QString HttpRequestWorker::http_attribute_encode(QString attribute_name, QString input) { + // result structure follows RFC 5987 + bool need_utf_encoding = false; + QString result = ""; + QByteArray input_c = input.toLocal8Bit(); + char c; + for (int i = 0; i < input_c.length(); i++) { + c = input_c.at(i); + if (c == '\\' || c == '/' || c == '\0' || c < ' ' || c > '~') { + // ignore and request utf-8 version + need_utf_encoding = true; + } + else if (c == '"') { + result += "\\\""; + } + else { + result += c; + } + } + + if (result.length() == 0) { + need_utf_encoding = true; + } + + if (!need_utf_encoding) { + // return simple version + return QString("%1=\"%2\"").arg(attribute_name, result); + } + + QString result_utf8 = ""; + for (int i = 0; i < input_c.length(); i++) { + c = input_c.at(i); + if ( + (c >= '0' && c <= '9') + || (c >= 'A' && c <= 'Z') + || (c >= 'a' && c <= 'z') + ) { + result_utf8 += c; + } + else { + result_utf8 += "%" + QString::number(static_cast(input_c.at(i)), 16).toUpper(); + } + } + + // return enhanced version with UTF-8 support + return QString("%1=\"%2\"; %1*=utf-8''%3").arg(attribute_name, result, result_utf8); +} + +void HttpRequestWorker::execute(HttpRequestInput *input) { + + // reset variables + + QByteArray request_content = ""; + response = ""; + error_type = QNetworkReply::NoError; + error_str = ""; + bool isFormData = false; + + + // decide on the variable layout + + if (input->files.length() > 0) { + input->var_layout = MULTIPART; + } + if (input->var_layout == NOT_SET) { + input->var_layout = input->http_method == "GET" || input->http_method == "HEAD" ? ADDRESS : URL_ENCODED; + } + + + // prepare request content + + QString boundary = ""; + + if (input->var_layout == ADDRESS || input->var_layout == URL_ENCODED) { + // variable layout is ADDRESS or URL_ENCODED + + if (input->vars.count() > 0) { + bool first = true; + isFormData = true; + foreach (QString key, input->vars.keys()) { + if (!first) { + request_content.append("&"); + } + first = false; + + request_content.append(QUrl::toPercentEncoding(key)); + request_content.append("="); + request_content.append(QUrl::toPercentEncoding(input->vars.value(key))); + } + + if (input->var_layout == ADDRESS) { + input->url_str += "?" + request_content; + request_content = ""; + } + } + } + else { + // variable layout is MULTIPART + + boundary = "__-----------------------" + + QString::number(QDateTime::currentDateTime().toTime_t()) + + QString::number(qrand()); + QString boundary_delimiter = "--"; + QString new_line = "\r\n"; + + // add variables + foreach (QString key, input->vars.keys()) { + // add boundary + request_content.append(boundary_delimiter); + request_content.append(boundary); + request_content.append(new_line); + + // add header + request_content.append("Content-Disposition: form-data; "); + request_content.append(http_attribute_encode("name", key)); + request_content.append(new_line); + request_content.append("Content-Type: text/plain"); + request_content.append(new_line); + + // add header to body splitter + request_content.append(new_line); + + // add variable content + request_content.append(input->vars.value(key)); + request_content.append(new_line); + } + + // add files + for (QList::iterator file_info = input->files.begin(); file_info != input->files.end(); file_info++) { + QFileInfo fi(file_info->local_filename); + + // ensure necessary variables are available + if ( + file_info->local_filename == NULL || file_info->local_filename.isEmpty() + || file_info->variable_name == NULL || file_info->variable_name.isEmpty() + || !fi.exists() || !fi.isFile() || !fi.isReadable() + ) { + // silent abort for the current file + continue; + } + + QFile file(file_info->local_filename); + if (!file.open(QIODevice::ReadOnly)) { + // silent abort for the current file + continue; + } + + // ensure filename for the request + if (file_info->request_filename == NULL || file_info->request_filename.isEmpty()) { + file_info->request_filename = fi.fileName(); + if (file_info->request_filename.isEmpty()) { + file_info->request_filename = "file"; + } + } + + // add boundary + request_content.append(boundary_delimiter); + request_content.append(boundary); + request_content.append(new_line); + + // add header + request_content.append(QString("Content-Disposition: form-data; %1; %2").arg( + http_attribute_encode("name", file_info->variable_name), + http_attribute_encode("filename", file_info->request_filename) + )); + request_content.append(new_line); + + if (file_info->mime_type != NULL && !file_info->mime_type.isEmpty()) { + request_content.append("Content-Type: "); + request_content.append(file_info->mime_type); + request_content.append(new_line); + } + + request_content.append("Content-Transfer-Encoding: binary"); + request_content.append(new_line); + + // add header to body splitter + request_content.append(new_line); + + // add file content + request_content.append(file.readAll()); + request_content.append(new_line); + + file.close(); + } + + // add end of body + request_content.append(boundary_delimiter); + request_content.append(boundary); + request_content.append(boundary_delimiter); + } + + if(input->request_body.size() > 0) { + qDebug() << "got a request body"; + request_content.clear(); + request_content.append(input->request_body); + } + // prepare connection + + QNetworkRequest request = QNetworkRequest(QUrl(input->url_str)); + request.setRawHeader("User-Agent", "Swagger-Client"); + foreach(QString key, input->headers.keys()) { + request.setRawHeader(key.toStdString().c_str(), input->headers.value(key).toStdString().c_str()); + } + + if (request_content.size() > 0 && !isFormData) { + request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); + } + else if (input->var_layout == URL_ENCODED) { + request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); + } + else if (input->var_layout == MULTIPART) { + request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data; boundary=" + boundary); + } + + if (input->http_method == "GET") { + manager->get(request); + } + else if (input->http_method == "POST") { + manager->post(request, request_content); + } + else if (input->http_method == "PUT") { + manager->put(request, request_content); + } + else if (input->http_method == "HEAD") { + manager->head(request); + } + else if (input->http_method == "DELETE") { + manager->deleteResource(request); + } + else { + QBuffer buff(&request_content); + manager->sendCustomRequest(request, input->http_method.toLatin1(), &buff); + } + +} + +void HttpRequestWorker::on_manager_finished(QNetworkReply *reply) { + error_type = reply->error(); + if (error_type == QNetworkReply::NoError) { + response = reply->readAll(); + } + else { + error_str = reply->errorString(); + } + + reply->deleteLater(); + + emit on_execution_finished(this); +} diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/HttpRequest.h b/modules/swagger-codegen/src/main/resources/qt5cpp/HttpRequest.h new file mode 100644 index 000000000000..a2e91a0765ee --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/HttpRequest.h @@ -0,0 +1,75 @@ +/** + * Based on http://www.creativepulse.gr/en/blog/2014/restful-api-requests-using-qt-cpp-for-linux-mac-osx-ms-windows + * By Alex Stylianos + * + **/ + +#ifndef HTTPREQUESTWORKER_H +#define HTTPREQUESTWORKER_H + +#include +#include +#include +#include +#include + +enum HttpRequestVarLayout {NOT_SET, ADDRESS, URL_ENCODED, MULTIPART}; + + +class SWGHttpRequestInputFileElement { + +public: + QString variable_name; + QString local_filename; + QString request_filename; + QString mime_type; + +}; + + +class HttpRequestInput { + +public: + QString url_str; + QString http_method; + HttpRequestVarLayout var_layout; + QMap vars; + QMap headers; + QList files; + QByteArray request_body; + + HttpRequestInput(); + HttpRequestInput(QString v_url_str, QString v_http_method); + void initialize(); + void add_var(QString key, QString value); + void add_file(QString variable_name, QString local_filename, QString request_filename, QString mime_type); + +}; + + +class HttpRequestWorker : public QObject { + Q_OBJECT + +public: + QByteArray response; + QNetworkReply::NetworkError error_type; + QString error_str; + + explicit HttpRequestWorker(QObject *parent = 0); + virtual ~HttpRequestWorker(); + + QString http_attribute_encode(QString attribute_name, QString input); + void execute(HttpRequestInput *input); + +signals: + void on_execution_finished(HttpRequestWorker *worker); + +private: + QNetworkAccessManager *manager; + +private slots: + void on_manager_finished(QNetworkReply *reply); + +}; + +#endif // HTTPREQUESTWORKER_H diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/api-body.mustache b/modules/swagger-codegen/src/main/resources/qt5cpp/api-body.mustache new file mode 100644 index 000000000000..b63411041881 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/api-body.mustache @@ -0,0 +1,181 @@ +#include "{{classname}}.h" +#include "{{prefix}}Helpers.h" +#include "{{prefix}}ModelFactory.h" + +#include +#include + +namespace Swagger { +{{classname}}::{{classname}}() {} + +{{classname}}::~{{classname}}() {} + +{{classname}}::{{classname}}(QString host, QString basePath) { + this->host = host; + this->basePath = basePath; +} + +{{#operations}} +{{#operation}} +void +{{classname}}::{{nickname}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("{{path}}"); + + {{#pathParams}} + QString {{paramName}}PathParam("{"); {{paramName}}PathParam.append("{{paramName}}").append("}"); + fullPath.replace({{paramName}}PathParam, stringValue({{paramName}})); + {{/pathParams}} + + {{#queryParams}} + {{^collectionFormat}} + if(fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("{{paramName}}")) + .append("=") + .append(QUrl::toPercentEncoding(stringValue({{paramName}}))); + {{/collectionFormat}} + + {{#collectionFormat}} + + if({{{paramName}}}->size() > 0) { + if(QString("{{collectionFormat}}").indexOf("multi") == 0) { + foreach({{{baseType}}} t, *{{paramName}}) { + if(fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append("{{{paramName}}}=").append(stringValue(t)); + } + } + else if (QString("{{collectionFormat}}").indexOf("ssv") == 0) { + if(fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append("{{paramName}}="); + qint32 count = 0; + foreach({{{baseType}}} t, *{{paramName}}) { + if(count > 0) { + fullPath.append(" "); + } + fullPath.append(stringValue(t)); + } + } + else if (QString("{{collectionFormat}}").indexOf("tsv") == 0) { + if(fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append("{{paramName}}="); + qint32 count = 0; + foreach({{{baseType}}} t, *{{paramName}}) { + if(count > 0) { + fullPath.append("\t"); + } + fullPath.append(stringValue(t)); + } + } + } + + {{/collectionFormat}} + {{/queryParams}} + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "{{httpMethod}}"); + + {{#formParams}}{{^isFile}} + if({{paramName}} != NULL) { + input.add_var("{{paramName}}", *{{paramName}}); + } + {{/isFile}}{{/formParams}} + + {{#bodyParams}} + {{#isContainer}} + QJsonArray* {{paramName}}Array = new QJsonArray(); + toJsonArray((QList*){{paramName}}, {{paramName}}Array, QString("body"), QString("SWGUser*")); + + QJsonDocument doc(*{{paramName}}Array); + QByteArray bytes = doc.toJson(); + + input.request_body.append(bytes); + {{/isContainer}} + {{^isContainer}} + QString output = {{paramName}}.asJson(); + input.request_body.append(output); + {{/isContainer}}{{/bodyParams}} + + {{#headerParams}} + // TODO: add header support + {{/headerParams}} + + connect(worker, + &HttpRequestWorker::on_execution_finished, + this, + &{{classname}}::{{nickname}}Callback); + + worker->execute(&input); +} + +void +{{classname}}::{{nickname}}Callback(HttpRequestWorker * worker) { + QString msg; + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + + {{#returnType}}{{#isListContainer}} + {{{returnType}}} output = {{{defaultResponse}}}; + QString json(worker->response); + QByteArray array (json.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonArray jsonArray = doc.array(); + + foreach(QJsonValue obj, jsonArray) { + {{{returnBaseType}}}* o = new {{returnBaseType}}(); + QJsonObject jv = obj.toObject(); + QJsonObject * ptr = (QJsonObject*)&jv; + o->fromJsonObject(*ptr); + output->append(o); + } + {{/isListContainer}} + + {{^isListContainer}}{{#returnTypeIsPrimitive}} + {{{returnType}}} output; // TODO add primitive output support + {{/returnTypeIsPrimitive}} + {{#isMapContainer}} + {{{returnType}}} output = {{{defaultResponse}}}; + + QString json(worker->response); + QByteArray array (json.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject obj = doc.object(); + + foreach(QString key, obj.keys()) { + qint32* val; + setValue(&val, obj[key], "{{returnBaseType}}", ""); + output->insert(key, *val); + } + + + {{/isMapContainer}} + {{^isMapContainer}} + {{^returnTypeIsPrimitive}}QString json(worker->response); + {{{returnType}}} output = static_cast<{{{returnType}}}>(create(json, QString("{{{returnBaseType}}}"))); + {{/returnTypeIsPrimitive}} + {{/isMapContainer}} + {{/isListContainer}}{{/returnType}} + + worker->deleteLater(); + + {{#returnType}}emit {{nickname}}Signal(output);{{/returnType}} + {{^returnType}}emit {{nickname}}Signal();{{/returnType}} +} +{{/operation}} +{{/operations}} +} /* namespace Swagger */ diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/api-header.mustache b/modules/swagger-codegen/src/main/resources/qt5cpp/api-header.mustache new file mode 100644 index 000000000000..4260ba6ff865 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/api-header.mustache @@ -0,0 +1,34 @@ +#ifndef _SWG_{{classname}}_H_ +#define _SWG_{{classname}}_H_ + +#include "{{prefix}}HttpRequest.h" + +{{#imports}}{{{import}}} +{{/imports}} + +#include + +namespace Swagger { + +class {{classname}}: public QObject { + Q_OBJECT + +public: + {{classname}}(); + {{classname}}(QString host, QString basePath); + ~{{classname}}(); + + QString host; + QString basePath; + + {{#operations}}{{#operation}}void {{nickname}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{/operation}}{{/operations}} +private: + {{#operations}}{{#operation}}void {{nickname}}Callback (HttpRequestWorker * worker); + {{/operation}}{{/operations}} +signals: + {{#operations}}{{#operation}}void {{nickname}}Signal({{#returnType}}{{{returnType}}} summary{{/returnType}}); + {{/operation}}{{/operations}} +}; +} +#endif \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-body.mustache b/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-body.mustache new file mode 100644 index 000000000000..7f4d748c2dce --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-body.mustache @@ -0,0 +1,166 @@ +#include "SWGHelpers.h" +#include "SWGModelFactory.h" +#include "SWGObject.h" +#import +#import +#import + +namespace Swagger { + +void +setValue(void* value, QJsonValue obj, QString type, QString complexType) { + if(value == NULL) { + // can't set value with a null pointer + return; + } + if(QStringLiteral("bool").compare(type) == 0) { + bool * val = static_cast(value); + *val = obj.toBool(); + } + else if(QStringLiteral("qint32").compare(type) == 0) { + qint32 *val = static_cast(value); + *val = obj.toInt(); + } + else if(QStringLiteral("qint64").compare(type) == 0) { + qint64 *val = static_cast(value); + *val = obj.toVariant().toLongLong(); + } + else if (QStringLiteral("QString").compare(type) == 0) { + QString **val = static_cast(value); + + if(val != NULL) { + if(!obj.isNull()) { + // create a new value and return + delete *val; + *val = new QString(obj.toString()); + return; + } + else { + // set target to NULL + delete *val; + *val = NULL; + } + } + else { + qDebug() << "Can't set value because the target pointer is NULL"; + } + } + else if(type.startsWith("SWG") && obj.isObject()) { + // complex type + QJsonObject jsonObj = obj.toObject(); + SWGObject * so = (SWGObject*)Swagger::create(type); + if(so != NULL) { + so->fromJsonObject(jsonObj); + SWGObject **val = static_cast(value); + delete *val; + *val = so; + } + } + else if(type.startsWith("QList") && QString("").compare(complexType) != 0 && obj.isArray()) { + // list of values + QList* output = new QList(); + QJsonArray arr = obj.toArray(); + foreach (const QJsonValue & jval, arr) { + if(complexType.startsWith("SWG")) { + // it's an object + SWGObject * val = (SWGObject*)create(complexType); + QJsonObject t = jval.toObject(); + + val->fromJsonObject(t); + output->append(val); + } + else { + // primitives + if(QStringLiteral("qint32").compare(complexType) == 0) { + qint32 val; + setValue(&val, jval, QStringLiteral("qint32"), QStringLiteral("")); + output->append((void*)&val); + } + else if(QStringLiteral("qint64").compare(complexType) == 0) { + qint64 val; + setValue(&val, jval, QStringLiteral("qint64"), QStringLiteral("")); + output->append((void*)&val); + } + else if(QStringLiteral("bool").compare(complexType) == 0) { + bool val; + setValue(&val, jval, QStringLiteral("bool"), QStringLiteral("")); + output->append((void*)&val); + } + } + } + QList **val = static_cast**>(value); + delete *val; + *val = output; + } +} + +void +toJsonValue(QString name, void* value, QJsonObject* output, QString type) { + if(value == NULL) { + return; + } + if(type.startsWith("SWG")) { + SWGObject *swgObject = reinterpret_cast(value); + if(swgObject != NULL) { + QJsonObject* o = (*swgObject).asJsonObject(); + if(name != NULL) { + output->insert(name, *o); + delete o; + } + else { + output->empty(); + foreach(QString key, o->keys()) { + output->insert(key, o->value(key)); + } + } + } + } + else if(QStringLiteral("QString").compare(type) == 0) { + QString* str = static_cast(value); + output->insert(name, QJsonValue(*str)); + } + else if(QStringLiteral("qint32").compare(type) == 0) { + qint32* str = static_cast(value); + output->insert(name, QJsonValue(*str)); + } + else if(QStringLiteral("qint64").compare(type) == 0) { + qint64* str = static_cast(value); + output->insert(name, QJsonValue(*str)); + } + else if(QStringLiteral("bool").compare(type) == 0) { + bool* str = static_cast(value); + output->insert(name, QJsonValue(*str)); + } +} + +void +toJsonArray(QList* value, QJsonArray* output, QString innerName, QString innerType) { + foreach(void* obj, *value) { + QJsonObject element; + + toJsonValue(NULL, obj, &element, innerType); + output->append(element); + } +} + +QString +stringValue(QString* value) { + QString* str = static_cast(value); + return QString(*str); +} + +QString +stringValue(qint32 value) { + return QString::number(value); +} + +QString +stringValue(qint64 value) { + return QString::number(value); +} + +QString +stringValue(bool value) { + return QString(value ? "true" : "false"); +} +} /* namespace Swagger */ diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-header.mustache b/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-header.mustache new file mode 100644 index 000000000000..3a02c0952d55 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-header.mustache @@ -0,0 +1,17 @@ +#ifndef SWGHELPERS_H +#define SWGHELPERS_H + +#include + +namespace Swagger { + void setValue(void* value, QJsonValue obj, QString type, QString complexType); + void toJsonArray(QList* value, QJsonArray* output, QString innerName, QString innerType); + void toJsonValue(QString name, void* value, QJsonObject* output, QString type); + bool isCompatibleJsonValue(QString type); + QString stringValue(QString* value); + QString stringValue(qint32 value); + QString stringValue(qint64 value); + QString stringValue(bool value); +} + +#endif // SWGHELPERS_H diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/model-body.mustache b/modules/swagger-codegen/src/main/resources/qt5cpp/model-body.mustache new file mode 100644 index 000000000000..705cb8521086 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/model-body.mustache @@ -0,0 +1,109 @@ +{{#models}}{{#model}} +#include "{{classname}}.h" + +#include "SWGHelpers.h" + +#include +#include +#include +#include + +namespace Swagger { + + +{{classname}}::{{classname}}(QString* json) { + init(); + this->fromJson(*json); +} + +{{classname}}::{{classname}}() { + init(); +} + +{{classname}}::~{{classname}}() { + this->cleanup(); +} + +void +{{classname}}::init() { + {{#vars}}{{name}} = {{{defaultValue}}}; + {{/vars}} +} + +void +{{classname}}::cleanup() { + {{#vars}}{{#complexType}}if({{name}} != NULL) { + {{#isContainer}}QList<{{complexType}}*>* arr = {{name}}; + foreach({{complexType}}* o, *arr) { + delete o; + } + {{/isContainer}}delete {{name}}; + }{{/complexType}} + {{/vars}} +} + +{{classname}}* +{{classname}}::fromJson(QString &json) { + QByteArray array (json.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); + return this; +} + +void +{{classname}}::fromJsonObject(QJsonObject &pJson) { + {{#vars}}setValue(&{{name}}, pJson["{{name}}"], "{{baseType}}", "{{complexType}}"); + {{/vars}} +} + +QString +{{classname}}::asJson () +{ + QJsonObject* obj = this->asJsonObject(); + + QJsonDocument doc(*obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject* +{{classname}}::asJsonObject() { + QJsonObject* obj = new QJsonObject(); + {{#vars}}{{#complexType}} + {{^isContainer}}{{#complexType}} + toJsonValue(QString("{{name}}"), {{name}}, obj, QString("{{complexType}}")); + {{/complexType}}{{^complexType}} + else if({{name}} != NULL && *{{name}} != NULL) { + obj->insert("{{name}}", QJsonValue(*{{name}})); + }{{/complexType}} + {{/isContainer}}{{#isContainer}} + QList<{{complexType}}*>* {{name}}List = {{name}}; + QJsonArray {{name}}JsonArray; + toJsonArray((QList*){{name}}, &{{name}}JsonArray, "{{name}}", "{{complexType}}"); + + obj->insert("{{name}}", {{name}}JsonArray); + {{/isContainer}} + {{/complexType}}{{^complexType}}obj->insert("{{name}}", QJsonValue({{name}}));{{/complexType}} + {{/vars}} + + return obj; +} + +{{#vars}} +{{{datatype}}} +{{classname}}::{{getter}}() { + return {{name}}; +} +void +{{classname}}::{{setter}}({{{datatype}}} {{name}}) { + this->{{name}} = {{name}}; +} + +{{/vars}} + + +} /* namespace Swagger */ + +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/model-header.mustache b/modules/swagger-codegen/src/main/resources/qt5cpp/model-header.mustache new file mode 100644 index 000000000000..7b0b6cdcc1b1 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/model-header.mustache @@ -0,0 +1,47 @@ +{{#models}}{{#model}}/* + * {{classname}}.h + * + * {{description}} + */ + +#ifndef {{classname}}_H_ +#define {{classname}}_H_ + +#include + +{{/model}}{{/models}} +{{#imports}}{{{import}}} +{{/imports}} + +#include "SWGObject.h" + +{{#models}}{{#model}} +namespace Swagger { + +class {{classname}}: public SWGObject { +public: + {{classname}}(); + {{classname}}(QString* json); + virtual ~{{classname}}(); + void init(); + void cleanup(); + + QString asJson (); + QJsonObject* asJsonObject(); + void fromJsonObject(QJsonObject &json); + {{classname}}* fromJson(QString &jsonString); + + {{#vars}}{{{datatype}}} {{getter}}(); + void {{setter}}({{{datatype}}} {{name}}); + {{/vars}} + +private: + {{#vars}}{{{datatype}}} {{name}}; + {{/vars}} +}; + +} /* namespace Swagger */ + +#endif /* {{classname}}_H_ */ +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/model.mustache b/modules/swagger-codegen/src/main/resources/qt5cpp/model.mustache new file mode 100644 index 000000000000..1a2a831f5ac2 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/model.mustache @@ -0,0 +1,58 @@ +{{#models}}{{#model}}/* + * {{classname}}.h + * + * {{description}} + */ + +#ifndef {{classname}}_H_ +#define {{classname}}_H_ + +#include +#include +#include +#include +#include "{{prefix}}Helpers.h" +#include "{{prefix}}Object.h" + +using namespace Tizen::Web::Json; + +{{/model}}{{/models}} +{{#imports}}{{{import}}} +{{/imports}} + +{{#models}}{{#model}} +namespace Swagger { + +class {{classname}}: public {{prefix}}Object { +public: + {{classname}}(); + {{classname}}(String* json); + virtual ~{{classname}}(); + + void init(); + + void cleanup(); + + String asJson (); + + JsonObject* asJsonObject(); + + void fromJsonObject(IJsonValue* json); + + {{classname}}* fromJson(String* obj); + + {{#vars}} + {{datatype}} {{getter}}(); + void {{setter}}({{datatype}} {{name}}); + {{/vars}} + +private: + {{#vars}}{{datatype}} {{name}}; + {{/vars}} +}; + +} /* namespace Swagger */ + +#endif /* {{classname}}_H_ */ +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/modelFactory.mustache b/modules/swagger-codegen/src/main/resources/qt5cpp/modelFactory.mustache new file mode 100644 index 000000000000..4ec9e6f74113 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/modelFactory.mustache @@ -0,0 +1,29 @@ +#ifndef ModelFactory_H_ +#define ModelFactory_H_ + +{{#models}}{{#model}} +#include "{{classname}}.h"{{/model}}{{/models}} + +namespace Swagger { + inline void* create(QString type) { + {{#models}}{{#model}}if(QString("{{classname}}").compare(type) == 0) { + return new {{classname}}(); + } + {{/model}}{{/models}} + return NULL; + } + + inline void* create(QString json, QString type) { + void* val = create(type); + if(val != NULL) { + SWGObject* obj = static_cast(val); + return obj->fromJson(json); + } + if(type.startsWith("QString")) { + return new QString(); + } + return NULL; + } +} /* namespace Swagger */ + +#endif /* ModelFactory_H_ */ diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/object.mustache b/modules/swagger-codegen/src/main/resources/qt5cpp/object.mustache new file mode 100644 index 000000000000..62914cb51626 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/object.mustache @@ -0,0 +1,24 @@ +#ifndef _{{prefix}}_OBJECT_H_ +#define _{{prefix}}_OBJECT_H_ + +#include + +class {{prefix}}Object { + public: + virtual QJsonObject* asJsonObject() { + return NULL; + } + virtual ~SWGObject() {} + virtual SWGObject* fromJson(QString &jsonString) { + Q_UNUSED(jsonString); + return NULL; + } + virtual void fromJsonObject(QJsonObject &json) { + Q_UNUSED(json); + } + virtual QString asJson() { + return QString(""); + } +}; + +#endif /* _{{prefix}}_OBJECT_H_ */ diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index 5b0d37322832..ba38a8157b55 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -1,72 +1,59 @@ require "uri" +module {{moduleName}} {{#operations}} -class {{classname}} - basePath = "{{basePath}}" - # apiInvoker = APIInvoker + class {{classname}} + basePath = "{{basePath}}" + # apiInvoker = APIInvoker {{#operation}} {{newline}} - # {{summary}} - # {{notes}} -{{#allParams}}{{#required}} # @param {{paramName}} {{description}} -{{/required}}{{/allParams}} # @param [Hash] opts the optional parameters -{{#allParams}}{{^required}} # @option opts [{{dataType}}] :{{paramName}} {{description}} -{{/required}}{{/allParams}} # @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} - def self.{{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {}) - # verify existence of params{{#allParams}}{{#required}} - raise "{{{paramName}}} is required" if {{{paramName}}}.nil?{{/required}}{{/allParams}} + # {{summary}} + # {{notes}} +{{#allParams}}{{#required}} # @param {{paramName}} {{description}} +{{/required}}{{/allParams}} # @param [Hash] opts the optional parameters +{{#allParams}}{{^required}} # @option opts [{{dataType}}] :{{paramName}} {{description}} +{{/required}}{{/allParams}} # @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} + def self.{{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {}) + {{#allParams}}{{#required}} + # verify the required parameter '{{paramName}}' is set + raise "Missing the required parameter '{{paramName}}' when calling {{nickname}}" if {{{paramName}}}.nil? + {{/required}}{{/allParams}} - # resource path - path = "{{path}}".sub('{format}','json'){{#pathParams}}.sub('{' + '{{baseName}}' + '}', {{paramName}}.to_s){{/pathParams}} + # resource path + path = "{{path}}".sub('{format}','json'){{#pathParams}}.sub('{' + '{{baseName}}' + '}', {{paramName}}.to_s){{/pathParams}} - # query parameters - query_params = {}{{#queryParams}}{{#required}} - query_params[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/queryParams}}{{#queryParams}}{{^required}} - query_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/queryParams}} + # query parameters + query_params = {}{{#queryParams}}{{#required}} + query_params[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/queryParams}}{{#queryParams}}{{^required}} + query_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/queryParams}} - # header parameters - header_params = {} + # header parameters + header_params = {} - _header_accept = '{{#produces}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/produces}}' - header_params['Accept'] = _header_accept if _header_accept != '' + # HTTP header 'Accept' (if needed) + _header_accept = [{{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - _header_content_type = [{{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json'{{#headerParams}}{{#required}} - header_params[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/headerParams}}{{#headerParams}}{{^required}} - header_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/headerParams}} + # HTTP header 'Content-Type' + _header_content_type = [{{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type){{#headerParams}}{{#required}} + header_params[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/headerParams}}{{#headerParams}}{{^required}} + header_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/headerParams}} - # form parameters - form_params = {}{{#formParams}}{{#required}} - form_params["{{baseName}}"] = {{paramName}}{{/required}}{{/formParams}}{{#formParams}}{{^required}} - form_params["{{baseName}}"] = opts[:'{{paramName}}'] if opts[:'{{paramName}}']{{/required}}{{/formParams}} + # form parameters + form_params = {}{{#formParams}}{{#required}} + form_params["{{baseName}}"] = {{paramName}}{{/required}}{{/formParams}}{{#formParams}}{{^required}} + form_params["{{baseName}}"] = opts[:'{{paramName}}'] if opts[:'{{paramName}}']{{/required}}{{/formParams}} - # http body (model) - post_body = nil{{#bodyParam}} - _body_param = {{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}} - if _body_param != nil - if _body_param.is_a?(Array) - _array = Array.new - _body_param.each do |item| - if item.respond_to?(:to_body) - _array.push item.to_body - else - _array.push item - end - end - post_body = _array - else - if _body_param.respond_to?(:to_body) - post_body = _body_param.to_body - else - post_body = _body_param - end - end - end{{/bodyParam}} + # http body (model) + {{^bodyParam}}post_body = nil + {{/bodyParam}}{{#bodyParam}}post_body = Swagger::Request.object_to_http_body({{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}}) + {{/bodyParam}} -{{#returnType}} - response = Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body - {{#returnContainer}}response.map {|response| {{/returnContainer}}{{returnBaseType}}.new(response){{#returnContainer}} }{{/returnContainer}}{{/returnType}}{{^returnType}} Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make{{/returnType}} + {{#returnType}}response = Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body + {{#returnContainer}}response.map {|response| {{/returnContainer}}obj = {{returnBaseType}}.new() and obj.build_from_hash(response){{#returnContainer}} }{{/returnContainer}}{{/returnType}}{{^returnType}} Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make{{/returnType}} end {{/operation}} -end + end {{/operations}} +end diff --git a/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache new file mode 100644 index 000000000000..c0e563a0bb72 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache @@ -0,0 +1,83 @@ +module {{moduleName}} + # base class containing fundamental method such as to_hash, build_from_hash and more + class BaseObject + + # return the object in the form of hash + def to_body + body = {} + self.class.attribute_map.each_pair do |key, value| + body[value] = self.send(key) unless self.send(key).nil? + end + body + end + + # build the object from hash + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.swagger_types.each_pair do |key, type| + if type =~ /^array\[(.*)\]/i + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) + else + #TODO show warning in debug mode + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + else + # data not found in attributes(hash), not an issue as the data can be optional + end + end + + self + end + + def _deserialize(type, value) + case type.to_sym + when :DateTime + DateTime.parse(value) + when :string + value.to_s + when :int + value.to_i + when :double + value.to_f + when :boolean + if value =~ /^(true|t|yes|y|1)$/i + true + else + false + end + else # model + _model = {{moduleName}}.const_get(type).new + _model.build_from_hash(value) + end + end + + # to_body is an alias to to_body (backward compatibility) + def to_hash + hash = {} + self.class.attribute_map.each_pair do |key, value| + if self.send(key).is_a?(Array) + next if self.send(key).empty? + hash[value] = self.send(key).select{|v| !v.nil?}.map{ |v| _to_hash v} unless self.send(key).nil? + else + unless (_tmp_value = _to_hash self.send(key)).nil? + hash[value] = _tmp_value + end + end + end + hash + end + + # Method to output non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + def _to_hash(value) + if value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end +end diff --git a/modules/swagger-codegen/src/main/resources/ruby/model.mustache b/modules/swagger-codegen/src/main/resources/ruby/model.mustache index 397a64f6471f..d0d4e7877564 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/model.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/model.mustache @@ -1,35 +1,40 @@ -{{#models}} +module {{moduleName}} +{{#models}} # {{description}} +{{#model}} class {{classname}} < BaseObject + attr_accessor {{#vars}}:{{{name}}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{newline}} + # attribute mapping from ruby-style variable name to JSON key + def self.attribute_map + { + {{#vars}} + # {{description}} + :'{{{name}}}' => :'{{{baseName}}}'{{#hasMore}},{{/hasMore}} + {{/vars}} + } + end -{{#model}} -class {{classname}} - attr_accessor {{#vars}}:{{{name}}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{newline}} - # :internal => :external - def self.attribute_map - { - {{#vars}}:{{{name}}} => :'{{{baseName}}}'{{#hasMore}},{{/hasMore}} + # attribute type + def self.swagger_types + { + {{#vars}}:'{{{name}}}' => :'{{{datatype}}}'{{#hasMore}},{{/hasMore}} + {{/vars}} + } + end + + def initialize(attributes = {}) + return if !attributes.is_a?(Hash) || attributes.empty? + + # convert string to symbol for hash key + attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} + + {{#vars}} + if attributes[:'{{{baseName}}}'] + {{#isContainer}}if (value = attributes[:'{{{baseName}}}']).is_a?(Array) + @{{{name}}} = value + end{{/isContainer}}{{^isContainer}}@{{{name}}} = attributes[:'{{{baseName}}}']{{/isContainer}} + end {{/vars}} - } - end - - def initialize(attributes = {}) - return if attributes.empty? - # Morph attribute keys into undescored rubyish style - {{#vars}} - if self.class.attribute_map[:"{{{name}}}"] - {{#isContainer}}if (value = attributes["{{{baseName}}}"]).is_a?(Array) - @{{{name}}} = value{{#complexType}}.map{ |v| {{complexType}}.new(v) }{{/complexType}} - end{{/isContainer}}{{^isContainer}}@{{{name}}} = attributes["{{{baseName}}}"]{{/isContainer}} end - {{/vars}} end - - def to_body - body = {} - self.class.attribute_map.each_pair do |key, value| - body[value] = self.send(key) unless self.send(key).nil? - end - body - end -end {{/model}} {{/models}} +end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger-client.gemspec.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger-client.gemspec.mustache deleted file mode 100644 index c002e581b8b6..000000000000 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger-client.gemspec.mustache +++ /dev/null @@ -1,33 +0,0 @@ -# -*- encoding: utf-8 -*- -$:.push File.expand_path("../lib", __FILE__) -require "swagger/version" - -Gem::Specification.new do |s| - s.name = "{{artifactId}}" - s.version = Swagger::VERSION - s.platform = Gem::Platform::RUBY - s.authors = ["Zeke Sikelianos", "Tony Tam"] - s.email = ["zeke@wordnik.com", "tony@wordnik.com"] - s.homepage = "http://developer.wordnik.com" - s.summary = %q{A ruby wrapper for the swagger APIs} - s.description = %q{This gem maps to a swagger API} - - s.rubyforge_project = "{{artifactId}}" - - s.add_dependency 'typhoeus', '>=0.2.1' - s.add_dependency 'addressable', '>=2.2.4' - s.add_dependency 'json', '>=1.4.6' - - s.add_development_dependency 'rspec', '>=2.5.0' - s.add_development_dependency 'vcr', '>=1.5.1' - s.add_development_dependency 'webmock', '>=1.6.2' - s.add_development_dependency 'autotest' - s.add_development_dependency 'autotest-rails-pure' - s.add_development_dependency 'autotest-growl' - s.add_development_dependency 'autotest-fsevent' - - s.files = `find *`.split("\n").uniq.sort.select{|f| !f.empty? } - s.test_files = `find spec/*`.split("\n") - s.executables = [] - s.require_paths = ["lib"] -end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger-client.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger-client.mustache deleted file mode 100644 index b13f83b1dbcf..000000000000 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger-client.mustache +++ /dev/null @@ -1,5 +0,0 @@ -require 'monkey' -require 'swagger' - -Dir[File.join(File.dirname(__FILE__), "../lib/*.rb")].each {|file| require file if file !~ /swagger-client\.rb\z/ } -Dir[File.join(File.dirname(__FILE__), "../models/*.rb")].each {|file| require file } diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache index fff098e96fcc..750e6ac5155d 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache @@ -1,85 +1,78 @@ -require 'monkey' -require 'swagger/configuration' -require 'swagger/request' -require 'swagger/response' -require 'swagger/version' require 'logger' +require 'json' -module Swagger - - @configuration = Configuration.new +module {{moduleName}} + module Swagger + class << self + attr_accessor :logger - class << self - attr_accessor :logger - - # A Swagger configuration object. Must act like a hash and return sensible - # values for all Swagger configuration options. See Swagger::Configuration. - attr_accessor :configuration + # A Swagger configuration object. Must act like a hash and return sensible + # values for all Swagger configuration options. See Swagger::Configuration. + attr_accessor :configuration - attr_accessor :resources - - # Call this method to modify defaults in your initializers. - # - # @example - # Swagger.configure do |config| - # config.api_key = '1234567890abcdef' # required - # config.username = 'wordlover' # optional, but needed for user-related functions - # config.password = 'i<3words' # optional, but needed for user-related functions - # config.format = 'json' # optional, defaults to 'json' - # end - # - def configure - yield(configuration) if block_given? + attr_accessor :resources - # Configure logger. Default to use Rails - self.logger ||= configuration.logger || (defined?(Rails) ? Rails.logger : Logger.new(STDOUT)) + # Call this method to modify defaults in your initializers. + # + # @example + # Swagger.configure do |config| + # config.api_key = '1234567890abcdef' # required + # config.username = 'wordlover' # optional, but needed for user-related functions + # config.password = 'i<3words' # optional, but needed for user-related functions + # config.format = 'json' # optional, defaults to 'json' + # end + # + def configure + yield(configuration) if block_given? - # remove :// from scheme - configuration.scheme.sub!(/:\/\//, '') + # Configure logger. Default to use Rails + self.logger ||= configuration.logger || (defined?(Rails) ? Rails.logger : Logger.new(STDOUT)) - # remove http(s):// and anything after a slash - configuration.host.sub!(/https?:\/\//, '') - configuration.host = configuration.host.split('/').first + # remove :// from scheme + configuration.scheme.sub!(/:\/\//, '') - # Add leading and trailing slashes to base_path - configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/') - configuration.base_path = "" if configuration.base_path == "/" - end - - def authenticated? - Swagger.configuration.auth_token.present? - end - - def de_authenticate - Swagger.configuration.auth_token = nil - end - - def authenticate - return if Swagger.authenticated? - - if Swagger.configuration.username.blank? || Swagger.configuration.password.blank? - raise ClientError, "Username and password are required to authenticate." + # remove http(s):// and anything after a slash + configuration.host.sub!(/https?:\/\//, '') + configuration.host = configuration.host.split('/').first + + # Add leading and trailing slashes to base_path + configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/') + configuration.base_path = "" if configuration.base_path == "/" + end + + def authenticated? + Swagger.configuration.auth_token.present? + end + + def de_authenticate + Swagger.configuration.auth_token = nil + end + + def authenticate + return if Swagger.authenticated? + + if Swagger.configuration.username.blank? || Swagger.configuration.password.blank? + raise ClientError, "Username and password are required to authenticate." + end + + request = Swagger::Request.new( + :get, + "account/authenticate/{username}", + :params => { + :username => Swagger.configuration.username, + :password => Swagger.configuration.password + } + ) + + response_body = request.response.body + Swagger.configuration.auth_token = response_body['token'] end - - request = Swagger::Request.new( - :get, - "account/authenticate/{username}", - :params => { - :username => Swagger.configuration.username, - :password => Swagger.configuration.password - } - ) - - response_body = request.response.body - Swagger.configuration.auth_token = response_body['token'] end - end - -end -class ServerError < StandardError -end + class ServerError < StandardError + end -class ClientError < StandardError -end \ No newline at end of file + class ClientError < StandardError + end +end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache index d27109aa445b..e780a9c8e7df 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache @@ -1,22 +1,19 @@ -module Swagger - - class Configuration - require 'swagger/version' +module {{moduleName}} + module Swagger + class Configuration + attr_accessor :format, :api_key, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params, :user_agent - attr_accessor :format, :api_key, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params, :user_agent - - # Defaults go in here.. - def initialize - @format = 'json' - @scheme = '{{scheme}}' - @host = '{{host}}' - @base_path = '{{contextPath}}' - @user_agent = "ruby-swagger-#{Swagger::VERSION}" - @inject_format = false - @force_ending_format = false - @camelize_params = true + # Defaults go in here.. + def initialize + @format = 'json' + @scheme = '{{scheme}}' + @host = '{{host}}' + @base_path = '{{contextPath}}' + @user_agent = "ruby-swagger-#{Swagger::VERSION}" + @inject_format = false + @force_ending_format = false + @camelize_params = true + end end - end - end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache index fbd70eeb9f54..14718bb6b3c3 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache @@ -1,212 +1,257 @@ -module Swagger +module {{moduleName}} + module Swagger + class Request + require 'uri' + require 'addressable/uri' + require 'typhoeus' - class Request - require 'uri' - require 'addressable/uri' - require 'typhoeus' - require "swagger/version" + attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params - attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params + # All requests must have an HTTP method and a path + # Optionals parameters are :params, :headers, :body, :format, :host + def initialize(http_method, path, attributes={}) + attributes[:format] ||= Swagger.configuration.format + attributes[:params] ||= {} + # Set default headers + default_headers = { + 'Content-Type' => "application/#{attributes[:format].downcase}", + :api_key => Swagger.configuration.api_key, + 'User-Agent' => Swagger.configuration.user_agent + } - # All requests must have an HTTP method and a path - # Optionals parameters are :params, :headers, :body, :format, :host - # - def initialize(http_method, path, attributes={}) - attributes[:format] ||= Swagger.configuration.format - attributes[:params] ||= {} + # api_key from headers hash trumps the default, even if its value is blank + if attributes[:headers].present? && attributes[:headers].has_key?(:api_key) + default_headers.delete(:api_key) + end - # Set default headers - default_headers = { - 'Content-Type' => "application/#{attributes[:format].downcase}", - :api_key => Swagger.configuration.api_key, - 'User-Agent' => Swagger.configuration.user_agent - } + # api_key from params hash trumps all others (headers and default_headers) + if attributes[:params].present? && attributes[:params].has_key?(:api_key) + default_headers.delete(:api_key) + attributes[:headers].delete(:api_key) if attributes[:headers].present? + end - # api_key from headers hash trumps the default, even if its value is blank - if attributes[:headers].present? && attributes[:headers].has_key?(:api_key) - default_headers.delete(:api_key) - end - - # api_key from params hash trumps all others (headers and default_headers) - if attributes[:params].present? && attributes[:params].has_key?(:api_key) - default_headers.delete(:api_key) - attributes[:headers].delete(:api_key) if attributes[:headers].present? - end - - # Merge argument headers into defaults - attributes[:headers] = default_headers.merge(attributes[:headers] || {}) - - # Stick in the auth token if there is one - if Swagger.authenticated? - attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token}) - end - - self.http_method = http_method.to_sym - self.path = path - attributes.each do |name, value| - send("#{name.to_s.underscore.to_sym}=", value) - end - end + # Merge argument headers into defaults + attributes[:headers] = default_headers.merge(attributes[:headers] || {}) - # Construct a base URL - # - def url(options = {}) - u = Addressable::URI.new( - :scheme => Swagger.configuration.scheme, - :host => Swagger.configuration.host, - :path => self.interpreted_path, - :query => self.query_string.sub(/\?/, '') - ).to_s - - # Drop trailing question mark, if present - u.sub! /\?$/, '' - - # Obfuscate API key? - u.sub! /api\_key=\w+/, 'api_key=YOUR_API_KEY' if options[:obfuscated] - - u - end + # Stick in the auth token if there is one + if Swagger.authenticated? + attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token}) + end - # Iterate over the params hash, injecting any path values into the path string - # - # e.g. /word.{format}/{word}/entries => /word.json/cat/entries - def interpreted_path - p = self.path.dup - - # Stick a .{format} placeholder into the path if there isn't - # one already or an actual format like json or xml - # e.g. /words/blah => /words.{format}/blah - if Swagger.configuration.inject_format - unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } - p = p.sub(/^(\/?\w+)/, "\\1.#{format}") + self.http_method = http_method.to_sym + self.path = path + attributes.each do |name, value| + send("#{name.to_s.underscore.to_sym}=", value) end end - # Stick a .{format} placeholder on the end of the path if there isn't - # one already or an actual format like json or xml - # e.g. /words/blah => /words/blah.{format} - if Swagger.configuration.force_ending_format - unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } - p = "#{p}.#{format}" + # Construct a base URL + def url(options = {}) + u = Addressable::URI.new( + :scheme => Swagger.configuration.scheme, + :host => Swagger.configuration.host, + :path => self.interpreted_path, + :query => self.query_string.sub(/\?/, '') + ).to_s + + # Drop trailing question mark, if present + u.sub! /\?$/, '' + + # Obfuscate API key? + u.sub! /api\_key=\w+/, 'api_key=YOUR_API_KEY' if options[:obfuscated] + + u + end + + # Iterate over the params hash, injecting any path values into the path string + # e.g. /word.{format}/{word}/entries => /word.json/cat/entries + def interpreted_path + p = self.path.dup + + # Stick a .{format} placeholder into the path if there isn't + # one already or an actual format like json or xml + # e.g. /words/blah => /words.{format}/blah + if Swagger.configuration.inject_format + unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } + p = p.sub(/^(\/?\w+)/, "\\1.#{format}") + end + end + + # Stick a .{format} placeholder on the end of the path if there isn't + # one already or an actual format like json or xml + # e.g. /words/blah => /words/blah.{format} + if Swagger.configuration.force_ending_format + unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } + p = "#{p}.#{format}" + end + end + + p = p.sub("{format}", self.format.to_s) + + URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/') + end + + # Massage the request body into a state of readiness + # If body is a hash, camelize all keys then convert to a json string + def body=(value) + if value.is_a?(Hash) + value = value.inject({}) do |memo, (k,v)| + memo[k.to_s.camelize(:lower).to_sym] = v + memo + end + end + @body = value + end + + # If body is an object, JSONify it before making the actual request. + # For form parameters, remove empty value + def outgoing_body + # http form + if @body.nil? && @form_params && !@form_params.empty? + data = form_params.dup + data.each do |key, value| + data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter + end + data + else # http body is JSON + @body.is_a?(String) ? @body : @body.to_json end end - p = p.sub("{format}", self.format.to_s) - - URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/') - end - - # Massage the request body into a state of readiness - # If body is a hash, camelize all keys then convert to a json string - # - def body=(value) - if value.is_a?(Hash) - value = value.inject({}) do |memo, (k,v)| - memo[k.to_s.camelize(:lower).to_sym] = v - memo + # Construct a query string from the query-string-type params + def query_string + # Iterate over all params, + # .. removing the ones that are part of the path itself. + # .. stringifying values so Addressable doesn't blow up. + query_values = {} + self.params.each_pair do |key, value| + next if self.path.include? "{#{key}}" # skip path params + next if value.blank? && value.class != FalseClass # skip empties + if Swagger.configuration.camelize_params + key = key.to_s.camelize(:lower).to_sym unless key.to_sym == :api_key # api_key is not a camelCased param + end + query_values[key] = value.to_s + end + + # We don't want to end up with '?' as our query string + # if there aren't really any params + return "" if query_values.blank? + + # Addressable requires query_values to be set after initialization.. + qs = Addressable::URI.new + qs.query_values = query_values + qs.to_s + end + + def make + #TODO use configuration setting to determine if debugging + #logger = Logger.new STDOUT + #logger.debug self.url + response = case self.http_method.to_sym + when :get,:GET + Typhoeus::Request.get( + self.url, + :headers => self.headers.stringify_keys, + ) + + when :post,:POST + Typhoeus::Request.post( + self.url, + :body => self.outgoing_body, + :headers => self.headers.stringify_keys, + ) + + when :patch,:PATCH + Typhoeus::Request.patch( + self.url, + :body => self.outgoing_body, + :headers => self.headers.stringify_keys, + ) + + when :put,:PUT + Typhoeus::Request.put( + self.url, + :body => self.outgoing_body, + :headers => self.headers.stringify_keys, + ) + + when :delete,:DELETE + Typhoeus::Request.delete( + self.url, + :body => self.outgoing_body, + :headers => self.headers.stringify_keys, + ) + end + Response.new(response) + end + + def response + self.make + end + + def response_code_pretty + return unless @response.present? + @response.code.to_s + end + + def response_headers_pretty + return unless @response.present? + # JSON.pretty_generate(@response.headers).gsub(/\n/, '
') # <- This was for RestClient + @response.headers.gsub(/\n/, '
') # <- This is for Typhoeus + end + + # return 'Accept' based on an array of accept provided + # @param [Array] header_accept_array Array fo 'Accept' + # @return String Accept (e.g. application/json) + def self.select_header_accept header_accept_array + if header_accept_array.empty? + return + elsif header_accept_array.any?{ |s| s.casecmp('application/json')==0 } + 'application/json' # look for json data by default + else + header_accept_array.join(',') end end - @body = value - end - - # If body is an object, JSONify it before making the actual request. - # For form parameters, remove empty value - def outgoing_body - # http form - if @body.nil? && @form_params && !@form_params.empty? - data = form_params.dup - data.each do |key, value| - data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter + + # return the content type based on an array of content-type provided + # @param [Array] content_type_array Array fo content-type + # @return String Content-Type (e.g. application/json) + def self.select_header_content_type content_type_array + if content_type_array.empty? + 'application/json' # use application/json by default + elsif content_type_array.any?{ |s| s.casecmp('application/json')==0 } + 'application/json' # use application/json if it's included + else + content_type_array[0]; # otherwise, use the first one end - data - else # http body is JSON - @body.is_a?(String) ? @body : @body.to_json end - end - - # Construct a query string from the query-string-type params - def query_string - # Iterate over all params, - # .. removing the ones that are part of the path itself. - # .. stringifying values so Addressable doesn't blow up. - query_values = {} - self.params.each_pair do |key, value| - next if self.path.include? "{#{key}}" # skip path params - next if value.blank? && value.class != FalseClass # skip empties - if Swagger.configuration.camelize_params - key = key.to_s.camelize(:lower).to_sym unless key.to_sym == :api_key # api_key is not a camelCased param + # static method to convert object (array, hash, object, etc) to JSON string + # @param model object to be converted into JSON string + # @return string JSON string representation of the object + def self.object_to_http_body model + return if model.nil? + _body = nil + if model.is_a?(Array) + _body = model.map{|m| object_to_hash(m) } + else + _body = object_to_hash(model) end - query_values[key] = value.to_s + _body.to_json end - - # We don't want to end up with '?' as our query string - # if there aren't really any params - return "" if query_values.blank? - - # Addressable requires query_values to be set after initialization.. - qs = Addressable::URI.new - qs.query_values = query_values - qs.to_s - end - - def make - #TODO use configuration setting to determine if debugging - #logger = Logger.new STDOUT - #logger.debug self.url - response = case self.http_method.to_sym - when :get,:GET - Typhoeus::Request.get( - self.url, - :headers => self.headers.stringify_keys, - ) - when :post,:POST - Typhoeus::Request.post( - self.url, - :body => self.outgoing_body, - :headers => self.headers.stringify_keys, - ) - - when :patch,:PATCH - Typhoeus::Request.patch( - self.url, - :body => self.outgoing_body, - :headers => self.headers.stringify_keys, - ) - - when :put,:PUT - Typhoeus::Request.put( - self.url, - :body => self.outgoing_body, - :headers => self.headers.stringify_keys, - ) - - when :delete,:DELETE - Typhoeus::Request.delete( - self.url, - :body => self.outgoing_body, - :headers => self.headers.stringify_keys, - ) + # static method to convert object(non-array) to hash + # @param obj object to be converted into JSON string + # @return string JSON string representation of the object + def self.object_to_hash obj + if obj.respond_to?(:to_hash) + obj.to_hash + else + obj + end end - Response.new(response) - end - - def response - self.make - end - - def response_code_pretty - return unless @response.present? - @response.code.to_s - end - - def response_headers_pretty - return unless @response.present? - # JSON.pretty_generate(@response.headers).gsub(/\n/, '
') # <- This was for RestClient - @response.headers.gsub(/\n/, '
') # <- This is for Typhoeus - end + end end end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache index 02a1a458eb4c..e7bb482fb663 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache @@ -1,70 +1,70 @@ -module Swagger +module {{moduleName}} + module Swagger + class Response + require 'json' - class Response - require 'json' + attr_accessor :raw - attr_accessor :raw + def initialize(raw) + self.raw = raw - def initialize(raw) - self.raw = raw + case self.code + when 500..510 then raise(ServerError, self.error_message) + when 299..426 then raise(ClientError, self.error_message) + end + end - case self.code - when 500..510 then raise(ServerError, self.error_message) - when 299..426 then raise(ClientError, self.error_message) + def code + raw.code + end + + # Account for error messages that take different forms... + def error_message + body['message'] + rescue + body + end + + # If body is JSON, parse it + # Otherwise return raw string + def body + JSON.parse(raw.body, :symbolize_names => true) + rescue + raw.body + end + + # `headers_hash` is a Typhoeus-specific extension of Hash, + # so simplify it back into a regular old Hash. + def headers + h = {} + raw.headers_hash.each {|k,v| h[k] = v } + h + end + + # Extract the response format from the header hash + # e.g. {'Content-Type' => 'application/json'} + def format + headers['Content-Type'].split("/").last.downcase + end + + def json? + format == 'json' + end + + def xml? + format == 'xml' + end + + def pretty_body + return unless body.present? + case format + when 'json' then JSON.pretty_generate(body).gsub(/\n/, '
') + end + end + + def pretty_headers + JSON.pretty_generate(headers).gsub(/\n/, '
') end end - - def code - raw.code - end - - # Account for error messages that take different forms... - def error_message - body['message'] - rescue - body - end - - # If body is JSON, parse it - # Otherwise return raw string - def body - JSON.parse raw.body - rescue - raw.body - end - - # `headers_hash` is a Typhoeus-specific extension of Hash, - # so simplify it back into a regular old Hash. - def headers - h = {} - raw.headers_hash.each {|k,v| h[k] = v } - h - end - - # Extract the response format from the header hash - # e.g. {'Content-Type' => 'application/json'} - def format - headers['Content-Type'].split("/").last.downcase - end - - def json? - format == 'json' - end - - def xml? - format == 'xml' - end - - def pretty_body - return unless body.present? - case format - when 'json' then JSON.pretty_generate(body).gsub(/\n/, '
') - end - end - - def pretty_headers - JSON.pretty_generate(headers).gsub(/\n/, '
') - end - end -end \ No newline at end of file +end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger/version.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/version.mustache index 39357c0ed6db..332a5e66f45f 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/version.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/version.mustache @@ -1,4 +1,5 @@ -module Swagger - VERSION = "4.06.08" +module {{moduleName}} + module Swagger + VERSION = "{{appVersion}}" + end end - diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger_client.gemspec.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger_client.gemspec.mustache new file mode 100644 index 000000000000..9f84d88d4e12 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger_client.gemspec.mustache @@ -0,0 +1,32 @@ +# -*- encoding: utf-8 -*- +$:.push File.expand_path("../lib", __FILE__) +require "{{gemName}}/swagger/version" + +Gem::Specification.new do |s| + s.name = "{{gemName}}" + s.version = {{moduleName}}::Swagger::VERSION + s.platform = Gem::Platform::RUBY + s.authors = ["Zeke Sikelianos", "Tony Tam"] + s.email = ["zeke@wordnik.com", "tony@wordnik.com"] + s.homepage = "http://developer.wordnik.com" + s.summary = %q{A ruby wrapper for the swagger APIs} + s.description = %q{This gem maps to a swagger API} + s.license = "Apache-2.0" + + s.add_runtime_dependency 'typhoeus', '~> 0.2', '>= 0.2.1' + s.add_runtime_dependency 'addressable', '~> 2.2', '>= 2.2.4' + s.add_runtime_dependency 'json', '~> 1.4', '>= 1.4.6' + + s.add_development_dependency 'rspec', '~> 3.2', '>= 3.2.0' + s.add_development_dependency 'vcr', '~> 2.9', '>= 2.9.3' + s.add_development_dependency 'webmock', '~> 1.6', '>= 1.6.2' + s.add_development_dependency 'autotest', '~> 4.4', '>= 4.4.6' + s.add_development_dependency 'autotest-rails-pure', '~> 4.1', '>= 4.1.2' + s.add_development_dependency 'autotest-growl', '~> 0.2', '>= 0.2.16' + s.add_development_dependency 'autotest-fsevent', '~> 0.2', '>= 0.2.10' + + s.files = `find *`.split("\n").uniq.sort.select{|f| !f.empty? } + s.test_files = `find spec/*`.split("\n") + s.executables = [] + s.require_paths = ["lib"] +end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache new file mode 100644 index 000000000000..df675ddf26ea --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache @@ -0,0 +1,25 @@ +# Swagger common files +require '{{gemName}}/monkey' +require '{{gemName}}/swagger' +require '{{gemName}}/swagger/configuration' +require '{{gemName}}/swagger/request' +require '{{gemName}}/swagger/response' +require '{{gemName}}/swagger/version' + +# Models +require '{{modelPackage}}/base_object' +{{#models}} +require '{{importPath}}' +{{/models}} + +# APIs +{{#apiInfo}} +{{#apis}} +require '{{importPath}}' +{{/apis}} +{{/apiInfo}} + +module {{moduleName}} + # Initialize the default configuration + Swagger.configuration ||= Swagger::Configuration.new +end diff --git a/modules/swagger-codegen/src/main/resources/scala/api.mustache b/modules/swagger-codegen/src/main/resources/scala/api.mustache index 0610123ce8bc..9452a10c56ae 100644 --- a/modules/swagger-codegen/src/main/resources/scala/api.mustache +++ b/modules/swagger-codegen/src/main/resources/scala/api.mustache @@ -5,6 +5,11 @@ package {{package}} import {{invokerPackage}}.ApiInvoker import {{invokerPackage}}.ApiException +import com.sun.jersey.multipart.FormDataMultiPart +import com.sun.jersey.multipart.file.FileDataBodyPart + +import javax.ws.rs.core.MediaType + import java.io.File import java.util.Date @@ -31,18 +36,13 @@ class {{classname}}(val defBasePath: String = "{{basePath}}", {{/pathParams}} - {{newline}} - val contentType = { - {{#bodyParam}}if({{paramName}} != null && {{paramName}}.isInstanceOf[File] ) - "multipart/form-data" - else "application/json" - {{/bodyParam}} - {{^bodyParam}}"application/json"{{/bodyParam}} - } + val contentTypes = List({{#consumes}}"{{mediaType}}", {{/consumes}}"application/json") + val contentType = contentTypes(0) // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] + val formParams = new HashMap[String, String] {{#requiredParamCount}} // verify required params are set @@ -58,8 +58,25 @@ class {{classname}}(val defBasePath: String = "{{basePath}}", {{#headerParams}}headerParams += "{{baseName}}" -> {{paramName}} {{/headerParams}} + var postBody: AnyRef = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}} + + if(contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart() + {{#formParams}}{{#notFile}} + mp.field("{{baseName}}", {{paramName}}.toString(), MediaType.MULTIPART_FORM_DATA_TYPE) + {{/notFile}}{{#isFile}} + mp.field("{{baseName}}", file.getName) + mp.bodyPart(new FileDataBodyPart("{{baseName}}", {{paramName}}, MediaType.MULTIPART_FORM_DATA_TYPE)) + {{/isFile}}{{/formParams}} + postBody = mp + } + else { + {{#formParams}}{{#notFile}}formParams += "{{baseName}}" -> {{paramName}}.toString(){{/notFile}} + {{/formParams}} + } + try { - apiInvoker.invokeApi(basePath, path, "{{httpMethod}}", queryParams.toMap, {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}None{{/bodyParam}}, headerParams.toMap, contentType) match { + apiInvoker.invokeApi(basePath, path, "{{httpMethod}}", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => {{#returnType}} Some(ApiInvoker.deserialize(s, "{{returnContainer}}", classOf[{{returnBaseType}}]).asInstanceOf[{{returnType}}]) {{/returnType}} diff --git a/modules/swagger-codegen/src/main/resources/scala/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/scala/apiInvoker.mustache index c8bd04196587..f432c2dc59e4 100644 --- a/modules/swagger-codegen/src/main/resources/scala/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/scala/apiInvoker.mustache @@ -6,6 +6,7 @@ import com.sun.jersey.api.client.config.ClientConfig import com.sun.jersey.api.client.config.DefaultClientConfig import com.sun.jersey.api.client.filter.LoggingFilter +import com.sun.jersey.core.util.MultivaluedMapImpl import com.sun.jersey.multipart.FormDataMultiPart import com.sun.jersey.multipart.file.FileDataBodyPart @@ -94,7 +95,7 @@ class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper, } else null } - def invokeApi(host: String, path: String, method: String, queryParams: Map[String, String], body: AnyRef, headerParams: Map[String, String], contentType: String): String = { + def invokeApi(host: String, path: String, method: String, queryParams: Map[String, String], formParams: Map[String, String], body: AnyRef, headerParams: Map[String, String], contentType: String): String = { val client = getClient(host) val querystring = queryParams.filter(k => k._2 != null).map(k => (escape(k._1) + "=" + escape(k._2))).mkString("?", "&", "") @@ -106,13 +107,19 @@ class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper, case false => if (p._2 != null) builder.header(p._1, p._2) } }) + var formData: MultivaluedMapImpl = null + if(contentType == "application/x-www-form-urlencoded") { + formData = new MultivaluedMapImpl() + formParams.map(p => formData.add(p._1, p._2)) + } val response: ClientResponse = method match { case "GET" => { builder.get(classOf[ClientResponse]).asInstanceOf[ClientResponse] } case "POST" => { - if(body != null && body.isInstanceOf[File]) { + if(formData != null) builder.post(classOf[ClientResponse], formData) + else if(body != null && body.isInstanceOf[File]) { val file = body.asInstanceOf[File] val form = new FormDataMultiPart() form.field("filename", file.getName()) @@ -125,7 +132,8 @@ class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper, } } case "PUT" => { - if(body == null) builder.put(classOf[ClientResponse], null) + if(formData != null) builder.post(classOf[ClientResponse], formData) + else if(body == null) builder.put(classOf[ClientResponse], null) else builder.`type`(contentType).put(classOf[ClientResponse], serialize(body)) } case "DELETE" => { diff --git a/modules/swagger-codegen/src/main/resources/swagger-static/assets/css/style.css b/modules/swagger-codegen/src/main/resources/swagger-static/assets/css/style.css index b26d2ef13ca8..f14f6bdb62c5 100644 --- a/modules/swagger-codegen/src/main/resources/swagger-static/assets/css/style.css +++ b/modules/swagger-codegen/src/main/resources/swagger-static/assets/css/style.css @@ -151,15 +151,31 @@ padding-top: 20px; } -.param { +li.parameter { + list-style: none; display: block; - float: left; - width: 220px; - clear: left; + padding-left: 1em; +} + +.param{ + display: block; +} + +.param-name { + margin-left: 1em; +} + +.param-in { + font-weight: bold; + font-size: 1.1em; +} +.param-type { + margin-left: 1em; + font-style: italic; } .param-description { - float: left; + display: block; font-family: 'Helvetica Neue', Arial, 'Liberation Sans', FreeSans, sans-serif; } @@ -289,4 +305,4 @@ .top-bar ul#nav:hover li { border-color: #222222; -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/swagger-static/assets/js/main.js b/modules/swagger-codegen/src/main/resources/swagger-static/assets/js/main.js index 660d628567cd..ee0d2f92470a 100644 --- a/modules/swagger-codegen/src/main/resources/swagger-static/assets/js/main.js +++ b/modules/swagger-codegen/src/main/resources/swagger-static/assets/js/main.js @@ -1,13 +1,8 @@ -function main() {} - window.onhashchange = function() { choose(window.location.href.toString()); } -var url = 'http://motyar.blogspot.com/search?q={term}', selectionImage; - -function showModel(e, model) { -} +var selectionImage; function choose(url) { var f = url.split("/").slice(-1)[0].split("?")[0]; @@ -20,8 +15,8 @@ function choose(url) { // rebind the models $(".model a").on("click", function(e){ e.preventDefault(); - var model = $(this).parent().attr("id") - var parentOffset = $(this).parent().offset(); + var model = $(this).parent().attr("data-model") + var parentOffset = $(this).parent().offset(); var encodedWord = encodeURI(model); if(!selectionImage) { @@ -33,7 +28,7 @@ function choose(url) { $('div.model-container').append(selectionImage); } - selectionImage.load("/models/" + encodedWord + ".html") + selectionImage.load("models/" + encodedWord + ".html") selectionImage.attr('href',url.replace('{term}',encodeURI(model))).css({ left: e.pageX + 20, top: e.pageY - 10, diff --git a/modules/swagger-codegen/src/main/resources/swagger-static/operation.mustache b/modules/swagger-codegen/src/main/resources/swagger-static/operation.mustache index d0e35f1b2963..c2c70aa906de 100644 --- a/modules/swagger-codegen/src/main/resources/swagger-static/operation.mustache +++ b/modules/swagger-codegen/src/main/resources/swagger-static/operation.mustache @@ -13,40 +13,23 @@

HTTP Method

{{httpMethod}}

Response Type

- +

Parameters

    {{#allParams}} -
    - {{#isContainer}} - {{#complexType}} - - {{/complexType}} - {{#simpleType}} - -
    {{paramName}} : {{dataType}} ({{type}})
    - {{#optional}}optional{{/optional}} -
    - {{/simpleType}} - {{/isContainer}} - {{#isNotContainer}} - {{#simpleType}} - -
    {{paramName}} : {{dataType}} ({{type}})
    - {{#optional}}optional{{/optional}} - - {{/simpleType}} - {{/isNotContainer}} - - {{#foo}} -
    {{paramName}} : {{#complexType}} 
    {{dataType}}{{/complexType}}{{#simpleType}}{{dataType}}{{/simpleType}} ({{type}})
    - {{#optional}}optional{{/optional}} -
    - {{/foo}} -

    {{description}}

    - +
  • + {{#isFormParam}}Form: {{/isFormParam}} + {{#isQueryParam}}Query: {{/isQueryParam}} + {{#isPathParam}}Path: {{/isPathParam}} + {{#isHeaderParam}}Header: {{/isHeaderParam}} + {{#isBodyParam}}Body: {{/isBodyParam}} + {{paramName}} + {{dataType}}{{#baseType}}({{baseType}}){{/baseType}} + {{#optional}}(optional){{/optional}} +

    {{description}}

    +
  • {{/allParams}}
{{/operation}} {{/operations}} - \ No newline at end of file + diff --git a/modules/swagger-codegen/src/test/scala/php/PhpModelTest.scala b/modules/swagger-codegen/src/test/scala/php/PhpModelTest.scala index ffb1e59c85d3..1e4926d43d79 100644 --- a/modules/swagger-codegen/src/test/scala/php/PhpModelTest.scala +++ b/modules/swagger-codegen/src/test/scala/php/PhpModelTest.scala @@ -217,8 +217,9 @@ class PhpModelTest extends FlatSpec with Matchers { cm.classname should be ("Sample") cm.description should be ("an array model") cm.vars.size should be (0) - cm.imports.size should be (1) - (cm.imports.asScala.toSet & Set("Children")).size should be (1) + // skip import test as import is not used by PHP codegen + //cm.imports.size should be (1) + //(cm.imports.asScala.toSet & Set("Children")).size should be (1) } it should "convert an map model" in { @@ -237,23 +238,25 @@ class PhpModelTest extends FlatSpec with Matchers { (cm.imports.asScala.toSet & Set("Children")).size should be (1) } - it should "create proper imports per #316" in { - val model = new SwaggerParser() - .read("src/test/resources/2_0/postBodyTest.json") - val codegen = new PhpClientCodegen() + // skip import test as import is not used by PHP codegen + //it should "create proper imports per #316" in { + // val model = new SwaggerParser() + // .read("src/test/resources/2_0/postBodyTest.json") + // val codegen = new PhpClientCodegen() - val animalPaths = model.getPaths() - val animalOps = animalPaths.get("/animals") - animalOps.getPost() should not be (null) - val animalCo = codegen.fromOperation("/animals", "POST", animalOps.getPost(), model.getDefinitions()) - animalCo.imports.size should be (1) - animalCo.imports.contains("Animal") should equal (true) + // val animalPaths = model.getPaths() + // val animalOps = animalPaths.get("/animals") + // animalOps.getPost() should not be (null) + // val animalCo = codegen.fromOperation("/animals", "POST", animalOps.getPost(), model.getDefinitions()) + // animalCo.imports should be (1) + // animalCo.imports.size should be (1) + // animalCo.imports.contains("Animal") should equal (true) - val insectPaths = model.getPaths() - val insectOps = insectPaths.get("/insects") - insectOps.getPost() should not be (null) - val insectCo = codegen.fromOperation("/insects", "POST", insectOps.getPost(), model.getDefinitions()) - insectCo.imports.size should be (1) - insectCo.imports.contains("Insect") should equal (true) - } + // val insectPaths = model.getPaths() + // val insectOps = insectPaths.get("/insects") + // insectOps.getPost() should not be (null) + // val insectCo = codegen.fromOperation("/insects", "POST", insectOps.getPost(), model.getDefinitions()) + // insectCo.imports.size should be (1) + // insectCo.imports.contains("Insect") should equal (true) + //} } diff --git a/pom.xml b/pom.xml index fd7d05b546a2..e28a46bb442a 100644 --- a/pom.xml +++ b/pom.xml @@ -302,6 +302,18 @@ samples/client/petstore/java + + scala-client + + + env + scala + + + + samples/client/petstore/scala + + objc-client @@ -361,6 +373,7 @@ samples/client/petstore/android-java samples/client/petstore/java + samples/client/petstore/scala samples/server/petstore/jaxrs samples/server/petstore/spring-mvc samples/client/petstore/objc diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/PetApi.java index c8da678b2f98..88fdfdb69808 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/PetApi.java @@ -46,7 +46,6 @@ public class PetApi { */ public void updatePet (Pet body) throws ApiException { Object postBody = body; - // create path and map variables @@ -101,7 +100,6 @@ public class PetApi { */ public void addPet (Pet body) throws ApiException { Object postBody = body; - // create path and map variables @@ -156,7 +154,6 @@ public class PetApi { */ public List findPetsByStatus (List status) throws ApiException { Object postBody = null; - // create path and map variables @@ -213,7 +210,6 @@ public class PetApi { */ public List findPetsByTags (List tags) throws ApiException { Object postBody = null; - // create path and map variables @@ -270,7 +266,11 @@ public class PetApi { */ public Pet getPetById (Long petId) throws ApiException { Object postBody = null; - + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling getPetById"); + } // create path and map variables @@ -327,7 +327,11 @@ public class PetApi { */ public void updatePetWithForm (String petId, String name, String status) throws ApiException { Object postBody = null; - + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling updatePetWithForm"); + } // create path and map variables @@ -393,7 +397,11 @@ public class PetApi { */ public void deletePet (String apiKey, Long petId) throws ApiException { Object postBody = null; - + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling deletePet"); + } // create path and map variables @@ -451,7 +459,11 @@ public class PetApi { */ public void uploadFile (Long petId, String additionalMetadata, File file) throws ApiException { Object postBody = null; - + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling uploadFile"); + } // create path and map variables diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/StoreApi.java index 1e2ff3bba8a7..ecd8e8330490 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/StoreApi.java @@ -45,7 +45,6 @@ public class StoreApi { */ public Map getInventory () throws ApiException { Object postBody = null; - // create path and map variables @@ -100,7 +99,6 @@ public class StoreApi { */ public Order placeOrder (Order body) throws ApiException { Object postBody = body; - // create path and map variables @@ -155,7 +153,11 @@ public class StoreApi { */ public Order getOrderById (String orderId) throws ApiException { Object postBody = null; - + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById"); + } // create path and map variables @@ -210,7 +212,11 @@ public class StoreApi { */ public void deleteOrder (String orderId) throws ApiException { Object postBody = null; - + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder"); + } // create path and map variables diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/UserApi.java index da105638c5f5..e1df3fd4f128 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/UserApi.java @@ -46,7 +46,6 @@ public class UserApi { */ public void createUser (User body) throws ApiException { Object postBody = body; - // create path and map variables @@ -101,7 +100,6 @@ public class UserApi { */ public void createUsersWithArrayInput (List body) throws ApiException { Object postBody = body; - // create path and map variables @@ -156,7 +154,6 @@ public class UserApi { */ public void createUsersWithListInput (List body) throws ApiException { Object postBody = body; - // create path and map variables @@ -212,7 +209,6 @@ public class UserApi { */ public String loginUser (String username, String password) throws ApiException { Object postBody = null; - // create path and map variables @@ -270,7 +266,6 @@ public class UserApi { */ public void logoutUser () throws ApiException { Object postBody = null; - // create path and map variables @@ -325,7 +320,11 @@ public class UserApi { */ public User getUserByName (String username) throws ApiException { Object postBody = null; - + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling getUserByName"); + } // create path and map variables @@ -381,7 +380,11 @@ public class UserApi { */ public void updateUser (String username, User body) throws ApiException { Object postBody = body; - + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser"); + } // create path and map variables @@ -436,7 +439,11 @@ public class UserApi { */ public void deleteUser (String username) throws ApiException { Object postBody = null; - + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling deleteUser"); + } // create path and map variables diff --git a/samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/PetApiTest.java index 97f3b5f80060..e7fd31f2996c 100644 --- a/samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ b/samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -100,11 +100,11 @@ public class PetApiTest { api.addPet(pet); Pet fetched = api.getPetById(pet.getId()); - + assertEquals("frank", fetched.getName()); + api.updatePetWithForm(String.valueOf(fetched.getId()), "furt", null); Pet updated = api.getPetById(fetched.getId()); - - assertEquals(updated.getName(), fetched.getName()); + assertEquals("furt", updated.getName()); } @Test @@ -152,4 +152,4 @@ public class PetApiTest { return pet; } -} \ No newline at end of file +} diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java index 842c080024a8..b5d6bb70d79d 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java @@ -249,6 +249,11 @@ public class PetApi { public Pet getPetById (Long petId) throws ApiException { Object postBody = null; + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling getPetById"); + } + // create path and map variables String path = "/pet/{petId}".replaceAll("\\{format\\}","json") @@ -302,6 +307,11 @@ public class PetApi { public void updatePetWithForm (String petId, String name, String status) throws ApiException { Object postBody = null; + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling updatePetWithForm"); + } + // create path and map variables String path = "/pet/{petId}".replaceAll("\\{format\\}","json") @@ -362,6 +372,11 @@ public class PetApi { public void deletePet (String apiKey, Long petId) throws ApiException { Object postBody = null; + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling deletePet"); + } + // create path and map variables String path = "/pet/{petId}".replaceAll("\\{format\\}","json") @@ -416,6 +431,11 @@ public class PetApi { public void uploadFile (Long petId, String additionalMetadata, File file) throws ApiException { Object postBody = null; + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling uploadFile"); + } + // create path and map variables String path = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/src/main/java/io/swagger/client/api/StoreApi.java index cff340e69d7d..6da7b5abb2f2 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/api/StoreApi.java @@ -144,6 +144,11 @@ public class StoreApi { public Order getOrderById (String orderId) throws ApiException { Object postBody = null; + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById"); + } + // create path and map variables String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json") @@ -195,6 +200,11 @@ public class StoreApi { public void deleteOrder (String orderId) throws ApiException { Object postBody = null; + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder"); + } + // create path and map variables String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json") diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/src/main/java/io/swagger/client/api/UserApi.java index 2296c0223ce1..d0974d95a52b 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/api/UserApi.java @@ -299,6 +299,11 @@ public class UserApi { public User getUserByName (String username) throws ApiException { Object postBody = null; + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling getUserByName"); + } + // create path and map variables String path = "/user/{username}".replaceAll("\\{format\\}","json") @@ -351,6 +356,11 @@ public class UserApi { public void updateUser (String username, User body) throws ApiException { Object postBody = body; + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser"); + } + // create path and map variables String path = "/user/{username}".replaceAll("\\{format\\}","json") @@ -402,6 +412,11 @@ public class UserApi { public void deleteUser (String username) throws ApiException { Object postBody = null; + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling deleteUser"); + } + // create path and map variables String path = "/user/{username}".replaceAll("\\{format\\}","json") diff --git a/samples/client/petstore/objc/PetstoreClient.xcworkspace/contents.xcworkspacedata b/samples/client/petstore/objc/PetstoreClient.xcworkspace/contents.xcworkspacedata index 834f64caf7e7..4ea151191719 100644 --- a/samples/client/petstore/objc/PetstoreClient.xcworkspace/contents.xcworkspacedata +++ b/samples/client/petstore/objc/PetstoreClient.xcworkspace/contents.xcworkspacedata @@ -1 +1,10 @@ - \ No newline at end of file + + + + + + + diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.pbxproj b/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.pbxproj index 24cb04d3f7c8..c22d57fa0acc 100644 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.pbxproj @@ -39,7 +39,6 @@ EAEA85EE1811D3AE00F06E69 /* SWGUser.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85E11811D3AE00F06E69 /* SWGUser.m */; }; EAEA85EF1811D3AE00F06E69 /* SWGUserApi.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85E31811D3AE00F06E69 /* SWGUserApi.m */; }; EAFBEABB1A925B8500A27431 /* test-1.png in Resources */ = {isa = PBXBuildFile; fileRef = EAFBEABA1A925B8500A27431 /* test-1.png */; }; - EAFBEABE1A92C42700A27431 /* SWGApiResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = EAFBEABD1A92C42700A27431 /* SWGApiResponse.m */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -105,8 +104,6 @@ EAEA85E21811D3AE00F06E69 /* SWGUserApi.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGUserApi.h; sourceTree = ""; }; EAEA85E31811D3AE00F06E69 /* SWGUserApi.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGUserApi.m; sourceTree = ""; }; EAFBEABA1A925B8500A27431 /* test-1.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "test-1.png"; sourceTree = ""; }; - EAFBEABC1A92C42700A27431 /* SWGApiResponse.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGApiResponse.h; sourceTree = ""; }; - EAFBEABD1A92C42700A27431 /* SWGApiResponse.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGApiResponse.m; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -229,8 +226,6 @@ children = ( EA8B8AA21AC6683700638FBB /* SWGQueryParamCollection.h */, EA8B8AA31AC6683700638FBB /* SWGQueryParamCollection.m */, - EAFBEABC1A92C42700A27431 /* SWGApiResponse.h */, - EAFBEABD1A92C42700A27431 /* SWGApiResponse.m */, EAEA85CC1811D3AE00F06E69 /* SWGApiClient.h */, EAEA85CD1811D3AE00F06E69 /* SWGApiClient.m */, EAEA85CE1811D3AE00F06E69 /* SWGCategory.h */, @@ -400,7 +395,6 @@ EA6699B31811D2FA00A70D03 /* ViewController.m in Sources */, EA6699AA1811D2FA00A70D03 /* AppDelegate.m in Sources */, EAEA85EE1811D3AE00F06E69 /* SWGUser.m in Sources */, - EAFBEABE1A92C42700A27431 /* SWGApiResponse.m in Sources */, EAEA85EF1811D3AE00F06E69 /* SWGUserApi.m in Sources */, EAEA85EB1811D3AE00F06E69 /* SWGPetApi.m in Sources */, EAEA85E61811D3AE00F06E69 /* SWGDate.m in Sources */, diff --git a/samples/client/petstore/objc/client/SWGApiResponse.h b/samples/client/petstore/objc/client/SWGApiResponse.h deleted file mode 100644 index 2021a408f03e..000000000000 --- a/samples/client/petstore/objc/client/SWGApiResponse.h +++ /dev/null @@ -1,18 +0,0 @@ -#import -#import "SWGObject.h" - - -@interface SWGApiResponse : SWGObject - -@property(nonatomic) NSNumber* code; -@property(nonatomic) NSString* type; -@property(nonatomic) NSString* message; -- (id) code: (NSNumber*) code - type: (NSString*) type - message: (NSString*) message; - - -- (id) initWithValues: (NSDictionary*)dict; -- (NSDictionary*) asDictionary; - -@end diff --git a/samples/client/petstore/objc/client/SWGApiResponse.m b/samples/client/petstore/objc/client/SWGApiResponse.m deleted file mode 100644 index b6391774790a..000000000000 --- a/samples/client/petstore/objc/client/SWGApiResponse.m +++ /dev/null @@ -1,54 +0,0 @@ -#import "SWGDate.h" -#import "SWGApiResponse.h" - -@implementation SWGApiResponse - --(id)code: (NSNumber*) code - type: (NSString*) type - message: (NSString*) message - -{ - _code = code; - _type = type; - _message = message; - - - return self; -} - --(id) initWithValues:(NSDictionary*)dict -{ - self = [super init]; - if(self) { - _code = dict[@"code"]; - - _type = dict[@"type"]; - - _message = dict[@"message"]; - - - } - return self; -} - --(NSDictionary*) asDictionary { - NSMutableDictionary* dict = [[NSMutableDictionary alloc] init]; - - - if(_code != nil) dict[@"code"] = _code ; - - - - if(_type != nil) dict[@"type"] = _type ; - - - - if(_message != nil) dict[@"message"] = _message ; - - - - NSDictionary* output = [dict copy]; - return output; -} - -@end diff --git a/samples/client/petstore/objc/client/SWGOrder.h b/samples/client/petstore/objc/client/SWGOrder.h index 2e71906cd530..c4f4f6e81ad7 100644 --- a/samples/client/petstore/objc/client/SWGOrder.h +++ b/samples/client/petstore/objc/client/SWGOrder.h @@ -19,6 +19,6 @@ */ @property(nonatomic) NSString* status; -@property(nonatomic) NSNumber* complete; +@property(nonatomic) BOOL complete; @end diff --git a/samples/client/petstore/objc/client/SWGPetApi.h b/samples/client/petstore/objc/client/SWGPetApi.h index 40d475d5e0af..e7a3a84a9f51 100644 --- a/samples/client/petstore/objc/client/SWGPetApi.h +++ b/samples/client/petstore/objc/client/SWGPetApi.h @@ -116,13 +116,13 @@ Deletes a pet - @param api_key + @param apiKey @param petId Pet id to delete return type: */ --(NSNumber*) deletePetWithCompletionBlock :(NSString*) api_key +-(NSNumber*) deletePetWithCompletionBlock :(NSString*) apiKey petId:(NSNumber*) petId diff --git a/samples/client/petstore/objc/client/SWGPetApi.m b/samples/client/petstore/objc/client/SWGPetApi.m index dca990cb118f..62bc34acbee5 100644 --- a/samples/client/petstore/objc/client/SWGPetApi.m +++ b/samples/client/petstore/objc/client/SWGPetApi.m @@ -587,11 +587,11 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; /*! * Deletes a pet * - * \param api_key + * \param apiKey * \param petId Pet id to delete * \returns void */ --(NSNumber*) deletePetWithCompletionBlock: (NSString*) api_key +-(NSNumber*) deletePetWithCompletionBlock: (NSString*) apiKey petId: (NSNumber*) petId @@ -616,8 +616,8 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - if(api_key != nil) - headerParams[@"api_key"] = api_key; + if(apiKey != nil) + headerParams[@"api_key"] = apiKey; id bodyDictionary = nil; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/APIClient.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/APIClient.pm new file mode 100644 index 000000000000..0f0fea793e36 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/APIClient.pm @@ -0,0 +1,291 @@ +package WWW::SwaggerClient::APIClient; + +use strict; +use warnings; +use utf8; + +use LWP::UserAgent; +use HTTP::Headers; +use HTTP::Response; +use HTTP::Request::Common qw(DELETE POST GET HEAD PUT); +use HTTP::Status; +use URI::Query; +use JSON; +use URI::Escape; +use Scalar::Util; +use Log::Any qw($log); +use Carp; +use Switch; +use Module::Runtime qw(use_module); + +# class variables +my $ua = LWP::UserAgent->new; +my $http_user_agent = 'Perl-Swagger'; # HTTP user-agent +my $http_timeout; #timeout +my $base_url = "http://petstore.swagger.io/v2"; + + +sub new +{ + my $class = shift; + my %args = @_; + + return bless \%args, $class; +} + +# Set the user agent of the API client +# +# @param string $user_agent The user agent of the API client +# +sub set_user_agent { + my $user_agent = shift; + $http_user_agent= $user_agent; +} + +# Set timeout +# +# @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] +# +sub set_timeout { + my $seconds = shift; + if (!looks_like_number($seconds)) { + croak('Timeout variable must be numeric.'); + } + $http_timeout = $seconds; +} + +# make the HTTP request +# @param string $resourcePath path to method endpoint +# @param string $method method to call +# @param array $queryParams parameters to be place in query URL +# @param array $postData parameters to be placed in POST body +# @param array $headerParams parameters to be place in request header +# @return mixed +sub call_api { + my $self = shift; + my ($resource_path, $method, $query_params, $post_params, $header_params, $body_data) = @_; + + my $headers = HTTP::Headers->new(%$header_params); + + my $_url = $base_url . $resource_path; + + # build query + if (%$query_params) { + $_url = ($_url . '?' . eval { URI::Query->new($query_params)->stringify }); + } + + # body data + $body_data = to_json($body_data->to_hash) if defined $body_data && $body_data->can('to_hash'); # model to json string + my $_body_data = %$post_params ? $post_params : $body_data; + + # Make the HTTP request + my $_request; + switch ($method) { + case 'POST' { + # multipart + my $_content_type = lc $header_params->{'Content-Type'} eq 'multipart/form' ? + 'form-data' : $header_params->{'Content-Type'}; + + $_request = POST($_url, Accept => $header_params->{Accept}, + Content_Type => $_content_type, Content => $_body_data); + } + case 'PUT' { + # multipart + my $_content_type = lc $header_params->{'Content-Type'} eq 'multipart/form' ? + 'form-data' : $header_params->{'Content-Type'}; + $_request = PUT($_url, Accept => $header_params->{Accept}, + Content_Type => $_content_type, Content => $_body_data); + } + case 'GET' { + $_request = GET($_url, Accept => $header_params->{'Accept'}, + Content_Type => $header_params->{'Content-Type'}); + } + case 'HEAD' { + $_request = HEAD($_url, Accept => $header_params->{'Accept'}, + Content_Type => $header_params->{'Content-Type'}); + } + case 'DELETE' { #TODO support form data + $_request = DELETE($_url, Accept => $header_params->{'Accept'}, + Content_Type => $header_params->{'Content-Type'}, Content => $_body_data); + } + case 'PATCH' { #TODO + } + + } + + $ua->timeout($http_timeout); + $ua->agent($http_user_agent); + + my $_response = $ua->request($_request); + + unless ($_response->is_success) { + croak("API Exception(".$_response->code."): ".$_response->message); + } + + return $_response->content; + +} + + +# Build a JSON POST object +sub sanitize_for_serialization +{ +# my $data = shift; +# if (is_scalar($data) || null === $data) { +# $sanitized = $data; +# } else if ($data instanceof \DateTime) { +# $sanitized = $data->format(\DateTime::ISO8601); +# } else if (is_array($data)) { +# foreach ($data as $property => $value) { +# $data[$property] = $this->sanitizeForSerialization($value); +# } +# $sanitized = $data; +# } else if (is_object($data)) { +# $values = array(); +# foreach (array_keys($data::$swaggerTypes) as $property) { +# $values[$data::$attributeMap[$property]] = $this->sanitizeForSerialization($data->$property); +# } +# $sanitized = $values; +# } else { +# $sanitized = (string)$data; +# } +# +# return $sanitized; +} + + +# Take value and turn it into a string suitable for inclusion in +# the path, by url-encoding. +# @param string $value a string which will be part of the path +# @return string the serialized object +sub to_path_value { + my $value = shift; + return uri_escape(to_string($value)); +} + + +# Take value and turn it into a string suitable for inclusion in +# the query, by imploding comma-separated if it's an object. +# If it's a string, pass through unchanged. It will be url-encoded +# later. +# @param object $object an object to be serialized to a string +# @return string the serialized object +sub to_query_value { + my $object = shift; + if (is_array($object)) { + return implode(',', $object); + } else { + return toString($object); + } +} + + +# Take value and turn it into a string suitable for inclusion in +# the header. If it's a string, pass through unchanged +# If it's a datetime object, format it in ISO8601 +# @param string $value a string which will be part of the header +# @return string the header string +sub to_header_value { + my $value = shift; + return to_string($value); +} + +# Take value and turn it into a string suitable for inclusion in +# the http body (form parameter). If it's a string, pass through unchanged +# If it's a datetime object, format it in ISO8601 +# @param string $value the value of the form parameter +# @return string the form string +sub to_form_value { + my $value = shift; + return to_string($value); +} + +# Take value and turn it into a string suitable for inclusion in +# the parameter. If it's a string, pass through unchanged +# If it's a datetime object, format it in ISO8601 +# @param string $value the value of the parameter +# @return string the header string +sub to_string { + my $value = shift; + if (ref($value) eq "DateTime") { # datetime in ISO8601 format + return $value->datetime(); + } + else { + return $value; + } +} + +# Deserialize a JSON string into an object +# +# @param string $class class name is passed as a string +# @param string $data data of the body +# @return object an instance of $class +sub deserialize +{ + my ($self, $class, $data) = @_; + $log->debugf("deserializing %s for %s", $data, $class); + my $_result; + + if (not defined $data) { + return undef; + } elsif ( lc(substr($class, 0, 4)) eq 'map[') { #hash + $_result = \(json_decode $data); + } elsif ( lc(substr($class, 0, 6)) eq 'array[' ) { # array of data + return $data if $data eq '[]'; # return if empty array + + my $_sub_class = substr($class, 6, -1); + my @_json_data = json_decode $data; + my @_values = (); + foreach my $_value (@_json_data) { + push @_values, $self->deserialize($_sub_class, $_value); + } + $_result = \@_values; + } elsif ($class eq 'DateTime') { + $_result = DateTime->from_epoch(epoch => str2time($data)); + } elsif (grep /^$data$/, ('string', 'int', 'float', 'bool')) { #TODO revise the primitive type + $_result= $data; + } else { # model + my $_instance = use_module("WWW::SwaggerClient::Object::$class")->new; + $_result = $_instance->from_hash(decode_json $data); + } + + return $_result; + +} + +# return 'Accept' based on an array of accept provided +# @param [Array] header_accept_array Array fo 'Accept' +# @return String Accept (e.g. application/json) +sub select_header_accept +{ + my ($self, @header) = @_; + + if (@header == 0 || (@header == 1 && $header[0] eq '')) { + return undef; + } elsif (grep(/^application\/json$/i, @header)) { + return 'application/json'; + } else { + return join(',', @header); + } + +} + +# return the content type based on an array of content-type provided +# @param [Array] content_type_array Array fo content-type +# @return String Content-Type (e.g. application/json) +sub select_header_content_type +{ + my ($self, @header) = @_; + + if (@header == 0 || (@header == 1 && $header[0] eq '')) { + return 'application/json'; # default to application/json + } elsif (grep(/^application\/json$/i, @header)) { + return 'application/json'; + } else { + return join(',', @header); + } + +} + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/BaseObject.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/BaseObject.pm new file mode 100644 index 000000000000..c4fd4e6aece3 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/BaseObject.pm @@ -0,0 +1,76 @@ +package WWW::SwaggerClient::Object::BaseObject; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + + +# +# +# +#NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# + + +# return json string +sub to_hash { + return decode_json(JSON->new->convert_blessed->encode( shift )); +} + +# used by JSON for serialization +sub TO_JSON { + my $self = shift; + my $_data = {}; + foreach my $_key (keys $self->get_attribute_map) { + if (defined $self->{$_key}) { + $_data->{$self->get_attribute_map->{$_key}} = $self->{$_key}; + } + } + return $_data; +} + +# from json string +sub from_hash { + my ($self, $hash) = @_; + # loop through attributes and use swagger_types to deserialize the data + while ( my ($_key, $_type) = each $self->get_swagger_types ) { + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$self->get_attribute_map->{$_key}}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif (defined $hash->{$_key}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_key}); + } else { + $log->debugf("warning: %s not defined\n", $_key); + } + } + + return $self; +} + +# deserialize non-array data +sub _deserialize { + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; + return $_instance->from_hash($data); + } +} + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm new file mode 100644 index 000000000000..857dccdce5a0 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm @@ -0,0 +1,55 @@ +package WWW::SwaggerClient::Object::Category; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + +use base "WWW::SwaggerClient::Object::BaseObject"; + +# +# +# +#NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# + +my $swagger_types = { + 'id' => 'int', + 'name' => 'string' +}; + +my $attribute_map = { + 'id' => 'id', + 'name' => 'name' +}; + +# new object +sub new { + my ($class, %args) = @_; + my $self = { + # + 'id' => $args{'id'}, + # + 'name' => $args{'name'} + }; + + return bless $self, $class; +} + +# get swagger type of the attribute +sub get_swagger_types { + return $swagger_types; +} + +# get attribute mappping +sub get_attribute_map { + return $attribute_map; +} + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm new file mode 100644 index 000000000000..35449647e132 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm @@ -0,0 +1,71 @@ +package WWW::SwaggerClient::Object::Order; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + +use base "WWW::SwaggerClient::Object::BaseObject"; + +# +# +# +#NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# + +my $swagger_types = { + 'id' => 'int', + 'pet_id' => 'int', + 'quantity' => 'int', + 'ship_date' => 'DateTime', + 'status' => 'string', + 'complete' => 'boolean' +}; + +my $attribute_map = { + 'id' => 'id', + 'pet_id' => 'petId', + 'quantity' => 'quantity', + 'ship_date' => 'shipDate', + 'status' => 'status', + 'complete' => 'complete' +}; + +# new object +sub new { + my ($class, %args) = @_; + my $self = { + # + 'id' => $args{'id'}, + # + 'pet_id' => $args{'petId'}, + # + 'quantity' => $args{'quantity'}, + # + 'ship_date' => $args{'shipDate'}, + #Order Status + 'status' => $args{'status'}, + # + 'complete' => $args{'complete'} + }; + + return bless $self, $class; +} + +# get swagger type of the attribute +sub get_swagger_types { + return $swagger_types; +} + +# get attribute mappping +sub get_attribute_map { + return $attribute_map; +} + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm new file mode 100644 index 000000000000..df32665e8266 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm @@ -0,0 +1,71 @@ +package WWW::SwaggerClient::Object::Pet; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + +use base "WWW::SwaggerClient::Object::BaseObject"; + +# +# +# +#NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# + +my $swagger_types = { + 'id' => 'int', + 'category' => 'Category', + 'name' => 'string', + 'photo_urls' => 'ARRAY[string]', + 'tags' => 'ARRAY[Tag]', + 'status' => 'string' +}; + +my $attribute_map = { + 'id' => 'id', + 'category' => 'category', + 'name' => 'name', + 'photo_urls' => 'photoUrls', + 'tags' => 'tags', + 'status' => 'status' +}; + +# new object +sub new { + my ($class, %args) = @_; + my $self = { + # + 'id' => $args{'id'}, + # + 'category' => $args{'category'}, + # + 'name' => $args{'name'}, + # + 'photo_urls' => $args{'photoUrls'}, + # + 'tags' => $args{'tags'}, + #pet status in the store + 'status' => $args{'status'} + }; + + return bless $self, $class; +} + +# get swagger type of the attribute +sub get_swagger_types { + return $swagger_types; +} + +# get attribute mappping +sub get_attribute_map { + return $attribute_map; +} + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm new file mode 100644 index 000000000000..35850032d5c2 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm @@ -0,0 +1,55 @@ +package WWW::SwaggerClient::Object::Tag; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + +use base "WWW::SwaggerClient::Object::BaseObject"; + +# +# +# +#NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# + +my $swagger_types = { + 'id' => 'int', + 'name' => 'string' +}; + +my $attribute_map = { + 'id' => 'id', + 'name' => 'name' +}; + +# new object +sub new { + my ($class, %args) = @_; + my $self = { + # + 'id' => $args{'id'}, + # + 'name' => $args{'name'} + }; + + return bless $self, $class; +} + +# get swagger type of the attribute +sub get_swagger_types { + return $swagger_types; +} + +# get attribute mappping +sub get_attribute_map { + return $attribute_map; +} + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm new file mode 100644 index 000000000000..88a396ece3a7 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm @@ -0,0 +1,79 @@ +package WWW::SwaggerClient::Object::User; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + +use base "WWW::SwaggerClient::Object::BaseObject"; + +# +# +# +#NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# + +my $swagger_types = { + 'id' => 'int', + 'username' => 'string', + 'first_name' => 'string', + 'last_name' => 'string', + 'email' => 'string', + 'password' => 'string', + 'phone' => 'string', + 'user_status' => 'int' +}; + +my $attribute_map = { + 'id' => 'id', + 'username' => 'username', + 'first_name' => 'firstName', + 'last_name' => 'lastName', + 'email' => 'email', + 'password' => 'password', + 'phone' => 'phone', + 'user_status' => 'userStatus' +}; + +# new object +sub new { + my ($class, %args) = @_; + my $self = { + # + 'id' => $args{'id'}, + # + 'username' => $args{'username'}, + # + 'first_name' => $args{'firstName'}, + # + 'last_name' => $args{'lastName'}, + # + 'email' => $args{'email'}, + # + 'password' => $args{'password'}, + # + 'phone' => $args{'phone'}, + #User Status + 'user_status' => $args{'userStatus'} + }; + + return bless $self, $class; +} + +# get swagger type of the attribute +sub get_swagger_types { + return $swagger_types; +} + +# get attribute mappping +sub get_attribute_map { + return $attribute_map; +} + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm new file mode 100644 index 000000000000..57237a96974d --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm @@ -0,0 +1,543 @@ +# +# Copyright 2015 Reverb Technologies, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# +package WWW::SwaggerClient::PetApi; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use Exporter; +use Carp qw( croak ); +use Log::Any qw($log); + + +#use WWW::Swagger::Model::Category; +#use WWW::Swagger::Model::Pet; + + +use WWW::SwaggerClient::APIClient; + +our @EXPORT_OK = qw( + update_pet + add_pet + find_pets_by_status + find_pets_by_tags + get_pet_by_id + update_pet_with_form + delete_pet + upload_file + +); + +sub new { + my $class = shift; + my $default_api_client = WWW::SwaggerClient::APIClient->new; + my (%self) = ( + 'api_client' => $default_api_client, + @_ + ); + + #my $self = { + # #api_client => $options->{api_client} + # api_client => $default_api_client + #}; + + bless \%self, $class; + +} + + + # + # update_pet + # + # Update an existing pet + # + # @param Pet $body Pet object that needs to be added to the store (required) + # @return void + # + sub update_pet { + my ($self, %args) = @_; + + + + # parse inputs + my $_resource_path = '/pet'; + $_resource_path =~ s/{format}/json/; # default format to json + + my $_method = 'PUT'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json', 'application/xml', ); + + + + + + my $_body_data; + # body params + if ( exists $args{'body'}) { + $_body_data = $args{'body'}; + } + + # for HTTP post (form) + #$_body_data = $_body ? undef : $form_params; + + # make the API Call + + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data); + return; + + } + + # + # add_pet + # + # Add a new pet to the store + # + # @param Pet $body Pet object that needs to be added to the store (required) + # @return void + # + sub add_pet { + my ($self, %args) = @_; + + + + # parse inputs + my $_resource_path = '/pet'; + $_resource_path =~ s/{format}/json/; # default format to json + + my $_method = 'POST'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json', 'application/xml', ); + + + + + + my $_body_data; + # body params + if ( exists $args{'body'}) { + $_body_data = $args{'body'}; + } + + # for HTTP post (form) + #$_body_data = $_body ? undef : $form_params; + + # make the API Call + + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data); + return; + + } + + # + # find_pets_by_status + # + # Finds Pets by status + # + # @param ARRAY[string] $status Status values that need to be considered for filter (required) + # @return ARRAY[Pet] + # + sub find_pets_by_status { + my ($self, %args) = @_; + + + + # parse inputs + my $_resource_path = '/pet/findByStatus'; + $_resource_path =~ s/{format}/json/; # default format to json + + my $_method = 'GET'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + + # query params + if ( exists $args{'status'}) { + $query_params->{'status'} = WWW::::APIClient::to_query_value($args{'status'}); + } + + + + my $_body_data; + + + # for HTTP post (form) + #$_body_data = $_body ? undef : $form_params; + + # make the API Call + my $response = $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data); + if (!$response) { + return; + } + my $_response_object = $self->{api_client}->deserialize('ARRAY[Pet]', $response); + return $_response_object; + + } + + # + # find_pets_by_tags + # + # Finds Pets by tags + # + # @param ARRAY[string] $tags Tags to filter by (required) + # @return ARRAY[Pet] + # + sub find_pets_by_tags { + my ($self, %args) = @_; + + + + # parse inputs + my $_resource_path = '/pet/findByTags'; + $_resource_path =~ s/{format}/json/; # default format to json + + my $_method = 'GET'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + + # query params + if ( exists $args{'tags'}) { + $query_params->{'tags'} = WWW::::APIClient::to_query_value($args{'tags'}); + } + + + + my $_body_data; + + + # for HTTP post (form) + #$_body_data = $_body ? undef : $form_params; + + # make the API Call + my $response = $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data); + if (!$response) { + return; + } + my $_response_object = $self->{api_client}->deserialize('ARRAY[Pet]', $response); + return $_response_object; + + } + + # + # get_pet_by_id + # + # Find pet by ID + # + # @param int $pet_id ID of pet that needs to be fetched (required) + # @return Pet + # + sub get_pet_by_id { + my ($self, %args) = @_; + + + # verify the required parameter 'pet_id' is set + unless (exists $args{'pet_id'}) { + croak("Missing the required parameter 'pet_id' when calling get_pet_by_id"); + } + + + # parse inputs + my $_resource_path = '/pet/{petId}'; + $_resource_path =~ s/{format}/json/; # default format to json + + my $_method = 'GET'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + + + + # path params + if ( exists $args{'pet_id'}) { + my $_base_variable = "{" . "petId" . "}"; + my $_base_value = WWW::SwaggerClient::APIClient::to_path_value($args{'pet_id'}); + $_resource_path =~ s/$_base_variable/$_base_value/g; + } + + my $_body_data; + + + # for HTTP post (form) + #$_body_data = $_body ? undef : $form_params; + + # make the API Call + my $response = $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data); + if (!$response) { + return; + } + my $_response_object = $self->{api_client}->deserialize('Pet', $response); + return $_response_object; + + } + + # + # update_pet_with_form + # + # Updates a pet in the store with form data + # + # @param string $pet_id ID of pet that needs to be updated (required) + # @param string $name Updated name of the pet (required) + # @param string $status Updated status of the pet (required) + # @return void + # + sub update_pet_with_form { + my ($self, %args) = @_; + + + # verify the required parameter 'pet_id' is set + unless (exists $args{'pet_id'}) { + croak("Missing the required parameter 'pet_id' when calling update_pet_with_form"); + } + + + # parse inputs + my $_resource_path = '/pet/{petId}'; + $_resource_path =~ s/{format}/json/; # default format to json + + my $_method = 'POST'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/x-www-form-urlencoded', ); + + + + # path params + if ( exists $args{'pet_id'}) { + my $_base_variable = "{" . "petId" . "}"; + my $_base_value = WWW::SwaggerClient::APIClient::to_path_value($args{'pet_id'}); + $_resource_path =~ s/$_base_variable/$_base_value/g; + } + # form params + if ( exists $args{'name'} ) { + + $form_params->{'name'} = WWW::SwaggerClient::APIClient::to_form_value($args{'name'}); + + } # form params + if ( exists $args{'status'} ) { + + $form_params->{'status'} = WWW::SwaggerClient::APIClient::to_form_value($args{'status'}); + + } + my $_body_data; + + + # for HTTP post (form) + #$_body_data = $_body ? undef : $form_params; + + # make the API Call + + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data); + return; + + } + + # + # delete_pet + # + # Deletes a pet + # + # @param string $api_key (required) + # @param int $pet_id Pet id to delete (required) + # @return void + # + sub delete_pet { + my ($self, %args) = @_; + + + # verify the required parameter 'pet_id' is set + unless (exists $args{'pet_id'}) { + croak("Missing the required parameter 'pet_id' when calling delete_pet"); + } + + + # parse inputs + my $_resource_path = '/pet/{petId}'; + $_resource_path =~ s/{format}/json/; # default format to json + + my $_method = 'DELETE'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + + + # header params + if ( exists $args{'api_key'}) { + $header_params->{'api_key'} = WWW::SwaggerClient::APIClient::to_header_value($args{'api_key'}); + } + # path params + if ( exists $args{'pet_id'}) { + my $_base_variable = "{" . "petId" . "}"; + my $_base_value = WWW::SwaggerClient::APIClient::to_path_value($args{'pet_id'}); + $_resource_path =~ s/$_base_variable/$_base_value/g; + } + + my $_body_data; + + + # for HTTP post (form) + #$_body_data = $_body ? undef : $form_params; + + # make the API Call + + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data); + return; + + } + + # + # upload_file + # + # uploads an image + # + # @param int $pet_id ID of pet to update (required) + # @param string $additional_metadata Additional data to pass to server (required) + # @param file $file file to upload (required) + # @return void + # + sub upload_file { + my ($self, %args) = @_; + + + # verify the required parameter 'pet_id' is set + unless (exists $args{'pet_id'}) { + croak("Missing the required parameter 'pet_id' when calling upload_file"); + } + + + # parse inputs + my $_resource_path = '/pet/{petId}/uploadImage'; + $_resource_path =~ s/{format}/json/; # default format to json + + my $_method = 'POST'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('multipart/form-data', ); + + + + # path params + if ( exists $args{'pet_id'}) { + my $_base_variable = "{" . "petId" . "}"; + my $_base_value = WWW::SwaggerClient::APIClient::to_path_value($args{'pet_id'}); + $_resource_path =~ s/$_base_variable/$_base_value/g; + } + # form params + if ( exists $args{'additional_metadata'} ) { + + $form_params->{'additionalMetadata'} = WWW::SwaggerClient::APIClient::to_form_value($args{'additional_metadata'}); + + } # form params + if ( exists $args{'file'} ) { + $form_params->{'file'} = [] unless defined $form_params->{'file'}; + push $form_params->{'file'}, $args{'file'}; + + + } + my $_body_data; + + + # for HTTP post (form) + #$_body_data = $_body ? undef : $form_params; + + # make the API Call + + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data); + return; + + } + + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm new file mode 100644 index 000000000000..d4261c6bbec4 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm @@ -0,0 +1,288 @@ +# +# Copyright 2015 Reverb Technologies, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# +package WWW::SwaggerClient::StoreApi; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use Exporter; +use Carp qw( croak ); +use Log::Any qw($log); + + +#use WWW::Swagger::Model::Category; +#use WWW::Swagger::Model::Pet; + + +use WWW::SwaggerClient::APIClient; + +our @EXPORT_OK = qw( + get_inventory + place_order + get_order_by_id + delete_order + +); + +sub new { + my $class = shift; + my $default_api_client = WWW::SwaggerClient::APIClient->new; + my (%self) = ( + 'api_client' => $default_api_client, + @_ + ); + + #my $self = { + # #api_client => $options->{api_client} + # api_client => $default_api_client + #}; + + bless \%self, $class; + +} + + + # + # get_inventory + # + # Returns pet inventories by status + # + # @return HASH[string,int] + # + sub get_inventory { + my ($self, %args) = @_; + + + + # parse inputs + my $_resource_path = '/store/inventory'; + $_resource_path =~ s/{format}/json/; # default format to json + + my $_method = 'GET'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + + + + + + my $_body_data; + + + # for HTTP post (form) + #$_body_data = $_body ? undef : $form_params; + + # make the API Call + my $response = $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data); + if (!$response) { + return; + } + my $_response_object = $self->{api_client}->deserialize('HASH[string,int]', $response); + return $_response_object; + + } + + # + # place_order + # + # Place an order for a pet + # + # @param Order $body order placed for purchasing the pet (required) + # @return Order + # + sub place_order { + my ($self, %args) = @_; + + + + # parse inputs + my $_resource_path = '/store/order'; + $_resource_path =~ s/{format}/json/; # default format to json + + my $_method = 'POST'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + + + + + + my $_body_data; + # body params + if ( exists $args{'body'}) { + $_body_data = $args{'body'}; + } + + # for HTTP post (form) + #$_body_data = $_body ? undef : $form_params; + + # make the API Call + my $response = $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data); + if (!$response) { + return; + } + my $_response_object = $self->{api_client}->deserialize('Order', $response); + return $_response_object; + + } + + # + # get_order_by_id + # + # Find purchase order by ID + # + # @param string $order_id ID of pet that needs to be fetched (required) + # @return Order + # + sub get_order_by_id { + my ($self, %args) = @_; + + + # verify the required parameter 'order_id' is set + unless (exists $args{'order_id'}) { + croak("Missing the required parameter 'order_id' when calling get_order_by_id"); + } + + + # parse inputs + my $_resource_path = '/store/order/{orderId}'; + $_resource_path =~ s/{format}/json/; # default format to json + + my $_method = 'GET'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + + + + # path params + if ( exists $args{'order_id'}) { + my $_base_variable = "{" . "orderId" . "}"; + my $_base_value = WWW::SwaggerClient::APIClient::to_path_value($args{'order_id'}); + $_resource_path =~ s/$_base_variable/$_base_value/g; + } + + my $_body_data; + + + # for HTTP post (form) + #$_body_data = $_body ? undef : $form_params; + + # make the API Call + my $response = $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data); + if (!$response) { + return; + } + my $_response_object = $self->{api_client}->deserialize('Order', $response); + return $_response_object; + + } + + # + # delete_order + # + # Delete purchase order by ID + # + # @param string $order_id ID of the order that needs to be deleted (required) + # @return void + # + sub delete_order { + my ($self, %args) = @_; + + + # verify the required parameter 'order_id' is set + unless (exists $args{'order_id'}) { + croak("Missing the required parameter 'order_id' when calling delete_order"); + } + + + # parse inputs + my $_resource_path = '/store/order/{orderId}'; + $_resource_path =~ s/{format}/json/; # default format to json + + my $_method = 'DELETE'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + + + + # path params + if ( exists $args{'order_id'}) { + my $_base_variable = "{" . "orderId" . "}"; + my $_base_value = WWW::SwaggerClient::APIClient::to_path_value($args{'order_id'}); + $_resource_path =~ s/$_base_variable/$_base_value/g; + } + + my $_body_data; + + + # for HTTP post (form) + #$_body_data = $_body ? undef : $form_params; + + # make the API Call + + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data); + return; + + } + + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm new file mode 100644 index 000000000000..2e5889ba39e0 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm @@ -0,0 +1,508 @@ +# +# Copyright 2015 Reverb Technologies, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# +package WWW::SwaggerClient::UserApi; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use Exporter; +use Carp qw( croak ); +use Log::Any qw($log); + + +#use WWW::Swagger::Model::Category; +#use WWW::Swagger::Model::Pet; + + +use WWW::SwaggerClient::APIClient; + +our @EXPORT_OK = qw( + create_user + create_users_with_array_input + create_users_with_list_input + login_user + logout_user + get_user_by_name + update_user + delete_user + +); + +sub new { + my $class = shift; + my $default_api_client = WWW::SwaggerClient::APIClient->new; + my (%self) = ( + 'api_client' => $default_api_client, + @_ + ); + + #my $self = { + # #api_client => $options->{api_client} + # api_client => $default_api_client + #}; + + bless \%self, $class; + +} + + + # + # create_user + # + # Create user + # + # @param User $body Created user object (required) + # @return void + # + sub create_user { + my ($self, %args) = @_; + + + + # parse inputs + my $_resource_path = '/user'; + $_resource_path =~ s/{format}/json/; # default format to json + + my $_method = 'POST'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + + + + + + my $_body_data; + # body params + if ( exists $args{'body'}) { + $_body_data = $args{'body'}; + } + + # for HTTP post (form) + #$_body_data = $_body ? undef : $form_params; + + # make the API Call + + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data); + return; + + } + + # + # create_users_with_array_input + # + # Creates list of users with given input array + # + # @param ARRAY[User] $body List of user object (required) + # @return void + # + sub create_users_with_array_input { + my ($self, %args) = @_; + + + + # parse inputs + my $_resource_path = '/user/createWithArray'; + $_resource_path =~ s/{format}/json/; # default format to json + + my $_method = 'POST'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + + + + + + my $_body_data; + # body params + if ( exists $args{'body'}) { + $_body_data = $args{'body'}; + } + + # for HTTP post (form) + #$_body_data = $_body ? undef : $form_params; + + # make the API Call + + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data); + return; + + } + + # + # create_users_with_list_input + # + # Creates list of users with given input array + # + # @param ARRAY[User] $body List of user object (required) + # @return void + # + sub create_users_with_list_input { + my ($self, %args) = @_; + + + + # parse inputs + my $_resource_path = '/user/createWithList'; + $_resource_path =~ s/{format}/json/; # default format to json + + my $_method = 'POST'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + + + + + + my $_body_data; + # body params + if ( exists $args{'body'}) { + $_body_data = $args{'body'}; + } + + # for HTTP post (form) + #$_body_data = $_body ? undef : $form_params; + + # make the API Call + + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data); + return; + + } + + # + # login_user + # + # Logs user into the system + # + # @param string $username The user name for login (required) + # @param string $password The password for login in clear text (required) + # @return string + # + sub login_user { + my ($self, %args) = @_; + + + + # parse inputs + my $_resource_path = '/user/login'; + $_resource_path =~ s/{format}/json/; # default format to json + + my $_method = 'GET'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + + # query params + if ( exists $args{'username'}) { + $query_params->{'username'} = WWW::::APIClient::to_query_value($args{'username'}); + } # query params + if ( exists $args{'password'}) { + $query_params->{'password'} = WWW::::APIClient::to_query_value($args{'password'}); + } + + + + my $_body_data; + + + # for HTTP post (form) + #$_body_data = $_body ? undef : $form_params; + + # make the API Call + my $response = $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data); + if (!$response) { + return; + } + my $_response_object = $self->{api_client}->deserialize('string', $response); + return $_response_object; + + } + + # + # logout_user + # + # Logs out current logged in user session + # + # @return void + # + sub logout_user { + my ($self, %args) = @_; + + + + # parse inputs + my $_resource_path = '/user/logout'; + $_resource_path =~ s/{format}/json/; # default format to json + + my $_method = 'GET'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + + + + + + my $_body_data; + + + # for HTTP post (form) + #$_body_data = $_body ? undef : $form_params; + + # make the API Call + + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data); + return; + + } + + # + # get_user_by_name + # + # Get user by user name + # + # @param string $username The name that needs to be fetched. Use user1 for testing. (required) + # @return User + # + sub get_user_by_name { + my ($self, %args) = @_; + + + # verify the required parameter 'username' is set + unless (exists $args{'username'}) { + croak("Missing the required parameter 'username' when calling get_user_by_name"); + } + + + # parse inputs + my $_resource_path = '/user/{username}'; + $_resource_path =~ s/{format}/json/; # default format to json + + my $_method = 'GET'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + + + + # path params + if ( exists $args{'username'}) { + my $_base_variable = "{" . "username" . "}"; + my $_base_value = WWW::SwaggerClient::APIClient::to_path_value($args{'username'}); + $_resource_path =~ s/$_base_variable/$_base_value/g; + } + + my $_body_data; + + + # for HTTP post (form) + #$_body_data = $_body ? undef : $form_params; + + # make the API Call + my $response = $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data); + if (!$response) { + return; + } + my $_response_object = $self->{api_client}->deserialize('User', $response); + return $_response_object; + + } + + # + # update_user + # + # Updated user + # + # @param string $username name that need to be deleted (required) + # @param User $body Updated user object (required) + # @return void + # + sub update_user { + my ($self, %args) = @_; + + + # verify the required parameter 'username' is set + unless (exists $args{'username'}) { + croak("Missing the required parameter 'username' when calling update_user"); + } + + + # parse inputs + my $_resource_path = '/user/{username}'; + $_resource_path =~ s/{format}/json/; # default format to json + + my $_method = 'PUT'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + + + + # path params + if ( exists $args{'username'}) { + my $_base_variable = "{" . "username" . "}"; + my $_base_value = WWW::SwaggerClient::APIClient::to_path_value($args{'username'}); + $_resource_path =~ s/$_base_variable/$_base_value/g; + } + + my $_body_data; + # body params + if ( exists $args{'body'}) { + $_body_data = $args{'body'}; + } + + # for HTTP post (form) + #$_body_data = $_body ? undef : $form_params; + + # make the API Call + + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data); + return; + + } + + # + # delete_user + # + # Delete user + # + # @param string $username The name that needs to be deleted (required) + # @return void + # + sub delete_user { + my ($self, %args) = @_; + + + # verify the required parameter 'username' is set + unless (exists $args{'username'}) { + croak("Missing the required parameter 'username' when calling delete_user"); + } + + + # parse inputs + my $_resource_path = '/user/{username}'; + $_resource_path =~ s/{format}/json/; # default format to json + + my $_method = 'DELETE'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + + + + # path params + if ( exists $args{'username'}) { + my $_base_variable = "{" . "username" . "}"; + my $_base_value = WWW::SwaggerClient::APIClient::to_path_value($args{'username'}); + $_resource_path =~ s/$_base_variable/$_base_value/g; + } + + my $_body_data; + + + # for HTTP post (form) + #$_body_data = $_body ? undef : $form_params; + + # make the API Call + + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data); + return; + + } + + + +1; diff --git a/samples/client/petstore/perl/pom.xml b/samples/client/petstore/perl/pom.xml new file mode 100644 index 000000000000..1ce1761c4334 --- /dev/null +++ b/samples/client/petstore/perl/pom.xml @@ -0,0 +1,46 @@ + + 4.0.0 + com.wordnik + PerlPetstoreClientTests + pom + 1.0-SNAPSHOT + Perl Swagger Petstore Client + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + Test::More + integration-test + + exec + + + perl + + t/01_pet_api.t + + + + + + + + diff --git a/samples/client/petstore/perl/t/01_pet_api.t b/samples/client/petstore/perl/t/01_pet_api.t new file mode 100644 index 000000000000..7855254e6578 --- /dev/null +++ b/samples/client/petstore/perl/t/01_pet_api.t @@ -0,0 +1,69 @@ +use Test::More tests => 31; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + +use_ok('WWW::SwaggerClient::PetApi'); +use_ok('WWW::SwaggerClient::APIClient'); +use_ok('WWW::SwaggerClient::Object::Pet'); +use_ok('WWW::SwaggerClient::Object::Tag'); +use_ok('WWW::SwaggerClient::Object::Category'); +my $api = WWW::SwaggerClient::PetApi->new(); + +# test select_header_content_type +is $api->{api_client}->select_header_content_type('application/xml', 'Application/JSON'), 'application/json', 'get the proper content type application/json but not application/xml'; +is $api->{api_client}->select_header_content_type('application/xml'), 'application/xml', 'get the proper content type application/json'; +is $api->{api_client}->select_header_content_type(''), 'application/json', 'get the proper content type application/json (default)'; + +# test select_header_accept +is $api->{api_client}->select_header_accept('application/xml', 'Application/JSON'), 'application/json', 'get the proper accept application/json but not application/xml'; +is $api->{api_client}->select_header_content_type('application/xml'), 'application/xml', 'get the proper accept application/json'; +is $api->{api_client}->select_header_accept(''), undef, 'get the proper accept "undef" (default)'; + +my $pet_id = 10008; + +my $category = WWW::SwaggerClient::Object::Category->new('id' => '22', 'name' => 'perl'); +my $tag = WWW::SwaggerClient::Object::Tag->new('id' => '11', 'name' => 'just kidding'); +my $pet = WWW::SwaggerClient::Object::Pet->new('id' => $pet_id, 'name' => 'perl test', + "photoUrls" => ['123', 'oop'], 'tags' => [$tag], 'status' => 'pending', 'category' => $category); + +isa_ok($api, 'WWW::SwaggerClient::PetApi'); +isa_ok($category, 'WWW::SwaggerClient::Object::Category'); +isa_ok($tag, 'WWW::SwaggerClient::Object::Tag'); +isa_ok($pet, 'WWW::SwaggerClient::Object::Pet'); + +my $pet_hash = $pet->to_hash; + +is $pet_hash->{category}->{id}, '22', 'get the proper category id'; +is $pet_hash->{category}->{name}, 'perl', 'get the proper category name'; +is $pet_hash->{tags}[0]->{name}, 'just kidding', 'get the proper tag name'; +is $pet_hash->{tags}[0]->{id}, '11', 'get the proper tag id'; + +my $add_pet = $api->add_pet(body => $pet); + +my $get_pet = $api->get_pet_by_id(pet_id => $pet_id); +my $get_pet_hash = $get_pet->to_hash; +is $get_pet_hash->{name}, 'perl test', 'get the proper pet name from get_pet_by_id'; +is $get_pet_hash->{id}, '10008', 'get the proper pet id from get_pet_by_id'; +is $get_pet_hash->{category}->{name}, 'perl', 'get the proper category name from get_pet_by_id'; +is $get_pet_hash->{category}->{id}, '22', 'get the proper category id from get_pet_by_id'; +is $get_pet_hash->{category}->{name}, 'perl', 'get the proper category from get_pet_by_id'; +is $get_pet_hash->{tags}[0]->{name}, 'just kidding', 'get the proper tag from get_pet_by_id'; +is $get_pet_hash->{tags}[0]->{id}, '11', 'get the proper tag id from get_pet_by_id'; + +my $update_pet_with_form = $api->update_pet_with_form(pet_id => $pet_id, name => 'test_name', status => 'sold'); +is $update_pet_with_form, undef, 'get the null response from update_pet_wth_form'; + +my $get_pet_after_update = $api->get_pet_by_id(pet_id => $pet_id); +is $get_pet_after_update->{status}, 'sold', 'get the updated status after update_pet_with_form'; + +my $upload_pet = $api->upload_file(pet_id => $pet_id, additional_metadata => 'testabc', file => 'test.pl'); +is $upload_pet, undef, 'get the null response from upload_pet'; + +my $delete_pet = $api->delete_pet(pet_id => $pet_id); +is $delete_pet, undef, 'get the null response from delete_pet'; +throws_ok{$api->get_pet_by_id(pet_id => $pet_id)} qr/API Exception\(404\): Not Found/, "throw 404 error about pet not found after delete"; +#is $get_pet_after_delete->{status}, undef, 'get the updated status after update_pet_with_form'; + diff --git a/samples/client/petstore/perl/test.pl b/samples/client/petstore/perl/test.pl new file mode 100755 index 000000000000..eb06f786f98e --- /dev/null +++ b/samples/client/petstore/perl/test.pl @@ -0,0 +1,39 @@ +#!/usr/bin/perl +# +# +use lib 'lib'; +use strict; +use warnings; +use WWW::SwaggerClient::PetApi; +use WWW::SwaggerClient::APIClient; +use WWW::SwaggerClient::Object::Pet; +use WWW::SwaggerClient::Object::Tag; +use WWW::SwaggerClient::Object::Category; +use JSON; +use Data::Dumper; +use DateTime; + +my $api = WWW::SwaggerClient::PetApi->new(); + +my $pet_id = 10008; + +my $category = WWW::SwaggerClient::Object::Category->new('id' => '2', 'name' => 'perl'); +my $tag = WWW::SwaggerClient::Object::Tag->new('id' => '1', 'name' => 'just kidding'); +my $pet = WWW::SwaggerClient::Object::Pet->new('id' => $pet_id, 'name' => 'perl test', + "photoUrls" => ['123', 'oop'], 'tags' => [$tag], 'status' => 'pending', 'category' => $category); + +print "\npet(object)=".Dumper $pet; +my $json = JSON->new->convert_blessed; + +my $new_pet = WWW::SwaggerClient::Object::Pet->new(); +$new_pet = $new_pet->from_hash($pet->to_hash); +print "new_pet(hash):".Dumper($new_pet->to_hash); + +print "\nTest Petstore endpoints\n"; +print "\nupload_file:".Dumper $api->upload_file(pet_id => $pet_id, additional_metadata => 'testabc', file => './test.pl'); +print "\nadd_pet:".Dumper $api->add_pet(body => $pet); +print "\nget_pet_by_id:".Dumper $api->get_pet_by_id(pet_id => $pet_id); +print "\nupdate_pet_with_form:".Dumper $api->update_pet_with_form(pet_id => $pet_id, name => 'test_name', status => 'test status'); +print "\ndelete_pet:".Dumper $api->delete_pet(pet_id => $pet_id); + + diff --git a/samples/client/petstore/php/SwaggerClient-php/SwaggerClient.php b/samples/client/petstore/php/SwaggerClient-php/SwaggerClient.php index 058aa169504c..3c02d861ef18 100644 --- a/samples/client/petstore/php/SwaggerClient-php/SwaggerClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/SwaggerClient.php @@ -1,7 +1,4 @@ headerName . ": " . $this->headerValue; } - if ((isset($headerName['Content-Type']) and strpos($headerName['Content-Type'], "multipart/form-data") === FALSE) and (is_object($postData) or is_array($postData))) { + // form data + if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers)) { + $postData = http_build_query($postData); + } + else if ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers)) { // json model $postData = json_encode($this->sanitizeForSerialization($postData)); } @@ -138,21 +142,20 @@ class APIClient { $response_info = curl_getinfo($curl); // Handle the response - if ($response_info['http_code'] == 0) { - throw new APIClientException("TIMEOUT: api call to " . $url . - " took more than 5s to return", 0, $response_info, $response); + if ($response === false) { // error, likely in the client side + throw new APIClientException("API Error ($url): ".curl_error($curl), 0, $response_info, $response); } else if ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { $data = json_decode($response); if (json_last_error() > 0) { // if response is a string $data = $response; } - } else if ($response_info['http_code'] == 401) { + } else if ($response_info['http_code'] == 401) { // server returns 401 throw new APIClientException("Unauthorized API request to " . $url . ": " . serialize($response), 0, $response_info, $response); - } else if ($response_info['http_code'] == 404) { + } else if ($response_info['http_code'] == 404) { // server returns 404 $data = null; } else { - throw new APIClientException("Can't connect to the api: " . $url . + throw new APIClientException("Can't connect to the API: " . $url . " response code: " . $response_info['http_code'], 0, $response_info, $response); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php index 80d9c040d1ef..07f6181a7309 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php @@ -38,6 +38,7 @@ class PetApi { * @return void */ public function updatePet($body) { + // parse inputs $resourcePath = "/pet"; @@ -67,11 +68,9 @@ class PetApi { // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } - - // for HTTP post (form) - if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") !== FALSE) { - $httpBody = http_build_query($formParams); + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; } // make the API Call @@ -91,6 +90,7 @@ class PetApi { * @return void */ public function addPet($body) { + // parse inputs $resourcePath = "/pet"; @@ -120,11 +120,9 @@ class PetApi { // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } - - // for HTTP post (form) - if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") !== FALSE) { - $httpBody = http_build_query($formParams); + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; } // make the API Call @@ -144,6 +142,7 @@ class PetApi { * @return array[Pet] */ public function findPetsByStatus($status) { + // parse inputs $resourcePath = "/pet/findByStatus"; @@ -172,11 +171,9 @@ class PetApi { // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } - - // for HTTP post (form) - if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") !== FALSE) { - $httpBody = http_build_query($formParams); + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; } // make the API Call @@ -202,6 +199,7 @@ class PetApi { * @return array[Pet] */ public function findPetsByTags($tags) { + // parse inputs $resourcePath = "/pet/findByTags"; @@ -230,11 +228,9 @@ class PetApi { // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } - - // for HTTP post (form) - if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") !== FALSE) { - $httpBody = http_build_query($formParams); + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; } // make the API Call @@ -260,6 +256,12 @@ class PetApi { * @return Pet */ public function getPetById($pet_id) { + + // verify the required parameter 'pet_id' is set + if ($pet_id === null) { + throw new \Exception("Missing the required parameter $pet_id when calling getPetById"); + } + // parse inputs $resourcePath = "/pet/{petId}"; @@ -289,11 +291,9 @@ class PetApi { // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } - - // for HTTP post (form) - if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") !== FALSE) { - $httpBody = http_build_query($formParams); + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; } // make the API Call @@ -321,6 +321,12 @@ class PetApi { * @return void */ public function updatePetWithForm($pet_id, $name, $status) { + + // verify the required parameter 'pet_id' is set + if ($pet_id === null) { + throw new \Exception("Missing the required parameter $pet_id when calling updatePetWithForm"); + } + // parse inputs $resourcePath = "/pet/{petId}"; @@ -356,11 +362,9 @@ class PetApi { // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } - - // for HTTP post (form) - if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") !== FALSE) { - $httpBody = http_build_query($formParams); + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; } // make the API Call @@ -381,6 +385,12 @@ class PetApi { * @return void */ public function deletePet($api_key, $pet_id) { + + // verify the required parameter 'pet_id' is set + if ($pet_id === null) { + throw new \Exception("Missing the required parameter $pet_id when calling deletePet"); + } + // parse inputs $resourcePath = "/pet/{petId}"; @@ -413,11 +423,9 @@ class PetApi { // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } - - // for HTTP post (form) - if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") !== FALSE) { - $httpBody = http_build_query($formParams); + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; } // make the API Call @@ -435,10 +443,16 @@ class PetApi { * * @param int $pet_id ID of pet to update (required) * @param string $additional_metadata Additional data to pass to server (required) - * @param file $file file to upload (required) + * @param string $file file to upload (required) * @return void */ public function uploadFile($pet_id, $additional_metadata, $file) { + + // verify the required parameter 'pet_id' is set + if ($pet_id === null) { + throw new \Exception("Missing the required parameter $pet_id when calling uploadFile"); + } + // parse inputs $resourcePath = "/pet/{petId}/uploadImage"; @@ -474,11 +488,9 @@ class PetApi { // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } - - // for HTTP post (form) - if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") !== FALSE) { - $httpBody = http_build_query($formParams); + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; } // make the API Call diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php index 4e40ed983b93..78e23ec90344 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php @@ -37,6 +37,7 @@ class StoreApi { * @return map[string,int] */ public function getInventory() { + // parse inputs $resourcePath = "/store/inventory"; @@ -62,11 +63,9 @@ class StoreApi { // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } - - // for HTTP post (form) - if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") !== FALSE) { - $httpBody = http_build_query($formParams); + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; } // make the API Call @@ -92,6 +91,7 @@ class StoreApi { * @return Order */ public function placeOrder($body) { + // parse inputs $resourcePath = "/store/order"; @@ -121,11 +121,9 @@ class StoreApi { // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } - - // for HTTP post (form) - if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") !== FALSE) { - $httpBody = http_build_query($formParams); + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; } // make the API Call @@ -151,6 +149,12 @@ class StoreApi { * @return Order */ public function getOrderById($order_id) { + + // verify the required parameter 'order_id' is set + if ($order_id === null) { + throw new \Exception("Missing the required parameter $order_id when calling getOrderById"); + } + // parse inputs $resourcePath = "/store/order/{orderId}"; @@ -180,11 +184,9 @@ class StoreApi { // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } - - // for HTTP post (form) - if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") !== FALSE) { - $httpBody = http_build_query($formParams); + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; } // make the API Call @@ -210,6 +212,12 @@ class StoreApi { * @return void */ public function deleteOrder($order_id) { + + // verify the required parameter 'order_id' is set + if ($order_id === null) { + throw new \Exception("Missing the required parameter $order_id when calling deleteOrder"); + } + // parse inputs $resourcePath = "/store/order/{orderId}"; @@ -239,11 +247,9 @@ class StoreApi { // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } - - // for HTTP post (form) - if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") !== FALSE) { - $httpBody = http_build_query($formParams); + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; } // make the API Call diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php index f3e9e7f4cc6b..a3ed8a8ab255 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php @@ -38,6 +38,7 @@ class UserApi { * @return void */ public function createUser($body) { + // parse inputs $resourcePath = "/user"; @@ -67,11 +68,9 @@ class UserApi { // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } - - // for HTTP post (form) - if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") !== FALSE) { - $httpBody = http_build_query($formParams); + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; } // make the API Call @@ -91,6 +90,7 @@ class UserApi { * @return void */ public function createUsersWithArrayInput($body) { + // parse inputs $resourcePath = "/user/createWithArray"; @@ -120,11 +120,9 @@ class UserApi { // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } - - // for HTTP post (form) - if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") !== FALSE) { - $httpBody = http_build_query($formParams); + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; } // make the API Call @@ -144,6 +142,7 @@ class UserApi { * @return void */ public function createUsersWithListInput($body) { + // parse inputs $resourcePath = "/user/createWithList"; @@ -173,11 +172,9 @@ class UserApi { // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } - - // for HTTP post (form) - if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") !== FALSE) { - $httpBody = http_build_query($formParams); + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; } // make the API Call @@ -198,6 +195,7 @@ class UserApi { * @return string */ public function loginUser($username, $password) { + // parse inputs $resourcePath = "/user/login"; @@ -229,11 +227,9 @@ class UserApi { // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } - - // for HTTP post (form) - if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") !== FALSE) { - $httpBody = http_build_query($formParams); + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; } // make the API Call @@ -258,6 +254,7 @@ class UserApi { * @return void */ public function logoutUser() { + // parse inputs $resourcePath = "/user/logout"; @@ -283,11 +280,9 @@ class UserApi { // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } - - // for HTTP post (form) - if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") !== FALSE) { - $httpBody = http_build_query($formParams); + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; } // make the API Call @@ -307,6 +302,12 @@ class UserApi { * @return User */ public function getUserByName($username) { + + // verify the required parameter 'username' is set + if ($username === null) { + throw new \Exception("Missing the required parameter $username when calling getUserByName"); + } + // parse inputs $resourcePath = "/user/{username}"; @@ -336,11 +337,9 @@ class UserApi { // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } - - // for HTTP post (form) - if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") !== FALSE) { - $httpBody = http_build_query($formParams); + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; } // make the API Call @@ -367,6 +366,12 @@ class UserApi { * @return void */ public function updateUser($username, $body) { + + // verify the required parameter 'username' is set + if ($username === null) { + throw new \Exception("Missing the required parameter $username when calling updateUser"); + } + // parse inputs $resourcePath = "/user/{username}"; @@ -400,11 +405,9 @@ class UserApi { // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } - - // for HTTP post (form) - if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") !== FALSE) { - $httpBody = http_build_query($formParams); + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; } // make the API Call @@ -424,6 +427,12 @@ class UserApi { * @return void */ public function deleteUser($username) { + + // verify the required parameter 'username' is set + if ($username === null) { + throw new \Exception("Missing the required parameter $username when calling deleteUser"); + } + // parse inputs $resourcePath = "/user/{username}"; @@ -453,11 +462,9 @@ class UserApi { // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } - - // for HTTP post (form) - if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") !== FALSE) { - $httpBody = http_build_query($formParams); + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; } // make the API Call diff --git a/samples/client/petstore/php/SwaggerClient-php/pom.xml b/samples/client/petstore/php/SwaggerClient-php/pom.xml new file mode 100644 index 000000000000..b1aeddcf7ead --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/pom.xml @@ -0,0 +1,60 @@ + + 4.0.0 + com.wordnik + PhpPetstoreClientTests + pom + 1.0-SNAPSHOT + PHP Swagger Petstore Client + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + bundle-install + pre-integration-test + + exec + + + composer + + install + + + + + bundle-test + integration-test + + exec + + + vendor/bin/phpunit + + tests + + + + + + + + + diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index 3286208ec56b..d2d398ae1406 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -1,16 +1,146 @@ id = $new_pet_id; + $new_pet->name = "PHP Unit Test"; + // new tag + $tag= new SwaggerClient\models\Tag; + $tag->id = $new_pet_id; // use the same id as pet + $tag->name = "test php tag"; + // new category + $category = new SwaggerClient\models\Category; + $category->id = $new_pet_id; // use the same id as pet + $category->name = "test php category"; + + $new_pet->tags = [$tag]; + $new_pet->category = $category; + + $pet_api = new SwaggerClient\PetAPI($api_client); + // add a new pet (model) + $add_response = $pet_api->addPet($new_pet); + } + + // test getPetById with a Pet object (id 10005) public function testGetPetById() { // initialize the API client $api_client = new SwaggerClient\APIClient('http://petstore.swagger.io/v2'); - $petId = 10005; // ID of pet that needs to be fetched + $pet_id = 10005; // ID of pet that needs to be fetched $pet_api = new SwaggerClient\PetAPI($api_client); // return Pet (model) - $response = $pet_api->getPetById($petId); - $this->assertSame($response->id, $petId); + $response = $pet_api->getPetById($pet_id); + $this->assertSame($response->id, $pet_id); + $this->assertSame($response->name, 'PHP Unit Test'); + $this->assertSame($response->category->id, $pet_id); + $this->assertSame($response->category->name, 'test php category'); + $this->assertSame($response->tags[0]->id, $pet_id); + $this->assertSame($response->tags[0]->name, 'test php tag'); } + + // test getPetByStatus and verify by the "id" of the response + public function testFindPetByStatus() + { + // initialize the API client + $api_client = new SwaggerClient\APIClient('http://petstore.swagger.io/v2'); + $pet_api = new SwaggerClient\PetAPI($api_client); + // return Pet (model) + $response = $pet_api->findPetsByStatus("available"); + $this->assertGreaterThan(0, count($response)); // at least one object returned + $this->assertSame(get_class($response[0]), "SwaggerClient\models\Pet"); // verify the object is Pet + // loop through result to ensure status is "available" + foreach ($response as $_pet) { + $this->assertSame($_pet['status'], "available"); + } + // test invalid status + $response = $pet_api->findPetsByStatus("unknown_and_incorrect_status"); + $this->assertSame(count($response), 0); // confirm no object returned + } + + // test updatePet (model/json)and verify by the "id" of the response + public function testUpdatePet() + { + // initialize the API client + $api_client = new SwaggerClient\APIClient('http://petstore.swagger.io/v2'); + $pet_id = 10001; // ID of pet that needs to be fetched + $pet_api = new SwaggerClient\PetAPI($api_client); + // create updated pet object + $updated_pet = new SwaggerClient\models\Pet; + $updated_pet->id = $pet_id; + $updated_pet->status = "pending"; // new status + // update Pet (model/json) + $update_response = $pet_api->updatePet($updated_pet); + // return nothing (void) + $this->assertSame($update_response, NULL); + // verify updated Pet + $response = $pet_api->getPetById($pet_id); + $this->assertSame($response->id, $pet_id); + $this->assertSame($response->status, 'pending'); + } + + // test updatePet and verify by the "id" of the response + public function testUpdatePetWithForm() + { + // initialize the API client + $api_client = new SwaggerClient\APIClient('http://petstore.swagger.io/v2'); + $pet_id = 10001; // ID of pet that needs to be fetched + $pet_api = new SwaggerClient\PetAPI($api_client); + // update Pet (form) + $update_response = $pet_api->updatePetWithForm($pet_id, null, 'sold'); + // return nothing (void) + $this->assertSame($update_response, NULL); + // TODO commented out for the time being since it's broken + // https://github.com/swagger-api/swagger-codegen/issues/656 + // verify updated Pet + //$response = $pet_api->getPetById($pet_id); + //$this->assertSame($response->id, $pet_id); + //$this->assertSame($response->status, 'sold'); + } + + // test addPet and verify by the "id" and "name" of the response + public function testAddPet() + { + // initialize the API client + $api_client = new SwaggerClient\APIClient('http://petstore.swagger.io/v2'); + $new_pet_id = 10001; + $new_pet = new SwaggerClient\models\Pet; + $new_pet->id = $new_pet_id; + $new_pet->name = "PHP Unit Test"; + $pet_api = new SwaggerClient\PetAPI($api_client); + // add a new pet (model) + $add_response = $pet_api->addPet($new_pet); + // return nothing (void) + $this->assertSame($add_response, NULL); + // verify added Pet + $response = $pet_api->getPetById($new_pet_id); + $this->assertSame($response->id, $new_pet_id); + $this->assertSame($response->name, 'PHP Unit Test'); + } + + // test + public function testUploadFile() + { + // initialize the API client + $api_client = new SwaggerClient\APIClient('http://petstore.swagger.io/v2'); + $pet_api = new SwaggerClient\PetAPI($api_client); + // upload file + $pet_id = 10001; + $add_response = $pet_api->uploadFile($pet_id, "test meta", "./composer.json"); + // return nothing (void) + $this->assertSame($add_response, NULL); + } + } + ?> + diff --git a/samples/client/petstore/qt5cpp/PetStore/PetApiTests.cpp b/samples/client/petstore/qt5cpp/PetStore/PetApiTests.cpp new file mode 100644 index 000000000000..829fbe926409 --- /dev/null +++ b/samples/client/petstore/qt5cpp/PetStore/PetApiTests.cpp @@ -0,0 +1,273 @@ +#include "PetApiTests.h" + +#include +#include +#include +#include + +PetApiTests::PetApiTests () {} + +PetApiTests::~PetApiTests () { + exit(1); +} + +SWGPetApi* PetApiTests::getApi() { + SWGPetApi* api = new SWGPetApi(); + api->host = "http://petstore.swagger.io"; + api->basePath = "/v2"; + return api; +} + +SWGPet* PetApiTests::createRandomPet() { + SWGPet* pet = new SWGPet(); + qint64 id = QDateTime::currentMSecsSinceEpoch(); + + pet->setName(new QString("monster")); + pet->setId(id); + pet->setStatus(new QString("freaky")); + + return pet; +} + +void PetApiTests::runTests() { + PetApiTests* tests = new PetApiTests(); + QTest::qExec(tests); + delete tests; +} + +void PetApiTests::getPetByIdTest() { + SWGPetApi* api = getApi(); + + static QEventLoop loop; + QTimer timer; + timer.setInterval(1000); + timer.setSingleShot(true); + + auto validator = [](SWGPet* pet) { + QVERIFY(pet->getId() == 3); + loop.quit(); + }; + + connect(api, &SWGPetApi::getPetByIdSignal, this, validator); + connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit); + api->getPetById(3); + timer.start(); + loop.exec(); + QVERIFY2(timer.isActive(), "didn't finish within timeout"); + delete api; +} + +void PetApiTests::findPetsByStatusTest() { + SWGPetApi* api = getApi(); + + static QEventLoop loop; + QTimer timer; + timer.setInterval(1000); + timer.setSingleShot(true); + + auto validator = [](QList* pets) { + foreach(SWGPet* pet, *pets) { + QVERIFY(pet->getStatus()->startsWith("available") || pet->getStatus()->startsWith("sold")); + } + loop.quit(); + }; + + connect(api, &SWGPetApi::findPetsByStatusSignal, this, validator); + connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit); + + QList* status = new QList(); + status->append(new QString("available")); + status->append(new QString("sold")); + api->findPetsByStatus(status); + timer.start(); + loop.exec(); + QVERIFY2(timer.isActive(), "didn't finish within timeout"); + delete api; +} + +void PetApiTests::createAndGetPetTest() { + SWGPetApi* api = getApi(); + + static QEventLoop loop; + QTimer timer; + timer.setInterval(1000); + timer.setSingleShot(true); + + auto validator = []() { + // pet created + loop.quit(); + }; + + connect(api, &SWGPetApi::addPetSignal, this, validator); + connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit); + + SWGPet* pet = createRandomPet(); + qint64 id = pet->getId(); + + api->addPet(*pet); + timer.start(); + loop.exec(); + QVERIFY2(timer.isActive(), "didn't finish within timeout"); + + timer.setInterval(1000); + timer.setSingleShot(true); + + auto getPetValidator = [](SWGPet* pet) { + QVERIFY(pet->getId() > 0); + QVERIFY(pet->getStatus()->compare("freaky") == 0); + loop.quit(); + }; + + connect(api, &SWGPetApi::getPetByIdSignal, this, getPetValidator); + connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit); + + api->getPetById(id); + timer.start(); + loop.exec(); + QVERIFY2(timer.isActive(), "didn't finish within timeout"); + delete api; +} + +void PetApiTests::updatePetTest() { + static SWGPetApi* api = getApi(); + + SWGPet* pet = createRandomPet(); + static SWGPet* petToCheck; + qint64 id = pet->getId(); + static QEventLoop loop; + QTimer timer; + timer.setInterval(100000); + timer.setSingleShot(true); + + auto validator = []() { + loop.quit(); + }; + + connect(api, &SWGPetApi::addPetSignal, this, validator); + connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit); + + // create pet + api->addPet(*pet); + timer.start(); + loop.exec(); + QVERIFY2(timer.isActive(), "didn't finish within timeout"); + + // fetch it + timer.setInterval(1000); + timer.setSingleShot(true); + + auto fetchPet = [](SWGPet* pet) { + petToCheck = pet; + loop.quit(); + }; + connect(api, &SWGPetApi::getPetByIdSignal, this, fetchPet); + connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit); + + // create pet + api->getPetById(id); + timer.start(); + loop.exec(); + QVERIFY2(timer.isActive(), "didn't finish within timeout"); + + // update it + timer.setInterval(1000); + timer.setSingleShot(true); + auto updatePetTest = []() { + loop.quit(); + }; + + connect(api, &SWGPetApi::updatePetSignal, this, updatePetTest); + connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit); + + // update pet + petToCheck->setStatus(new QString("scary")); + api->updatePet(*petToCheck); + timer.start(); + loop.exec(); + QVERIFY2(timer.isActive(), "didn't finish within timeout"); + + // check it + timer.setInterval(1000); + timer.setSingleShot(true); + + auto fetchPet2 = [](SWGPet* pet) { + QVERIFY(pet->getId() == petToCheck->getId()); + QVERIFY(pet->getStatus()->compare(petToCheck->getStatus()) == 0); + loop.quit(); + }; + connect(api, &SWGPetApi::getPetByIdSignal, this, fetchPet2); + connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit); + api->getPetById(id); + timer.start(); + loop.exec(); + QVERIFY2(timer.isActive(), "didn't finish within timeout"); +} + +void PetApiTests::updatePetWithFormTest() { + static SWGPetApi* api = getApi(); + + SWGPet* pet = createRandomPet(); + static SWGPet* petToCheck; + qint64 id = pet->getId(); + static QEventLoop loop; + QTimer timer; + + // create pet + timer.setInterval(1000); + timer.setSingleShot(true); + + auto validator = []() { + loop.quit(); + }; + + connect(api, &SWGPetApi::addPetSignal, this, validator); + connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit); + api->addPet(*pet); + timer.start(); + loop.exec(); + QVERIFY2(timer.isActive(), "didn't finish within timeout"); + + // fetch it + timer.setInterval(1000); + timer.setSingleShot(true); + + auto fetchPet = [](SWGPet* pet) { + petToCheck = pet; + loop.quit(); + }; + connect(api, &SWGPetApi::getPetByIdSignal, this, fetchPet); + connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit); + + api->getPetById(id); + timer.start(); + loop.exec(); + QVERIFY2(timer.isActive(), "didn't finish within timeout"); + + // update it + timer.setInterval(1000); + timer.setSingleShot(true); + + connect(api, &SWGPetApi::updatePetWithFormSignal, this, [](){loop.quit();}); + connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit); + + api->updatePetWithForm(new QString(QString::number(id)), new QString("gorilla"), NULL); + timer.start(); + loop.exec(); + QVERIFY2(timer.isActive(), "didn't finish within timeout"); + + // fetch it + timer.setInterval(1000); + timer.setSingleShot(true); + + auto fetchUpdatedPet = [](SWGPet* pet) { + QVERIFY(pet->getName()->compare(QString("gorilla")) == 0); + loop.quit(); + }; + connect(api, &SWGPetApi::getPetByIdSignal, this, fetchUpdatedPet); + connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit); + + api->getPetById(id); + timer.start(); + loop.exec(); + QVERIFY2(timer.isActive(), "didn't finish within timeout"); +} diff --git a/samples/client/petstore/qt5cpp/PetStore/PetApiTests.h b/samples/client/petstore/qt5cpp/PetStore/PetApiTests.h new file mode 100644 index 000000000000..9fdc939ab11b --- /dev/null +++ b/samples/client/petstore/qt5cpp/PetStore/PetApiTests.h @@ -0,0 +1,35 @@ +#ifndef PETAPITESTS_H +#define PETAPITESTS_H + +#include +#include + +#include "../client/SWGPetApi.h" + +using namespace Swagger; + +class PetApiTests: public QObject { +Q_OBJECT +public: + PetApiTests(); + virtual ~PetApiTests(); + + static void runTests(); + +private: + SWGPetApi* getApi(); + SWGPet* createRandomPet(); + +signals: + void quit(); + bool success(); + +private slots: + void getPetByIdTest(); + void findPetsByStatusTest(); + void createAndGetPetTest(); + void updatePetTest(); + void updatePetWithFormTest(); +}; + +#endif // PETAPITESTS_H diff --git a/samples/client/petstore/qt5cpp/PetStore/PetStore.pro b/samples/client/petstore/qt5cpp/PetStore/PetStore.pro new file mode 100644 index 000000000000..70b3618cba63 --- /dev/null +++ b/samples/client/petstore/qt5cpp/PetStore/PetStore.pro @@ -0,0 +1,46 @@ +#------------------------------------------------- +# +# Project created by QtCreator 2015-05-14T20:56:31 +# +#------------------------------------------------- + +QT += core gui testlib network + +QT -= gui + +TARGET = PetStore +CONFIG += console +CONFIG -= app_bundle + +CONFIG += c++11 + +TEMPLATE = app + + +SOURCES += main.cpp \ + ../client/SWGCategory.cpp \ + ../client/SWGHelpers.cpp \ + ../client/SWGHttpRequest.cpp \ + ../client/SWGOrder.cpp \ + ../client/SWGPet.cpp \ + ../client/SWGPetApi.cpp \ + ../client/SWGStoreApi.cpp \ + ../client/SWGTag.cpp \ + ../client/SWGUser.cpp \ + ../client/SWGUserApi.cpp \ + PetApiTests.cpp + +HEADERS += \ + ../client/SWGCategory.h \ + ../client/SWGHelpers.h \ + ../client/SWGHttpRequest.h \ + ../client/SWGObject.h \ + ../client/SWGOrder.h \ + ../client/SWGPet.h \ + ../client/SWGPetApi.h \ + ../client/SWGStoreApi.h \ + ../client/SWGTag.h \ + ../client/SWGUser.h \ + ../client/SWGUserApi.h \ + PetApiTests.h \ + ../client/SWGModelFactory.h diff --git a/samples/client/petstore/qt5cpp/PetStore/PetStore.pro.user b/samples/client/petstore/qt5cpp/PetStore/PetStore.pro.user new file mode 100644 index 000000000000..a506d15a1d19 --- /dev/null +++ b/samples/client/petstore/qt5cpp/PetStore/PetStore.pro.user @@ -0,0 +1,269 @@ + + + + + + EnvironmentId + {e1009bf2-3b8d-440a-a972-23a1fd0a9453} + + + ProjectExplorer.Project.ActiveTarget + 0 + + + ProjectExplorer.Project.EditorSettings + + true + false + true + + Cpp + + CppGlobal + + + + QmlJS + + QmlJSGlobal + + + 2 + UTF-8 + false + 4 + false + 80 + true + true + 1 + true + false + 0 + true + 0 + 8 + true + 1 + true + true + true + false + + + + ProjectExplorer.Project.PluginSettings + + + + ProjectExplorer.Project.Target.0 + + Desktop Qt 5.4.1 clang 64bit + Desktop Qt 5.4.1 clang 64bit + qt.54.clang_64_kit + 0 + 0 + 0 + + /Users/tony/dev/projects/swagger-api/swagger-codegen/samples/client/petstore/qt5cpp/build-PetStore-Desktop_Qt_5_4_1_clang_64bit-Debug + + + true + qmake + + QtProjectManager.QMakeBuildStep + false + true + + false + false + + + true + Make + + Qt4ProjectManager.MakeStep + + -w + -r + + false + + + + 2 + Build + + ProjectExplorer.BuildSteps.Build + + + + true + Make + + Qt4ProjectManager.MakeStep + + -w + -r + + true + clean + + + 1 + Clean + + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Debug + + Qt4ProjectManager.Qt4BuildConfiguration + 2 + true + + + /Users/tony/dev/projects/swagger-api/swagger-codegen/samples/client/petstore/qt5cpp/build-PetStore-Desktop_Qt_5_4_1_clang_64bit-Release + + + true + qmake + + QtProjectManager.QMakeBuildStep + false + true + + false + false + + + true + Make + + Qt4ProjectManager.MakeStep + + -w + -r + + false + + + + 2 + Build + + ProjectExplorer.BuildSteps.Build + + + + true + Make + + Qt4ProjectManager.MakeStep + + -w + -r + + true + clean + + + 1 + Clean + + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Release + + Qt4ProjectManager.Qt4BuildConfiguration + 0 + true + + 2 + + + 0 + Deploy + + ProjectExplorer.BuildSteps.Deploy + + 1 + Deploy locally + + ProjectExplorer.DefaultDeployConfiguration + + 1 + + + + false + false + false + false + true + 0.01 + 10 + true + 1 + 25 + + 1 + true + false + true + /usr/local/bin/valgrind + + 11 + 14 + 12 + 13 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 0 + 1 + + 2 + + PetStore + + Qt4ProjectManager.Qt4RunConfiguration:/Users/tony/dev/projects/swagger-api/swagger-codegen/samples/client/petstore/qt5cpp/PetStore/PetStore.pro + + PetStore.pro + false + false + + 3768 + false + true + false + false + true + + 1 + + + + ProjectExplorer.Project.TargetCount + 1 + + + ProjectExplorer.Project.Updater.FileVersion + 18 + + + Version + 18 + + diff --git a/samples/client/petstore/qt5cpp/PetStore/main.cpp b/samples/client/petstore/qt5cpp/PetStore/main.cpp new file mode 100644 index 000000000000..800544fbded9 --- /dev/null +++ b/samples/client/petstore/qt5cpp/PetStore/main.cpp @@ -0,0 +1,12 @@ +#include +#include "PetApiTests.h" + +int main(int argc, char *argv[]) { + QCoreApplication a(argc, argv); + + PetApiTests::runTests(); + + + + return a.exec(); +} diff --git a/samples/client/petstore/qt5cpp/client/SWGCategory.cpp b/samples/client/petstore/qt5cpp/client/SWGCategory.cpp new file mode 100644 index 000000000000..9a5aaa14af71 --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/SWGCategory.cpp @@ -0,0 +1,105 @@ + +#include "SWGCategory.h" + +#include "SWGHelpers.h" + +#include +#include +#include +#include + +namespace Swagger { + + +SWGCategory::SWGCategory(QString* json) { + init(); + this->fromJson(*json); +} + +SWGCategory::SWGCategory() { + init(); +} + +SWGCategory::~SWGCategory() { + this->cleanup(); +} + +void +SWGCategory::init() { + id = 0L; + name = new QString(""); + +} + +void +SWGCategory::cleanup() { + + if(name != NULL) { + delete name; + } + +} + +SWGCategory* +SWGCategory::fromJson(QString &json) { + QByteArray array (json.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); + return this; +} + +void +SWGCategory::fromJsonObject(QJsonObject &pJson) { + setValue(&id, pJson["id"], "qint64", ""); + setValue(&name, pJson["name"], "QString", "QString"); + +} + +QString +SWGCategory::asJson () +{ + QJsonObject* obj = this->asJsonObject(); + + QJsonDocument doc(*obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject* +SWGCategory::asJsonObject() { + QJsonObject* obj = new QJsonObject(); + obj->insert("id", QJsonValue(id)); + + + toJsonValue(QString("name"), name, obj, QString("QString")); + + + + + + return obj; +} + +qint64 +SWGCategory::getId() { + return id; +} +void +SWGCategory::setId(qint64 id) { + this->id = id; +} + +QString* +SWGCategory::getName() { + return name; +} +void +SWGCategory::setName(QString* name) { + this->name = name; +} + + + +} /* namespace Swagger */ + diff --git a/samples/client/petstore/qt5cpp/client/SWGCategory.h b/samples/client/petstore/qt5cpp/client/SWGCategory.h new file mode 100644 index 000000000000..b1d5b65538f1 --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/SWGCategory.h @@ -0,0 +1,47 @@ +/* + * SWGCategory.h + * + * + */ + +#ifndef SWGCategory_H_ +#define SWGCategory_H_ + +#include + + +#include + +#include "SWGObject.h" + + +namespace Swagger { + +class SWGCategory: public SWGObject { +public: + SWGCategory(); + SWGCategory(QString* json); + virtual ~SWGCategory(); + void init(); + void cleanup(); + + QString asJson (); + QJsonObject* asJsonObject(); + void fromJsonObject(QJsonObject &json); + SWGCategory* fromJson(QString &jsonString); + + qint64 getId(); + void setId(qint64 id); + QString* getName(); + void setName(QString* name); + + +private: + qint64 id; + QString* name; + +}; + +} /* namespace Swagger */ + +#endif /* SWGCategory_H_ */ diff --git a/samples/client/petstore/qt5cpp/client/SWGHelpers.cpp b/samples/client/petstore/qt5cpp/client/SWGHelpers.cpp new file mode 100644 index 000000000000..7f4d748c2dce --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/SWGHelpers.cpp @@ -0,0 +1,166 @@ +#include "SWGHelpers.h" +#include "SWGModelFactory.h" +#include "SWGObject.h" +#import +#import +#import + +namespace Swagger { + +void +setValue(void* value, QJsonValue obj, QString type, QString complexType) { + if(value == NULL) { + // can't set value with a null pointer + return; + } + if(QStringLiteral("bool").compare(type) == 0) { + bool * val = static_cast(value); + *val = obj.toBool(); + } + else if(QStringLiteral("qint32").compare(type) == 0) { + qint32 *val = static_cast(value); + *val = obj.toInt(); + } + else if(QStringLiteral("qint64").compare(type) == 0) { + qint64 *val = static_cast(value); + *val = obj.toVariant().toLongLong(); + } + else if (QStringLiteral("QString").compare(type) == 0) { + QString **val = static_cast(value); + + if(val != NULL) { + if(!obj.isNull()) { + // create a new value and return + delete *val; + *val = new QString(obj.toString()); + return; + } + else { + // set target to NULL + delete *val; + *val = NULL; + } + } + else { + qDebug() << "Can't set value because the target pointer is NULL"; + } + } + else if(type.startsWith("SWG") && obj.isObject()) { + // complex type + QJsonObject jsonObj = obj.toObject(); + SWGObject * so = (SWGObject*)Swagger::create(type); + if(so != NULL) { + so->fromJsonObject(jsonObj); + SWGObject **val = static_cast(value); + delete *val; + *val = so; + } + } + else if(type.startsWith("QList") && QString("").compare(complexType) != 0 && obj.isArray()) { + // list of values + QList* output = new QList(); + QJsonArray arr = obj.toArray(); + foreach (const QJsonValue & jval, arr) { + if(complexType.startsWith("SWG")) { + // it's an object + SWGObject * val = (SWGObject*)create(complexType); + QJsonObject t = jval.toObject(); + + val->fromJsonObject(t); + output->append(val); + } + else { + // primitives + if(QStringLiteral("qint32").compare(complexType) == 0) { + qint32 val; + setValue(&val, jval, QStringLiteral("qint32"), QStringLiteral("")); + output->append((void*)&val); + } + else if(QStringLiteral("qint64").compare(complexType) == 0) { + qint64 val; + setValue(&val, jval, QStringLiteral("qint64"), QStringLiteral("")); + output->append((void*)&val); + } + else if(QStringLiteral("bool").compare(complexType) == 0) { + bool val; + setValue(&val, jval, QStringLiteral("bool"), QStringLiteral("")); + output->append((void*)&val); + } + } + } + QList **val = static_cast**>(value); + delete *val; + *val = output; + } +} + +void +toJsonValue(QString name, void* value, QJsonObject* output, QString type) { + if(value == NULL) { + return; + } + if(type.startsWith("SWG")) { + SWGObject *swgObject = reinterpret_cast(value); + if(swgObject != NULL) { + QJsonObject* o = (*swgObject).asJsonObject(); + if(name != NULL) { + output->insert(name, *o); + delete o; + } + else { + output->empty(); + foreach(QString key, o->keys()) { + output->insert(key, o->value(key)); + } + } + } + } + else if(QStringLiteral("QString").compare(type) == 0) { + QString* str = static_cast(value); + output->insert(name, QJsonValue(*str)); + } + else if(QStringLiteral("qint32").compare(type) == 0) { + qint32* str = static_cast(value); + output->insert(name, QJsonValue(*str)); + } + else if(QStringLiteral("qint64").compare(type) == 0) { + qint64* str = static_cast(value); + output->insert(name, QJsonValue(*str)); + } + else if(QStringLiteral("bool").compare(type) == 0) { + bool* str = static_cast(value); + output->insert(name, QJsonValue(*str)); + } +} + +void +toJsonArray(QList* value, QJsonArray* output, QString innerName, QString innerType) { + foreach(void* obj, *value) { + QJsonObject element; + + toJsonValue(NULL, obj, &element, innerType); + output->append(element); + } +} + +QString +stringValue(QString* value) { + QString* str = static_cast(value); + return QString(*str); +} + +QString +stringValue(qint32 value) { + return QString::number(value); +} + +QString +stringValue(qint64 value) { + return QString::number(value); +} + +QString +stringValue(bool value) { + return QString(value ? "true" : "false"); +} +} /* namespace Swagger */ diff --git a/samples/client/petstore/qt5cpp/client/SWGHelpers.h b/samples/client/petstore/qt5cpp/client/SWGHelpers.h new file mode 100644 index 000000000000..3a02c0952d55 --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/SWGHelpers.h @@ -0,0 +1,17 @@ +#ifndef SWGHELPERS_H +#define SWGHELPERS_H + +#include + +namespace Swagger { + void setValue(void* value, QJsonValue obj, QString type, QString complexType); + void toJsonArray(QList* value, QJsonArray* output, QString innerName, QString innerType); + void toJsonValue(QString name, void* value, QJsonObject* output, QString type); + bool isCompatibleJsonValue(QString type); + QString stringValue(QString* value); + QString stringValue(qint32 value); + QString stringValue(qint64 value); + QString stringValue(bool value); +} + +#endif // SWGHELPERS_H diff --git a/samples/client/petstore/qt5cpp/client/SWGHttpRequest.cpp b/samples/client/petstore/qt5cpp/client/SWGHttpRequest.cpp new file mode 100644 index 000000000000..f1e79c4d1975 --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/SWGHttpRequest.cpp @@ -0,0 +1,299 @@ +#include "SWGHttpRequest.h" +#include +#include +#include +#include + + +HttpRequestInput::HttpRequestInput() { + initialize(); +} + +HttpRequestInput::HttpRequestInput(QString v_url_str, QString v_http_method) { + initialize(); + url_str = v_url_str; + http_method = v_http_method; +} + +void HttpRequestInput::initialize() { + var_layout = NOT_SET; + url_str = ""; + http_method = "GET"; +} + +void HttpRequestInput::add_var(QString key, QString value) { + vars[key] = value; +} + +void HttpRequestInput::add_file(QString variable_name, QString local_filename, QString request_filename, QString mime_type) { + SWGHttpRequestInputFileElement file; + file.variable_name = variable_name; + file.local_filename = local_filename; + file.request_filename = request_filename; + file.mime_type = mime_type; + files.append(file); +} + + +HttpRequestWorker::HttpRequestWorker(QObject *parent) + : QObject(parent), manager(NULL) +{ + qsrand(QDateTime::currentDateTime().toTime_t()); + + manager = new QNetworkAccessManager(this); + connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(on_manager_finished(QNetworkReply*))); +} + +HttpRequestWorker::~HttpRequestWorker() { +} + +QString HttpRequestWorker::http_attribute_encode(QString attribute_name, QString input) { + // result structure follows RFC 5987 + bool need_utf_encoding = false; + QString result = ""; + QByteArray input_c = input.toLocal8Bit(); + char c; + for (int i = 0; i < input_c.length(); i++) { + c = input_c.at(i); + if (c == '\\' || c == '/' || c == '\0' || c < ' ' || c > '~') { + // ignore and request utf-8 version + need_utf_encoding = true; + } + else if (c == '"') { + result += "\\\""; + } + else { + result += c; + } + } + + if (result.length() == 0) { + need_utf_encoding = true; + } + + if (!need_utf_encoding) { + // return simple version + return QString("%1=\"%2\"").arg(attribute_name, result); + } + + QString result_utf8 = ""; + for (int i = 0; i < input_c.length(); i++) { + c = input_c.at(i); + if ( + (c >= '0' && c <= '9') + || (c >= 'A' && c <= 'Z') + || (c >= 'a' && c <= 'z') + ) { + result_utf8 += c; + } + else { + result_utf8 += "%" + QString::number(static_cast(input_c.at(i)), 16).toUpper(); + } + } + + // return enhanced version with UTF-8 support + return QString("%1=\"%2\"; %1*=utf-8''%3").arg(attribute_name, result, result_utf8); +} + +void HttpRequestWorker::execute(HttpRequestInput *input) { + + // reset variables + + QByteArray request_content = ""; + response = ""; + error_type = QNetworkReply::NoError; + error_str = ""; + bool isFormData = false; + + + // decide on the variable layout + + if (input->files.length() > 0) { + input->var_layout = MULTIPART; + } + if (input->var_layout == NOT_SET) { + input->var_layout = input->http_method == "GET" || input->http_method == "HEAD" ? ADDRESS : URL_ENCODED; + } + + + // prepare request content + + QString boundary = ""; + + if (input->var_layout == ADDRESS || input->var_layout == URL_ENCODED) { + // variable layout is ADDRESS or URL_ENCODED + + if (input->vars.count() > 0) { + bool first = true; + isFormData = true; + foreach (QString key, input->vars.keys()) { + if (!first) { + request_content.append("&"); + } + first = false; + + request_content.append(QUrl::toPercentEncoding(key)); + request_content.append("="); + request_content.append(QUrl::toPercentEncoding(input->vars.value(key))); + } + + if (input->var_layout == ADDRESS) { + input->url_str += "?" + request_content; + request_content = ""; + } + } + } + else { + // variable layout is MULTIPART + + boundary = "__-----------------------" + + QString::number(QDateTime::currentDateTime().toTime_t()) + + QString::number(qrand()); + QString boundary_delimiter = "--"; + QString new_line = "\r\n"; + + // add variables + foreach (QString key, input->vars.keys()) { + // add boundary + request_content.append(boundary_delimiter); + request_content.append(boundary); + request_content.append(new_line); + + // add header + request_content.append("Content-Disposition: form-data; "); + request_content.append(http_attribute_encode("name", key)); + request_content.append(new_line); + request_content.append("Content-Type: text/plain"); + request_content.append(new_line); + + // add header to body splitter + request_content.append(new_line); + + // add variable content + request_content.append(input->vars.value(key)); + request_content.append(new_line); + } + + // add files + for (QList::iterator file_info = input->files.begin(); file_info != input->files.end(); file_info++) { + QFileInfo fi(file_info->local_filename); + + // ensure necessary variables are available + if ( + file_info->local_filename == NULL || file_info->local_filename.isEmpty() + || file_info->variable_name == NULL || file_info->variable_name.isEmpty() + || !fi.exists() || !fi.isFile() || !fi.isReadable() + ) { + // silent abort for the current file + continue; + } + + QFile file(file_info->local_filename); + if (!file.open(QIODevice::ReadOnly)) { + // silent abort for the current file + continue; + } + + // ensure filename for the request + if (file_info->request_filename == NULL || file_info->request_filename.isEmpty()) { + file_info->request_filename = fi.fileName(); + if (file_info->request_filename.isEmpty()) { + file_info->request_filename = "file"; + } + } + + // add boundary + request_content.append(boundary_delimiter); + request_content.append(boundary); + request_content.append(new_line); + + // add header + request_content.append(QString("Content-Disposition: form-data; %1; %2").arg( + http_attribute_encode("name", file_info->variable_name), + http_attribute_encode("filename", file_info->request_filename) + )); + request_content.append(new_line); + + if (file_info->mime_type != NULL && !file_info->mime_type.isEmpty()) { + request_content.append("Content-Type: "); + request_content.append(file_info->mime_type); + request_content.append(new_line); + } + + request_content.append("Content-Transfer-Encoding: binary"); + request_content.append(new_line); + + // add header to body splitter + request_content.append(new_line); + + // add file content + request_content.append(file.readAll()); + request_content.append(new_line); + + file.close(); + } + + // add end of body + request_content.append(boundary_delimiter); + request_content.append(boundary); + request_content.append(boundary_delimiter); + } + + if(input->request_body.size() > 0) { + qDebug() << "got a request body"; + request_content.clear(); + request_content.append(input->request_body); + } + // prepare connection + + QNetworkRequest request = QNetworkRequest(QUrl(input->url_str)); + request.setRawHeader("User-Agent", "Swagger-Client"); + foreach(QString key, input->headers.keys()) { + request.setRawHeader(key.toStdString().c_str(), input->headers.value(key).toStdString().c_str()); + } + + if (request_content.size() > 0 && !isFormData) { + request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); + } + else if (input->var_layout == URL_ENCODED) { + request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); + } + else if (input->var_layout == MULTIPART) { + request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data; boundary=" + boundary); + } + + if (input->http_method == "GET") { + manager->get(request); + } + else if (input->http_method == "POST") { + manager->post(request, request_content); + } + else if (input->http_method == "PUT") { + manager->put(request, request_content); + } + else if (input->http_method == "HEAD") { + manager->head(request); + } + else if (input->http_method == "DELETE") { + manager->deleteResource(request); + } + else { + QBuffer buff(&request_content); + manager->sendCustomRequest(request, input->http_method.toLatin1(), &buff); + } + +} + +void HttpRequestWorker::on_manager_finished(QNetworkReply *reply) { + error_type = reply->error(); + if (error_type == QNetworkReply::NoError) { + response = reply->readAll(); + } + else { + error_str = reply->errorString(); + } + + reply->deleteLater(); + + emit on_execution_finished(this); +} diff --git a/samples/client/petstore/qt5cpp/client/SWGHttpRequest.h b/samples/client/petstore/qt5cpp/client/SWGHttpRequest.h new file mode 100644 index 000000000000..a2e91a0765ee --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/SWGHttpRequest.h @@ -0,0 +1,75 @@ +/** + * Based on http://www.creativepulse.gr/en/blog/2014/restful-api-requests-using-qt-cpp-for-linux-mac-osx-ms-windows + * By Alex Stylianos + * + **/ + +#ifndef HTTPREQUESTWORKER_H +#define HTTPREQUESTWORKER_H + +#include +#include +#include +#include +#include + +enum HttpRequestVarLayout {NOT_SET, ADDRESS, URL_ENCODED, MULTIPART}; + + +class SWGHttpRequestInputFileElement { + +public: + QString variable_name; + QString local_filename; + QString request_filename; + QString mime_type; + +}; + + +class HttpRequestInput { + +public: + QString url_str; + QString http_method; + HttpRequestVarLayout var_layout; + QMap vars; + QMap headers; + QList files; + QByteArray request_body; + + HttpRequestInput(); + HttpRequestInput(QString v_url_str, QString v_http_method); + void initialize(); + void add_var(QString key, QString value); + void add_file(QString variable_name, QString local_filename, QString request_filename, QString mime_type); + +}; + + +class HttpRequestWorker : public QObject { + Q_OBJECT + +public: + QByteArray response; + QNetworkReply::NetworkError error_type; + QString error_str; + + explicit HttpRequestWorker(QObject *parent = 0); + virtual ~HttpRequestWorker(); + + QString http_attribute_encode(QString attribute_name, QString input); + void execute(HttpRequestInput *input); + +signals: + void on_execution_finished(HttpRequestWorker *worker); + +private: + QNetworkAccessManager *manager; + +private slots: + void on_manager_finished(QNetworkReply *reply); + +}; + +#endif // HTTPREQUESTWORKER_H diff --git a/samples/client/petstore/qt5cpp/client/SWGModelFactory.h b/samples/client/petstore/qt5cpp/client/SWGModelFactory.h new file mode 100644 index 000000000000..588a7ad952b1 --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/SWGModelFactory.h @@ -0,0 +1,45 @@ +#ifndef ModelFactory_H_ +#define ModelFactory_H_ + + +#include "SWGUser.h" +#include "SWGCategory.h" +#include "SWGPet.h" +#include "SWGTag.h" +#include "SWGOrder.h" + +namespace Swagger { + inline void* create(QString type) { + if(QString("SWGUser").compare(type) == 0) { + return new SWGUser(); + } + if(QString("SWGCategory").compare(type) == 0) { + return new SWGCategory(); + } + if(QString("SWGPet").compare(type) == 0) { + return new SWGPet(); + } + if(QString("SWGTag").compare(type) == 0) { + return new SWGTag(); + } + if(QString("SWGOrder").compare(type) == 0) { + return new SWGOrder(); + } + + return NULL; + } + + inline void* create(QString json, QString type) { + void* val = create(type); + if(val != NULL) { + SWGObject* obj = static_cast(val); + return obj->fromJson(json); + } + if(type.startsWith("QString")) { + return new QString(); + } + return NULL; + } +} /* namespace Swagger */ + +#endif /* ModelFactory_H_ */ diff --git a/samples/client/petstore/qt5cpp/client/SWGObject.h b/samples/client/petstore/qt5cpp/client/SWGObject.h new file mode 100644 index 000000000000..6cb5c0427727 --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/SWGObject.h @@ -0,0 +1,24 @@ +#ifndef _SWG_OBJECT_H_ +#define _SWG_OBJECT_H_ + +#include + +class SWGObject { + public: + virtual QJsonObject* asJsonObject() { + return NULL; + } + virtual ~SWGObject() {} + virtual SWGObject* fromJson(QString &jsonString) { + Q_UNUSED(jsonString); + return NULL; + } + virtual void fromJsonObject(QJsonObject &json) { + Q_UNUSED(json); + } + virtual QString asJson() { + return QString(""); + } +}; + +#endif /* _SWG_OBJECT_H_ */ diff --git a/samples/client/petstore/qt5cpp/client/SWGOrder.cpp b/samples/client/petstore/qt5cpp/client/SWGOrder.cpp new file mode 100644 index 000000000000..3e34f2669c72 --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/SWGOrder.cpp @@ -0,0 +1,164 @@ + +#include "SWGOrder.h" + +#include "SWGHelpers.h" + +#include +#include +#include +#include + +namespace Swagger { + + +SWGOrder::SWGOrder(QString* json) { + init(); + this->fromJson(*json); +} + +SWGOrder::SWGOrder() { + init(); +} + +SWGOrder::~SWGOrder() { + this->cleanup(); +} + +void +SWGOrder::init() { + id = 0L; + petId = 0L; + quantity = 0; + shipDate = NULL; + status = new QString(""); + complete = false; + +} + +void +SWGOrder::cleanup() { + + + + if(shipDate != NULL) { + delete shipDate; + } + if(status != NULL) { + delete status; + } + + +} + +SWGOrder* +SWGOrder::fromJson(QString &json) { + QByteArray array (json.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); + return this; +} + +void +SWGOrder::fromJsonObject(QJsonObject &pJson) { + setValue(&id, pJson["id"], "qint64", ""); + setValue(&petId, pJson["petId"], "qint64", ""); + setValue(&quantity, pJson["quantity"], "qint32", ""); + setValue(&shipDate, pJson["shipDate"], "QDateTime", "QDateTime"); + setValue(&status, pJson["status"], "QString", "QString"); + setValue(&complete, pJson["complete"], "bool", ""); + +} + +QString +SWGOrder::asJson () +{ + QJsonObject* obj = this->asJsonObject(); + + QJsonDocument doc(*obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject* +SWGOrder::asJsonObject() { + QJsonObject* obj = new QJsonObject(); + obj->insert("id", QJsonValue(id)); + obj->insert("petId", QJsonValue(petId)); + obj->insert("quantity", QJsonValue(quantity)); + + + toJsonValue(QString("shipDate"), shipDate, obj, QString("QDateTime")); + + + + + + toJsonValue(QString("status"), status, obj, QString("QString")); + + + + obj->insert("complete", QJsonValue(complete)); + + + return obj; +} + +qint64 +SWGOrder::getId() { + return id; +} +void +SWGOrder::setId(qint64 id) { + this->id = id; +} + +qint64 +SWGOrder::getPetId() { + return petId; +} +void +SWGOrder::setPetId(qint64 petId) { + this->petId = petId; +} + +qint32 +SWGOrder::getQuantity() { + return quantity; +} +void +SWGOrder::setQuantity(qint32 quantity) { + this->quantity = quantity; +} + +QDateTime* +SWGOrder::getShipDate() { + return shipDate; +} +void +SWGOrder::setShipDate(QDateTime* shipDate) { + this->shipDate = shipDate; +} + +QString* +SWGOrder::getStatus() { + return status; +} +void +SWGOrder::setStatus(QString* status) { + this->status = status; +} + +bool +SWGOrder::getComplete() { + return complete; +} +void +SWGOrder::setComplete(bool complete) { + this->complete = complete; +} + + + +} /* namespace Swagger */ + diff --git a/samples/client/petstore/qt5cpp/client/SWGOrder.h b/samples/client/petstore/qt5cpp/client/SWGOrder.h new file mode 100644 index 000000000000..d17713afe787 --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/SWGOrder.h @@ -0,0 +1,60 @@ +/* + * SWGOrder.h + * + * + */ + +#ifndef SWGOrder_H_ +#define SWGOrder_H_ + +#include + + +#include "QDateTime.h" +#include + +#include "SWGObject.h" + + +namespace Swagger { + +class SWGOrder: public SWGObject { +public: + SWGOrder(); + SWGOrder(QString* json); + virtual ~SWGOrder(); + void init(); + void cleanup(); + + QString asJson (); + QJsonObject* asJsonObject(); + void fromJsonObject(QJsonObject &json); + SWGOrder* fromJson(QString &jsonString); + + qint64 getId(); + void setId(qint64 id); + qint64 getPetId(); + void setPetId(qint64 petId); + qint32 getQuantity(); + void setQuantity(qint32 quantity); + QDateTime* getShipDate(); + void setShipDate(QDateTime* shipDate); + QString* getStatus(); + void setStatus(QString* status); + bool getComplete(); + void setComplete(bool complete); + + +private: + qint64 id; + qint64 petId; + qint32 quantity; + QDateTime* shipDate; + QString* status; + bool complete; + +}; + +} /* namespace Swagger */ + +#endif /* SWGOrder_H_ */ diff --git a/samples/client/petstore/qt5cpp/client/SWGPet.cpp b/samples/client/petstore/qt5cpp/client/SWGPet.cpp new file mode 100644 index 000000000000..d0e5b8280e21 --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/SWGPet.cpp @@ -0,0 +1,199 @@ + +#include "SWGPet.h" + +#include "SWGHelpers.h" + +#include +#include +#include +#include + +namespace Swagger { + + +SWGPet::SWGPet(QString* json) { + init(); + this->fromJson(*json); +} + +SWGPet::SWGPet() { + init(); +} + +SWGPet::~SWGPet() { + this->cleanup(); +} + +void +SWGPet::init() { + id = 0L; + category = new SWGCategory(); + name = new QString(""); + photoUrls = new QList(); + tags = new QList(); + status = new QString(""); + +} + +void +SWGPet::cleanup() { + + if(category != NULL) { + delete category; + } + if(name != NULL) { + delete name; + } + if(photoUrls != NULL) { + QList* arr = photoUrls; + foreach(QString* o, *arr) { + delete o; + } + delete photoUrls; + } + if(tags != NULL) { + QList* arr = tags; + foreach(SWGTag* o, *arr) { + delete o; + } + delete tags; + } + if(status != NULL) { + delete status; + } + +} + +SWGPet* +SWGPet::fromJson(QString &json) { + QByteArray array (json.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); + return this; +} + +void +SWGPet::fromJsonObject(QJsonObject &pJson) { + setValue(&id, pJson["id"], "qint64", ""); + setValue(&category, pJson["category"], "SWGCategory", "SWGCategory"); + setValue(&name, pJson["name"], "QString", "QString"); + setValue(&photoUrls, pJson["photoUrls"], "QList", "QString"); + setValue(&tags, pJson["tags"], "QList", "SWGTag"); + setValue(&status, pJson["status"], "QString", "QString"); + +} + +QString +SWGPet::asJson () +{ + QJsonObject* obj = this->asJsonObject(); + + QJsonDocument doc(*obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject* +SWGPet::asJsonObject() { + QJsonObject* obj = new QJsonObject(); + obj->insert("id", QJsonValue(id)); + + + toJsonValue(QString("category"), category, obj, QString("SWGCategory")); + + + + + + toJsonValue(QString("name"), name, obj, QString("QString")); + + + + + + QList* photoUrlsList = photoUrls; + QJsonArray photoUrlsJsonArray; + toJsonArray((QList*)photoUrls, &photoUrlsJsonArray, "photoUrls", "QString"); + + obj->insert("photoUrls", photoUrlsJsonArray); + + + + + QList* tagsList = tags; + QJsonArray tagsJsonArray; + toJsonArray((QList*)tags, &tagsJsonArray, "tags", "SWGTag"); + + obj->insert("tags", tagsJsonArray); + + + + + toJsonValue(QString("status"), status, obj, QString("QString")); + + + + + + return obj; +} + +qint64 +SWGPet::getId() { + return id; +} +void +SWGPet::setId(qint64 id) { + this->id = id; +} + +SWGCategory* +SWGPet::getCategory() { + return category; +} +void +SWGPet::setCategory(SWGCategory* category) { + this->category = category; +} + +QString* +SWGPet::getName() { + return name; +} +void +SWGPet::setName(QString* name) { + this->name = name; +} + +QList* +SWGPet::getPhotoUrls() { + return photoUrls; +} +void +SWGPet::setPhotoUrls(QList* photoUrls) { + this->photoUrls = photoUrls; +} + +QList* +SWGPet::getTags() { + return tags; +} +void +SWGPet::setTags(QList* tags) { + this->tags = tags; +} + +QString* +SWGPet::getStatus() { + return status; +} +void +SWGPet::setStatus(QString* status) { + this->status = status; +} + + + +} /* namespace Swagger */ + diff --git a/samples/client/petstore/qt5cpp/client/SWGPet.h b/samples/client/petstore/qt5cpp/client/SWGPet.h new file mode 100644 index 000000000000..3f9320f15074 --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/SWGPet.h @@ -0,0 +1,62 @@ +/* + * SWGPet.h + * + * + */ + +#ifndef SWGPet_H_ +#define SWGPet_H_ + +#include + + +#include +#include "SWGCategory.h" +#include +#include "SWGTag.h" + +#include "SWGObject.h" + + +namespace Swagger { + +class SWGPet: public SWGObject { +public: + SWGPet(); + SWGPet(QString* json); + virtual ~SWGPet(); + void init(); + void cleanup(); + + QString asJson (); + QJsonObject* asJsonObject(); + void fromJsonObject(QJsonObject &json); + SWGPet* fromJson(QString &jsonString); + + qint64 getId(); + void setId(qint64 id); + SWGCategory* getCategory(); + void setCategory(SWGCategory* category); + QString* getName(); + void setName(QString* name); + QList* getPhotoUrls(); + void setPhotoUrls(QList* photoUrls); + QList* getTags(); + void setTags(QList* tags); + QString* getStatus(); + void setStatus(QString* status); + + +private: + qint64 id; + SWGCategory* category; + QString* name; + QList* photoUrls; + QList* tags; + QString* status; + +}; + +} /* namespace Swagger */ + +#endif /* SWGPet_H_ */ diff --git a/samples/client/petstore/qt5cpp/client/SWGPetApi.cpp b/samples/client/petstore/qt5cpp/client/SWGPetApi.cpp new file mode 100644 index 000000000000..af7b2371ebcc --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/SWGPetApi.cpp @@ -0,0 +1,531 @@ +#include "SWGPetApi.h" +#include "SWGHelpers.h" +#include "SWGModelFactory.h" + +#include +#include + +namespace Swagger { +SWGPetApi::SWGPetApi() {} + +SWGPetApi::~SWGPetApi() {} + +SWGPetApi::SWGPetApi(QString host, QString basePath) { + this->host = host; + this->basePath = basePath; +} + +void +SWGPetApi::updatePet(SWGPet body) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/pet"); + + + + + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "PUT"); + + + + + + + QString output = body.asJson(); + input.request_body.append(output); + + + + + connect(worker, + &HttpRequestWorker::on_execution_finished, + this, + &SWGPetApi::updatePetCallback); + + worker->execute(&input); +} + +void +SWGPetApi::updatePetCallback(HttpRequestWorker * worker) { + QString msg; + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + + + + worker->deleteLater(); + + + emit updatePetSignal(); +} +void +SWGPetApi::addPet(SWGPet body) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/pet"); + + + + + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "POST"); + + + + + + + QString output = body.asJson(); + input.request_body.append(output); + + + + + connect(worker, + &HttpRequestWorker::on_execution_finished, + this, + &SWGPetApi::addPetCallback); + + worker->execute(&input); +} + +void +SWGPetApi::addPetCallback(HttpRequestWorker * worker) { + QString msg; + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + + + + worker->deleteLater(); + + + emit addPetSignal(); +} +void +SWGPetApi::findPetsByStatus(QList* status) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/pet/findByStatus"); + + + + + + + + + if(status->size() > 0) { + if(QString("multi").indexOf("multi") == 0) { + foreach(QString* t, *status) { + if(fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append("status=").append(stringValue(t)); + } + } + else if (QString("multi").indexOf("ssv") == 0) { + if(fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append("status="); + qint32 count = 0; + foreach(QString* t, *status) { + if(count > 0) { + fullPath.append(" "); + } + fullPath.append(stringValue(t)); + } + } + else if (QString("multi").indexOf("tsv") == 0) { + if(fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append("status="); + qint32 count = 0; + foreach(QString* t, *status) { + if(count > 0) { + fullPath.append("\t"); + } + fullPath.append(stringValue(t)); + } + } + } + + + + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "GET"); + + + + + + + + connect(worker, + &HttpRequestWorker::on_execution_finished, + this, + &SWGPetApi::findPetsByStatusCallback); + + worker->execute(&input); +} + +void +SWGPetApi::findPetsByStatusCallback(HttpRequestWorker * worker) { + QString msg; + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + + + QList* output = new QList(); + QString json(worker->response); + QByteArray array (json.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonArray jsonArray = doc.array(); + + foreach(QJsonValue obj, jsonArray) { + SWGPet* o = new SWGPet(); + QJsonObject jv = obj.toObject(); + QJsonObject * ptr = (QJsonObject*)&jv; + o->fromJsonObject(*ptr); + output->append(o); + } + + + + + worker->deleteLater(); + + emit findPetsByStatusSignal(output); + +} +void +SWGPetApi::findPetsByTags(QList* tags) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/pet/findByTags"); + + + + + + + + + if(tags->size() > 0) { + if(QString("multi").indexOf("multi") == 0) { + foreach(QString* t, *tags) { + if(fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append("tags=").append(stringValue(t)); + } + } + else if (QString("multi").indexOf("ssv") == 0) { + if(fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append("tags="); + qint32 count = 0; + foreach(QString* t, *tags) { + if(count > 0) { + fullPath.append(" "); + } + fullPath.append(stringValue(t)); + } + } + else if (QString("multi").indexOf("tsv") == 0) { + if(fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append("tags="); + qint32 count = 0; + foreach(QString* t, *tags) { + if(count > 0) { + fullPath.append("\t"); + } + fullPath.append(stringValue(t)); + } + } + } + + + + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "GET"); + + + + + + + + connect(worker, + &HttpRequestWorker::on_execution_finished, + this, + &SWGPetApi::findPetsByTagsCallback); + + worker->execute(&input); +} + +void +SWGPetApi::findPetsByTagsCallback(HttpRequestWorker * worker) { + QString msg; + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + + + QList* output = new QList(); + QString json(worker->response); + QByteArray array (json.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonArray jsonArray = doc.array(); + + foreach(QJsonValue obj, jsonArray) { + SWGPet* o = new SWGPet(); + QJsonObject jv = obj.toObject(); + QJsonObject * ptr = (QJsonObject*)&jv; + o->fromJsonObject(*ptr); + output->append(o); + } + + + + + worker->deleteLater(); + + emit findPetsByTagsSignal(output); + +} +void +SWGPetApi::getPetById(qint64 petId) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/pet/{petId}"); + + + QString petIdPathParam("{"); petIdPathParam.append("petId").append("}"); + fullPath.replace(petIdPathParam, stringValue(petId)); + + + + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "GET"); + + + + + + + + connect(worker, + &HttpRequestWorker::on_execution_finished, + this, + &SWGPetApi::getPetByIdCallback); + + worker->execute(&input); +} + +void +SWGPetApi::getPetByIdCallback(HttpRequestWorker * worker) { + QString msg; + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + + + + + + + QString json(worker->response); + SWGPet* output = static_cast(create(json, QString("SWGPet"))); + + + + + worker->deleteLater(); + + emit getPetByIdSignal(output); + +} +void +SWGPetApi::updatePetWithForm(QString* petId, QString* name, QString* status) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/pet/{petId}"); + + + QString petIdPathParam("{"); petIdPathParam.append("petId").append("}"); + fullPath.replace(petIdPathParam, stringValue(petId)); + + + + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "POST"); + + + if(name != NULL) { + input.add_var("name", *name); + } + + if(status != NULL) { + input.add_var("status", *status); + } + + + + + + + connect(worker, + &HttpRequestWorker::on_execution_finished, + this, + &SWGPetApi::updatePetWithFormCallback); + + worker->execute(&input); +} + +void +SWGPetApi::updatePetWithFormCallback(HttpRequestWorker * worker) { + QString msg; + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + + + + worker->deleteLater(); + + + emit updatePetWithFormSignal(); +} +void +SWGPetApi::deletePet(QString* api_key, qint64 petId) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/pet/{petId}"); + + + QString petIdPathParam("{"); petIdPathParam.append("petId").append("}"); + fullPath.replace(petIdPathParam, stringValue(petId)); + + + + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "DELETE"); + + + + + + + // TODO: add header support + + + connect(worker, + &HttpRequestWorker::on_execution_finished, + this, + &SWGPetApi::deletePetCallback); + + worker->execute(&input); +} + +void +SWGPetApi::deletePetCallback(HttpRequestWorker * worker) { + QString msg; + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + + + + worker->deleteLater(); + + + emit deletePetSignal(); +} +void +SWGPetApi::uploadFile(qint64 petId, QString* additionalMetadata, SWGHttpRequestInputFileElement* file) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/pet/{petId}/uploadImage"); + + + QString petIdPathParam("{"); petIdPathParam.append("petId").append("}"); + fullPath.replace(petIdPathParam, stringValue(petId)); + + + + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "POST"); + + + if(additionalMetadata != NULL) { + input.add_var("additionalMetadata", *additionalMetadata); + } + + + + + + + connect(worker, + &HttpRequestWorker::on_execution_finished, + this, + &SWGPetApi::uploadFileCallback); + + worker->execute(&input); +} + +void +SWGPetApi::uploadFileCallback(HttpRequestWorker * worker) { + QString msg; + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + + + + worker->deleteLater(); + + + emit uploadFileSignal(); +} +} /* namespace Swagger */ diff --git a/samples/client/petstore/qt5cpp/client/SWGPetApi.h b/samples/client/petstore/qt5cpp/client/SWGPetApi.h new file mode 100644 index 000000000000..2f65cade2c47 --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/SWGPetApi.h @@ -0,0 +1,56 @@ +#ifndef _SWG_SWGPetApi_H_ +#define _SWG_SWGPetApi_H_ + +#include "SWGHttpRequest.h" + +#include "SWGPet.h" +#include +#include "SWGHttpRequest.h" + +#include + +namespace Swagger { + +class SWGPetApi: public QObject { + Q_OBJECT + +public: + SWGPetApi(); + SWGPetApi(QString host, QString basePath); + ~SWGPetApi(); + + QString host; + QString basePath; + + void updatePet(SWGPet body); + void addPet(SWGPet body); + void findPetsByStatus(QList* status); + void findPetsByTags(QList* tags); + void getPetById(qint64 petId); + void updatePetWithForm(QString* petId, QString* name, QString* status); + void deletePet(QString* api_key, qint64 petId); + void uploadFile(qint64 petId, QString* additionalMetadata, SWGHttpRequestInputFileElement* file); + +private: + void updatePetCallback (HttpRequestWorker * worker); + void addPetCallback (HttpRequestWorker * worker); + void findPetsByStatusCallback (HttpRequestWorker * worker); + void findPetsByTagsCallback (HttpRequestWorker * worker); + void getPetByIdCallback (HttpRequestWorker * worker); + void updatePetWithFormCallback (HttpRequestWorker * worker); + void deletePetCallback (HttpRequestWorker * worker); + void uploadFileCallback (HttpRequestWorker * worker); + +signals: + void updatePetSignal(); + void addPetSignal(); + void findPetsByStatusSignal(QList* summary); + void findPetsByTagsSignal(QList* summary); + void getPetByIdSignal(SWGPet* summary); + void updatePetWithFormSignal(); + void deletePetSignal(); + void uploadFileSignal(); + +}; +} +#endif \ No newline at end of file diff --git a/samples/client/petstore/qt5cpp/client/SWGStoreApi.cpp b/samples/client/petstore/qt5cpp/client/SWGStoreApi.cpp new file mode 100644 index 000000000000..be603573f621 --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/SWGStoreApi.cpp @@ -0,0 +1,239 @@ +#include "SWGStoreApi.h" +#include "SWGHelpers.h" +#include "SWGModelFactory.h" + +#include +#include + +namespace Swagger { +SWGStoreApi::SWGStoreApi() {} + +SWGStoreApi::~SWGStoreApi() {} + +SWGStoreApi::SWGStoreApi(QString host, QString basePath) { + this->host = host; + this->basePath = basePath; +} + +void +SWGStoreApi::getInventory() { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/store/inventory"); + + + + + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "GET"); + + + + + + + + connect(worker, + &HttpRequestWorker::on_execution_finished, + this, + &SWGStoreApi::getInventoryCallback); + + worker->execute(&input); +} + +void +SWGStoreApi::getInventoryCallback(HttpRequestWorker * worker) { + QString msg; + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + + + + + + QMap* output = new QMap(); + + QString json(worker->response); + QByteArray array (json.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject obj = doc.object(); + + foreach(QString key, obj.keys()) { + qint32* val; + setValue(&val, obj[key], "QMap", ""); + output->insert(key, *val); + } + + + + + + + worker->deleteLater(); + + emit getInventorySignal(output); + +} +void +SWGStoreApi::placeOrder(SWGOrder body) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/store/order"); + + + + + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "POST"); + + + + + + + QString output = body.asJson(); + input.request_body.append(output); + + + + + connect(worker, + &HttpRequestWorker::on_execution_finished, + this, + &SWGStoreApi::placeOrderCallback); + + worker->execute(&input); +} + +void +SWGStoreApi::placeOrderCallback(HttpRequestWorker * worker) { + QString msg; + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + + + + + + + QString json(worker->response); + SWGOrder* output = static_cast(create(json, QString("SWGOrder"))); + + + + + worker->deleteLater(); + + emit placeOrderSignal(output); + +} +void +SWGStoreApi::getOrderById(QString* orderId) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/store/order/{orderId}"); + + + QString orderIdPathParam("{"); orderIdPathParam.append("orderId").append("}"); + fullPath.replace(orderIdPathParam, stringValue(orderId)); + + + + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "GET"); + + + + + + + + connect(worker, + &HttpRequestWorker::on_execution_finished, + this, + &SWGStoreApi::getOrderByIdCallback); + + worker->execute(&input); +} + +void +SWGStoreApi::getOrderByIdCallback(HttpRequestWorker * worker) { + QString msg; + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + + + + + + + QString json(worker->response); + SWGOrder* output = static_cast(create(json, QString("SWGOrder"))); + + + + + worker->deleteLater(); + + emit getOrderByIdSignal(output); + +} +void +SWGStoreApi::deleteOrder(QString* orderId) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/store/order/{orderId}"); + + + QString orderIdPathParam("{"); orderIdPathParam.append("orderId").append("}"); + fullPath.replace(orderIdPathParam, stringValue(orderId)); + + + + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "DELETE"); + + + + + + + + connect(worker, + &HttpRequestWorker::on_execution_finished, + this, + &SWGStoreApi::deleteOrderCallback); + + worker->execute(&input); +} + +void +SWGStoreApi::deleteOrderCallback(HttpRequestWorker * worker) { + QString msg; + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + + + + worker->deleteLater(); + + + emit deleteOrderSignal(); +} +} /* namespace Swagger */ diff --git a/samples/client/petstore/qt5cpp/client/SWGStoreApi.h b/samples/client/petstore/qt5cpp/client/SWGStoreApi.h new file mode 100644 index 000000000000..7bbe8e5f92ae --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/SWGStoreApi.h @@ -0,0 +1,44 @@ +#ifndef _SWG_SWGStoreApi_H_ +#define _SWG_SWGStoreApi_H_ + +#include "SWGHttpRequest.h" + +#include "QMap.h" +#include "SWGOrder.h" +#include + +#include + +namespace Swagger { + +class SWGStoreApi: public QObject { + Q_OBJECT + +public: + SWGStoreApi(); + SWGStoreApi(QString host, QString basePath); + ~SWGStoreApi(); + + QString host; + QString basePath; + + void getInventory(); + void placeOrder(SWGOrder body); + void getOrderById(QString* orderId); + void deleteOrder(QString* orderId); + +private: + void getInventoryCallback (HttpRequestWorker * worker); + void placeOrderCallback (HttpRequestWorker * worker); + void getOrderByIdCallback (HttpRequestWorker * worker); + void deleteOrderCallback (HttpRequestWorker * worker); + +signals: + void getInventorySignal(QMap* summary); + void placeOrderSignal(SWGOrder* summary); + void getOrderByIdSignal(SWGOrder* summary); + void deleteOrderSignal(); + +}; +} +#endif \ No newline at end of file diff --git a/samples/client/petstore/qt5cpp/client/SWGTag.cpp b/samples/client/petstore/qt5cpp/client/SWGTag.cpp new file mode 100644 index 000000000000..bb4404de8dfb --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/SWGTag.cpp @@ -0,0 +1,105 @@ + +#include "SWGTag.h" + +#include "SWGHelpers.h" + +#include +#include +#include +#include + +namespace Swagger { + + +SWGTag::SWGTag(QString* json) { + init(); + this->fromJson(*json); +} + +SWGTag::SWGTag() { + init(); +} + +SWGTag::~SWGTag() { + this->cleanup(); +} + +void +SWGTag::init() { + id = 0L; + name = new QString(""); + +} + +void +SWGTag::cleanup() { + + if(name != NULL) { + delete name; + } + +} + +SWGTag* +SWGTag::fromJson(QString &json) { + QByteArray array (json.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); + return this; +} + +void +SWGTag::fromJsonObject(QJsonObject &pJson) { + setValue(&id, pJson["id"], "qint64", ""); + setValue(&name, pJson["name"], "QString", "QString"); + +} + +QString +SWGTag::asJson () +{ + QJsonObject* obj = this->asJsonObject(); + + QJsonDocument doc(*obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject* +SWGTag::asJsonObject() { + QJsonObject* obj = new QJsonObject(); + obj->insert("id", QJsonValue(id)); + + + toJsonValue(QString("name"), name, obj, QString("QString")); + + + + + + return obj; +} + +qint64 +SWGTag::getId() { + return id; +} +void +SWGTag::setId(qint64 id) { + this->id = id; +} + +QString* +SWGTag::getName() { + return name; +} +void +SWGTag::setName(QString* name) { + this->name = name; +} + + + +} /* namespace Swagger */ + diff --git a/samples/client/petstore/qt5cpp/client/SWGTag.h b/samples/client/petstore/qt5cpp/client/SWGTag.h new file mode 100644 index 000000000000..067b200675b9 --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/SWGTag.h @@ -0,0 +1,47 @@ +/* + * SWGTag.h + * + * + */ + +#ifndef SWGTag_H_ +#define SWGTag_H_ + +#include + + +#include + +#include "SWGObject.h" + + +namespace Swagger { + +class SWGTag: public SWGObject { +public: + SWGTag(); + SWGTag(QString* json); + virtual ~SWGTag(); + void init(); + void cleanup(); + + QString asJson (); + QJsonObject* asJsonObject(); + void fromJsonObject(QJsonObject &json); + SWGTag* fromJson(QString &jsonString); + + qint64 getId(); + void setId(qint64 id); + QString* getName(); + void setName(QString* name); + + +private: + qint64 id; + QString* name; + +}; + +} /* namespace Swagger */ + +#endif /* SWGTag_H_ */ diff --git a/samples/client/petstore/qt5cpp/client/SWGUser.cpp b/samples/client/petstore/qt5cpp/client/SWGUser.cpp new file mode 100644 index 000000000000..f0d58c7e97b7 --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/SWGUser.cpp @@ -0,0 +1,218 @@ + +#include "SWGUser.h" + +#include "SWGHelpers.h" + +#include +#include +#include +#include + +namespace Swagger { + + +SWGUser::SWGUser(QString* json) { + init(); + this->fromJson(*json); +} + +SWGUser::SWGUser() { + init(); +} + +SWGUser::~SWGUser() { + this->cleanup(); +} + +void +SWGUser::init() { + id = 0L; + username = new QString(""); + firstName = new QString(""); + lastName = new QString(""); + email = new QString(""); + password = new QString(""); + phone = new QString(""); + userStatus = 0; + +} + +void +SWGUser::cleanup() { + + if(username != NULL) { + delete username; + } + if(firstName != NULL) { + delete firstName; + } + if(lastName != NULL) { + delete lastName; + } + if(email != NULL) { + delete email; + } + if(password != NULL) { + delete password; + } + if(phone != NULL) { + delete phone; + } + + +} + +SWGUser* +SWGUser::fromJson(QString &json) { + QByteArray array (json.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); + return this; +} + +void +SWGUser::fromJsonObject(QJsonObject &pJson) { + setValue(&id, pJson["id"], "qint64", ""); + setValue(&username, pJson["username"], "QString", "QString"); + setValue(&firstName, pJson["firstName"], "QString", "QString"); + setValue(&lastName, pJson["lastName"], "QString", "QString"); + setValue(&email, pJson["email"], "QString", "QString"); + setValue(&password, pJson["password"], "QString", "QString"); + setValue(&phone, pJson["phone"], "QString", "QString"); + setValue(&userStatus, pJson["userStatus"], "qint32", ""); + +} + +QString +SWGUser::asJson () +{ + QJsonObject* obj = this->asJsonObject(); + + QJsonDocument doc(*obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject* +SWGUser::asJsonObject() { + QJsonObject* obj = new QJsonObject(); + obj->insert("id", QJsonValue(id)); + + + toJsonValue(QString("username"), username, obj, QString("QString")); + + + + + + toJsonValue(QString("firstName"), firstName, obj, QString("QString")); + + + + + + toJsonValue(QString("lastName"), lastName, obj, QString("QString")); + + + + + + toJsonValue(QString("email"), email, obj, QString("QString")); + + + + + + toJsonValue(QString("password"), password, obj, QString("QString")); + + + + + + toJsonValue(QString("phone"), phone, obj, QString("QString")); + + + + obj->insert("userStatus", QJsonValue(userStatus)); + + + return obj; +} + +qint64 +SWGUser::getId() { + return id; +} +void +SWGUser::setId(qint64 id) { + this->id = id; +} + +QString* +SWGUser::getUsername() { + return username; +} +void +SWGUser::setUsername(QString* username) { + this->username = username; +} + +QString* +SWGUser::getFirstName() { + return firstName; +} +void +SWGUser::setFirstName(QString* firstName) { + this->firstName = firstName; +} + +QString* +SWGUser::getLastName() { + return lastName; +} +void +SWGUser::setLastName(QString* lastName) { + this->lastName = lastName; +} + +QString* +SWGUser::getEmail() { + return email; +} +void +SWGUser::setEmail(QString* email) { + this->email = email; +} + +QString* +SWGUser::getPassword() { + return password; +} +void +SWGUser::setPassword(QString* password) { + this->password = password; +} + +QString* +SWGUser::getPhone() { + return phone; +} +void +SWGUser::setPhone(QString* phone) { + this->phone = phone; +} + +qint32 +SWGUser::getUserStatus() { + return userStatus; +} +void +SWGUser::setUserStatus(qint32 userStatus) { + this->userStatus = userStatus; +} + + + +} /* namespace Swagger */ + diff --git a/samples/client/petstore/qt5cpp/client/SWGUser.h b/samples/client/petstore/qt5cpp/client/SWGUser.h new file mode 100644 index 000000000000..eaa0e496c396 --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/SWGUser.h @@ -0,0 +1,65 @@ +/* + * SWGUser.h + * + * + */ + +#ifndef SWGUser_H_ +#define SWGUser_H_ + +#include + + +#include + +#include "SWGObject.h" + + +namespace Swagger { + +class SWGUser: public SWGObject { +public: + SWGUser(); + SWGUser(QString* json); + virtual ~SWGUser(); + void init(); + void cleanup(); + + QString asJson (); + QJsonObject* asJsonObject(); + void fromJsonObject(QJsonObject &json); + SWGUser* fromJson(QString &jsonString); + + qint64 getId(); + void setId(qint64 id); + QString* getUsername(); + void setUsername(QString* username); + QString* getFirstName(); + void setFirstName(QString* firstName); + QString* getLastName(); + void setLastName(QString* lastName); + QString* getEmail(); + void setEmail(QString* email); + QString* getPassword(); + void setPassword(QString* password); + QString* getPhone(); + void setPhone(QString* phone); + qint32 getUserStatus(); + void setUserStatus(qint32 userStatus); + + +private: + qint64 id; + QString* username; + QString* firstName; + QString* lastName; + QString* email; + QString* password; + QString* phone; + qint32 userStatus; + +}; + +} /* namespace Swagger */ + +#endif /* SWGUser_H_ */ diff --git a/samples/client/petstore/qt5cpp/client/SWGUserApi.cpp b/samples/client/petstore/qt5cpp/client/SWGUserApi.cpp new file mode 100644 index 000000000000..6341231a8840 --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/SWGUserApi.cpp @@ -0,0 +1,443 @@ +#include "SWGUserApi.h" +#include "SWGHelpers.h" +#include "SWGModelFactory.h" + +#include +#include + +namespace Swagger { +SWGUserApi::SWGUserApi() {} + +SWGUserApi::~SWGUserApi() {} + +SWGUserApi::SWGUserApi(QString host, QString basePath) { + this->host = host; + this->basePath = basePath; +} + +void +SWGUserApi::createUser(SWGUser body) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/user"); + + + + + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "POST"); + + + + + + + QString output = body.asJson(); + input.request_body.append(output); + + + + + connect(worker, + &HttpRequestWorker::on_execution_finished, + this, + &SWGUserApi::createUserCallback); + + worker->execute(&input); +} + +void +SWGUserApi::createUserCallback(HttpRequestWorker * worker) { + QString msg; + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + + + + worker->deleteLater(); + + + emit createUserSignal(); +} +void +SWGUserApi::createUsersWithArrayInput(QList* body) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/user/createWithArray"); + + + + + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "POST"); + + + + + + QJsonArray* bodyArray = new QJsonArray(); + toJsonArray((QList*)body, bodyArray, QString("body"), QString("SWGUser*")); + + QJsonDocument doc(*bodyArray); + QByteArray bytes = doc.toJson(); + + input.request_body.append(bytes); + + + + + + connect(worker, + &HttpRequestWorker::on_execution_finished, + this, + &SWGUserApi::createUsersWithArrayInputCallback); + + worker->execute(&input); +} + +void +SWGUserApi::createUsersWithArrayInputCallback(HttpRequestWorker * worker) { + QString msg; + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + + + + worker->deleteLater(); + + + emit createUsersWithArrayInputSignal(); +} +void +SWGUserApi::createUsersWithListInput(QList* body) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/user/createWithList"); + + + + + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "POST"); + + + + + + QJsonArray* bodyArray = new QJsonArray(); + toJsonArray((QList*)body, bodyArray, QString("body"), QString("SWGUser*")); + + QJsonDocument doc(*bodyArray); + QByteArray bytes = doc.toJson(); + + input.request_body.append(bytes); + + + + + + connect(worker, + &HttpRequestWorker::on_execution_finished, + this, + &SWGUserApi::createUsersWithListInputCallback); + + worker->execute(&input); +} + +void +SWGUserApi::createUsersWithListInputCallback(HttpRequestWorker * worker) { + QString msg; + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + + + + worker->deleteLater(); + + + emit createUsersWithListInputSignal(); +} +void +SWGUserApi::loginUser(QString* username, QString* password) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/user/login"); + + + + + + if(fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("username")) + .append("=") + .append(QUrl::toPercentEncoding(stringValue(username))); + + + + + + if(fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("password")) + .append("=") + .append(QUrl::toPercentEncoding(stringValue(password))); + + + + + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "GET"); + + + + + + + + connect(worker, + &HttpRequestWorker::on_execution_finished, + this, + &SWGUserApi::loginUserCallback); + + worker->execute(&input); +} + +void +SWGUserApi::loginUserCallback(HttpRequestWorker * worker) { + QString msg; + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + + + + + + + QString json(worker->response); + QString* output = static_cast(create(json, QString("QString"))); + + + + + worker->deleteLater(); + + emit loginUserSignal(output); + +} +void +SWGUserApi::logoutUser() { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/user/logout"); + + + + + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "GET"); + + + + + + + + connect(worker, + &HttpRequestWorker::on_execution_finished, + this, + &SWGUserApi::logoutUserCallback); + + worker->execute(&input); +} + +void +SWGUserApi::logoutUserCallback(HttpRequestWorker * worker) { + QString msg; + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + + + + worker->deleteLater(); + + + emit logoutUserSignal(); +} +void +SWGUserApi::getUserByName(QString* username) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/user/{username}"); + + + QString usernamePathParam("{"); usernamePathParam.append("username").append("}"); + fullPath.replace(usernamePathParam, stringValue(username)); + + + + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "GET"); + + + + + + + + connect(worker, + &HttpRequestWorker::on_execution_finished, + this, + &SWGUserApi::getUserByNameCallback); + + worker->execute(&input); +} + +void +SWGUserApi::getUserByNameCallback(HttpRequestWorker * worker) { + QString msg; + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + + + + + + + QString json(worker->response); + SWGUser* output = static_cast(create(json, QString("SWGUser"))); + + + + + worker->deleteLater(); + + emit getUserByNameSignal(output); + +} +void +SWGUserApi::updateUser(QString* username, SWGUser body) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/user/{username}"); + + + QString usernamePathParam("{"); usernamePathParam.append("username").append("}"); + fullPath.replace(usernamePathParam, stringValue(username)); + + + + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "PUT"); + + + + + + + QString output = body.asJson(); + input.request_body.append(output); + + + + + connect(worker, + &HttpRequestWorker::on_execution_finished, + this, + &SWGUserApi::updateUserCallback); + + worker->execute(&input); +} + +void +SWGUserApi::updateUserCallback(HttpRequestWorker * worker) { + QString msg; + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + + + + worker->deleteLater(); + + + emit updateUserSignal(); +} +void +SWGUserApi::deleteUser(QString* username) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/user/{username}"); + + + QString usernamePathParam("{"); usernamePathParam.append("username").append("}"); + fullPath.replace(usernamePathParam, stringValue(username)); + + + + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "DELETE"); + + + + + + + + connect(worker, + &HttpRequestWorker::on_execution_finished, + this, + &SWGUserApi::deleteUserCallback); + + worker->execute(&input); +} + +void +SWGUserApi::deleteUserCallback(HttpRequestWorker * worker) { + QString msg; + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + + + + worker->deleteLater(); + + + emit deleteUserSignal(); +} +} /* namespace Swagger */ diff --git a/samples/client/petstore/qt5cpp/client/SWGUserApi.h b/samples/client/petstore/qt5cpp/client/SWGUserApi.h new file mode 100644 index 000000000000..2e3e119dc780 --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/SWGUserApi.h @@ -0,0 +1,56 @@ +#ifndef _SWG_SWGUserApi_H_ +#define _SWG_SWGUserApi_H_ + +#include "SWGHttpRequest.h" + +#include "SWGUser.h" +#include +#include + +#include + +namespace Swagger { + +class SWGUserApi: public QObject { + Q_OBJECT + +public: + SWGUserApi(); + SWGUserApi(QString host, QString basePath); + ~SWGUserApi(); + + QString host; + QString basePath; + + void createUser(SWGUser body); + void createUsersWithArrayInput(QList* body); + void createUsersWithListInput(QList* body); + void loginUser(QString* username, QString* password); + void logoutUser(); + void getUserByName(QString* username); + void updateUser(QString* username, SWGUser body); + void deleteUser(QString* username); + +private: + void createUserCallback (HttpRequestWorker * worker); + void createUsersWithArrayInputCallback (HttpRequestWorker * worker); + void createUsersWithListInputCallback (HttpRequestWorker * worker); + void loginUserCallback (HttpRequestWorker * worker); + void logoutUserCallback (HttpRequestWorker * worker); + void getUserByNameCallback (HttpRequestWorker * worker); + void updateUserCallback (HttpRequestWorker * worker); + void deleteUserCallback (HttpRequestWorker * worker); + +signals: + void createUserSignal(); + void createUsersWithArrayInputSignal(); + void createUsersWithListInputSignal(); + void loginUserSignal(QString* summary); + void logoutUserSignal(); + void getUserByNameSignal(SWGUser* summary); + void updateUserSignal(); + void deleteUserSignal(); + +}; +} +#endif \ No newline at end of file diff --git a/samples/client/petstore/ruby/Gemfile.lock b/samples/client/petstore/ruby/Gemfile.lock index 232facf4677c..e9e03f10b779 100644 --- a/samples/client/petstore/ruby/Gemfile.lock +++ b/samples/client/petstore/ruby/Gemfile.lock @@ -1,10 +1,10 @@ PATH remote: . specs: - swagger-client (4.06.08) - addressable (>= 2.2.4) - json (>= 1.4.6) - typhoeus (>= 0.2.1) + swagger_client (1.0.0) + addressable (~> 2.2, >= 2.2.4) + json (~> 1.4, >= 1.4.6) + typhoeus (~> 0.2, >= 0.2.1) GEM remote: http://rubygems.org/ @@ -51,11 +51,11 @@ PLATFORMS ruby DEPENDENCIES - autotest - autotest-fsevent - autotest-growl - autotest-rails-pure - rspec (>= 2.5.0) - swagger-client! - vcr (>= 1.5.1) - webmock (>= 1.6.2) + autotest (~> 4.4, >= 4.4.6) + autotest-fsevent (~> 0.2, >= 0.2.10) + autotest-growl (~> 0.2, >= 0.2.16) + autotest-rails-pure (~> 4.1, >= 4.1.2) + rspec (~> 3.2, >= 3.2.0) + swagger_client! + vcr (~> 2.9, >= 2.9.3) + webmock (~> 1.6, >= 1.6.2) diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index 29a7ce844ce6..2a15c1661ccd 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -5,20 +5,20 @@ You can build the generated client into a gem: ```shell -gem build swagger-client.gemspec +gem build swagger_client.gemspec ``` Then you can either install the gem: ```shell -gem install ./swagger-client-4.06.08.gem +gem install ./swagger_client-1.0.0.gem ``` or publish the gem to a gem server like [RubyGems](https://rubygems.org/). Finally add this to your Gemfile: - gem 'swagger-client', '~> 4.06.08' + gem 'swagger_client', '~> 1.0.0' ### Host as a git repository @@ -27,7 +27,7 @@ https://github.com/xhh/swagger-petstore-ruby Then you can reference it in Gemfile: - gem 'swagger-client', :git => 'https://github.com/xhh/swagger-petstore-ruby.git' + gem 'swagger_client', :git => 'https://github.com/xhh/swagger-petstore-ruby.git' ### Use without installation @@ -40,9 +40,9 @@ ruby -Ilib script.rb ## Configuration ```ruby -require 'swagger-client' +require 'swagger_client' -Swagger.configure do |config| +SwaggerClient::Swagger.configure do |config| config.api_key = 'special-key' config.host = 'petstore.swagger.io' config.base_path = '/v2' @@ -52,6 +52,6 @@ end ## Getting Started ```ruby -pet = PetApi.getPetById(5) +pet = SwaggerClient::PetApi.get_pet_by_id(5) puts pet.to_body ``` diff --git a/samples/client/petstore/ruby/lib/pet_api.rb b/samples/client/petstore/ruby/lib/pet_api.rb deleted file mode 100644 index 6b032510c416..000000000000 --- a/samples/client/petstore/ruby/lib/pet_api.rb +++ /dev/null @@ -1,321 +0,0 @@ -require "uri" - -class PetApi - basePath = "http://petstore.swagger.io/v2" - # apiInvoker = APIInvoker - - # Update an existing pet - # - # @param [Hash] opts the optional parameters - # @option opts [Pet] :body Pet object that needs to be added to the store - # @return void - def self.update_pet(opts = {}) - # verify existence of params - - # resource path - path = "/pet".sub('{format}','json') - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' - - _header_content_type = ['application/json', 'application/xml', ] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - _body_param = opts[:'body'] - if _body_param != nil - if _body_param.is_a?(Array) - _array = Array.new - _body_param.each do |item| - if item.respond_to?(:to_body) - _array.push item.to_body - else - _array.push item - end - end - post_body = _array - else - if _body_param.respond_to?(:to_body) - post_body = _body_param.to_body - else - post_body = _body_param - end - end - end - - Swagger::Request.new(:PUT, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end - - # Add a new pet to the store - # - # @param [Hash] opts the optional parameters - # @option opts [Pet] :body Pet object that needs to be added to the store - # @return void - def self.add_pet(opts = {}) - # verify existence of params - - # resource path - path = "/pet".sub('{format}','json') - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' - - _header_content_type = ['application/json', 'application/xml', ] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - _body_param = opts[:'body'] - if _body_param != nil - if _body_param.is_a?(Array) - _array = Array.new - _body_param.each do |item| - if item.respond_to?(:to_body) - _array.push item.to_body - else - _array.push item - end - end - post_body = _array - else - if _body_param.respond_to?(:to_body) - post_body = _body_param.to_body - else - post_body = _body_param - end - end - end - - Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end - - # Finds Pets by status - # Multiple status values can be provided with comma seperated strings - # @param [Hash] opts the optional parameters - # @option opts [array[string]] :status Status values that need to be considered for filter - # @return array[Pet] - def self.find_pets_by_status(opts = {}) - # verify existence of params - - # resource path - path = "/pet/findByStatus".sub('{format}','json') - - # query parameters - query_params = {} - query_params[:'status'] = opts[:'status'] if opts[:'status'] - - # header parameters - header_params = {} - - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' - - _header_content_type = [] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body - response.map {|response| Pet.new(response) } - end - - # Finds Pets by tags - # Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - # @param [Hash] opts the optional parameters - # @option opts [array[string]] :tags Tags to filter by - # @return array[Pet] - def self.find_pets_by_tags(opts = {}) - # verify existence of params - - # resource path - path = "/pet/findByTags".sub('{format}','json') - - # query parameters - query_params = {} - query_params[:'tags'] = opts[:'tags'] if opts[:'tags'] - - # header parameters - header_params = {} - - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' - - _header_content_type = [] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body - response.map {|response| Pet.new(response) } - end - - # Find pet by ID - # Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - # @param pet_id ID of pet that needs to be fetched - # @param [Hash] opts the optional parameters - # @return Pet - def self.get_pet_by_id(pet_id, opts = {}) - # verify existence of params - raise "pet_id is required" if pet_id.nil? - - # resource path - path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' - - _header_content_type = [] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body - Pet.new(response) - end - - # Updates a pet in the store with form data - # - # @param pet_id ID of pet that needs to be updated - # @param [Hash] opts the optional parameters - # @option opts [string] :name Updated name of the pet - # @option opts [string] :status Updated status of the pet - # @return void - def self.update_pet_with_form(pet_id, opts = {}) - # verify existence of params - raise "pet_id is required" if pet_id.nil? - - # resource path - path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' - - _header_content_type = ['application/x-www-form-urlencoded', ] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' - - # form parameters - form_params = {} - form_params["name"] = opts[:'name'] if opts[:'name'] - form_params["status"] = opts[:'status'] if opts[:'status'] - - # http body (model) - post_body = nil - - Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end - - # Deletes a pet - # - # @param pet_id Pet id to delete - # @param [Hash] opts the optional parameters - # @option opts [string] :api_key - # @return void - def self.delete_pet(pet_id, opts = {}) - # verify existence of params - raise "pet_id is required" if pet_id.nil? - - # resource path - path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' - - _header_content_type = [] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' - header_params[:'api_key'] = opts[:'api_key'] if opts[:'api_key'] - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end - - # uploads an image - # - # @param pet_id ID of pet to update - # @param [Hash] opts the optional parameters - # @option opts [string] :additional_metadata Additional data to pass to server - # @option opts [file] :file file to upload - # @return void - def self.upload_file(pet_id, opts = {}) - # verify existence of params - raise "pet_id is required" if pet_id.nil? - - # resource path - path = "/pet/{petId}/uploadImage".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' - - _header_content_type = ['multipart/form-data', ] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' - - # form parameters - form_params = {} - form_params["additionalMetadata"] = opts[:'additional_metadata'] if opts[:'additional_metadata'] - form_params["file"] = opts[:'file'] if opts[:'file'] - - # http body (model) - post_body = nil - - Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end -end diff --git a/samples/client/petstore/ruby/lib/store_api.rb b/samples/client/petstore/ruby/lib/store_api.rb deleted file mode 100644 index 6cd3296039bf..000000000000 --- a/samples/client/petstore/ruby/lib/store_api.rb +++ /dev/null @@ -1,158 +0,0 @@ -require "uri" - -class StoreApi - basePath = "http://petstore.swagger.io/v2" - # apiInvoker = APIInvoker - - # Returns pet inventories by status - # Returns a map of status codes to quantities - # @param [Hash] opts the optional parameters - # @return map[string,int] - def self.get_inventory(opts = {}) - # verify existence of params - - # resource path - path = "/store/inventory".sub('{format}','json') - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' - - _header_content_type = [] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body - response.map {|response| map.new(response) } - end - - # Place an order for a pet - # - # @param [Hash] opts the optional parameters - # @option opts [Order] :body order placed for purchasing the pet - # @return Order - def self.place_order(opts = {}) - # verify existence of params - - # resource path - path = "/store/order".sub('{format}','json') - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' - - _header_content_type = [] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - _body_param = opts[:'body'] - if _body_param != nil - if _body_param.is_a?(Array) - _array = Array.new - _body_param.each do |item| - if item.respond_to?(:to_body) - _array.push item.to_body - else - _array.push item - end - end - post_body = _array - else - if _body_param.respond_to?(:to_body) - post_body = _body_param.to_body - else - post_body = _body_param - end - end - end - - response = Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body - Order.new(response) - end - - # Find purchase order by ID - # For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - # @param order_id ID of pet that needs to be fetched - # @param [Hash] opts the optional parameters - # @return Order - def self.get_order_by_id(order_id, opts = {}) - # verify existence of params - raise "order_id is required" if order_id.nil? - - # resource path - path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', order_id.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' - - _header_content_type = [] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body - Order.new(response) - end - - # Delete purchase order by ID - # For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - # @param order_id ID of the order that needs to be deleted - # @param [Hash] opts the optional parameters - # @return void - def self.delete_order(order_id, opts = {}) - # verify existence of params - raise "order_id is required" if order_id.nil? - - # resource path - path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', order_id.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' - - _header_content_type = [] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end -end diff --git a/samples/client/petstore/ruby/lib/swagger-client.rb b/samples/client/petstore/ruby/lib/swagger-client.rb deleted file mode 100644 index b13f83b1dbcf..000000000000 --- a/samples/client/petstore/ruby/lib/swagger-client.rb +++ /dev/null @@ -1,5 +0,0 @@ -require 'monkey' -require 'swagger' - -Dir[File.join(File.dirname(__FILE__), "../lib/*.rb")].each {|file| require file if file !~ /swagger-client\.rb\z/ } -Dir[File.join(File.dirname(__FILE__), "../models/*.rb")].each {|file| require file } diff --git a/samples/client/petstore/ruby/lib/swagger.rb b/samples/client/petstore/ruby/lib/swagger.rb deleted file mode 100644 index fff098e96fcc..000000000000 --- a/samples/client/petstore/ruby/lib/swagger.rb +++ /dev/null @@ -1,85 +0,0 @@ -require 'monkey' -require 'swagger/configuration' -require 'swagger/request' -require 'swagger/response' -require 'swagger/version' -require 'logger' - -module Swagger - - @configuration = Configuration.new - - class << self - attr_accessor :logger - - # A Swagger configuration object. Must act like a hash and return sensible - # values for all Swagger configuration options. See Swagger::Configuration. - attr_accessor :configuration - - attr_accessor :resources - - # Call this method to modify defaults in your initializers. - # - # @example - # Swagger.configure do |config| - # config.api_key = '1234567890abcdef' # required - # config.username = 'wordlover' # optional, but needed for user-related functions - # config.password = 'i<3words' # optional, but needed for user-related functions - # config.format = 'json' # optional, defaults to 'json' - # end - # - def configure - yield(configuration) if block_given? - - # Configure logger. Default to use Rails - self.logger ||= configuration.logger || (defined?(Rails) ? Rails.logger : Logger.new(STDOUT)) - - # remove :// from scheme - configuration.scheme.sub!(/:\/\//, '') - - # remove http(s):// and anything after a slash - configuration.host.sub!(/https?:\/\//, '') - configuration.host = configuration.host.split('/').first - - # Add leading and trailing slashes to base_path - configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/') - configuration.base_path = "" if configuration.base_path == "/" - end - - def authenticated? - Swagger.configuration.auth_token.present? - end - - def de_authenticate - Swagger.configuration.auth_token = nil - end - - def authenticate - return if Swagger.authenticated? - - if Swagger.configuration.username.blank? || Swagger.configuration.password.blank? - raise ClientError, "Username and password are required to authenticate." - end - - request = Swagger::Request.new( - :get, - "account/authenticate/{username}", - :params => { - :username => Swagger.configuration.username, - :password => Swagger.configuration.password - } - ) - - response_body = request.response.body - Swagger.configuration.auth_token = response_body['token'] - end - - end - -end - -class ServerError < StandardError -end - -class ClientError < StandardError -end \ No newline at end of file diff --git a/samples/client/petstore/ruby/lib/swagger/configuration.rb b/samples/client/petstore/ruby/lib/swagger/configuration.rb deleted file mode 100644 index 2a3728483f5e..000000000000 --- a/samples/client/petstore/ruby/lib/swagger/configuration.rb +++ /dev/null @@ -1,22 +0,0 @@ -module Swagger - - class Configuration - require 'swagger/version' - - attr_accessor :format, :api_key, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params, :user_agent - - # Defaults go in here.. - def initialize - @format = 'json' - @scheme = 'http' - @host = 'petstore.swagger.io' - @base_path = '/v2' - @user_agent = "ruby-swagger-#{Swagger::VERSION}" - @inject_format = false - @force_ending_format = false - @camelize_params = true - end - - end - -end diff --git a/samples/client/petstore/ruby/lib/swagger/request.rb b/samples/client/petstore/ruby/lib/swagger/request.rb deleted file mode 100644 index fbd70eeb9f54..000000000000 --- a/samples/client/petstore/ruby/lib/swagger/request.rb +++ /dev/null @@ -1,212 +0,0 @@ -module Swagger - - class Request - require 'uri' - require 'addressable/uri' - require 'typhoeus' - require "swagger/version" - - attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params - - - # All requests must have an HTTP method and a path - # Optionals parameters are :params, :headers, :body, :format, :host - # - def initialize(http_method, path, attributes={}) - attributes[:format] ||= Swagger.configuration.format - attributes[:params] ||= {} - - # Set default headers - default_headers = { - 'Content-Type' => "application/#{attributes[:format].downcase}", - :api_key => Swagger.configuration.api_key, - 'User-Agent' => Swagger.configuration.user_agent - } - - # api_key from headers hash trumps the default, even if its value is blank - if attributes[:headers].present? && attributes[:headers].has_key?(:api_key) - default_headers.delete(:api_key) - end - - # api_key from params hash trumps all others (headers and default_headers) - if attributes[:params].present? && attributes[:params].has_key?(:api_key) - default_headers.delete(:api_key) - attributes[:headers].delete(:api_key) if attributes[:headers].present? - end - - # Merge argument headers into defaults - attributes[:headers] = default_headers.merge(attributes[:headers] || {}) - - # Stick in the auth token if there is one - if Swagger.authenticated? - attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token}) - end - - self.http_method = http_method.to_sym - self.path = path - attributes.each do |name, value| - send("#{name.to_s.underscore.to_sym}=", value) - end - end - - # Construct a base URL - # - def url(options = {}) - u = Addressable::URI.new( - :scheme => Swagger.configuration.scheme, - :host => Swagger.configuration.host, - :path => self.interpreted_path, - :query => self.query_string.sub(/\?/, '') - ).to_s - - # Drop trailing question mark, if present - u.sub! /\?$/, '' - - # Obfuscate API key? - u.sub! /api\_key=\w+/, 'api_key=YOUR_API_KEY' if options[:obfuscated] - - u - end - - # Iterate over the params hash, injecting any path values into the path string - # - # e.g. /word.{format}/{word}/entries => /word.json/cat/entries - def interpreted_path - p = self.path.dup - - # Stick a .{format} placeholder into the path if there isn't - # one already or an actual format like json or xml - # e.g. /words/blah => /words.{format}/blah - if Swagger.configuration.inject_format - unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } - p = p.sub(/^(\/?\w+)/, "\\1.#{format}") - end - end - - # Stick a .{format} placeholder on the end of the path if there isn't - # one already or an actual format like json or xml - # e.g. /words/blah => /words/blah.{format} - if Swagger.configuration.force_ending_format - unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } - p = "#{p}.#{format}" - end - end - - p = p.sub("{format}", self.format.to_s) - - URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/') - end - - # Massage the request body into a state of readiness - # If body is a hash, camelize all keys then convert to a json string - # - def body=(value) - if value.is_a?(Hash) - value = value.inject({}) do |memo, (k,v)| - memo[k.to_s.camelize(:lower).to_sym] = v - memo - end - end - @body = value - end - - # If body is an object, JSONify it before making the actual request. - # For form parameters, remove empty value - def outgoing_body - # http form - if @body.nil? && @form_params && !@form_params.empty? - data = form_params.dup - data.each do |key, value| - data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter - end - data - else # http body is JSON - @body.is_a?(String) ? @body : @body.to_json - end - end - - # Construct a query string from the query-string-type params - def query_string - - # Iterate over all params, - # .. removing the ones that are part of the path itself. - # .. stringifying values so Addressable doesn't blow up. - query_values = {} - self.params.each_pair do |key, value| - next if self.path.include? "{#{key}}" # skip path params - next if value.blank? && value.class != FalseClass # skip empties - if Swagger.configuration.camelize_params - key = key.to_s.camelize(:lower).to_sym unless key.to_sym == :api_key # api_key is not a camelCased param - end - query_values[key] = value.to_s - end - - # We don't want to end up with '?' as our query string - # if there aren't really any params - return "" if query_values.blank? - - # Addressable requires query_values to be set after initialization.. - qs = Addressable::URI.new - qs.query_values = query_values - qs.to_s - end - - def make - #TODO use configuration setting to determine if debugging - #logger = Logger.new STDOUT - #logger.debug self.url - response = case self.http_method.to_sym - when :get,:GET - Typhoeus::Request.get( - self.url, - :headers => self.headers.stringify_keys, - ) - - when :post,:POST - Typhoeus::Request.post( - self.url, - :body => self.outgoing_body, - :headers => self.headers.stringify_keys, - ) - - when :patch,:PATCH - Typhoeus::Request.patch( - self.url, - :body => self.outgoing_body, - :headers => self.headers.stringify_keys, - ) - - when :put,:PUT - Typhoeus::Request.put( - self.url, - :body => self.outgoing_body, - :headers => self.headers.stringify_keys, - ) - - when :delete,:DELETE - Typhoeus::Request.delete( - self.url, - :body => self.outgoing_body, - :headers => self.headers.stringify_keys, - ) - end - Response.new(response) - end - - def response - self.make - end - - def response_code_pretty - return unless @response.present? - @response.code.to_s - end - - def response_headers_pretty - return unless @response.present? - # JSON.pretty_generate(@response.headers).gsub(/\n/, '
') # <- This was for RestClient - @response.headers.gsub(/\n/, '
') # <- This is for Typhoeus - end - - end -end diff --git a/samples/client/petstore/ruby/lib/swagger/response.rb b/samples/client/petstore/ruby/lib/swagger/response.rb deleted file mode 100644 index 02a1a458eb4c..000000000000 --- a/samples/client/petstore/ruby/lib/swagger/response.rb +++ /dev/null @@ -1,70 +0,0 @@ -module Swagger - - class Response - require 'json' - - attr_accessor :raw - - def initialize(raw) - self.raw = raw - - case self.code - when 500..510 then raise(ServerError, self.error_message) - when 299..426 then raise(ClientError, self.error_message) - end - end - - def code - raw.code - end - - # Account for error messages that take different forms... - def error_message - body['message'] - rescue - body - end - - # If body is JSON, parse it - # Otherwise return raw string - def body - JSON.parse raw.body - rescue - raw.body - end - - # `headers_hash` is a Typhoeus-specific extension of Hash, - # so simplify it back into a regular old Hash. - def headers - h = {} - raw.headers_hash.each {|k,v| h[k] = v } - h - end - - # Extract the response format from the header hash - # e.g. {'Content-Type' => 'application/json'} - def format - headers['Content-Type'].split("/").last.downcase - end - - def json? - format == 'json' - end - - def xml? - format == 'xml' - end - - def pretty_body - return unless body.present? - case format - when 'json' then JSON.pretty_generate(body).gsub(/\n/, '
') - end - end - - def pretty_headers - JSON.pretty_generate(headers).gsub(/\n/, '
') - end - - end -end \ No newline at end of file diff --git a/samples/client/petstore/ruby/lib/swagger/version.rb b/samples/client/petstore/ruby/lib/swagger/version.rb deleted file mode 100644 index 39357c0ed6db..000000000000 --- a/samples/client/petstore/ruby/lib/swagger/version.rb +++ /dev/null @@ -1,4 +0,0 @@ -module Swagger - VERSION = "4.06.08" -end - diff --git a/samples/client/petstore/ruby/lib/swagger_client.rb b/samples/client/petstore/ruby/lib/swagger_client.rb new file mode 100644 index 000000000000..6d239185005c --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client.rb @@ -0,0 +1,25 @@ +# Swagger common files +require 'swagger_client/monkey' +require 'swagger_client/swagger' +require 'swagger_client/swagger/configuration' +require 'swagger_client/swagger/request' +require 'swagger_client/swagger/response' +require 'swagger_client/swagger/version' + +# Models +require 'swagger_client/models/base_object' +require 'swagger_client/models/user' +require 'swagger_client/models/category' +require 'swagger_client/models/pet' +require 'swagger_client/models/tag' +require 'swagger_client/models/order' + +# APIs +require 'swagger_client/api/user_api' +require 'swagger_client/api/pet_api' +require 'swagger_client/api/store_api' + +module SwaggerClient + # Initialize the default configuration + Swagger.configuration ||= Swagger::Configuration.new +end diff --git a/samples/client/petstore/ruby/lib/swagger_client/api/pet_api.rb b/samples/client/petstore/ruby/lib/swagger_client/api/pet_api.rb new file mode 100644 index 000000000000..6f2740b22e95 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client/api/pet_api.rb @@ -0,0 +1,315 @@ +require "uri" + +module SwaggerClient + class PetApi + basePath = "http://petstore.swagger.io/v2" + # apiInvoker = APIInvoker + + # Update an existing pet + # + # @param [Hash] opts the optional parameters + # @option opts [Pet] :body Pet object that needs to be added to the store + # @return void + def self.update_pet(opts = {}) + + + # resource path + path = "/pet".sub('{format}','json') + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = ['application/json', 'application/xml', ] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = Swagger::Request.object_to_http_body(opts[:'body']) + + + Swagger::Request.new(:PUT, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end + + # Add a new pet to the store + # + # @param [Hash] opts the optional parameters + # @option opts [Pet] :body Pet object that needs to be added to the store + # @return void + def self.add_pet(opts = {}) + + + # resource path + path = "/pet".sub('{format}','json') + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = ['application/json', 'application/xml', ] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = Swagger::Request.object_to_http_body(opts[:'body']) + + + Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end + + # Finds Pets by status + # Multiple status values can be provided with comma seperated strings + # @param [Hash] opts the optional parameters + # @option opts [array[string]] :status Status values that need to be considered for filter + # @return array[Pet] + def self.find_pets_by_status(opts = {}) + + + # resource path + path = "/pet/findByStatus".sub('{format}','json') + + # query parameters + query_params = {} + query_params[:'status'] = opts[:'status'] if opts[:'status'] + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = [] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + + response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body + response.map {|response| obj = Pet.new() and obj.build_from_hash(response) } + end + + # Finds Pets by tags + # Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + # @param [Hash] opts the optional parameters + # @option opts [array[string]] :tags Tags to filter by + # @return array[Pet] + def self.find_pets_by_tags(opts = {}) + + + # resource path + path = "/pet/findByTags".sub('{format}','json') + + # query parameters + query_params = {} + query_params[:'tags'] = opts[:'tags'] if opts[:'tags'] + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = [] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + + response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body + response.map {|response| obj = Pet.new() and obj.build_from_hash(response) } + end + + # Find pet by ID + # Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + # @param pet_id ID of pet that needs to be fetched + # @param [Hash] opts the optional parameters + # @return Pet + def self.get_pet_by_id(pet_id, opts = {}) + + # verify the required parameter 'pet_id' is set + raise "Missing the required parameter 'pet_id' when calling get_pet_by_id" if pet_id.nil? + + + # resource path + path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = [] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + + response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body + obj = Pet.new() and obj.build_from_hash(response) + end + + # Updates a pet in the store with form data + # + # @param pet_id ID of pet that needs to be updated + # @param [Hash] opts the optional parameters + # @option opts [string] :name Updated name of the pet + # @option opts [string] :status Updated status of the pet + # @return void + def self.update_pet_with_form(pet_id, opts = {}) + + # verify the required parameter 'pet_id' is set + raise "Missing the required parameter 'pet_id' when calling update_pet_with_form" if pet_id.nil? + + + # resource path + path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = ['application/x-www-form-urlencoded', ] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + form_params["name"] = opts[:'name'] if opts[:'name'] + form_params["status"] = opts[:'status'] if opts[:'status'] + + # http body (model) + post_body = nil + + + Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end + + # Deletes a pet + # + # @param pet_id Pet id to delete + # @param [Hash] opts the optional parameters + # @option opts [string] :api_key + # @return void + def self.delete_pet(pet_id, opts = {}) + + # verify the required parameter 'pet_id' is set + raise "Missing the required parameter 'pet_id' when calling delete_pet" if pet_id.nil? + + + # resource path + path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = [] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params[:'api_key'] = opts[:'api_key'] if opts[:'api_key'] + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + + Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end + + # uploads an image + # + # @param pet_id ID of pet to update + # @param [Hash] opts the optional parameters + # @option opts [string] :additional_metadata Additional data to pass to server + # @option opts [file] :file file to upload + # @return void + def self.upload_file(pet_id, opts = {}) + + # verify the required parameter 'pet_id' is set + raise "Missing the required parameter 'pet_id' when calling upload_file" if pet_id.nil? + + + # resource path + path = "/pet/{petId}/uploadImage".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = ['multipart/form-data', ] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + form_params["additionalMetadata"] = opts[:'additional_metadata'] if opts[:'additional_metadata'] + form_params["file"] = opts[:'file'] if opts[:'file'] + + # http body (model) + post_body = nil + + + Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end + end +end diff --git a/samples/client/petstore/ruby/lib/swagger_client/api/store_api.rb b/samples/client/petstore/ruby/lib/swagger_client/api/store_api.rb new file mode 100644 index 000000000000..37595c2147e1 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client/api/store_api.rb @@ -0,0 +1,156 @@ +require "uri" + +module SwaggerClient + class StoreApi + basePath = "http://petstore.swagger.io/v2" + # apiInvoker = APIInvoker + + # Returns pet inventories by status + # Returns a map of status codes to quantities + # @param [Hash] opts the optional parameters + # @return map[string,int] + def self.get_inventory(opts = {}) + + + # resource path + path = "/store/inventory".sub('{format}','json') + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = [] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + + response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body + response.map {|response| obj = map.new() and obj.build_from_hash(response) } + end + + # Place an order for a pet + # + # @param [Hash] opts the optional parameters + # @option opts [Order] :body order placed for purchasing the pet + # @return Order + def self.place_order(opts = {}) + + + # resource path + path = "/store/order".sub('{format}','json') + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = [] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = Swagger::Request.object_to_http_body(opts[:'body']) + + + response = Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body + obj = Order.new() and obj.build_from_hash(response) + end + + # Find purchase order by ID + # For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + # @param order_id ID of pet that needs to be fetched + # @param [Hash] opts the optional parameters + # @return Order + def self.get_order_by_id(order_id, opts = {}) + + # verify the required parameter 'order_id' is set + raise "Missing the required parameter 'order_id' when calling get_order_by_id" if order_id.nil? + + + # resource path + path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', order_id.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = [] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + + response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body + obj = Order.new() and obj.build_from_hash(response) + end + + # Delete purchase order by ID + # For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + # @param order_id ID of the order that needs to be deleted + # @param [Hash] opts the optional parameters + # @return void + def self.delete_order(order_id, opts = {}) + + # verify the required parameter 'order_id' is set + raise "Missing the required parameter 'order_id' when calling delete_order" if order_id.nil? + + + # resource path + path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', order_id.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = [] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + + Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end + end +end diff --git a/samples/client/petstore/ruby/lib/swagger_client/api/user_api.rb b/samples/client/petstore/ruby/lib/swagger_client/api/user_api.rb new file mode 100644 index 000000000000..12a45561e3f1 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client/api/user_api.rb @@ -0,0 +1,302 @@ +require "uri" + +module SwaggerClient + class UserApi + basePath = "http://petstore.swagger.io/v2" + # apiInvoker = APIInvoker + + # Create user + # This can only be done by the logged in user. + # @param [Hash] opts the optional parameters + # @option opts [User] :body Created user object + # @return void + def self.create_user(opts = {}) + + + # resource path + path = "/user".sub('{format}','json') + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = [] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = Swagger::Request.object_to_http_body(opts[:'body']) + + + Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end + + # Creates list of users with given input array + # + # @param [Hash] opts the optional parameters + # @option opts [array[User]] :body List of user object + # @return void + def self.create_users_with_array_input(opts = {}) + + + # resource path + path = "/user/createWithArray".sub('{format}','json') + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = [] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = Swagger::Request.object_to_http_body(opts[:'body']) + + + Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end + + # Creates list of users with given input array + # + # @param [Hash] opts the optional parameters + # @option opts [array[User]] :body List of user object + # @return void + def self.create_users_with_list_input(opts = {}) + + + # resource path + path = "/user/createWithList".sub('{format}','json') + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = [] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = Swagger::Request.object_to_http_body(opts[:'body']) + + + Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end + + # Logs user into the system + # + # @param [Hash] opts the optional parameters + # @option opts [string] :username The user name for login + # @option opts [string] :password The password for login in clear text + # @return string + def self.login_user(opts = {}) + + + # resource path + path = "/user/login".sub('{format}','json') + + # query parameters + query_params = {} + query_params[:'username'] = opts[:'username'] if opts[:'username'] + query_params[:'password'] = opts[:'password'] if opts[:'password'] + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = [] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + + response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body + obj = string.new() and obj.build_from_hash(response) + end + + # Logs out current logged in user session + # + # @param [Hash] opts the optional parameters + # @return void + def self.logout_user(opts = {}) + + + # resource path + path = "/user/logout".sub('{format}','json') + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = [] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + + Swagger::Request.new(:GET, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end + + # Get user by user name + # + # @param username The name that needs to be fetched. Use user1 for testing. + # @param [Hash] opts the optional parameters + # @return User + def self.get_user_by_name(username, opts = {}) + + # verify the required parameter 'username' is set + raise "Missing the required parameter 'username' when calling get_user_by_name" if username.nil? + + + # resource path + path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = [] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + + response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body + obj = User.new() and obj.build_from_hash(response) + end + + # Updated user + # This can only be done by the logged in user. + # @param username name that need to be deleted + # @param [Hash] opts the optional parameters + # @option opts [User] :body Updated user object + # @return void + def self.update_user(username, opts = {}) + + # verify the required parameter 'username' is set + raise "Missing the required parameter 'username' when calling update_user" if username.nil? + + + # resource path + path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = [] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = Swagger::Request.object_to_http_body(opts[:'body']) + + + Swagger::Request.new(:PUT, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end + + # Delete user + # This can only be done by the logged in user. + # @param username The name that needs to be deleted + # @param [Hash] opts the optional parameters + # @return void + def self.delete_user(username, opts = {}) + + # verify the required parameter 'username' is set + raise "Missing the required parameter 'username' when calling delete_user" if username.nil? + + + # resource path + path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = [] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + + Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end + end +end diff --git a/samples/client/petstore/ruby/lib/swagger_client/models/base_object.rb b/samples/client/petstore/ruby/lib/swagger_client/models/base_object.rb new file mode 100644 index 000000000000..642e4769e559 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client/models/base_object.rb @@ -0,0 +1,83 @@ +module SwaggerClient + # base class containing fundamental method such as to_hash, build_from_hash and more + class BaseObject + + # return the object in the form of hash + def to_body + body = {} + self.class.attribute_map.each_pair do |key, value| + body[value] = self.send(key) unless self.send(key).nil? + end + body + end + + # build the object from hash + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.swagger_types.each_pair do |key, type| + if type =~ /^array\[(.*)\]/i + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) + else + #TODO show warning in debug mode + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + else + # data not found in attributes(hash), not an issue as the data can be optional + end + end + + self + end + + def _deserialize(type, value) + case type.to_sym + when :DateTime + DateTime.parse(value) + when :string + value.to_s + when :int + value.to_i + when :double + value.to_f + when :boolean + if value =~ /^(true|t|yes|y|1)$/i + true + else + false + end + else # model + _model = SwaggerClient.const_get(type).new + _model.build_from_hash(value) + end + end + + # to_body is an alias to to_body (backward compatibility) + def to_hash + hash = {} + self.class.attribute_map.each_pair do |key, value| + if self.send(key).is_a?(Array) + next if self.send(key).empty? + hash[value] = self.send(key).select{|v| !v.nil?}.map{ |v| _to_hash v} unless self.send(key).nil? + else + unless (_tmp_value = _to_hash self.send(key)).nil? + hash[value] = _tmp_value + end + end + end + hash + end + + # Method to output non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + def _to_hash(value) + if value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end +end diff --git a/samples/client/petstore/ruby/lib/swagger_client/models/category.rb b/samples/client/petstore/ruby/lib/swagger_client/models/category.rb new file mode 100644 index 000000000000..fe195c7ac871 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client/models/category.rb @@ -0,0 +1,44 @@ +module SwaggerClient + # + class Category < BaseObject + attr_accessor :id, :name + # attribute mapping from ruby-style variable name to JSON key + def self.attribute_map + { + + # + :'id' => :'id', + + # + :'name' => :'name' + + } + end + + # attribute type + def self.swagger_types + { + :'id' => :'int', + :'name' => :'string' + + } + end + + def initialize(attributes = {}) + return if !attributes.is_a?(Hash) || attributes.empty? + + # convert string to symbol for hash key + attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} + + + if attributes[:'id'] + @id = attributes[:'id'] + end + + if attributes[:'name'] + @name = attributes[:'name'] + end + + end + end +end diff --git a/samples/client/petstore/ruby/lib/swagger_client/models/order.rb b/samples/client/petstore/ruby/lib/swagger_client/models/order.rb new file mode 100644 index 000000000000..3fe0282ed9b8 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client/models/order.rb @@ -0,0 +1,76 @@ +module SwaggerClient + # + class Order < BaseObject + attr_accessor :id, :pet_id, :quantity, :ship_date, :status, :complete + # attribute mapping from ruby-style variable name to JSON key + def self.attribute_map + { + + # + :'id' => :'id', + + # + :'pet_id' => :'petId', + + # + :'quantity' => :'quantity', + + # + :'ship_date' => :'shipDate', + + # Order Status + :'status' => :'status', + + # + :'complete' => :'complete' + + } + end + + # attribute type + def self.swagger_types + { + :'id' => :'int', + :'pet_id' => :'int', + :'quantity' => :'int', + :'ship_date' => :'DateTime', + :'status' => :'string', + :'complete' => :'boolean' + + } + end + + def initialize(attributes = {}) + return if !attributes.is_a?(Hash) || attributes.empty? + + # convert string to symbol for hash key + attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} + + + if attributes[:'id'] + @id = attributes[:'id'] + end + + if attributes[:'petId'] + @pet_id = attributes[:'petId'] + end + + if attributes[:'quantity'] + @quantity = attributes[:'quantity'] + end + + if attributes[:'shipDate'] + @ship_date = attributes[:'shipDate'] + end + + if attributes[:'status'] + @status = attributes[:'status'] + end + + if attributes[:'complete'] + @complete = attributes[:'complete'] + end + + end + end +end diff --git a/samples/client/petstore/ruby/lib/swagger_client/models/pet.rb b/samples/client/petstore/ruby/lib/swagger_client/models/pet.rb new file mode 100644 index 000000000000..32f95646c726 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client/models/pet.rb @@ -0,0 +1,80 @@ +module SwaggerClient + # + class Pet < BaseObject + attr_accessor :id, :category, :name, :photo_urls, :tags, :status + # attribute mapping from ruby-style variable name to JSON key + def self.attribute_map + { + + # + :'id' => :'id', + + # + :'category' => :'category', + + # + :'name' => :'name', + + # + :'photo_urls' => :'photoUrls', + + # + :'tags' => :'tags', + + # pet status in the store + :'status' => :'status' + + } + end + + # attribute type + def self.swagger_types + { + :'id' => :'int', + :'category' => :'Category', + :'name' => :'string', + :'photo_urls' => :'array[string]', + :'tags' => :'array[Tag]', + :'status' => :'string' + + } + end + + def initialize(attributes = {}) + return if !attributes.is_a?(Hash) || attributes.empty? + + # convert string to symbol for hash key + attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} + + + if attributes[:'id'] + @id = attributes[:'id'] + end + + if attributes[:'category'] + @category = attributes[:'category'] + end + + if attributes[:'name'] + @name = attributes[:'name'] + end + + if attributes[:'photoUrls'] + if (value = attributes[:'photoUrls']).is_a?(Array) + @photo_urls = value + end + end + + if attributes[:'tags'] + if (value = attributes[:'tags']).is_a?(Array) + @tags = value + end + end + + if attributes[:'status'] + @status = attributes[:'status'] + end + + end + end +end diff --git a/samples/client/petstore/ruby/lib/swagger_client/models/tag.rb b/samples/client/petstore/ruby/lib/swagger_client/models/tag.rb new file mode 100644 index 000000000000..9c5cdde1af67 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client/models/tag.rb @@ -0,0 +1,44 @@ +module SwaggerClient + # + class Tag < BaseObject + attr_accessor :id, :name + # attribute mapping from ruby-style variable name to JSON key + def self.attribute_map + { + + # + :'id' => :'id', + + # + :'name' => :'name' + + } + end + + # attribute type + def self.swagger_types + { + :'id' => :'int', + :'name' => :'string' + + } + end + + def initialize(attributes = {}) + return if !attributes.is_a?(Hash) || attributes.empty? + + # convert string to symbol for hash key + attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} + + + if attributes[:'id'] + @id = attributes[:'id'] + end + + if attributes[:'name'] + @name = attributes[:'name'] + end + + end + end +end diff --git a/samples/client/petstore/ruby/lib/swagger_client/models/user.rb b/samples/client/petstore/ruby/lib/swagger_client/models/user.rb new file mode 100644 index 000000000000..2d723da54c44 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client/models/user.rb @@ -0,0 +1,92 @@ +module SwaggerClient + # + class User < BaseObject + attr_accessor :id, :username, :first_name, :last_name, :email, :password, :phone, :user_status + # attribute mapping from ruby-style variable name to JSON key + def self.attribute_map + { + + # + :'id' => :'id', + + # + :'username' => :'username', + + # + :'first_name' => :'firstName', + + # + :'last_name' => :'lastName', + + # + :'email' => :'email', + + # + :'password' => :'password', + + # + :'phone' => :'phone', + + # User Status + :'user_status' => :'userStatus' + + } + end + + # attribute type + def self.swagger_types + { + :'id' => :'int', + :'username' => :'string', + :'first_name' => :'string', + :'last_name' => :'string', + :'email' => :'string', + :'password' => :'string', + :'phone' => :'string', + :'user_status' => :'int' + + } + end + + def initialize(attributes = {}) + return if !attributes.is_a?(Hash) || attributes.empty? + + # convert string to symbol for hash key + attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} + + + if attributes[:'id'] + @id = attributes[:'id'] + end + + if attributes[:'username'] + @username = attributes[:'username'] + end + + if attributes[:'firstName'] + @first_name = attributes[:'firstName'] + end + + if attributes[:'lastName'] + @last_name = attributes[:'lastName'] + end + + if attributes[:'email'] + @email = attributes[:'email'] + end + + if attributes[:'password'] + @password = attributes[:'password'] + end + + if attributes[:'phone'] + @phone = attributes[:'phone'] + end + + if attributes[:'userStatus'] + @user_status = attributes[:'userStatus'] + end + + end + end +end diff --git a/samples/client/petstore/ruby/lib/monkey.rb b/samples/client/petstore/ruby/lib/swagger_client/monkey.rb similarity index 100% rename from samples/client/petstore/ruby/lib/monkey.rb rename to samples/client/petstore/ruby/lib/swagger_client/monkey.rb diff --git a/samples/client/petstore/ruby/lib/swagger_client/swagger.rb b/samples/client/petstore/ruby/lib/swagger_client/swagger.rb new file mode 100644 index 000000000000..278db36e4cad --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client/swagger.rb @@ -0,0 +1,78 @@ +require 'logger' +require 'json' + +module SwaggerClient + module Swagger + class << self + attr_accessor :logger + + # A Swagger configuration object. Must act like a hash and return sensible + # values for all Swagger configuration options. See Swagger::Configuration. + attr_accessor :configuration + + attr_accessor :resources + + # Call this method to modify defaults in your initializers. + # + # @example + # Swagger.configure do |config| + # config.api_key = '1234567890abcdef' # required + # config.username = 'wordlover' # optional, but needed for user-related functions + # config.password = 'i<3words' # optional, but needed for user-related functions + # config.format = 'json' # optional, defaults to 'json' + # end + # + def configure + yield(configuration) if block_given? + + # Configure logger. Default to use Rails + self.logger ||= configuration.logger || (defined?(Rails) ? Rails.logger : Logger.new(STDOUT)) + + # remove :// from scheme + configuration.scheme.sub!(/:\/\//, '') + + # remove http(s):// and anything after a slash + configuration.host.sub!(/https?:\/\//, '') + configuration.host = configuration.host.split('/').first + + # Add leading and trailing slashes to base_path + configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/') + configuration.base_path = "" if configuration.base_path == "/" + end + + def authenticated? + Swagger.configuration.auth_token.present? + end + + def de_authenticate + Swagger.configuration.auth_token = nil + end + + def authenticate + return if Swagger.authenticated? + + if Swagger.configuration.username.blank? || Swagger.configuration.password.blank? + raise ClientError, "Username and password are required to authenticate." + end + + request = Swagger::Request.new( + :get, + "account/authenticate/{username}", + :params => { + :username => Swagger.configuration.username, + :password => Swagger.configuration.password + } + ) + + response_body = request.response.body + Swagger.configuration.auth_token = response_body['token'] + end + end + end + + class ServerError < StandardError + end + + class ClientError < StandardError + end +end diff --git a/samples/client/petstore/ruby/lib/swagger_client/swagger/configuration.rb b/samples/client/petstore/ruby/lib/swagger_client/swagger/configuration.rb new file mode 100644 index 000000000000..51f9539a9abe --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client/swagger/configuration.rb @@ -0,0 +1,19 @@ +module SwaggerClient + module Swagger + class Configuration + attr_accessor :format, :api_key, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params, :user_agent + + # Defaults go in here.. + def initialize + @format = 'json' + @scheme = 'http' + @host = 'petstore.swagger.io' + @base_path = '/v2' + @user_agent = "ruby-swagger-#{Swagger::VERSION}" + @inject_format = false + @force_ending_format = false + @camelize_params = true + end + end + end +end diff --git a/samples/client/petstore/ruby/lib/swagger_client/swagger/request.rb b/samples/client/petstore/ruby/lib/swagger_client/swagger/request.rb new file mode 100644 index 000000000000..d5f266267dac --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client/swagger/request.rb @@ -0,0 +1,257 @@ +module SwaggerClient + module Swagger + class Request + require 'uri' + require 'addressable/uri' + require 'typhoeus' + + attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params + + # All requests must have an HTTP method and a path + # Optionals parameters are :params, :headers, :body, :format, :host + def initialize(http_method, path, attributes={}) + attributes[:format] ||= Swagger.configuration.format + attributes[:params] ||= {} + + # Set default headers + default_headers = { + 'Content-Type' => "application/#{attributes[:format].downcase}", + :api_key => Swagger.configuration.api_key, + 'User-Agent' => Swagger.configuration.user_agent + } + + # api_key from headers hash trumps the default, even if its value is blank + if attributes[:headers].present? && attributes[:headers].has_key?(:api_key) + default_headers.delete(:api_key) + end + + # api_key from params hash trumps all others (headers and default_headers) + if attributes[:params].present? && attributes[:params].has_key?(:api_key) + default_headers.delete(:api_key) + attributes[:headers].delete(:api_key) if attributes[:headers].present? + end + + # Merge argument headers into defaults + attributes[:headers] = default_headers.merge(attributes[:headers] || {}) + + # Stick in the auth token if there is one + if Swagger.authenticated? + attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token}) + end + + self.http_method = http_method.to_sym + self.path = path + attributes.each do |name, value| + send("#{name.to_s.underscore.to_sym}=", value) + end + end + + # Construct a base URL + def url(options = {}) + u = Addressable::URI.new( + :scheme => Swagger.configuration.scheme, + :host => Swagger.configuration.host, + :path => self.interpreted_path, + :query => self.query_string.sub(/\?/, '') + ).to_s + + # Drop trailing question mark, if present + u.sub! /\?$/, '' + + # Obfuscate API key? + u.sub! /api\_key=\w+/, 'api_key=YOUR_API_KEY' if options[:obfuscated] + + u + end + + # Iterate over the params hash, injecting any path values into the path string + # e.g. /word.{format}/{word}/entries => /word.json/cat/entries + def interpreted_path + p = self.path.dup + + # Stick a .{format} placeholder into the path if there isn't + # one already or an actual format like json or xml + # e.g. /words/blah => /words.{format}/blah + if Swagger.configuration.inject_format + unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } + p = p.sub(/^(\/?\w+)/, "\\1.#{format}") + end + end + + # Stick a .{format} placeholder on the end of the path if there isn't + # one already or an actual format like json or xml + # e.g. /words/blah => /words/blah.{format} + if Swagger.configuration.force_ending_format + unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } + p = "#{p}.#{format}" + end + end + + p = p.sub("{format}", self.format.to_s) + + URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/') + end + + # Massage the request body into a state of readiness + # If body is a hash, camelize all keys then convert to a json string + def body=(value) + if value.is_a?(Hash) + value = value.inject({}) do |memo, (k,v)| + memo[k.to_s.camelize(:lower).to_sym] = v + memo + end + end + @body = value + end + + # If body is an object, JSONify it before making the actual request. + # For form parameters, remove empty value + def outgoing_body + # http form + if @body.nil? && @form_params && !@form_params.empty? + data = form_params.dup + data.each do |key, value| + data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter + end + data + else # http body is JSON + @body.is_a?(String) ? @body : @body.to_json + end + end + + # Construct a query string from the query-string-type params + def query_string + # Iterate over all params, + # .. removing the ones that are part of the path itself. + # .. stringifying values so Addressable doesn't blow up. + query_values = {} + self.params.each_pair do |key, value| + next if self.path.include? "{#{key}}" # skip path params + next if value.blank? && value.class != FalseClass # skip empties + if Swagger.configuration.camelize_params + key = key.to_s.camelize(:lower).to_sym unless key.to_sym == :api_key # api_key is not a camelCased param + end + query_values[key] = value.to_s + end + + # We don't want to end up with '?' as our query string + # if there aren't really any params + return "" if query_values.blank? + + # Addressable requires query_values to be set after initialization.. + qs = Addressable::URI.new + qs.query_values = query_values + qs.to_s + end + + def make + #TODO use configuration setting to determine if debugging + #logger = Logger.new STDOUT + #logger.debug self.url + response = case self.http_method.to_sym + when :get,:GET + Typhoeus::Request.get( + self.url, + :headers => self.headers.stringify_keys, + ) + + when :post,:POST + Typhoeus::Request.post( + self.url, + :body => self.outgoing_body, + :headers => self.headers.stringify_keys, + ) + + when :patch,:PATCH + Typhoeus::Request.patch( + self.url, + :body => self.outgoing_body, + :headers => self.headers.stringify_keys, + ) + + when :put,:PUT + Typhoeus::Request.put( + self.url, + :body => self.outgoing_body, + :headers => self.headers.stringify_keys, + ) + + when :delete,:DELETE + Typhoeus::Request.delete( + self.url, + :body => self.outgoing_body, + :headers => self.headers.stringify_keys, + ) + end + Response.new(response) + end + + def response + self.make + end + + def response_code_pretty + return unless @response.present? + @response.code.to_s + end + + def response_headers_pretty + return unless @response.present? + # JSON.pretty_generate(@response.headers).gsub(/\n/, '
') # <- This was for RestClient + @response.headers.gsub(/\n/, '
') # <- This is for Typhoeus + end + + # return 'Accept' based on an array of accept provided + # @param [Array] header_accept_array Array fo 'Accept' + # @return String Accept (e.g. application/json) + def self.select_header_accept header_accept_array + if header_accept_array.empty? + return + elsif header_accept_array.any?{ |s| s.casecmp('application/json')==0 } + 'application/json' # look for json data by default + else + header_accept_array.join(',') + end + end + + # return the content type based on an array of content-type provided + # @param [Array] content_type_array Array fo content-type + # @return String Content-Type (e.g. application/json) + def self.select_header_content_type content_type_array + if content_type_array.empty? + 'application/json' # use application/json by default + elsif content_type_array.any?{ |s| s.casecmp('application/json')==0 } + 'application/json' # use application/json if it's included + else + content_type_array[0]; # otherwise, use the first one + end + end + + # static method to convert object (array, hash, object, etc) to JSON string + # @param model object to be converted into JSON string + # @return string JSON string representation of the object + def self.object_to_http_body model + return if model.nil? + _body = nil + if model.is_a?(Array) + _body = model.map{|m| object_to_hash(m) } + else + _body = object_to_hash(model) + end + _body.to_json + end + + # static method to convert object(non-array) to hash + # @param obj object to be converted into JSON string + # @return string JSON string representation of the object + def self.object_to_hash obj + if obj.respond_to?(:to_hash) + obj.to_hash + else + obj + end + end + + end + end +end diff --git a/samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb b/samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb new file mode 100644 index 000000000000..538821bea691 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb @@ -0,0 +1,70 @@ +module SwaggerClient + module Swagger + class Response + require 'json' + + attr_accessor :raw + + def initialize(raw) + self.raw = raw + + case self.code + when 500..510 then raise(ServerError, self.error_message) + when 299..426 then raise(ClientError, self.error_message) + end + end + + def code + raw.code + end + + # Account for error messages that take different forms... + def error_message + body['message'] + rescue + body + end + + # If body is JSON, parse it + # Otherwise return raw string + def body + JSON.parse(raw.body, :symbolize_names => true) + rescue + raw.body + end + + # `headers_hash` is a Typhoeus-specific extension of Hash, + # so simplify it back into a regular old Hash. + def headers + h = {} + raw.headers_hash.each {|k,v| h[k] = v } + h + end + + # Extract the response format from the header hash + # e.g. {'Content-Type' => 'application/json'} + def format + headers['Content-Type'].split("/").last.downcase + end + + def json? + format == 'json' + end + + def xml? + format == 'xml' + end + + def pretty_body + return unless body.present? + case format + when 'json' then JSON.pretty_generate(body).gsub(/\n/, '
') + end + end + + def pretty_headers + JSON.pretty_generate(headers).gsub(/\n/, '
') + end + end + end +end diff --git a/samples/client/petstore/ruby/lib/swagger_client/swagger/version.rb b/samples/client/petstore/ruby/lib/swagger_client/swagger/version.rb new file mode 100644 index 000000000000..c6e8d5aee53d --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client/swagger/version.rb @@ -0,0 +1,5 @@ +module SwaggerClient + module Swagger + VERSION = "1.0.0" + end +end diff --git a/samples/client/petstore/ruby/lib/user_api.rb b/samples/client/petstore/ruby/lib/user_api.rb deleted file mode 100644 index dead94897cd3..000000000000 --- a/samples/client/petstore/ruby/lib/user_api.rb +++ /dev/null @@ -1,350 +0,0 @@ -require "uri" - -class UserApi - basePath = "http://petstore.swagger.io/v2" - # apiInvoker = APIInvoker - - # Create user - # This can only be done by the logged in user. - # @param [Hash] opts the optional parameters - # @option opts [User] :body Created user object - # @return void - def self.create_user(opts = {}) - # verify existence of params - - # resource path - path = "/user".sub('{format}','json') - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' - - _header_content_type = [] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - _body_param = opts[:'body'] - if _body_param != nil - if _body_param.is_a?(Array) - _array = Array.new - _body_param.each do |item| - if item.respond_to?(:to_body) - _array.push item.to_body - else - _array.push item - end - end - post_body = _array - else - if _body_param.respond_to?(:to_body) - post_body = _body_param.to_body - else - post_body = _body_param - end - end - end - - Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end - - # Creates list of users with given input array - # - # @param [Hash] opts the optional parameters - # @option opts [array[User]] :body List of user object - # @return void - def self.create_users_with_array_input(opts = {}) - # verify existence of params - - # resource path - path = "/user/createWithArray".sub('{format}','json') - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' - - _header_content_type = [] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - _body_param = opts[:'body'] - if _body_param != nil - if _body_param.is_a?(Array) - _array = Array.new - _body_param.each do |item| - if item.respond_to?(:to_body) - _array.push item.to_body - else - _array.push item - end - end - post_body = _array - else - if _body_param.respond_to?(:to_body) - post_body = _body_param.to_body - else - post_body = _body_param - end - end - end - - Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end - - # Creates list of users with given input array - # - # @param [Hash] opts the optional parameters - # @option opts [array[User]] :body List of user object - # @return void - def self.create_users_with_list_input(opts = {}) - # verify existence of params - - # resource path - path = "/user/createWithList".sub('{format}','json') - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' - - _header_content_type = [] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - _body_param = opts[:'body'] - if _body_param != nil - if _body_param.is_a?(Array) - _array = Array.new - _body_param.each do |item| - if item.respond_to?(:to_body) - _array.push item.to_body - else - _array.push item - end - end - post_body = _array - else - if _body_param.respond_to?(:to_body) - post_body = _body_param.to_body - else - post_body = _body_param - end - end - end - - Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end - - # Logs user into the system - # - # @param [Hash] opts the optional parameters - # @option opts [string] :username The user name for login - # @option opts [string] :password The password for login in clear text - # @return string - def self.login_user(opts = {}) - # verify existence of params - - # resource path - path = "/user/login".sub('{format}','json') - - # query parameters - query_params = {} - query_params[:'username'] = opts[:'username'] if opts[:'username'] - query_params[:'password'] = opts[:'password'] if opts[:'password'] - - # header parameters - header_params = {} - - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' - - _header_content_type = [] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body - string.new(response) - end - - # Logs out current logged in user session - # - # @param [Hash] opts the optional parameters - # @return void - def self.logout_user(opts = {}) - # verify existence of params - - # resource path - path = "/user/logout".sub('{format}','json') - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' - - _header_content_type = [] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - Swagger::Request.new(:GET, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end - - # Get user by user name - # - # @param username The name that needs to be fetched. Use user1 for testing. - # @param [Hash] opts the optional parameters - # @return User - def self.get_user_by_name(username, opts = {}) - # verify existence of params - raise "username is required" if username.nil? - - # resource path - path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' - - _header_content_type = [] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body - User.new(response) - end - - # Updated user - # This can only be done by the logged in user. - # @param username name that need to be deleted - # @param [Hash] opts the optional parameters - # @option opts [User] :body Updated user object - # @return void - def self.update_user(username, opts = {}) - # verify existence of params - raise "username is required" if username.nil? - - # resource path - path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' - - _header_content_type = [] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - _body_param = opts[:'body'] - if _body_param != nil - if _body_param.is_a?(Array) - _array = Array.new - _body_param.each do |item| - if item.respond_to?(:to_body) - _array.push item.to_body - else - _array.push item - end - end - post_body = _array - else - if _body_param.respond_to?(:to_body) - post_body = _body_param.to_body - else - post_body = _body_param - end - end - end - - Swagger::Request.new(:PUT, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end - - # Delete user - # This can only be done by the logged in user. - # @param username The name that needs to be deleted - # @param [Hash] opts the optional parameters - # @return void - def self.delete_user(username, opts = {}) - # verify existence of params - raise "username is required" if username.nil? - - # resource path - path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' - - _header_content_type = [] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end -end diff --git a/samples/client/petstore/ruby/models/category.rb b/samples/client/petstore/ruby/models/category.rb deleted file mode 100644 index 64ca857e17e6..000000000000 --- a/samples/client/petstore/ruby/models/category.rb +++ /dev/null @@ -1,34 +0,0 @@ - -class Category - attr_accessor :id, :name - # :internal => :external - def self.attribute_map - { - :id => :'id', - :name => :'name' - - } - end - - def initialize(attributes = {}) - return if attributes.empty? - # Morph attribute keys into undescored rubyish style - - if self.class.attribute_map[:"id"] - @id = attributes["id"] - end - - if self.class.attribute_map[:"name"] - @name = attributes["name"] - end - - end - - def to_body - body = {} - self.class.attribute_map.each_pair do |key, value| - body[value] = self.send(key) unless self.send(key).nil? - end - body - end -end diff --git a/samples/client/petstore/ruby/models/order.rb b/samples/client/petstore/ruby/models/order.rb deleted file mode 100644 index 5434fbd8e2d8..000000000000 --- a/samples/client/petstore/ruby/models/order.rb +++ /dev/null @@ -1,54 +0,0 @@ - -class Order - attr_accessor :id, :pet_id, :quantity, :ship_date, :status, :complete - # :internal => :external - def self.attribute_map - { - :id => :'id', - :pet_id => :'petId', - :quantity => :'quantity', - :ship_date => :'shipDate', - :status => :'status', - :complete => :'complete' - - } - end - - def initialize(attributes = {}) - return if attributes.empty? - # Morph attribute keys into undescored rubyish style - - if self.class.attribute_map[:"id"] - @id = attributes["id"] - end - - if self.class.attribute_map[:"pet_id"] - @pet_id = attributes["petId"] - end - - if self.class.attribute_map[:"quantity"] - @quantity = attributes["quantity"] - end - - if self.class.attribute_map[:"ship_date"] - @ship_date = attributes["shipDate"] - end - - if self.class.attribute_map[:"status"] - @status = attributes["status"] - end - - if self.class.attribute_map[:"complete"] - @complete = attributes["complete"] - end - - end - - def to_body - body = {} - self.class.attribute_map.each_pair do |key, value| - body[value] = self.send(key) unless self.send(key).nil? - end - body - end -end diff --git a/samples/client/petstore/ruby/models/pet.rb b/samples/client/petstore/ruby/models/pet.rb deleted file mode 100644 index 38767b46dd7a..000000000000 --- a/samples/client/petstore/ruby/models/pet.rb +++ /dev/null @@ -1,58 +0,0 @@ - -class Pet - attr_accessor :id, :category, :name, :photo_urls, :tags, :status - # :internal => :external - def self.attribute_map - { - :id => :'id', - :category => :'category', - :name => :'name', - :photo_urls => :'photoUrls', - :tags => :'tags', - :status => :'status' - - } - end - - def initialize(attributes = {}) - return if attributes.empty? - # Morph attribute keys into undescored rubyish style - - if self.class.attribute_map[:"id"] - @id = attributes["id"] - end - - if self.class.attribute_map[:"category"] - @category = attributes["category"] - end - - if self.class.attribute_map[:"name"] - @name = attributes["name"] - end - - if self.class.attribute_map[:"photo_urls"] - if (value = attributes["photoUrls"]).is_a?(Array) - @photo_urls = value - end - end - - if self.class.attribute_map[:"tags"] - if (value = attributes["tags"]).is_a?(Array) - @tags = value.map{ |v| Tag.new(v) } - end - end - - if self.class.attribute_map[:"status"] - @status = attributes["status"] - end - - end - - def to_body - body = {} - self.class.attribute_map.each_pair do |key, value| - body[value] = self.send(key) unless self.send(key).nil? - end - body - end -end diff --git a/samples/client/petstore/ruby/models/tag.rb b/samples/client/petstore/ruby/models/tag.rb deleted file mode 100644 index 24e3d1d0706e..000000000000 --- a/samples/client/petstore/ruby/models/tag.rb +++ /dev/null @@ -1,34 +0,0 @@ - -class Tag - attr_accessor :id, :name - # :internal => :external - def self.attribute_map - { - :id => :'id', - :name => :'name' - - } - end - - def initialize(attributes = {}) - return if attributes.empty? - # Morph attribute keys into undescored rubyish style - - if self.class.attribute_map[:"id"] - @id = attributes["id"] - end - - if self.class.attribute_map[:"name"] - @name = attributes["name"] - end - - end - - def to_body - body = {} - self.class.attribute_map.each_pair do |key, value| - body[value] = self.send(key) unless self.send(key).nil? - end - body - end -end diff --git a/samples/client/petstore/ruby/models/user.rb b/samples/client/petstore/ruby/models/user.rb deleted file mode 100644 index e270392a3b89..000000000000 --- a/samples/client/petstore/ruby/models/user.rb +++ /dev/null @@ -1,64 +0,0 @@ - -class User - attr_accessor :id, :username, :first_name, :last_name, :email, :password, :phone, :user_status - # :internal => :external - def self.attribute_map - { - :id => :'id', - :username => :'username', - :first_name => :'firstName', - :last_name => :'lastName', - :email => :'email', - :password => :'password', - :phone => :'phone', - :user_status => :'userStatus' - - } - end - - def initialize(attributes = {}) - return if attributes.empty? - # Morph attribute keys into undescored rubyish style - - if self.class.attribute_map[:"id"] - @id = attributes["id"] - end - - if self.class.attribute_map[:"username"] - @username = attributes["username"] - end - - if self.class.attribute_map[:"first_name"] - @first_name = attributes["firstName"] - end - - if self.class.attribute_map[:"last_name"] - @last_name = attributes["lastName"] - end - - if self.class.attribute_map[:"email"] - @email = attributes["email"] - end - - if self.class.attribute_map[:"password"] - @password = attributes["password"] - end - - if self.class.attribute_map[:"phone"] - @phone = attributes["phone"] - end - - if self.class.attribute_map[:"user_status"] - @user_status = attributes["userStatus"] - end - - end - - def to_body - body = {} - self.class.attribute_map.each_pair do |key, value| - body[value] = self.send(key) unless self.send(key).nil? - end - body - end -end diff --git a/samples/client/petstore/ruby/spec/pet_spec.rb b/samples/client/petstore/ruby/spec/pet_spec.rb index 67cee70c1ee5..f66f33cf84c0 100644 --- a/samples/client/petstore/ruby/spec/pet_spec.rb +++ b/samples/client/petstore/ruby/spec/pet_spec.rb @@ -1,52 +1,83 @@ require 'spec_helper' +require 'json' describe "Pet" do before do configure_swagger prepare_pet end - + describe "pet methods" do + it "should construct a new pet object" do + tag1 = SwaggerClient::Tag.new({'id' => 1, 'name'=> 'tag1'}) + tag2 = SwaggerClient::Tag.new({'id' => 2, 'name'=> 'tag2'}) + category1 = SwaggerClient::Category.new({:id => 1, :name => 'category unknown'}) + # initalize using both string and symbol key + pet_hash = {:'id' => 10002, :'name' => "RUBY UNIT TESTING", :'status' => "pending", + :'photo_urls' => ["url1", "url2"], :'category' => category1, + :'tags' => [tag1, tag2]} + pet = SwaggerClient::Pet.new(pet_hash) + # test new + pet.name.should == "RUBY UNIT TESTING" + pet.status.should == "pending" + pet.id.should == 10002 + pet.tags[0].id.should == 1 + pet.tags[1].name.should == 'tag2' + pet.category.name.should == 'category unknown' + + # test build_from_hash + pet2 = SwaggerClient::Pet.new + pet2.build_from_hash(pet.to_hash) + pet.to_hash.should == pet2.to_hash + + # make sure sub-object has different object id + pet.tags[0].object_id.should_not == pet2.tags[0].object_id + pet.tags[1].object_id.should_not == pet2.tags[1].object_id + pet.category.object_id.should_not == pet2.category.object_id + end + it "should fetch a pet object" do - pet = PetApi.get_pet_by_id(10002) - pet.should be_a(Pet) + pet = SwaggerClient::PetApi.get_pet_by_id(10002) + pet.should be_a(SwaggerClient::Pet) pet.id.should == 10002 pet.name.should == "RUBY UNIT TESTING" + pet.tags[0].name.should == "tag test" + pet.category.name.should == "category test" end it "should find pets by status" do - pets = PetApi.find_pets_by_status(:status => 'available') + pets = SwaggerClient::PetApi.find_pets_by_status(:status => 'available') pets.length.should >= 3 end - + it "should not find a pet with invalid status" do - pets = PetApi.find_pets_by_status(:status => 'invalid-status') + pets = SwaggerClient::PetApi.find_pets_by_status(:status => 'invalid-status') pets.length.should == 0 end it "should find a pet by status" do - pets = PetApi.find_pets_by_status(:status => "available,sold") - pets.map {|pet| - if(pet.status != 'available' && pet.status != 'sold') + pets = SwaggerClient::PetApi.find_pets_by_status(:status => "available,sold") + pets.map {|pet| + if(pet.status != 'available' && pet.status != 'sold') raise "pet status wasn't right" end } end - + it "should update a pet" do - pet = Pet.new({'id' => 10002, 'status' => 'sold'}) - PetApi.add_pet(:body => pet) - - fetched = PetApi.get_pet_by_id(10002) + pet = SwaggerClient::Pet.new({'id' => 10002, 'status' => 'sold'}) + SwaggerClient::PetApi.add_pet(:body => pet) + + fetched = SwaggerClient::PetApi.get_pet_by_id(10002) fetched.id.should == 10002 fetched.status.should == 'sold' end - it "should create a pet" do - pet = Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING") - PetApi.add_pet(:body => pet) + it "should create a pet" do + pet = SwaggerClient::Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING") + SwaggerClient::PetApi.add_pet(:body => pet) - pet = PetApi.get_pet_by_id(10002) + pet = SwaggerClient::PetApi.get_pet_by_id(10002) pet.id.should == 10002 pet.name.should == "RUBY UNIT TESTING" end diff --git a/samples/client/petstore/ruby/spec/request_spec.rb b/samples/client/petstore/ruby/spec/request_spec.rb index 61389eddc9c4..8856a0cf315d 100644 --- a/samples/client/petstore/ruby/spec/request_spec.rb +++ b/samples/client/petstore/ruby/spec/request_spec.rb @@ -1,9 +1,9 @@ require 'spec_helper' -describe Swagger::Request do +describe SwaggerClient::Swagger::Request do before(:each) do - Swagger.configure do |config| + SwaggerClient::Swagger.configure do |config| inject_format = true config.api_key = 'special-key' config.host = 'petstore.swagger.io' @@ -15,7 +15,7 @@ describe Swagger::Request do @default_params = { :params => {:foo => "1", :bar => "2"} } - @request = Swagger::Request.new(@default_http_method, @default_path, @default_params) + @request = SwaggerClient::Swagger::Request.new(@default_http_method, @default_path, @default_params) end describe "initialization" do @@ -24,7 +24,7 @@ describe Swagger::Request do end it "allows params to be nil" do - @request = Swagger::Request.new(@default_http_method, @default_path, :params => nil) + @request = SwaggerClient::Swagger::Request.new(@default_http_method, @default_path, :params => nil) @request.query_string.should == "" end @@ -59,7 +59,7 @@ describe Swagger::Request do describe "body" do it "camelCases parameters" do - @request = Swagger::Request.new(@default_http_method, @default_path, @default_params.merge({ + @request = SwaggerClient::Swagger::Request.new(@default_http_method, @default_path, @default_params.merge({ :body => { :bad_dog => 'bud', :goodDog => "dud" @@ -73,7 +73,7 @@ describe Swagger::Request do describe "path" do it "accounts for a total absence of format in the path string" do - @request = Swagger::Request.new(:get, "/word.{format}/cat/entries", @default_params.merge({ + @request = SwaggerClient::Swagger::Request.new(:get, "/word.{format}/cat/entries", @default_params.merge({ :format => "xml", :params => { } @@ -82,7 +82,7 @@ describe Swagger::Request do end it "does string substitution (format) on path params" do - @request = Swagger::Request.new(:get, "/word.{format}/cat/entries", @default_params.merge({ + @request = SwaggerClient::Swagger::Request.new(:get, "/word.{format}/cat/entries", @default_params.merge({ :format => "xml", :params => { } @@ -91,7 +91,7 @@ describe Swagger::Request do end it "leaves path-bound params out of the query string" do - @request = Swagger::Request.new(:get, "/word.{format}/{word}/entries", @default_params.merge({ + @request = SwaggerClient::Swagger::Request.new(:get, "/word.{format}/{word}/entries", @default_params.merge({ :params => { :word => "cat", :limit => 20 @@ -101,7 +101,7 @@ describe Swagger::Request do end it "returns a question-mark free (blank) query string if no query params are present" do - @request = Swagger::Request.new(:get, "/word.{format}/{word}/entries", @default_params.merge({ + @request = SwaggerClient::Swagger::Request.new(:get, "/word.{format}/{word}/entries", @default_params.merge({ :params => { :word => "cat", } @@ -110,7 +110,7 @@ describe Swagger::Request do end it "removes blank params" do - @request = Swagger::Request.new(:get, "words/fancy", @default_params.merge({ + @request = SwaggerClient::Swagger::Request.new(:get, "words/fancy", @default_params.merge({ :params => { :word => "dog", :limit => "", @@ -121,7 +121,7 @@ describe Swagger::Request do end it "URI encodes the path" do - @request = Swagger::Request.new(:get, "word.{format}/bill gates/definitions", @default_params.merge({ + @request = SwaggerClient::Swagger::Request.new(:get, "word.{format}/bill gates/definitions", @default_params.merge({ :params => { :word => "bill gates" } @@ -130,7 +130,7 @@ describe Swagger::Request do end it "converts numeric params to strings" do - @request = Swagger::Request.new(@default_http_method, @default_path, @default_params.merge({ + @request = SwaggerClient::Swagger::Request.new(@default_http_method, @default_path, @default_params.merge({ :params => { :limit => 100 } @@ -142,7 +142,7 @@ describe Swagger::Request do end it "camelCases parameters" do - @request = Swagger::Request.new(@default_http_method, @default_path, @default_params.merge({ + @request = SwaggerClient::Swagger::Request.new(@default_http_method, @default_path, @default_params.merge({ :params => { :bad_dog => 'bud', :goodDog => "dud" @@ -153,7 +153,7 @@ describe Swagger::Request do it "converts boolean values to their string representation" do params = {:stringy => "fish", :truthy => true, :falsey => false} - @request = Swagger::Request.new(:get, 'fakeMethod', :params => params) + @request = SwaggerClient::Swagger::Request.new(:get, 'fakeMethod', :params => params) @request.query_string.should == "?falsey=false&stringy=fish&truthy=true" end @@ -162,12 +162,12 @@ describe Swagger::Request do describe "API key" do it "is inferred from the Swagger base configuration by default" do - Swagger.configure {|c| c.api_key = "xyz" } - Swagger::Request.new(:get, "word/json").headers[:api_key].should == "xyz" + SwaggerClient::Swagger.configure {|c| c.api_key = "xyz" } + SwaggerClient::Swagger::Request.new(:get, "word/json").headers[:api_key].should == "xyz" end it "can be obfuscated for public display" do - @request = Swagger::Request.new(:get, "words/fancy", @default_params.merge({ + @request = SwaggerClient::Swagger::Request.new(:get, "words/fancy", @default_params.merge({ :params => { :word => "dog", :api_key => "123456" @@ -179,21 +179,21 @@ describe Swagger::Request do end it "allows a key in the params to override the configuration-level key, even if it's blank" do - Swagger.configure {|c| c.api_key = "abc" } - @request_with_key = Swagger::Request.new(:get, "word/json", :params => {:api_key => "jkl"}) + SwaggerClient::Swagger.configure {|c| c.api_key = "abc" } + @request_with_key = SwaggerClient::Swagger::Request.new(:get, "word/json", :params => {:api_key => "jkl"}) @request_with_key.headers[:api_key].should be_nil @request_with_key.params[:api_key].should == "jkl" - @request_without_key = Swagger::Request.new(:get, "word/json", :params => {:api_key => nil}) + @request_without_key = SwaggerClient::Swagger::Request.new(:get, "word/json", :params => {:api_key => nil}) @request_without_key.headers[:api_key].should be_nil @request_without_key.params[:api_key].should be_nil end it "allows a key in the headers to override the configuration-level key, even if it's blank" do - Swagger.configure {|c| c.api_key = "hij" } - Swagger::Request.new(:get, "word/json").headers[:api_key].should == "hij" - Swagger::Request.new(:get, "word/json", :headers => {:api_key => "jkl"}).headers[:api_key].should == "jkl" - Swagger::Request.new(:get, "word/json", :headers => {:api_key => nil}).headers[:api_key].should be_nil + SwaggerClient::Swagger.configure {|c| c.api_key = "hij" } + SwaggerClient::Swagger::Request.new(:get, "word/json").headers[:api_key].should == "hij" + SwaggerClient::Swagger::Request.new(:get, "word/json", :headers => {:api_key => "jkl"}).headers[:api_key].should == "jkl" + SwaggerClient::Swagger::Request.new(:get, "word/json", :headers => {:api_key => nil}).headers[:api_key].should be_nil end end diff --git a/samples/client/petstore/ruby/spec/response_spec.rb b/samples/client/petstore/ruby/spec/response_spec.rb index c0542005cb09..528b67e1fa71 100644 --- a/samples/client/petstore/ruby/spec/response_spec.rb +++ b/samples/client/petstore/ruby/spec/response_spec.rb @@ -1,6 +1,6 @@ require 'spec_helper' -describe Swagger::Response do +describe SwaggerClient::Swagger::Response do before do configure_swagger @@ -13,13 +13,13 @@ describe Swagger::Response do @raw = Typhoeus::Request.get("http://petstore.swagger.io/v2/pet/10002") end - @response = Swagger::Response.new(@raw) + @response = SwaggerClient::Swagger::Response.new(@raw) end describe "initialization" do it "sets body" do @response.body.class.should == Hash - @response.body.has_key?('name').should == true + @response.body.has_key?(:'name').should == true end it "sets code" do @@ -43,7 +43,7 @@ describe Swagger::Response do @raw = Typhoeus::Request.get("http://petstore.swagger.io/v2/pet/10002", :headers => {'Accept'=> "application/xml"}) end - @response = Swagger::Response.new(@raw) + @response = SwaggerClient::Swagger::Response.new(@raw) @response.format.should == 'xml' @response.xml?.should == true end diff --git a/samples/client/petstore/ruby/spec/spec_helper.rb b/samples/client/petstore/ruby/spec/spec_helper.rb index 71725a45a6c9..09012db29983 100644 --- a/samples/client/petstore/ruby/spec/spec_helper.rb +++ b/samples/client/petstore/ruby/spec/spec_helper.rb @@ -1,6 +1,6 @@ require 'rubygems' require 'bundler/setup' -require 'swagger-client' +require 'swagger_client' require 'vcr' require 'typhoeus' require 'json' @@ -37,7 +37,7 @@ end #end def configure_swagger - Swagger.configure do |config| + SwaggerClient::Swagger.configure do |config| config.api_key = 'special-key' config.host = 'petstore.swagger.io' config.base_path = '/v2' @@ -47,25 +47,29 @@ end # always delete and then re-create the pet object with 10002 def prepare_pet # remove the pet - PetApi.delete_pet(10002) + SwaggerClient::PetApi.delete_pet(10002) # recreate the pet - pet = Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING") - PetApi.add_pet(:body => pet) + category = SwaggerClient::Category.new('id' => 20002, 'name' => 'category test') + tag = SwaggerClient::Tag.new('id' => 30002, 'name' => 'tag test') + pet = SwaggerClient::Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING", 'photo_urls' => 'photo url', + 'category' => category, 'tags' => [tag], 'status' => 'pending') + + SwaggerClient::PetApi.add_pet(:'body'=> pet) end -# always delete and then re-create the store order +# always delete and then re-create the store order def prepare_store - order = Order.new("id" => 10002, + order = SwaggerClient::Order.new("id" => 10002, "petId" => 10002, "quantity" => 789, "shipDate" => "2015-04-06T23:42:01.678Z", "status" => "placed", "complete" => false) - StoreApi.place_order(:body => order) + SwaggerClient::StoreApi.place_order(:body => order) end configure_swagger -# A random string to tack onto stuff to ensure we're not seeing +# A random string to tack onto stuff to ensure we're not seeing # data from a previous test run RAND = ("a".."z").to_a.sample(8).join diff --git a/samples/client/petstore/ruby/spec/store_spec.rb b/samples/client/petstore/ruby/spec/store_spec.rb index a1e2bd3193fd..1b37400bc5c3 100644 --- a/samples/client/petstore/ruby/spec/store_spec.rb +++ b/samples/client/petstore/ruby/spec/store_spec.rb @@ -7,7 +7,7 @@ describe "Store" do end it "should fetch an order" do - item = StoreApi.get_order_by_id(10002) + item = SwaggerClient::StoreApi.get_order_by_id(10002) item.id.should == 10002 end end diff --git a/samples/client/petstore/ruby/spec/swagger_spec.rb b/samples/client/petstore/ruby/spec/swagger_spec.rb index 4aedc85382cc..38b4a850ae9b 100644 --- a/samples/client/petstore/ruby/spec/swagger_spec.rb +++ b/samples/client/petstore/ruby/spec/swagger_spec.rb @@ -1,7 +1,7 @@ # require 'spec_helper' require File.dirname(__FILE__) + '/spec_helper' -describe Swagger do +describe SwaggerClient::Swagger do before(:each) do configure_swagger @@ -16,35 +16,35 @@ describe Swagger do context 'host' do it 'removes http from host' do - Swagger.configure {|c| c.host = 'http://example.com' } - Swagger.configuration.host.should == 'example.com' + SwaggerClient::Swagger.configure {|c| c.host = 'http://example.com' } + SwaggerClient::Swagger.configuration.host.should == 'example.com' end it 'removes https from host' do - Swagger.configure {|c| c.host = 'https://wookiee.com' } - Swagger.configuration.host.should == 'wookiee.com' + SwaggerClient::Swagger.configure {|c| c.host = 'https://wookiee.com' } + SwaggerClient::Swagger.configuration.host.should == 'wookiee.com' end it 'removes trailing path from host' do - Swagger.configure {|c| c.host = 'hobo.com/v4' } - Swagger.configuration.host.should == 'hobo.com' + SwaggerClient::Swagger.configure {|c| c.host = 'hobo.com/v4' } + SwaggerClient::Swagger.configuration.host.should == 'hobo.com' end end context 'base_path' do it "prepends a slash to base_path" do - Swagger.configure {|c| c.base_path = 'v4/dog' } - Swagger.configuration.base_path.should == '/v4/dog' + SwaggerClient::Swagger.configure {|c| c.base_path = 'v4/dog' } + SwaggerClient::Swagger.configuration.base_path.should == '/v4/dog' end it "doesn't prepend a slash if one is already there" do - Swagger.configure {|c| c.base_path = '/v4/dog' } - Swagger.configuration.base_path.should == '/v4/dog' + SwaggerClient::Swagger.configure {|c| c.base_path = '/v4/dog' } + SwaggerClient::Swagger.configuration.base_path.should == '/v4/dog' end it "ends up as a blank string if nil" do - Swagger.configure {|c| c.base_path = nil } - Swagger.configuration.base_path.should == '' + SwaggerClient::Swagger.configure {|c| c.base_path = nil } + SwaggerClient::Swagger.configuration.base_path.should == '' end end @@ -53,4 +53,4 @@ describe Swagger do end -end \ No newline at end of file +end diff --git a/samples/client/petstore/ruby/swagger-client.gemspec b/samples/client/petstore/ruby/swagger-client.gemspec deleted file mode 100644 index bbff5f95f6bc..000000000000 --- a/samples/client/petstore/ruby/swagger-client.gemspec +++ /dev/null @@ -1,33 +0,0 @@ -# -*- encoding: utf-8 -*- -$:.push File.expand_path("../lib", __FILE__) -require "swagger/version" - -Gem::Specification.new do |s| - s.name = "swagger-client" - s.version = Swagger::VERSION - s.platform = Gem::Platform::RUBY - s.authors = ["Zeke Sikelianos", "Tony Tam"] - s.email = ["zeke@wordnik.com", "tony@wordnik.com"] - s.homepage = "http://developer.wordnik.com" - s.summary = %q{A ruby wrapper for the swagger APIs} - s.description = %q{This gem maps to a swagger API} - - s.rubyforge_project = "swagger-client" - - s.add_dependency 'typhoeus', '>=0.2.1' - s.add_dependency 'addressable', '>=2.2.4' - s.add_dependency 'json', '>=1.4.6' - - s.add_development_dependency 'rspec', '>=2.5.0' - s.add_development_dependency 'vcr', '>=1.5.1' - s.add_development_dependency 'webmock', '>=1.6.2' - s.add_development_dependency 'autotest' - s.add_development_dependency 'autotest-rails-pure' - s.add_development_dependency 'autotest-growl' - s.add_development_dependency 'autotest-fsevent' - - s.files = `find *`.split("\n").uniq.sort.select{|f| !f.empty? } - s.test_files = `find spec/*`.split("\n") - s.executables = [] - s.require_paths = ["lib"] -end diff --git a/samples/client/petstore/ruby/swagger_client.gemspec b/samples/client/petstore/ruby/swagger_client.gemspec new file mode 100644 index 000000000000..6ec2484e05c8 --- /dev/null +++ b/samples/client/petstore/ruby/swagger_client.gemspec @@ -0,0 +1,32 @@ +# -*- encoding: utf-8 -*- +$:.push File.expand_path("../lib", __FILE__) +require "swagger_client/swagger/version" + +Gem::Specification.new do |s| + s.name = "swagger_client" + s.version = SwaggerClient::Swagger::VERSION + s.platform = Gem::Platform::RUBY + s.authors = ["Zeke Sikelianos", "Tony Tam"] + s.email = ["zeke@wordnik.com", "tony@wordnik.com"] + s.homepage = "http://developer.wordnik.com" + s.summary = %q{A ruby wrapper for the swagger APIs} + s.description = %q{This gem maps to a swagger API} + s.license = "Apache-2.0" + + s.add_runtime_dependency 'typhoeus', '~> 0.2', '>= 0.2.1' + s.add_runtime_dependency 'addressable', '~> 2.2', '>= 2.2.4' + s.add_runtime_dependency 'json', '~> 1.4', '>= 1.4.6' + + s.add_development_dependency 'rspec', '~> 3.2', '>= 3.2.0' + s.add_development_dependency 'vcr', '~> 2.9', '>= 2.9.3' + s.add_development_dependency 'webmock', '~> 1.6', '>= 1.6.2' + s.add_development_dependency 'autotest', '~> 4.4', '>= 4.4.6' + s.add_development_dependency 'autotest-rails-pure', '~> 4.1', '>= 4.1.2' + s.add_development_dependency 'autotest-growl', '~> 0.2', '>= 0.2.16' + s.add_development_dependency 'autotest-fsevent', '~> 0.2', '>= 0.2.10' + + s.files = `find *`.split("\n").uniq.sort.select{|f| !f.empty? } + s.test_files = `find spec/*`.split("\n") + s.executables = [] + s.require_paths = ["lib"] +end diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/ApiInvoker.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/ApiInvoker.scala index f4b25de83069..91ab98471e9e 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/ApiInvoker.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/ApiInvoker.scala @@ -6,6 +6,7 @@ import com.sun.jersey.api.client.config.ClientConfig import com.sun.jersey.api.client.config.DefaultClientConfig import com.sun.jersey.api.client.filter.LoggingFilter +import com.sun.jersey.core.util.MultivaluedMapImpl import com.sun.jersey.multipart.FormDataMultiPart import com.sun.jersey.multipart.file.FileDataBodyPart @@ -94,7 +95,7 @@ class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper, } else null } - def invokeApi(host: String, path: String, method: String, queryParams: Map[String, String], body: AnyRef, headerParams: Map[String, String], contentType: String): String = { + def invokeApi(host: String, path: String, method: String, queryParams: Map[String, String], formParams: Map[String, String], body: AnyRef, headerParams: Map[String, String], contentType: String): String = { val client = getClient(host) val querystring = queryParams.filter(k => k._2 != null).map(k => (escape(k._1) + "=" + escape(k._2))).mkString("?", "&", "") @@ -106,13 +107,19 @@ class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper, case false => if (p._2 != null) builder.header(p._1, p._2) } }) + var formData: MultivaluedMapImpl = null + if(contentType == "application/x-www-form-urlencoded") { + formData = new MultivaluedMapImpl() + formParams.map(p => formData.add(p._1, p._2)) + } val response: ClientResponse = method match { case "GET" => { builder.get(classOf[ClientResponse]).asInstanceOf[ClientResponse] } case "POST" => { - if(body != null && body.isInstanceOf[File]) { + if(formData != null) builder.post(classOf[ClientResponse], formData) + else if(body != null && body.isInstanceOf[File]) { val file = body.asInstanceOf[File] val form = new FormDataMultiPart() form.field("filename", file.getName()) @@ -125,7 +132,8 @@ class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper, } } case "PUT" => { - if(body == null) builder.put(classOf[ClientResponse], null) + if(formData != null) builder.post(classOf[ClientResponse], formData) + else if(body == null) builder.put(classOf[ClientResponse], null) else builder.`type`(contentType).put(classOf[ClientResponse], serialize(body)) } case "DELETE" => { diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala index 242f64e5aecb..c17f0a129115 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala @@ -5,6 +5,11 @@ import java.io.File import io.swagger.client.ApiInvoker import io.swagger.client.ApiException +import com.sun.jersey.multipart.FormDataMultiPart +import com.sun.jersey.multipart.file.FileDataBodyPart + +import javax.ws.rs.core.MediaType + import java.io.File import java.util.Date @@ -28,18 +33,13 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", // create path and map variables val path = "/pet".replaceAll("\\{format\\}","json") - - val contentType = { - if(body != null && body.isInstanceOf[File] ) - "multipart/form-data" - else "application/json" - - - } + val contentTypes = List("application/json", "application/xml", "application/json") + val contentType = contentTypes(0) // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] + val formParams = new HashMap[String, String] @@ -47,8 +47,19 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", + var postBody: AnyRef = body + + if(contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart() + + postBody = mp + } + else { + + } + try { - apiInvoker.invokeApi(basePath, path, "PUT", queryParams.toMap, body, headerParams.toMap, contentType) match { + apiInvoker.invokeApi(basePath, path, "PUT", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => case _ => None @@ -69,18 +80,13 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", // create path and map variables val path = "/pet".replaceAll("\\{format\\}","json") - - val contentType = { - if(body != null && body.isInstanceOf[File] ) - "multipart/form-data" - else "application/json" - - - } + val contentTypes = List("application/json", "application/xml", "application/json") + val contentType = contentTypes(0) // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] + val formParams = new HashMap[String, String] @@ -88,8 +94,19 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", + var postBody: AnyRef = body + + if(contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart() + + postBody = mp + } + else { + + } + try { - apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap, contentType) match { + apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => case _ => None @@ -110,15 +127,13 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", // create path and map variables val path = "/pet/findByStatus".replaceAll("\\{format\\}","json") - - val contentType = { - - "application/json" - } + val contentTypes = List("application/json") + val contentType = contentTypes(0) // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] + val formParams = new HashMap[String, String] @@ -127,8 +142,19 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", + var postBody: AnyRef = null + + if(contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart() + + postBody = mp + } + else { + + } + try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => Some(ApiInvoker.deserialize(s, "array", classOf[Pet]).asInstanceOf[List[Pet]]) @@ -150,15 +176,13 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", // create path and map variables val path = "/pet/findByTags".replaceAll("\\{format\\}","json") - - val contentType = { - - "application/json" - } + val contentTypes = List("application/json") + val contentType = contentTypes(0) // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] + val formParams = new HashMap[String, String] @@ -167,8 +191,19 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", + var postBody: AnyRef = null + + if(contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart() + + postBody = mp + } + else { + + } + try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => Some(ApiInvoker.deserialize(s, "array", classOf[Pet]).asInstanceOf[List[Pet]]) @@ -192,15 +227,13 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", - - val contentType = { - - "application/json" - } + val contentTypes = List("application/json") + val contentType = contentTypes(0) // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] + val formParams = new HashMap[String, String] @@ -208,8 +241,19 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", + var postBody: AnyRef = null + + if(contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart() + + postBody = mp + } + else { + + } + try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => Some(ApiInvoker.deserialize(s, "", classOf[Pet]).asInstanceOf[Pet]) @@ -235,15 +279,13 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", - - val contentType = { - - "application/json" - } + val contentTypes = List("application/x-www-form-urlencoded", "application/json") + val contentType = contentTypes(0) // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] + val formParams = new HashMap[String, String] @@ -251,8 +293,25 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", + var postBody: AnyRef = null + + if(contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart() + + mp.field("name", name.toString(), MediaType.MULTIPART_FORM_DATA_TYPE) + + mp.field("status", status.toString(), MediaType.MULTIPART_FORM_DATA_TYPE) + + postBody = mp + } + else { + formParams += "name" -> name.toString() + formParams += "status" -> status.toString() + + } + try { - apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, None, headerParams.toMap, contentType) match { + apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => case _ => None @@ -276,15 +335,13 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", - - val contentType = { - - "application/json" - } + val contentTypes = List("application/json") + val contentType = contentTypes(0) // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] + val formParams = new HashMap[String, String] @@ -293,8 +350,19 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", headerParams += "api_key" -> api_key + var postBody: AnyRef = null + + if(contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart() + + postBody = mp + } + else { + + } + try { - apiInvoker.invokeApi(basePath, path, "DELETE", queryParams.toMap, None, headerParams.toMap, contentType) match { + apiInvoker.invokeApi(basePath, path, "DELETE", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => case _ => None @@ -319,15 +387,13 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", - - val contentType = { - - "application/json" - } + val contentTypes = List("multipart/form-data", "application/json") + val contentType = contentTypes(0) // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] + val formParams = new HashMap[String, String] @@ -335,8 +401,26 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", + var postBody: AnyRef = null + + if(contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart() + + mp.field("additionalMetadata", additionalMetadata.toString(), MediaType.MULTIPART_FORM_DATA_TYPE) + + mp.field("file", file.getName) + mp.bodyPart(new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE)) + + postBody = mp + } + else { + formParams += "additionalMetadata" -> additionalMetadata.toString() + + + } + try { - apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, None, headerParams.toMap, contentType) match { + apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => case _ => None diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/StoreApi.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/StoreApi.scala index 9c7e1cfe5838..9b3cc91d7883 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/StoreApi.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/StoreApi.scala @@ -4,6 +4,11 @@ import io.swagger.client.model.Order import io.swagger.client.ApiInvoker import io.swagger.client.ApiException +import com.sun.jersey.multipart.FormDataMultiPart +import com.sun.jersey.multipart.file.FileDataBodyPart + +import javax.ws.rs.core.MediaType + import java.io.File import java.util.Date @@ -26,15 +31,13 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", // create path and map variables val path = "/store/inventory".replaceAll("\\{format\\}","json") - - val contentType = { - - "application/json" - } + val contentTypes = List("application/json") + val contentType = contentTypes(0) // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] + val formParams = new HashMap[String, String] @@ -42,8 +45,19 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", + var postBody: AnyRef = null + + if(contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart() + + postBody = mp + } + else { + + } + try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => Some(ApiInvoker.deserialize(s, "map", classOf[Integer]).asInstanceOf[Map[String, Integer]]) @@ -65,18 +79,13 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", // create path and map variables val path = "/store/order".replaceAll("\\{format\\}","json") - - val contentType = { - if(body != null && body.isInstanceOf[File] ) - "multipart/form-data" - else "application/json" - - - } + val contentTypes = List("application/json") + val contentType = contentTypes(0) // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] + val formParams = new HashMap[String, String] @@ -84,8 +93,19 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", + var postBody: AnyRef = body + + if(contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart() + + postBody = mp + } + else { + + } + try { - apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap, contentType) match { + apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => Some(ApiInvoker.deserialize(s, "", classOf[Order]).asInstanceOf[Order]) @@ -109,15 +129,13 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", - - val contentType = { - - "application/json" - } + val contentTypes = List("application/json") + val contentType = contentTypes(0) // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] + val formParams = new HashMap[String, String] @@ -125,8 +143,19 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", + var postBody: AnyRef = null + + if(contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart() + + postBody = mp + } + else { + + } + try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => Some(ApiInvoker.deserialize(s, "", classOf[Order]).asInstanceOf[Order]) @@ -150,15 +179,13 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", - - val contentType = { - - "application/json" - } + val contentTypes = List("application/json") + val contentType = contentTypes(0) // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] + val formParams = new HashMap[String, String] @@ -166,8 +193,19 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", + var postBody: AnyRef = null + + if(contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart() + + postBody = mp + } + else { + + } + try { - apiInvoker.invokeApi(basePath, path, "DELETE", queryParams.toMap, None, headerParams.toMap, contentType) match { + apiInvoker.invokeApi(basePath, path, "DELETE", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => case _ => None diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/UserApi.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/UserApi.scala index 62d96f90cfbf..5a7b38f620aa 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/UserApi.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/UserApi.scala @@ -4,6 +4,11 @@ import io.swagger.client.model.User import io.swagger.client.ApiInvoker import io.swagger.client.ApiException +import com.sun.jersey.multipart.FormDataMultiPart +import com.sun.jersey.multipart.file.FileDataBodyPart + +import javax.ws.rs.core.MediaType + import java.io.File import java.util.Date @@ -27,18 +32,13 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", // create path and map variables val path = "/user".replaceAll("\\{format\\}","json") - - val contentType = { - if(body != null && body.isInstanceOf[File] ) - "multipart/form-data" - else "application/json" - - - } + val contentTypes = List("application/json") + val contentType = contentTypes(0) // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] + val formParams = new HashMap[String, String] @@ -46,8 +46,19 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", + var postBody: AnyRef = body + + if(contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart() + + postBody = mp + } + else { + + } + try { - apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap, contentType) match { + apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => case _ => None @@ -68,18 +79,13 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", // create path and map variables val path = "/user/createWithArray".replaceAll("\\{format\\}","json") - - val contentType = { - if(body != null && body.isInstanceOf[File] ) - "multipart/form-data" - else "application/json" - - - } + val contentTypes = List("application/json") + val contentType = contentTypes(0) // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] + val formParams = new HashMap[String, String] @@ -87,8 +93,19 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", + var postBody: AnyRef = body + + if(contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart() + + postBody = mp + } + else { + + } + try { - apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap, contentType) match { + apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => case _ => None @@ -109,18 +126,13 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", // create path and map variables val path = "/user/createWithList".replaceAll("\\{format\\}","json") - - val contentType = { - if(body != null && body.isInstanceOf[File] ) - "multipart/form-data" - else "application/json" - - - } + val contentTypes = List("application/json") + val contentType = contentTypes(0) // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] + val formParams = new HashMap[String, String] @@ -128,8 +140,19 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", + var postBody: AnyRef = body + + if(contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart() + + postBody = mp + } + else { + + } + try { - apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap, contentType) match { + apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => case _ => None @@ -151,15 +174,13 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", // create path and map variables val path = "/user/login".replaceAll("\\{format\\}","json") - - val contentType = { - - "application/json" - } + val contentTypes = List("application/json") + val contentType = contentTypes(0) // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] + val formParams = new HashMap[String, String] @@ -169,8 +190,19 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", + var postBody: AnyRef = null + + if(contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart() + + postBody = mp + } + else { + + } + try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => Some(ApiInvoker.deserialize(s, "", classOf[String]).asInstanceOf[String]) @@ -191,15 +223,13 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", // create path and map variables val path = "/user/logout".replaceAll("\\{format\\}","json") - - val contentType = { - - "application/json" - } + val contentTypes = List("application/json") + val contentType = contentTypes(0) // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] + val formParams = new HashMap[String, String] @@ -207,8 +237,19 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", + var postBody: AnyRef = null + + if(contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart() + + postBody = mp + } + else { + + } + try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => case _ => None @@ -231,15 +272,13 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", - - val contentType = { - - "application/json" - } + val contentTypes = List("application/json") + val contentType = contentTypes(0) // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] + val formParams = new HashMap[String, String] @@ -247,8 +286,19 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", + var postBody: AnyRef = null + + if(contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart() + + postBody = mp + } + else { + + } + try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => Some(ApiInvoker.deserialize(s, "", classOf[User]).asInstanceOf[User]) @@ -273,18 +323,13 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", - - val contentType = { - if(body != null && body.isInstanceOf[File] ) - "multipart/form-data" - else "application/json" - - - } + val contentTypes = List("application/json") + val contentType = contentTypes(0) // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] + val formParams = new HashMap[String, String] @@ -292,8 +337,19 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", + var postBody: AnyRef = body + + if(contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart() + + postBody = mp + } + else { + + } + try { - apiInvoker.invokeApi(basePath, path, "PUT", queryParams.toMap, body, headerParams.toMap, contentType) match { + apiInvoker.invokeApi(basePath, path, "PUT", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => case _ => None @@ -316,15 +372,13 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", - - val contentType = { - - "application/json" - } + val contentTypes = List("application/json") + val contentType = contentTypes(0) // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] + val formParams = new HashMap[String, String] @@ -332,8 +386,19 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", + var postBody: AnyRef = null + + if(contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart() + + postBody = mp + } + else { + + } + try { - apiInvoker.invokeApi(basePath, path, "DELETE", queryParams.toMap, None, headerParams.toMap, contentType) match { + apiInvoker.invokeApi(basePath, path, "DELETE", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => case _ => None diff --git a/samples/client/petstore/scala/src/test/scala/PetApiTest.scala b/samples/client/petstore/scala/src/test/scala/PetApiTest.scala index 24ce4826fcb4..f14a89c1f632 100644 --- a/samples/client/petstore/scala/src/test/scala/PetApiTest.scala +++ b/samples/client/petstore/scala/src/test/scala/PetApiTest.scala @@ -15,17 +15,7 @@ class PetApiTest extends FlatSpec with Matchers { behavior of "PetApi" val api = new PetApi - it should "fetch a pet" in { - api.getPetById(1) match { - case Some(pet) => { - pet should not be (null) - pet.id should be(1) - } - case None => fail("didn't find pet 1") - } - } - - it should "add a new pet" in { + it should "add and fetch a pet" in { val pet = Pet( 1000, Category(1, "sold"), diff --git a/samples/client/petstore/scala/src/test/scala/StoreApiTest.scala b/samples/client/petstore/scala/src/test/scala/StoreApiTest.scala index 053dffd055d2..68c5daf8f427 100644 --- a/samples/client/petstore/scala/src/test/scala/StoreApiTest.scala +++ b/samples/client/petstore/scala/src/test/scala/StoreApiTest.scala @@ -17,19 +17,7 @@ class StoreApiTest extends FlatSpec with Matchers { api.apiInvoker.defaultHeaders += "api_key" -> "special-key" - it should "fetch an order" in { - api.getOrderById("1") match { - case Some(order) => { - order.id should be(1) - order.petId should be(1) - order.quantity should be(2) - order.shipDate should not be (null) - } - case None => fail("didn't find order") - } - } - - it should "place an order" in { + it should "place and fetch an order" in { val now = new org.joda.time.DateTime val order = Order ( petId = 10, @@ -46,9 +34,10 @@ class StoreApiTest extends FlatSpec with Matchers { order.id should be(1000) order.petId should be(10) order.quantity should be(101) - order.shipDate.equals(now) should be (true) + // use `getMillis` to compare across timezones + order.shipDate.getMillis.equals(now.getMillis) should be (true) } - case None => + case None => fail("didn't find order created") } } @@ -65,13 +54,14 @@ class StoreApiTest extends FlatSpec with Matchers { api.placeOrder(order) api.getOrderById("1001") match { - case Some(order) => { - order.id should be(1001) - order.petId should be(10) - order.quantity should be(101) - order.shipDate.equals(now) should be (true) - } + case Some(order) => order.id should be(1001) + case None => fail("didn't find order created") + } + + api.deleteOrder("1001") + api.getOrderById("1001") match { + case Some(order) => fail("order should have been deleted") case None => } } -} \ No newline at end of file +} diff --git a/samples/dynamic-html/docs/assets/css/style.css b/samples/dynamic-html/docs/assets/css/style.css index b26d2ef13ca8..f14f6bdb62c5 100644 --- a/samples/dynamic-html/docs/assets/css/style.css +++ b/samples/dynamic-html/docs/assets/css/style.css @@ -151,15 +151,31 @@ padding-top: 20px; } -.param { +li.parameter { + list-style: none; display: block; - float: left; - width: 220px; - clear: left; + padding-left: 1em; +} + +.param{ + display: block; +} + +.param-name { + margin-left: 1em; +} + +.param-in { + font-weight: bold; + font-size: 1.1em; +} +.param-type { + margin-left: 1em; + font-style: italic; } .param-description { - float: left; + display: block; font-family: 'Helvetica Neue', Arial, 'Liberation Sans', FreeSans, sans-serif; } @@ -289,4 +305,4 @@ .top-bar ul#nav:hover li { border-color: #222222; -} \ No newline at end of file +} diff --git a/samples/dynamic-html/docs/assets/js/main.js b/samples/dynamic-html/docs/assets/js/main.js index 660d628567cd..ee0d2f92470a 100644 --- a/samples/dynamic-html/docs/assets/js/main.js +++ b/samples/dynamic-html/docs/assets/js/main.js @@ -1,13 +1,8 @@ -function main() {} - window.onhashchange = function() { choose(window.location.href.toString()); } -var url = 'http://motyar.blogspot.com/search?q={term}', selectionImage; - -function showModel(e, model) { -} +var selectionImage; function choose(url) { var f = url.split("/").slice(-1)[0].split("?")[0]; @@ -20,8 +15,8 @@ function choose(url) { // rebind the models $(".model a").on("click", function(e){ e.preventDefault(); - var model = $(this).parent().attr("id") - var parentOffset = $(this).parent().offset(); + var model = $(this).parent().attr("data-model") + var parentOffset = $(this).parent().offset(); var encodedWord = encodeURI(model); if(!selectionImage) { @@ -33,7 +28,7 @@ function choose(url) { $('div.model-container').append(selectionImage); } - selectionImage.load("/models/" + encodedWord + ".html") + selectionImage.load("models/" + encodedWord + ".html") selectionImage.attr('href',url.replace('{term}',encodeURI(model))).css({ left: e.pageX + 20, top: e.pageY - 10, diff --git a/samples/dynamic-html/docs/operations/PetApi.html b/samples/dynamic-html/docs/operations/PetApi.html index 11ca041d8d8b..0fd5a9ae3c6c 100644 --- a/samples/dynamic-html/docs/operations/PetApi.html +++ b/samples/dynamic-html/docs/operations/PetApi.html @@ -13,17 +13,21 @@

HTTP Method

PUT

Response Type

-
+

Parameters

    -
    +
  • - -

    Pet object that needs to be added to the store

    -
  • + + Body: + body + Pet + +

    Pet object that needs to be added to the store

    +
@@ -36,17 +40,21 @@

HTTP Method

POST

Response Type

-
+

Parameters

    -
    +
  • - -

    Pet object that needs to be added to the store

    -
  • + + Body: + body + Pet + +

    Pet object that needs to be added to the store

    +
@@ -59,17 +67,21 @@

HTTP Method

GET

Response Type

- +

Parameters

    -
    +
  • + + Query: - -

    Status values that need to be considered for filter

    -
  • + status + List(String) + +

    Status values that need to be considered for filter

    +
@@ -82,17 +94,21 @@

HTTP Method

GET

Response Type

- +

Parameters

    -
    +
  • + + Query: - -

    Tags to filter by

    -
  • + tags + List(String) + +

    Tags to filter by

    +
@@ -105,17 +121,21 @@

HTTP Method

GET

Response Type

- +

Parameters

    -
    +
  • - + Path: -

    ID of pet that needs to be fetched

    -
  • + + petId + Long + +

    ID of pet that needs to be fetched

    +
@@ -128,33 +148,45 @@

HTTP Method

POST

Response Type

-
+

Parameters

    -
    +
  • - + Path: -

    ID of pet that needs to be updated

    -
  • + + petId + String + +

    ID of pet that needs to be updated

    + -
    +
  • + Form: - -

    Updated name of the pet

    -
  • + + name + String + +

    Updated name of the pet

    + -
    +
  • + Form: - -

    Updated status of the pet

    -
  • + + status + String + +

    Updated status of the pet

    +
@@ -167,25 +199,33 @@

HTTP Method

DELETE

Response Type

-
+

Parameters

    -
    +
  • - -

    -
  • + Header: + + api_key + String + +

    + -
    +
  • - + Path: -

    Pet id to delete

    -
  • + + petId + Long + +

    Pet id to delete

    +
@@ -198,35 +238,47 @@

HTTP Method

POST

Response Type

-
+

Parameters

    -
    +
  • - + Path: -

    ID of pet to update

    -
  • + + petId + Long + +

    ID of pet to update

    + -
    +
  • + Form: - -

    Additional data to pass to server

    -
  • + + additionalMetadata + String + +

    Additional data to pass to server

    + -
    +
  • + Form: - -

    file to upload

    -
  • + + file + file + +

    file to upload

    +
- \ No newline at end of file + diff --git a/samples/dynamic-html/docs/operations/StoreApi.html b/samples/dynamic-html/docs/operations/StoreApi.html index 798372217f04..65990b214238 100644 --- a/samples/dynamic-html/docs/operations/StoreApi.html +++ b/samples/dynamic-html/docs/operations/StoreApi.html @@ -13,7 +13,7 @@

HTTP Method

GET

Response Type

- +

Parameters

    @@ -28,17 +28,21 @@

    HTTP Method

    POST

    Response Type

    - +

    Parameters

      -
      +
    • - -

      order placed for purchasing the pet

      -
    • + + Body: + body + Order + +

      order placed for purchasing the pet

      +
    @@ -51,17 +55,21 @@

    HTTP Method

    GET

    Response Type

    - +

    Parameters

      -
      +
    • - + Path: -

      ID of pet that needs to be fetched

      -
    • + + orderId + String + +

      ID of pet that needs to be fetched

      +
    @@ -74,19 +82,23 @@

    HTTP Method

    DELETE

    Response Type

    -
    +

    Parameters

      -
      +
    • - + Path: -

      ID of the order that needs to be deleted

      -
    • + + orderId + String + +

      ID of the order that needs to be deleted

      +
    - \ No newline at end of file + diff --git a/samples/dynamic-html/docs/operations/UserApi.html b/samples/dynamic-html/docs/operations/UserApi.html index cc573089bceb..f3af4dcaa769 100644 --- a/samples/dynamic-html/docs/operations/UserApi.html +++ b/samples/dynamic-html/docs/operations/UserApi.html @@ -13,17 +13,21 @@

    HTTP Method

    POST

    Response Type

    -
    +

    Parameters

      -
      +
    • - -

      Created user object

      -
    • + + Body: + body + User + +

      Created user object

      +
    @@ -36,20 +40,21 @@

    HTTP Method

    POST

    Response Type

    -
    +

    Parameters

      -
      - - - +
    • - -

      List of user object

      -
    • + + Body: + body + List + +

      List of user object

      +
    @@ -62,20 +67,21 @@

    HTTP Method

    POST

    Response Type

    -
    +

    Parameters

      -
      - - - +
    • - -

      List of user object

      -
    • + + Body: + body + List + +

      List of user object

      +
    @@ -88,25 +94,33 @@

    HTTP Method

    GET

    Response Type

    - +

    Parameters

      -
      +
    • + + Query: - -

      The user name for login

      -
    • + username + String + +

      The user name for login

      + -
      +
    • + + Query: - -

      The password for login in clear text

      -
    • + password + String + +

      The password for login in clear text

      +
    @@ -119,7 +133,7 @@

    HTTP Method

    GET

    Response Type

    -
    +

    Parameters

      @@ -134,17 +148,21 @@

      HTTP Method

      GET

      Response Type

      - +

      Parameters

        -
        +
      • - + Path: -

        The name that needs to be fetched. Use user1 for testing.

        -
      • + + username + String + +

        The name that needs to be fetched. Use user1 for testing.

        +
      @@ -157,25 +175,33 @@

      HTTP Method

      PUT

      Response Type

      -
      +

      Parameters

        -
        +
      • - + Path: -

        name that need to be deleted

        -
      • + + username + String + +

        name that need to be deleted

        + -
        +
      • - -

        Updated user object

        -
      • + + Body: + body + User + +

        Updated user object

        +
      @@ -188,19 +214,23 @@

      HTTP Method

      DELETE

      Response Type

      -
      +

      Parameters

        -
        +
      • - + Path: -

        The name that needs to be deleted

        -
      • + + username + String + +

        The name that needs to be deleted

        +
      - \ No newline at end of file + diff --git a/samples/html/index.html b/samples/html/index.html index bab16472c309..1025186dc4b6 100644 --- a/samples/html/index.html +++ b/samples/html/index.html @@ -2,7 +2,6 @@ API Reference -

      Swagger Petstore

      @@ -18,8 +17,321 @@ +
      +
      put: /pet
      +
      Pet
      +
      updatePet Update an existing pet
      +
      + +

      Parameters

      +
      +
      body (optional)
      + +
      Body Parameter — Pet object that needs to be added to the store
      + +
      +

      Return type

      + +
      + + +
      +
      + +
      +
      post: /pet
      +
      Pet
      +
      addPet Add a new pet to the store
      +
      + +

      Parameters

      +
      +
      body (optional)
      + +
      Body Parameter — Pet object that needs to be added to the store
      + +
      +

      Return type

      + +
      + + +
      +
      + +
      +
      get: /pet/findByStatus
      +
      Pet
      +
      findPetsByStatus Finds Pets by status
      +
      Multiple status values can be provided with comma seperated strings
      + +

      Parameters

      +
      +
      status (optional)
      + +
      Query Parameter — Status values that need to be considered for filter
      + +
      +

      Return type

      + + + + +

      Example data

      +
      Content-Type: application/json
      +
      [ {\n  "tags" : [ {\n    "id" : 123456789,\n    "name" : "aeiou"\n  } ],\n  "id" : 123456789,\n  "category" : {\n    "id" : 123456789,\n    "name" : "aeiou"\n  },\n  "status" : "aeiou",\n  "name" : "doggie",\n  "photoUrls" : [ "aeiou" ]\n} ]
      + +

      Example data

      +
      Content-Type: application/xml
      +
      \n  123456\n  \n    123456\n    string\n  \n  doggie\n  string\n  \n    123456\n    string\n  \n  string\n
      + +
      +
      + +
      +
      get: /pet/findByTags
      +
      Pet
      +
      findPetsByTags Finds Pets by tags
      +
      Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
      + +

      Parameters

      +
      +
      tags (optional)
      + +
      Query Parameter — Tags to filter by
      + +
      +

      Return type

      + + + + +

      Example data

      +
      Content-Type: application/json
      +
      [ {\n  "tags" : [ {\n    "id" : 123456789,\n    "name" : "aeiou"\n  } ],\n  "id" : 123456789,\n  "category" : {\n    "id" : 123456789,\n    "name" : "aeiou"\n  },\n  "status" : "aeiou",\n  "name" : "doggie",\n  "photoUrls" : [ "aeiou" ]\n} ]
      + +

      Example data

      +
      Content-Type: application/xml
      +
      \n  123456\n  \n    123456\n    string\n  \n  doggie\n  string\n  \n    123456\n    string\n  \n  string\n
      + +
      +
      + +
      +
      get: /pet/{petId}
      +
      Pet
      +
      getPetById Find pet by ID
      +
      Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions
      + +

      Parameters

      +
      +
      petId (required)
      + +
      Path Parameter — ID of pet that needs to be fetched
      + +
      +

      Return type

      + + + + +

      Example data

      +
      Content-Type: application/json
      +
      {\n  "tags" : [ {\n    "id" : 123456789,\n    "name" : "aeiou"\n  } ],\n  "id" : 123456789,\n  "category" : {\n    "id" : 123456789,\n    "name" : "aeiou"\n  },\n  "status" : "aeiou",\n  "name" : "doggie",\n  "photoUrls" : [ "aeiou" ]\n}
      + +

      Example data

      +
      Content-Type: application/xml
      +
      \n  123456\n  \n    123456\n    string\n  \n  doggie\n  string\n  \n    123456\n    string\n  \n  string\n
      + +
      +
      + +
      +
      post: /pet/{petId}
      +
      Pet
      +
      updatePetWithForm Updates a pet in the store with form data
      +
      + +

      Parameters

      +
      +
      petId (required)
      + +
      Path Parameter — ID of pet that needs to be updated
      +
      name (optional)
      + +
      Form Parameter — Updated name of the pet
      +
      status (optional)
      + +
      Form Parameter — Updated status of the pet
      + +
      +

      Return type

      + +
      + + +
      +
      + +
      +
      delete: /pet/{petId}
      +
      Pet
      +
      deletePet Deletes a pet
      +
      + +

      Parameters

      +
      +
      api_key (optional)
      + +
      Header Parameter
      +
      petId (required)
      + +
      Path Parameter — Pet id to delete
      + +
      +

      Return type

      + +
      + + +
      +
      + +
      +
      post: /pet/{petId}/uploadImage
      +
      Pet
      +
      uploadFile uploads an image
      +
      + +

      Parameters

      +
      +
      petId (required)
      + +
      Path Parameter — ID of pet to update
      +
      additionalMetadata (optional)
      + +
      Form Parameter — Additional data to pass to server
      +
      file (optional)
      + +
      Form Parameter — file to upload
      + +
      +

      Return type

      + +
      + + +
      +
      + +
      +
      get: /store/inventory
      +
      Store
      +
      getInventory Returns pet inventories by status
      +
      Returns a map of status codes to quantities
      + +

      Parameters

      +
      + +
      +

      Return type

      + + + + +

      Example data

      +
      Content-Type: application/json
      +
      {\n  "key" : 123\n}
      + +

      Example data

      +
      Content-Type: application/xml
      +
      not implemented com.wordnik.swagger.models.properties.MapProperty@5076b51c
      + +
      +
      + +
      +
      post: /store/order
      +
      Store
      +
      placeOrder Place an order for a pet
      +
      + +

      Parameters

      +
      +
      body (optional)
      + +
      Body Parameter — order placed for purchasing the pet
      + +
      +

      Return type

      + + + + +

      Example data

      +
      Content-Type: application/json
      +
      {\n  "id" : 123456789,\n  "petId" : 123456789,\n  "complete" : true,\n  "status" : "aeiou",\n  "quantity" : 123,\n  "shipDate" : "2015-05-12T09:58:06.953+0000"\n}
      + +

      Example data

      +
      Content-Type: application/xml
      +
      \n  123456\n  123456\n  0\n  2015-05-12T05:58:06.956Z\n  string\n  true\n
      + +
      +
      + +
      +
      get: /store/order/{orderId}
      +
      Store
      +
      getOrderById Find purchase order by ID
      +
      For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
      + +

      Parameters

      +
      +
      orderId (required)
      + +
      Path Parameter — ID of pet that needs to be fetched
      + +
      +

      Return type

      + + + + +

      Example data

      +
      Content-Type: application/json
      +
      {\n  "id" : 123456789,\n  "petId" : 123456789,\n  "complete" : true,\n  "status" : "aeiou",\n  "quantity" : 123,\n  "shipDate" : "2015-05-12T09:58:06.957+0000"\n}
      + +

      Example data

      +
      Content-Type: application/xml
      +
      \n  123456\n  123456\n  0\n  2015-05-12T05:58:06.957Z\n  string\n  true\n
      + +
      +
      + +
      +
      delete: /store/order/{orderId}
      +
      Store
      +
      deleteOrder Delete purchase order by ID
      +
      For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
      + +

      Parameters

      +
      +
      orderId (required)
      + +
      Path Parameter — ID of the order that needs to be deleted
      + +
      +

      Return type

      + +
      + + +
      +
      +
      post: /user
      +
      User
      createUser Create user
      This can only be done by the logged in user.
      @@ -40,6 +352,7 @@
      post: /user/createWithArray
      +
      User
      createUsersWithArrayInput Creates list of users with given input array
      @@ -60,6 +373,7 @@
      post: /user/createWithList
      +
      User
      createUsersWithListInput Creates list of users with given input array
      @@ -80,6 +394,7 @@
      get: /user/login
      +
      User
      loginUser Logs user into the system
      @@ -111,6 +426,7 @@
      get: /user/logout
      +
      User
      logoutUser Logs out current logged in user session
      @@ -128,6 +444,7 @@
      get: /user/{username}
      +
      User
      getUserByName Get user by user name
      @@ -156,6 +473,7 @@
      put: /user/{username}
      +
      User
      updateUser Updated user
      This can only be done by the logged in user.
      @@ -179,6 +497,7 @@
      delete: /user/{username}
      +
      User
      deleteUser Delete user
      This can only be done by the logged in user.
      @@ -198,310 +517,6 @@
      - -
      -
      put: /pet
      -
      updatePet Update an existing pet
      -
      - -

      Parameters

      -
      -
      body (optional)
      - -
      Body Parameter — Pet object that needs to be added to the store
      - -
      -

      Return type

      - -
      - - -
      -
      - -
      -
      post: /pet
      -
      addPet Add a new pet to the store
      -
      - -

      Parameters

      -
      -
      body (optional)
      - -
      Body Parameter — Pet object that needs to be added to the store
      - -
      -

      Return type

      - -
      - - -
      -
      - -
      -
      get: /pet/findByStatus
      -
      findPetsByStatus Finds Pets by status
      -
      Multiple status values can be provided with comma seperated strings
      - -

      Parameters

      -
      -
      status (optional)
      - -
      Query Parameter — Status values that need to be considered for filter
      - -
      -

      Return type

      - - - - -

      Example data

      -
      Content-Type: application/json
      -
      [ {\n  "tags" : [ {\n    "id" : 123456789,\n    "name" : "aeiou"\n  } ],\n  "id" : 123456789,\n  "category" : {\n    "id" : 123456789,\n    "name" : "aeiou"\n  },\n  "status" : "aeiou",\n  "name" : "doggie",\n  "photoUrls" : [ "aeiou" ]\n} ]
      - -

      Example data

      -
      Content-Type: application/xml
      -
      \n  123456\n  \n    123456\n    string\n  \n  doggie\n  string\n  \n    123456\n    string\n  \n  string\n
      - -
      -
      - -
      -
      get: /pet/findByTags
      -
      findPetsByTags Finds Pets by tags
      -
      Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
      - -

      Parameters

      -
      -
      tags (optional)
      - -
      Query Parameter — Tags to filter by
      - -
      -

      Return type

      - - - - -

      Example data

      -
      Content-Type: application/json
      -
      [ {\n  "tags" : [ {\n    "id" : 123456789,\n    "name" : "aeiou"\n  } ],\n  "id" : 123456789,\n  "category" : {\n    "id" : 123456789,\n    "name" : "aeiou"\n  },\n  "status" : "aeiou",\n  "name" : "doggie",\n  "photoUrls" : [ "aeiou" ]\n} ]
      - -

      Example data

      -
      Content-Type: application/xml
      -
      \n  123456\n  \n    123456\n    string\n  \n  doggie\n  string\n  \n    123456\n    string\n  \n  string\n
      - -
      -
      - -
      -
      get: /pet/{petId}
      -
      getPetById Find pet by ID
      -
      Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions
      - -

      Parameters

      -
      -
      petId (required)
      - -
      Path Parameter — ID of pet that needs to be fetched
      - -
      -

      Return type

      - - - - -

      Example data

      -
      Content-Type: application/json
      -
      {\n  "tags" : [ {\n    "id" : 123456789,\n    "name" : "aeiou"\n  } ],\n  "id" : 123456789,\n  "category" : {\n    "id" : 123456789,\n    "name" : "aeiou"\n  },\n  "status" : "aeiou",\n  "name" : "doggie",\n  "photoUrls" : [ "aeiou" ]\n}
      - -

      Example data

      -
      Content-Type: application/xml
      -
      \n  123456\n  \n    123456\n    string\n  \n  doggie\n  string\n  \n    123456\n    string\n  \n  string\n
      - -
      -
      - -
      -
      post: /pet/{petId}
      -
      updatePetWithForm Updates a pet in the store with form data
      -
      - -

      Parameters

      -
      -
      petId (required)
      - -
      Path Parameter — ID of pet that needs to be updated
      -
      name (optional)
      - -
      Form Parameter — Updated name of the pet
      -
      status (optional)
      - -
      Form Parameter — Updated status of the pet
      - -
      -

      Return type

      - -
      - - -
      -
      - -
      -
      delete: /pet/{petId}
      -
      deletePet Deletes a pet
      -
      - -

      Parameters

      -
      -
      api_key (optional)
      - -
      Header Parameter
      -
      petId (required)
      - -
      Path Parameter — Pet id to delete
      - -
      -

      Return type

      - -
      - - -
      -
      - -
      -
      post: /pet/{petId}/uploadImage
      -
      uploadFile uploads an image
      -
      - -

      Parameters

      -
      -
      petId (required)
      - -
      Path Parameter — ID of pet to update
      -
      additionalMetadata (optional)
      - -
      Form Parameter — Additional data to pass to server
      -
      file (optional)
      - -
      Form Parameter — file to upload
      - -
      -

      Return type

      - -
      - - -
      -
      - - - -
      -
      get: /store/inventory
      -
      getInventory Returns pet inventories by status
      -
      Returns a map of status codes to quantities
      - -

      Parameters

      -
      - -
      -

      Return type

      - - - - -

      Example data

      -
      Content-Type: application/json
      -
      {\n  "key" : 123\n}
      - -

      Example data

      -
      Content-Type: application/xml
      -
      not implemented com.wordnik.swagger.models.properties.MapProperty@3c536f11
      - -
      -
      - -
      -
      post: /store/order
      -
      placeOrder Place an order for a pet
      -
      - -

      Parameters

      -
      -
      body (optional)
      - -
      Body Parameter — order placed for purchasing the pet
      - -
      -

      Return type

      - - - - -

      Example data

      -
      Content-Type: application/json
      -
      {\n  "id" : 123456789,\n  "petId" : 123456789,\n  "complete" : true,\n  "status" : "aeiou",\n  "quantity" : 123,\n  "shipDate" : "2015-04-16T14:41:29.883+0000"\n}
      - -

      Example data

      -
      Content-Type: application/xml
      -
      \n  123456\n  123456\n  0\n  2015-04-16T22:41:29.886Z\n  string\n  true\n
      - -
      -
      - -
      -
      get: /store/order/{orderId}
      -
      getOrderById Find purchase order by ID
      -
      For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
      - -

      Parameters

      -
      -
      orderId (required)
      - -
      Path Parameter — ID of pet that needs to be fetched
      - -
      -

      Return type

      - - - - -

      Example data

      -
      Content-Type: application/json
      -
      {\n  "id" : 123456789,\n  "petId" : 123456789,\n  "complete" : true,\n  "status" : "aeiou",\n  "quantity" : 123,\n  "shipDate" : "2015-04-16T14:41:29.887+0000"\n}
      - -

      Example data

      -
      Content-Type: application/xml
      -
      \n  123456\n  123456\n  0\n  2015-04-16T22:41:29.888Z\n  string\n  true\n
      - -
      -
      - -
      -
      delete: /store/order/{orderId}
      -
      deleteOrder Delete purchase order by ID
      -
      For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
      - -

      Parameters

      -
      -
      orderId (required)
      - -
      Path Parameter — ID of the order that needs to be deleted
      - -
      -

      Return type

      - -
      - - -
      -
      - -

      Models

      @@ -631,6 +646,7 @@ hr { pre { padding: 10px; + margin-bottom: 2px; } pre.get { @@ -712,6 +728,19 @@ code { font-weight: bold; } +.method-tags { + text-align: right; +} + +.method-tag { + background: none repeat scroll 0% 0% #24A600; + border-radius: 3px; + padding: 2px 10px; + margin: 2px; + color: #FFF; + display: inline-block; + text-decoration: none; +} \ No newline at end of file diff --git a/samples/server/petstore/jaxrs/pom.xml b/samples/server/petstore/jaxrs/pom.xml index b2761f0369ab..c928b341b381 100644 --- a/samples/server/petstore/jaxrs/pom.xml +++ b/samples/server/petstore/jaxrs/pom.xml @@ -129,7 +129,7 @@ - 2.1.1-M2-SNAPSHOT + 1.5.2-M2-SNAPSHOT 9.2.9.v20150224 1.13 1.6.3 diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java index e58a4c2c120a..ca48e7b10ff0 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java @@ -73,7 +73,7 @@ public class PetApi { produces = { "application/json", "application/xml" }, method = RequestMethod.GET) - public ResponseEntity findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter") @RequestParam("status") List status) + public ResponseEntity findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter") @RequestParam(value = "status", required = false) List status) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -89,7 +89,7 @@ public class PetApi { produces = { "application/json", "application/xml" }, method = RequestMethod.GET) - public ResponseEntity findPetsByTags(@ApiParam(value = "Tags to filter by") @RequestParam("tags") List tags) + public ResponseEntity findPetsByTags(@ApiParam(value = "Tags to filter by") @RequestParam(value = "tags", required = false) List tags) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java index 4a84a38612b0..25671c6168d4 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java @@ -86,8 +86,8 @@ public class UserApi { produces = { "application/json", "application/xml" }, method = RequestMethod.GET) - public ResponseEntity loginUser(@ApiParam(value = "The user name for login") @RequestParam("username") String username, - @ApiParam(value = "The password for login in clear text") @RequestParam("password") String password) + public ResponseEntity loginUser(@ApiParam(value = "The user name for login") @RequestParam(value = "username", required = false) String username, + @ApiParam(value = "The password for login in clear text") @RequestParam(value = "password", required = false) String password) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK);