From 7e37f3294af3e4f2f93b0d974a8c6f0209a97249 Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 17 Apr 2015 20:01:58 +0800 Subject: [PATCH 01/67] bug fix for post (model) and update php test cases --- .gitignore | 3 + .../src/main/resources/php/APIClient.mustache | 6 +- .../src/main/resources/php/api.mustache | 8 +- .../php/SwaggerClient-php/lib/APIClient.php | 6 +- .../php/SwaggerClient-php/lib/PetApi.php | 64 ++++------- .../php/SwaggerClient-php/lib/StoreApi.php | 32 ++---- .../php/SwaggerClient-php/lib/UserApi.php | 64 ++++------- .../petstore/php/SwaggerClient-php/pom.xml | 60 ++++++++++ .../SwaggerClient-php/tests/PetApiTest.php | 108 +++++++++++++++++- 9 files changed, 241 insertions(+), 110 deletions(-) create mode 100644 samples/client/petstore/php/SwaggerClient-php/pom.xml 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/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..34cf1d989f79 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -81,11 +81,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/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php index f69675c1e9bb..d3fe07aa911d 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php @@ -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/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php index 80d9c040d1ef..5a6dece6f85b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php @@ -67,11 +67,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 @@ -120,11 +118,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 @@ -172,11 +168,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 @@ -230,11 +224,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 @@ -289,11 +281,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 @@ -356,11 +346,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 @@ -413,11 +401,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 @@ -474,11 +460,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..4c3563451b63 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php @@ -62,11 +62,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 @@ -121,11 +119,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 @@ -180,11 +176,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 @@ -239,11 +233,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..c531e5a9d975 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php @@ -67,11 +67,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 @@ -120,11 +118,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 @@ -173,11 +169,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 @@ -229,11 +223,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 @@ -283,11 +275,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 @@ -336,11 +326,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 @@ -400,11 +388,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 @@ -453,11 +439,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..f50fd1a8fc42 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -1,16 +1,118 @@ 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); + } + + // 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'); } + + // 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'); + } + } + ?> + From 4dd793c0ac65c109501c528826fe06f0b828be15 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Thu, 16 Apr 2015 17:34:11 +0800 Subject: [PATCH 02/67] Updated naming convention in objc client. --- .../codegen/languages/ObjcClientCodegen.java | 71 +++++++++++++------ .../petstore/objc/client/SWGApiResponse.h | 18 ----- .../petstore/objc/client/SWGApiResponse.m | 54 -------------- .../client/petstore/objc/client/SWGOrder.h | 2 +- .../client/petstore/objc/client/SWGPetApi.h | 4 +- .../client/petstore/objc/client/SWGPetApi.m | 8 +-- 6 files changed, 56 insertions(+), 101 deletions(-) delete mode 100644 samples/client/petstore/objc/client/SWGApiResponse.h delete mode 100644 samples/client/petstore/objc/client/SWGApiResponse.m 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/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; From 60ab624b23ba1620c09bce847a5d7fee9c2345f3 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Thu, 16 Apr 2015 18:39:21 +0800 Subject: [PATCH 03/67] Updated xcode project for petstore --- .../contents.xcworkspacedata | 11 ++++++++++- .../xcshareddata/PetstoreClient.xccheckout | 6 +++--- .../PetstoreClient.xcodeproj/project.pbxproj | 6 ------ 3 files changed, 13 insertions(+), 10 deletions(-) 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.xcworkspace/xcshareddata/PetstoreClient.xccheckout b/samples/client/petstore/objc/PetstoreClient.xcworkspace/xcshareddata/PetstoreClient.xccheckout index fafd21fb8eba..3d473491e3dc 100644 --- a/samples/client/petstore/objc/PetstoreClient.xcworkspace/xcshareddata/PetstoreClient.xccheckout +++ b/samples/client/petstore/objc/PetstoreClient.xcworkspace/xcshareddata/PetstoreClient.xccheckout @@ -5,13 +5,13 @@ IDESourceControlProjectFavoriteDictionaryKey IDESourceControlProjectIdentifier - 81EB09FA-DD8C-4FE1-82D3-1FB6FF0D9C43 + 06538C1C-B57B-41A2-BDB2-686B4A83D75C IDESourceControlProjectName PetstoreClient IDESourceControlProjectOriginsDictionary E5BBF0AA85077C865C95437976D06D819733A208 - ssh://github.com/wordnik/swagger-codegen.git + https://github.com/geekerzp/swagger-codegen.git IDESourceControlProjectPath samples/client/petstore/objc/PetstoreClient.xcworkspace @@ -21,7 +21,7 @@ ../../../../.. IDESourceControlProjectURL - ssh://github.com/wordnik/swagger-codegen.git + https://github.com/geekerzp/swagger-codegen.git IDESourceControlProjectVersion 111 IDESourceControlProjectWCCIdentifier 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 */, From 152eabbd6a8eab9fc0b5858b3498ee7102ad36a0 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Tue, 21 Apr 2015 16:33:28 +0800 Subject: [PATCH 04/67] Fixed `PetstoreClient.xccheckout`. --- .../xcshareddata/PetstoreClient.xccheckout | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/samples/client/petstore/objc/PetstoreClient.xcworkspace/xcshareddata/PetstoreClient.xccheckout b/samples/client/petstore/objc/PetstoreClient.xcworkspace/xcshareddata/PetstoreClient.xccheckout index 3d473491e3dc..fafd21fb8eba 100644 --- a/samples/client/petstore/objc/PetstoreClient.xcworkspace/xcshareddata/PetstoreClient.xccheckout +++ b/samples/client/petstore/objc/PetstoreClient.xcworkspace/xcshareddata/PetstoreClient.xccheckout @@ -5,13 +5,13 @@ IDESourceControlProjectFavoriteDictionaryKey IDESourceControlProjectIdentifier - 06538C1C-B57B-41A2-BDB2-686B4A83D75C + 81EB09FA-DD8C-4FE1-82D3-1FB6FF0D9C43 IDESourceControlProjectName PetstoreClient IDESourceControlProjectOriginsDictionary E5BBF0AA85077C865C95437976D06D819733A208 - https://github.com/geekerzp/swagger-codegen.git + ssh://github.com/wordnik/swagger-codegen.git IDESourceControlProjectPath samples/client/petstore/objc/PetstoreClient.xcworkspace @@ -21,7 +21,7 @@ ../../../../.. IDESourceControlProjectURL - https://github.com/geekerzp/swagger-codegen.git + ssh://github.com/wordnik/swagger-codegen.git IDESourceControlProjectVersion 111 IDESourceControlProjectWCCIdentifier From d5a3cc7300db7e1a2f0247bbbe4ee1bfcb8865f7 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 23 Apr 2015 00:42:36 +0800 Subject: [PATCH 05/67] fix php swagger type --- .../codegen/languages/PhpClientCodegen.java | 47 ++++++++++++++----- .../src/test/scala/php/PhpModelTest.scala | 41 ++++++++-------- .../php/SwaggerClient-php/lib/PetApi.php | 2 +- 3 files changed, 57 insertions(+), 33 deletions(-) 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/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/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php index 80d9c040d1ef..fb74c77f2d14 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php @@ -435,7 +435,7 @@ 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) { From 78072f753c765c6a3bf3f48ad668c195fa520722 Mon Sep 17 00:00:00 2001 From: xhh Date: Thu, 23 Apr 2015 09:38:27 +0800 Subject: [PATCH 06/67] Fix tests for Scala petstore sample --- .../scala/src/test/scala/PetApiTest.scala | 12 +------ .../scala/src/test/scala/StoreApiTest.scala | 34 +++++++------------ 2 files changed, 13 insertions(+), 33 deletions(-) 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 +} From 4f5f6a9e8fdc64bb191166930ac7ad994606a9a8 Mon Sep 17 00:00:00 2001 From: xhh Date: Thu, 23 Apr 2015 15:27:44 +0800 Subject: [PATCH 07/67] Include Scala petstore sample into integration test --- pom.xml | 13 +++++++++++++ 1 file changed, 13 insertions(+) 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 From 4a55223a8ffc8ac95980ec44f1b197c4aa981643 Mon Sep 17 00:00:00 2001 From: xhh Date: Fri, 24 Apr 2015 23:57:17 +0800 Subject: [PATCH 08/67] Add form parameters support to Scala codegen --- .../src/main/resources/scala/api.mustache | 35 +++- .../main/resources/scala/apiInvoker.mustache | 14 +- .../scala/io/swagger/client/ApiInvoker.scala | 14 +- .../scala/io/swagger/client/api/PetApi.scala | 192 +++++++++++++----- .../io/swagger/client/api/StoreApi.scala | 92 ++++++--- .../scala/io/swagger/client/api/UserApi.scala | 185 +++++++++++------ 6 files changed, 376 insertions(+), 156 deletions(-) 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/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 From fb3088b7650e02e95ca33c87de0a2c7d47fef3b8 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 29 Apr 2015 17:31:38 +0800 Subject: [PATCH 09/67] fixed required parameter in java api --- .../src/main/resources/Java/api.mustache | 10 +++++----- .../java/io/swagger/client/api/PetApi.java | 20 +++++++++++++++++++ .../java/io/swagger/client/api/StoreApi.java | 10 ++++++++++ .../java/io/swagger/client/api/UserApi.java | 15 ++++++++++++++ 4 files changed, 50 insertions(+), 5 deletions(-) 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/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") From 303378c5eb3184f658aa49722a732dab08f471f4 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 30 Apr 2015 16:29:21 +0800 Subject: [PATCH 10/67] fix android required parameter check --- .../main/resources/android-java/api.mustache | 11 ++++---- .../java/io/swagger/client/api/PetApi.java | 28 +++++++++++++------ .../java/io/swagger/client/api/StoreApi.java | 14 +++++++--- .../java/io/swagger/client/api/UserApi.java | 23 +++++++++------ samples/client/petstore/java/hello.txt | 1 + 5 files changed, 51 insertions(+), 26 deletions(-) create mode 100644 samples/client/petstore/java/hello.txt 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/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/java/hello.txt b/samples/client/petstore/java/hello.txt new file mode 100644 index 000000000000..6769dd60bdf5 --- /dev/null +++ b/samples/client/petstore/java/hello.txt @@ -0,0 +1 @@ +Hello world! \ No newline at end of file From 93e4ef0eecb2dec14ca26c477e9102539b14e8af Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 30 Apr 2015 16:52:33 +0800 Subject: [PATCH 11/67] fix required parameters check for php --- .../src/main/resources/php/api.mustache | 6 ++++ .../php/SwaggerClient-php/lib/PetApi.php | 28 +++++++++++++++++++ .../php/SwaggerClient-php/lib/StoreApi.php | 14 ++++++++++ .../php/SwaggerClient-php/lib/UserApi.php | 23 +++++++++++++++ 4 files changed, 71 insertions(+) diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index a434699f90ad..e0b94e6b2325 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}}"; diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php index 80d9c040d1ef..fc8331da4bd2 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"; @@ -91,6 +92,7 @@ class PetApi { * @return void */ public function addPet($body) { + // parse inputs $resourcePath = "/pet"; @@ -144,6 +146,7 @@ class PetApi { * @return array[Pet] */ public function findPetsByStatus($status) { + // parse inputs $resourcePath = "/pet/findByStatus"; @@ -202,6 +205,7 @@ class PetApi { * @return array[Pet] */ public function findPetsByTags($tags) { + // parse inputs $resourcePath = "/pet/findByTags"; @@ -260,6 +264,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}"; @@ -321,6 +331,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}"; @@ -381,6 +397,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}"; @@ -439,6 +461,12 @@ class PetApi { * @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"; diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php index 4e40ed983b93..6e3ce56e7ced 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"; @@ -92,6 +93,7 @@ class StoreApi { * @return Order */ public function placeOrder($body) { + // parse inputs $resourcePath = "/store/order"; @@ -151,6 +153,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}"; @@ -210,6 +218,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}"; diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php index f3e9e7f4cc6b..8296d5e92fd7 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"; @@ -91,6 +92,7 @@ class UserApi { * @return void */ public function createUsersWithArrayInput($body) { + // parse inputs $resourcePath = "/user/createWithArray"; @@ -144,6 +146,7 @@ class UserApi { * @return void */ public function createUsersWithListInput($body) { + // parse inputs $resourcePath = "/user/createWithList"; @@ -198,6 +201,7 @@ class UserApi { * @return string */ public function loginUser($username, $password) { + // parse inputs $resourcePath = "/user/login"; @@ -258,6 +262,7 @@ class UserApi { * @return void */ public function logoutUser() { + // parse inputs $resourcePath = "/user/logout"; @@ -307,6 +312,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}"; @@ -367,6 +378,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}"; @@ -424,6 +441,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}"; From 47a8ef3031c7c6ea318ce7dd5725964637b9e44f Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 30 Apr 2015 17:01:36 +0800 Subject: [PATCH 12/67] fix required parameters in ruby --- .../src/main/resources/ruby/api.mustache | 6 ++-- samples/client/petstore/ruby/lib/pet_api.rb | 32 ++++++++++++------- samples/client/petstore/ruby/lib/store_api.rb | 16 ++++++---- samples/client/petstore/ruby/lib/user_api.rb | 28 +++++++++------- 4 files changed, 51 insertions(+), 31 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index 5b0d37322832..210c7d819bac 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -13,8 +13,10 @@ class {{classname}} {{#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}} + {{#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}} diff --git a/samples/client/petstore/ruby/lib/pet_api.rb b/samples/client/petstore/ruby/lib/pet_api.rb index 6b032510c416..7cab0c8eb008 100644 --- a/samples/client/petstore/ruby/lib/pet_api.rb +++ b/samples/client/petstore/ruby/lib/pet_api.rb @@ -10,7 +10,7 @@ class PetApi # @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') @@ -62,7 +62,7 @@ class PetApi # @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') @@ -114,7 +114,7 @@ class PetApi # @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') @@ -148,7 +148,7 @@ class PetApi # @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') @@ -182,8 +182,10 @@ class PetApi # @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? + + # 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) @@ -218,8 +220,10 @@ class PetApi # @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? + + # 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) @@ -254,8 +258,10 @@ class PetApi # @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? + + # 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) @@ -290,8 +296,10 @@ class PetApi # @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? + + # 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) diff --git a/samples/client/petstore/ruby/lib/store_api.rb b/samples/client/petstore/ruby/lib/store_api.rb index 6cd3296039bf..1ce553cde9a9 100644 --- a/samples/client/petstore/ruby/lib/store_api.rb +++ b/samples/client/petstore/ruby/lib/store_api.rb @@ -9,7 +9,7 @@ class StoreApi # @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') @@ -42,7 +42,7 @@ class StoreApi # @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') @@ -95,8 +95,10 @@ class StoreApi # @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? + + # 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) @@ -129,8 +131,10 @@ class StoreApi # @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? + + # 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) diff --git a/samples/client/petstore/ruby/lib/user_api.rb b/samples/client/petstore/ruby/lib/user_api.rb index dead94897cd3..fa900d3d0059 100644 --- a/samples/client/petstore/ruby/lib/user_api.rb +++ b/samples/client/petstore/ruby/lib/user_api.rb @@ -10,7 +10,7 @@ class UserApi # @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') @@ -62,7 +62,7 @@ class UserApi # @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') @@ -114,7 +114,7 @@ class UserApi # @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') @@ -167,7 +167,7 @@ class UserApi # @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') @@ -201,7 +201,7 @@ class UserApi # @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') @@ -233,8 +233,10 @@ class UserApi # @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? + + # 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) @@ -268,8 +270,10 @@ class UserApi # @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? + + # 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) @@ -321,8 +325,10 @@ class UserApi # @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? + + # 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) From 2e85871a4b93ee798a19ba4aa6ae333b1903d06b Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 30 Apr 2015 17:12:25 +0800 Subject: [PATCH 13/67] remove hello.txt (created by mvn test) --- samples/client/petstore/java/hello.txt | 1 - 1 file changed, 1 deletion(-) delete mode 100644 samples/client/petstore/java/hello.txt diff --git a/samples/client/petstore/java/hello.txt b/samples/client/petstore/java/hello.txt deleted file mode 100644 index 6769dd60bdf5..000000000000 --- a/samples/client/petstore/java/hello.txt +++ /dev/null @@ -1 +0,0 @@ -Hello world! \ No newline at end of file From 070a6203e06acf177fecfc9f286db676f22a6500 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 7 May 2015 13:35:19 +0800 Subject: [PATCH 14/67] remove php comment --- .../swagger-codegen/src/main/resources/php/require.mustache | 3 --- .../client/petstore/php/SwaggerClient-php/SwaggerClient.php | 3 --- 2 files changed, 6 deletions(-) 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 @@ Date: Tue, 31 Mar 2015 23:54:45 +0800 Subject: [PATCH 15/67] add perl support - api template, bin, codegen --- bin/perl-petstore.sh | 31 ++ .../codegen/languages/PerlClientCodegen.java | 152 ++++++ .../com.wordnik.swagger.codegen.CodegenConfig | 1 + .../src/main/resources/perl/Swagger.mustache | 326 ++++++++++++ .../src/main/resources/perl/api.mustache | 121 +++++ .../src/main/resources/perl/model.mustache | 66 +++ samples/client/petstore/perl/PetApi.pl | 489 ++++++++++++++++++ samples/client/petstore/perl/StoreApi.pl | 264 ++++++++++ samples/client/petstore/perl/Swagger.pl | 326 ++++++++++++ samples/client/petstore/perl/UserApi.pl | 468 +++++++++++++++++ .../perl/WWW/Swagger/Model/Category.pl | 60 +++ .../perl/WWW/Swagger/Model/Category.pm | 60 +++ .../petstore/perl/WWW/Swagger/Model/Order.pl | 79 +++ .../petstore/perl/WWW/Swagger/Model/Order.pm | 79 +++ .../petstore/perl/WWW/Swagger/Model/Pet.pl | 79 +++ .../petstore/perl/WWW/Swagger/Model/Pet.pm | 79 +++ .../petstore/perl/WWW/Swagger/Model/Tag.pl | 60 +++ .../petstore/perl/WWW/Swagger/Model/Tag.pm | 60 +++ .../petstore/perl/WWW/Swagger/Model/User.pl | 87 ++++ .../petstore/perl/WWW/Swagger/Model/User.pm | 87 ++++ .../petstore/perl/WWW/Swagger/PetApi.pl | 481 +++++++++++++++++ .../petstore/perl/WWW/Swagger/PetApi.pm | 486 +++++++++++++++++ .../petstore/perl/WWW/Swagger/StoreApi.pl | 260 ++++++++++ .../petstore/perl/WWW/Swagger/StoreApi.pm | 262 ++++++++++ .../petstore/perl/WWW/Swagger/UserApi.pl | 460 ++++++++++++++++ .../petstore/perl/WWW/Swagger/UserApi.pm | 463 +++++++++++++++++ .../client/petstore/perl/models/Category.pl | 60 +++ samples/client/petstore/perl/models/Order.pl | 79 +++ samples/client/petstore/perl/models/Pet.pl | 79 +++ samples/client/petstore/perl/models/Tag.pl | 60 +++ samples/client/petstore/perl/models/User.pl | 87 ++++ 31 files changed, 5751 insertions(+) create mode 100755 bin/perl-petstore.sh create mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PerlClientCodegen.java create mode 100644 modules/swagger-codegen/src/main/resources/perl/Swagger.mustache create mode 100644 modules/swagger-codegen/src/main/resources/perl/api.mustache create mode 100644 modules/swagger-codegen/src/main/resources/perl/model.mustache create mode 100644 samples/client/petstore/perl/PetApi.pl create mode 100644 samples/client/petstore/perl/StoreApi.pl create mode 100644 samples/client/petstore/perl/Swagger.pl create mode 100644 samples/client/petstore/perl/UserApi.pl create mode 100644 samples/client/petstore/perl/WWW/Swagger/Model/Category.pl create mode 100644 samples/client/petstore/perl/WWW/Swagger/Model/Category.pm create mode 100644 samples/client/petstore/perl/WWW/Swagger/Model/Order.pl create mode 100644 samples/client/petstore/perl/WWW/Swagger/Model/Order.pm create mode 100644 samples/client/petstore/perl/WWW/Swagger/Model/Pet.pl create mode 100644 samples/client/petstore/perl/WWW/Swagger/Model/Pet.pm create mode 100644 samples/client/petstore/perl/WWW/Swagger/Model/Tag.pl create mode 100644 samples/client/petstore/perl/WWW/Swagger/Model/Tag.pm create mode 100644 samples/client/petstore/perl/WWW/Swagger/Model/User.pl create mode 100644 samples/client/petstore/perl/WWW/Swagger/Model/User.pm create mode 100644 samples/client/petstore/perl/WWW/Swagger/PetApi.pl create mode 100644 samples/client/petstore/perl/WWW/Swagger/PetApi.pm create mode 100644 samples/client/petstore/perl/WWW/Swagger/StoreApi.pl create mode 100644 samples/client/petstore/perl/WWW/Swagger/StoreApi.pm create mode 100644 samples/client/petstore/perl/WWW/Swagger/UserApi.pl create mode 100644 samples/client/petstore/perl/WWW/Swagger/UserApi.pm create mode 100644 samples/client/petstore/perl/models/Category.pl create mode 100644 samples/client/petstore/perl/models/Order.pl create mode 100644 samples/client/petstore/perl/models/Pet.pl create mode 100644 samples/client/petstore/perl/models/Tag.pl create mode 100644 samples/client/petstore/perl/models/User.pl 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/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..89afcd23b7ec --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PerlClientCodegen.java @@ -0,0 +1,152 @@ +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 = "com.wordnik.client"; + 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 = "Model"; + outputFolder = "generated-code/perl"; + modelTemplateFiles.put("model.mustache", ".pm"); + apiTemplateFiles.put("api.mustache", ".pm"); + templateDir = "perl"; + + 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") + ); + + additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put("groupId", groupId); + additionalProperties.put("artifactId", artifactId); + additionalProperties.put("artifactVersion", artifactVersion); + + languageSpecificPrimitives.add("int"); + languageSpecificPrimitives.add("array"); + languageSpecificPrimitives.add("map"); + languageSpecificPrimitives.add("string"); + languageSpecificPrimitives.add("DateTime"); + + typeMapping.put("long", "int"); + typeMapping.put("integer", "int"); + typeMapping.put("Array", "array"); + typeMapping.put("String", "string"); + typeMapping.put("List", "array"); + typeMapping.put("map", "map"); + + supportingFiles.add(new SupportingFile("Swagger.mustache", "", "Swagger.pl")); + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + "/WWW/Swagger/" + apiPackage().replace('.', File.separatorChar); + } + + public String modelFileFolder() { + return outputFolder + "/WWW/Swagger/" + 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); + } + +} 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..8cb09dcfc111 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,6 +5,7 @@ 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 diff --git a/modules/swagger-codegen/src/main/resources/perl/Swagger.mustache b/modules/swagger-codegen/src/main/resources/perl/Swagger.mustache new file mode 100644 index 000000000000..3d6b77d819e8 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/perl/Swagger.mustache @@ -0,0 +1,326 @@ +host = $host; + $this->headerName = $headerName; + $this->headerValue = $headerValue; + } + + /** + * Set the user agent of the API client + * + * @param string $user_agent The user agent of the API client + */ + public function setUserAgent($user_agent) { + if (!is_string($user_agent)) { + throw new Exception('User-agent must be a string.'); + } + $this->user_agent= $user_agent; + } + + /** + * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] + */ + public function setTimeout($seconds) { + if (!is_numeric($seconds)) { + throw new Exception('Timeout variable must be numeric.'); + } + $this->curl_timout = $seconds; + } + + /** + * @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 + */ + public function callAPI($resourcePath, $method, $queryParams, $postData, + $headerParams) { + + $headers = array(); + + # Allow API key from $headerParams to override default + $added_api_key = False; + if ($headerParams != null) { + foreach ($headerParams as $key => $val) { + $headers[] = "$key: $val"; + if ($key == $this->headerName) { + $added_api_key = True; + } + } + } + if (! $added_api_key && $this->headerName != null) { + $headers[] = $this->headerName . ": " . $this->headerValue; + } + + if (strpos($headers['Content-Type'], "multipart/form-data") < 0 and (is_object($postData) or is_array($postData))) { + $postData = json_encode($this->sanitizeForSerialization($postData)); + } + + $url = $this->host . $resourcePath; + + $curl = curl_init(); + if ($this->curl_timout) { + curl_setopt($curl, CURLOPT_TIMEOUT, $this->curl_timout); + } + // return the result on success, rather than just TRUE + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); + + if (! empty($queryParams)) { + $url = ($url . '?' . http_build_query($queryParams)); + } + + if ($method == self::$POST) { + curl_setopt($curl, CURLOPT_POST, true); + curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); + } else if ($method == self::$PATCH) { + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH"); + curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); + } else if ($method == self::$PUT) { + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); + curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); + } else if ($method == self::$DELETE) { + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); + curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); + } else if ($method != self::$GET) { + throw new Exception('Method ' . $method . ' is not recognized.'); + } + curl_setopt($curl, CURLOPT_URL, $url); + + // Set user agent + if ($this->user_agent) { + curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent); + } else { // use PHP-Swagger as the default user agent + curl_setopt($curl, CURLOPT_USERAGENT, 'PHP-Swagger'); + } + + // Make the request + $response = curl_exec($curl); + $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); + } 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) { + throw new APIClientException("Unauthorized API request to " . $url . + ": " . serialize($response), 0, $response_info, $response); + } else if ($response_info['http_code'] == 404) { + $data = null; + } else { + throw new APIClientException("Can't connect to the api: " . $url . + " response code: " . + $response_info['http_code'], 0, $response_info, $response); + } + return $data; + } + + /** + * Build a JSON POST object + */ + protected function sanitizeForSerialization($data) + { + 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 + */ + public static function toPathValue($value) { + return rawurlencode(toString($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 + */ + public static function toQueryValue($object) { + 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 + */ + public static function toHeaderValue($value) { + return toString($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 + */ + public static function toFormValue($value) { + return toString($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 + */ + public static function toString($value) { + if ($value instanceof \DateTime) { // datetime in ISO8601 format + return $value->format(\DateTime::ISO8601); + } + else { + return $value; + } + } + + /** + * Deserialize a JSON string into an object + * + * @param object $object object or primitive to be deserialized + * @param string $class class name is passed as a string + * @return object an instance of $class + */ + + public static function deserialize($data, $class) + { + if (null === $data) { + $deserialized = null; + } elseif (substr($class, 0, 4) == 'map[') { + $inner = substr($class, 4, -1); + $values = array(); + if(strrpos($inner, ",") !== false) { + $subClass_array = explode(',', $inner, 2); + $subClass = $subClass_array[1]; + foreach ($data as $key => $value) { + $values[] = array($key => self::deserialize($value, $subClass)); + } + } + $deserialized = $values; + } elseif (strcasecmp(substr($class, 0, 6),'array[') == 0) { + $subClass = substr($class, 6, -1); + $values = array(); + foreach ($data as $key => $value) { + $values[] = self::deserialize($value, $subClass); + } + $deserialized = $values; + } elseif ($class == 'DateTime') { + $deserialized = new \DateTime($data); + } elseif (in_array($class, array('string', 'int', 'float', 'bool'))) { + settype($data, $class); + $deserialized = $data; + } else { + $instance = new $class(); + foreach ($instance::$swaggerTypes as $property => $type) { + if (isset($data->$property)) { + $original_property_name = $instance::$attributeMap[$property]; + $instance->$property = self::deserialize($data->$original_property_name, $type); + } + } + $deserialized = $instance; + } + + return $deserialized; + } + +} + +class APIClientException extends Exception { + protected $response, $response_info; + + public function __construct($message="", $code=0, $response_info=null, $response=null) { + parent::__construct($message, $code); + $this->response_info = $response_info; + $this->response = $response; + } + + public function getResponse() { + return $this->response; + } + + public function getResponseInfo() { + return $this->response_info; + } +} 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..76f7b31aa0b5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/perl/api.mustache @@ -0,0 +1,121 @@ +# +# 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. +# + +require 5.6.0; +use strict; +use warnings; + +#use WWW::Swagger::Model::Category; +#use WWW::Swagger::Model::Pet; + +{{#operations}} +package WWW::Swagger::{{classname}}; + +our $VERSION = '2.09'; + + +sub new { + my $class = shift; + my $options = shift; + + croak("You must supply an API client") + unless $options->{api_client}; + + my $self = { + api_client => $options->{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 = shift; + my %args = @_; + + # parse inputs + my $resource_path = "{{path}}"; + $resource_path =~ s/{format}/json/; + + my $method = "{{httpMethod}}"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = '{{#produces}}{{mediaType}}{{#hasMore}},{{/hasMore}}{{/produces}}'; + $header_params->{'Content-Type'} = '{{#consumes}}{{mediaType}}{{#hasMore}},{{/hasMore}}{{/consumes}}'; + + {{#queryParams}} # query params + if($args{ {{paramName}} }) { + $query_params->{'{{baseName}}'} = $self->api_client->to_query_value($args{ {{paramName}} }); + }{{/queryParams}} + {{#headerParams}} # header params + if($args{ {{paramName}} }) { + $header_params->{'{{baseName}}'} = $self->apiClient->to_header_value($args{ {{paramName}} }); + }{{/headerParams}} + {{#pathParams}} # path params + if( $args{ {{paramName}} }) { + my $base_variable = "{" + "{{baseName}}" + "}"; + my $base_value = $self->api_client->to_path_value($args{ {{paramName}} }); + $resource_path = s/$base_variable/$base_value/; + }{{/pathParams}} + {{#formParams}} # form params + if ($args{ {{paramName}} }) { + $form_params->{'{{baseName}}'} = {{#isFile}}'@' . {{/isFile}}$self->api_client->to_form_value($args{ {{paramName}} }); + }{{/formParams}} + my $body; + {{#bodyParams}} # body params + if (isset(${{paramName}})) { + $body = ${{paramName}}; + }{{/bodyParams}} + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + {{#returnType}}if(!$response) { + return; + } + + my $response_object = $self->api_client->deserialize($response, '{{returnType}}'); + return $response_object;{{/returnType}} + } + {{/operation}} +{{newline}} +{{/operations}} + +1; diff --git a/modules/swagger-codegen/src/main/resources/perl/model.mustache b/modules/swagger-codegen/src/main/resources/perl/model.mustache new file mode 100644 index 000000000000..4540f973633f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/perl/model.mustache @@ -0,0 +1,66 @@ + '{{{datatype}}}'{{#hasMore}}, + {{/hasMore}}{{/vars}} + ); + + static $attributeMap = array( + {{#vars}}'{{name}}' => '{{baseName}}'{{#hasMore}}, + {{/hasMore}}{{/vars}} + ); + + {{#vars}}{{#description}} + /** + * {{{description}}} + */{{/description}} + public ${{name}}; /* {{{datatype}}} */{{/vars}} + + public function __construct(array $data) { + {{#vars}}$this->{{name}} = $data["{{name}}"];{{#hasMore}} + {{/hasMore}}{{/vars}} + } + + public function offsetExists($offset) { + return isset($this->$offset); + } + + public function offsetGet($offset) { + return $this->$offset; + } + + public function offsetSet($offset, $value) { + $this->$offset = $value; + } + + public function offsetUnset($offset) { + unset($this->$offset); + } +} +{{/model}} +{{/models}} diff --git a/samples/client/petstore/perl/PetApi.pl b/samples/client/petstore/perl/PetApi.pl new file mode 100644 index 000000000000..7dc8261cd770 --- /dev/null +++ b/samples/client/petstore/perl/PetApi.pl @@ -0,0 +1,489 @@ +# +# 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. +# + +require 5.6.0; +use strict; +use warnings; + +use WWW::Swagger::Model::Category; +use WWW::Swagger::Model::Pet; + +package WWW::Swagger::PetApiAPI; + +our $VERSION = '2.09'; + + +sub new { + my $class = shift; + my $options = shift; + + croak("You must supply an API client") + unless $options->{api_client}; + + my $self = { + api_client = $option->{api_client} + } + + bless $self, $class; + +} + + + # + # updatePet + # + # Update an existing pet + # + # @param Pet $body Pet object that needs to be added to the store (required) + # @return void + # + sub updatePet($body) { + + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/pet"; + $resource_path =~ s/{format}/json/; + + my $method = "PUT"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = 'application/json,application/xml'; + + + + + + # body params + my $body; + if (isset($body)) { + $body = $body; + } + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # addPet + # + # Add a new pet to the store + # + # @param Pet $body Pet object that needs to be added to the store (required) + # @return void + # + sub addPet($body) { + + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/pet"; + $resource_path =~ s/{format}/json/; + + my $method = "POST"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = 'application/json,application/xml'; + + + + + + # body params + my $body; + if (isset($body)) { + $body = $body; + } + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # findPetsByStatus + # + # Finds Pets by status + # + # @param array[string] $status Status values that need to be considered for filter (required) + # @return array[Pet] + # + sub findPetsByStatus($status) { + + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/pet/findByStatus"; + $resource_path =~ s/{format}/json/; + + my $method = "GET"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + # query params + if($status !== null) { + $query_params['status'] = $this->api_client->to_query_value($status); + } + + + + + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + if(!$response) { + return; + } + + $response_object = $this->api_client->deserialize($response, 'array[Pet]'); + return $responseObject; + } + + # + # findPetsByTags + # + # Finds Pets by tags + # + # @param array[string] $tags Tags to filter by (required) + # @return array[Pet] + # + sub findPetsByTags($tags) { + + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/pet/findByTags"; + $resource_path =~ s/{format}/json/; + + my $method = "GET"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + # query params + if($tags !== null) { + $query_params['tags'] = $this->api_client->to_query_value($tags); + } + + + + + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + if(!$response) { + return; + } + + $response_object = $this->api_client->deserialize($response, 'array[Pet]'); + return $responseObject; + } + + # + # getPetById + # + # Find pet by ID + # + # @param int $pet_id ID of pet that needs to be fetched (required) + # @return Pet + # + sub getPetById($pet_id) { + + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/pet/{petId}"; + $resource_path =~ s/{format}/json/; + + my $method = "GET"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + # path params + if($pet_id !== null) { + my $base_variable = "{" + "petId" + "}"; + my $base_value = $this->api_client->to_path_value($pet_id); + $resource_path = s/$base_variable/$base_value/; + } + + + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + if(!$response) { + return; + } + + $response_object = $this->api_client->deserialize($response, 'Pet'); + return $responseObject; + } + + # + # updatePetWithForm + # + # 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 updatePetWithForm($pet_id, $name, $status) { + + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/pet/{petId}"; + $resource_path =~ s/{format}/json/; + + my $method = "POST"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = 'application/x-www-form-urlencoded'; + + + + # path params + if($pet_id !== null) { + my $base_variable = "{" + "petId" + "}"; + my $base_value = $this->api_client->to_path_value($pet_id); + $resource_path = s/$base_variable/$base_value/; + } + # form params + if ($name !== null) { + $formParams->{'name'} = $this->api_client->to_form_value($name); + } # form params + if ($status !== null) { + $formParams->{'status'} = $this->api_client->to_form_value($status); + } + + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # deletePet + # + # Deletes a pet + # + # @param string $api_key (required) + # @param int $pet_id Pet id to delete (required) + # @return void + # + sub deletePet($api_key, $pet_id) { + + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/pet/{petId}"; + $resource_path =~ s/{format}/json/; + + my $method = "DELETE"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + # header params + if($api_key !== null) { + $headerParams['api_key'] = $this->apiClient->to_header_value($args[api_key]); + } + # path params + if($pet_id !== null) { + my $base_variable = "{" + "petId" + "}"; + my $base_value = $this->api_client->to_path_value($pet_id); + $resource_path = s/$base_variable/$base_value/; + } + + + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # uploadFile + # + # 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 uploadFile($pet_id, $additional_metadata, $file) { + + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/pet/{petId}/uploadImage"; + $resource_path =~ s/{format}/json/; + + my $method = "POST"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = 'multipart/form-data'; + + + + # path params + if($pet_id !== null) { + my $base_variable = "{" + "petId" + "}"; + my $base_value = $this->api_client->to_path_value($pet_id); + $resource_path = s/$base_variable/$base_value/; + } + # form params + if ($additional_metadata !== null) { + $formParams->{'additionalMetadata'} = $this->api_client->to_form_value($additional_metadata); + } # form params + if ($file !== null) { + $formParams->{'file'} = '@' . $this->api_client->to_form_value($file); + } + + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + +} + +1; diff --git a/samples/client/petstore/perl/StoreApi.pl b/samples/client/petstore/perl/StoreApi.pl new file mode 100644 index 000000000000..6ab1b62758e4 --- /dev/null +++ b/samples/client/petstore/perl/StoreApi.pl @@ -0,0 +1,264 @@ +# +# 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. +# + +require 5.6.0; +use strict; +use warnings; + +use WWW::Swagger::Model::Category; +use WWW::Swagger::Model::Pet; + +package WWW::Swagger::StoreApiAPI; + +our $VERSION = '2.09'; + + +sub new { + my $class = shift; + my $options = shift; + + croak("You must supply an API client") + unless $options->{api_client}; + + my $self = { + api_client = $option->{api_client} + } + + bless $self, $class; + +} + + + # + # getInventory + # + # Returns pet inventories by status + # + # @return map[string,int] + # + sub getInventory() { + + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/store/inventory"; + $resource_path =~ s/{format}/json/; + + my $method = "GET"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + + + + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + if(!$response) { + return; + } + + $response_object = $this->api_client->deserialize($response, 'map[string,int]'); + return $responseObject; + } + + # + # placeOrder + # + # Place an order for a pet + # + # @param Order $body order placed for purchasing the pet (required) + # @return Order + # + sub placeOrder($body) { + + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/store/order"; + $resource_path =~ s/{format}/json/; + + my $method = "POST"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + + + # body params + my $body; + if (isset($body)) { + $body = $body; + } + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + if(!$response) { + return; + } + + $response_object = $this->api_client->deserialize($response, 'Order'); + return $responseObject; + } + + # + # getOrderById + # + # Find purchase order by ID + # + # @param string $order_id ID of pet that needs to be fetched (required) + # @return Order + # + sub getOrderById($order_id) { + + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/store/order/{orderId}"; + $resource_path =~ s/{format}/json/; + + my $method = "GET"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + # path params + if($order_id !== null) { + my $base_variable = "{" + "orderId" + "}"; + my $base_value = $this->api_client->to_path_value($order_id); + $resource_path = s/$base_variable/$base_value/; + } + + + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + if(!$response) { + return; + } + + $response_object = $this->api_client->deserialize($response, 'Order'); + return $responseObject; + } + + # + # deleteOrder + # + # Delete purchase order by ID + # + # @param string $order_id ID of the order that needs to be deleted (required) + # @return void + # + sub deleteOrder($order_id) { + + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/store/order/{orderId}"; + $resource_path =~ s/{format}/json/; + + my $method = "DELETE"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + # path params + if($order_id !== null) { + my $base_variable = "{" + "orderId" + "}"; + my $base_value = $this->api_client->to_path_value($order_id); + $resource_path = s/$base_variable/$base_value/; + } + + + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + +} + +1; diff --git a/samples/client/petstore/perl/Swagger.pl b/samples/client/petstore/perl/Swagger.pl new file mode 100644 index 000000000000..3d6b77d819e8 --- /dev/null +++ b/samples/client/petstore/perl/Swagger.pl @@ -0,0 +1,326 @@ +host = $host; + $this->headerName = $headerName; + $this->headerValue = $headerValue; + } + + /** + * Set the user agent of the API client + * + * @param string $user_agent The user agent of the API client + */ + public function setUserAgent($user_agent) { + if (!is_string($user_agent)) { + throw new Exception('User-agent must be a string.'); + } + $this->user_agent= $user_agent; + } + + /** + * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] + */ + public function setTimeout($seconds) { + if (!is_numeric($seconds)) { + throw new Exception('Timeout variable must be numeric.'); + } + $this->curl_timout = $seconds; + } + + /** + * @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 + */ + public function callAPI($resourcePath, $method, $queryParams, $postData, + $headerParams) { + + $headers = array(); + + # Allow API key from $headerParams to override default + $added_api_key = False; + if ($headerParams != null) { + foreach ($headerParams as $key => $val) { + $headers[] = "$key: $val"; + if ($key == $this->headerName) { + $added_api_key = True; + } + } + } + if (! $added_api_key && $this->headerName != null) { + $headers[] = $this->headerName . ": " . $this->headerValue; + } + + if (strpos($headers['Content-Type'], "multipart/form-data") < 0 and (is_object($postData) or is_array($postData))) { + $postData = json_encode($this->sanitizeForSerialization($postData)); + } + + $url = $this->host . $resourcePath; + + $curl = curl_init(); + if ($this->curl_timout) { + curl_setopt($curl, CURLOPT_TIMEOUT, $this->curl_timout); + } + // return the result on success, rather than just TRUE + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); + + if (! empty($queryParams)) { + $url = ($url . '?' . http_build_query($queryParams)); + } + + if ($method == self::$POST) { + curl_setopt($curl, CURLOPT_POST, true); + curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); + } else if ($method == self::$PATCH) { + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH"); + curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); + } else if ($method == self::$PUT) { + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); + curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); + } else if ($method == self::$DELETE) { + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); + curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); + } else if ($method != self::$GET) { + throw new Exception('Method ' . $method . ' is not recognized.'); + } + curl_setopt($curl, CURLOPT_URL, $url); + + // Set user agent + if ($this->user_agent) { + curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent); + } else { // use PHP-Swagger as the default user agent + curl_setopt($curl, CURLOPT_USERAGENT, 'PHP-Swagger'); + } + + // Make the request + $response = curl_exec($curl); + $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); + } 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) { + throw new APIClientException("Unauthorized API request to " . $url . + ": " . serialize($response), 0, $response_info, $response); + } else if ($response_info['http_code'] == 404) { + $data = null; + } else { + throw new APIClientException("Can't connect to the api: " . $url . + " response code: " . + $response_info['http_code'], 0, $response_info, $response); + } + return $data; + } + + /** + * Build a JSON POST object + */ + protected function sanitizeForSerialization($data) + { + 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 + */ + public static function toPathValue($value) { + return rawurlencode(toString($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 + */ + public static function toQueryValue($object) { + 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 + */ + public static function toHeaderValue($value) { + return toString($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 + */ + public static function toFormValue($value) { + return toString($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 + */ + public static function toString($value) { + if ($value instanceof \DateTime) { // datetime in ISO8601 format + return $value->format(\DateTime::ISO8601); + } + else { + return $value; + } + } + + /** + * Deserialize a JSON string into an object + * + * @param object $object object or primitive to be deserialized + * @param string $class class name is passed as a string + * @return object an instance of $class + */ + + public static function deserialize($data, $class) + { + if (null === $data) { + $deserialized = null; + } elseif (substr($class, 0, 4) == 'map[') { + $inner = substr($class, 4, -1); + $values = array(); + if(strrpos($inner, ",") !== false) { + $subClass_array = explode(',', $inner, 2); + $subClass = $subClass_array[1]; + foreach ($data as $key => $value) { + $values[] = array($key => self::deserialize($value, $subClass)); + } + } + $deserialized = $values; + } elseif (strcasecmp(substr($class, 0, 6),'array[') == 0) { + $subClass = substr($class, 6, -1); + $values = array(); + foreach ($data as $key => $value) { + $values[] = self::deserialize($value, $subClass); + } + $deserialized = $values; + } elseif ($class == 'DateTime') { + $deserialized = new \DateTime($data); + } elseif (in_array($class, array('string', 'int', 'float', 'bool'))) { + settype($data, $class); + $deserialized = $data; + } else { + $instance = new $class(); + foreach ($instance::$swaggerTypes as $property => $type) { + if (isset($data->$property)) { + $original_property_name = $instance::$attributeMap[$property]; + $instance->$property = self::deserialize($data->$original_property_name, $type); + } + } + $deserialized = $instance; + } + + return $deserialized; + } + +} + +class APIClientException extends Exception { + protected $response, $response_info; + + public function __construct($message="", $code=0, $response_info=null, $response=null) { + parent::__construct($message, $code); + $this->response_info = $response_info; + $this->response = $response; + } + + public function getResponse() { + return $this->response; + } + + public function getResponseInfo() { + return $this->response_info; + } +} diff --git a/samples/client/petstore/perl/UserApi.pl b/samples/client/petstore/perl/UserApi.pl new file mode 100644 index 000000000000..49803ffa66b1 --- /dev/null +++ b/samples/client/petstore/perl/UserApi.pl @@ -0,0 +1,468 @@ +# +# 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. +# + +require 5.6.0; +use strict; +use warnings; + +use WWW::Swagger::Model::Category; +use WWW::Swagger::Model::Pet; + +package WWW::Swagger::UserApiAPI; + +our $VERSION = '2.09'; + + +sub new { + my $class = shift; + my $options = shift; + + croak("You must supply an API client") + unless $options->{api_client}; + + my $self = { + api_client = $option->{api_client} + } + + bless $self, $class; + +} + + + # + # createUser + # + # Create user + # + # @param User $body Created user object (required) + # @return void + # + sub createUser($body) { + + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/user"; + $resource_path =~ s/{format}/json/; + + my $method = "POST"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + + + # body params + my $body; + if (isset($body)) { + $body = $body; + } + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # createUsersWithArrayInput + # + # Creates list of users with given input array + # + # @param array[User] $body List of user object (required) + # @return void + # + sub createUsersWithArrayInput($body) { + + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/user/createWithArray"; + $resource_path =~ s/{format}/json/; + + my $method = "POST"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + + + # body params + my $body; + if (isset($body)) { + $body = $body; + } + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # createUsersWithListInput + # + # Creates list of users with given input array + # + # @param array[User] $body List of user object (required) + # @return void + # + sub createUsersWithListInput($body) { + + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/user/createWithList"; + $resource_path =~ s/{format}/json/; + + my $method = "POST"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + + + # body params + my $body; + if (isset($body)) { + $body = $body; + } + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # loginUser + # + # 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 loginUser($username, $password) { + + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/user/login"; + $resource_path =~ s/{format}/json/; + + my $method = "GET"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + # query params + if($username !== null) { + $query_params['username'] = $this->api_client->to_query_value($username); + } # query params + if($password !== null) { + $query_params['password'] = $this->api_client->to_query_value($password); + } + + + + + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + if(!$response) { + return; + } + + $response_object = $this->api_client->deserialize($response, 'string'); + return $responseObject; + } + + # + # logoutUser + # + # Logs out current logged in user session + # + # @return void + # + sub logoutUser() { + + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/user/logout"; + $resource_path =~ s/{format}/json/; + + my $method = "GET"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + + + + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # getUserByName + # + # Get user by user name + # + # @param string $username The name that needs to be fetched. Use user1 for testing. (required) + # @return User + # + sub getUserByName($username) { + + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/user/{username}"; + $resource_path =~ s/{format}/json/; + + my $method = "GET"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + # path params + if($username !== null) { + my $base_variable = "{" + "username" + "}"; + my $base_value = $this->api_client->to_path_value($username); + $resource_path = s/$base_variable/$base_value/; + } + + + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + if(!$response) { + return; + } + + $response_object = $this->api_client->deserialize($response, 'User'); + return $responseObject; + } + + # + # updateUser + # + # Updated user + # + # @param string $username name that need to be deleted (required) + # @param User $body Updated user object (required) + # @return void + # + sub updateUser($username, $body) { + + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/user/{username}"; + $resource_path =~ s/{format}/json/; + + my $method = "PUT"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + # path params + if($username !== null) { + my $base_variable = "{" + "username" + "}"; + my $base_value = $this->api_client->to_path_value($username); + $resource_path = s/$base_variable/$base_value/; + } + + # body params + my $body; + if (isset($body)) { + $body = $body; + } + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # deleteUser + # + # Delete user + # + # @param string $username The name that needs to be deleted (required) + # @return void + # + sub deleteUser($username) { + + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/user/{username}"; + $resource_path =~ s/{format}/json/; + + my $method = "DELETE"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + # path params + if($username !== null) { + my $base_variable = "{" + "username" + "}"; + my $base_value = $this->api_client->to_path_value($username); + $resource_path = s/$base_variable/$base_value/; + } + + + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + +} + +1; diff --git a/samples/client/petstore/perl/WWW/Swagger/Model/Category.pl b/samples/client/petstore/perl/WWW/Swagger/Model/Category.pl new file mode 100644 index 000000000000..98e7ba24800d --- /dev/null +++ b/samples/client/petstore/perl/WWW/Swagger/Model/Category.pl @@ -0,0 +1,60 @@ + 'int', + 'name' => 'string' + ); + + static $attributeMap = array( + 'id' => 'id', + 'name' => 'name' + ); + + + public $id; /* int */ + public $name; /* string */ + + public function __construct(array $data) { + $this->id = $data["id"]; + $this->name = $data["name"]; + } + + public function offsetExists($offset) { + return isset($this->$offset); + } + + public function offsetGet($offset) { + return $this->$offset; + } + + public function offsetSet($offset, $value) { + $this->$offset = $value; + } + + public function offsetUnset($offset) { + unset($this->$offset); + } +} diff --git a/samples/client/petstore/perl/WWW/Swagger/Model/Category.pm b/samples/client/petstore/perl/WWW/Swagger/Model/Category.pm new file mode 100644 index 000000000000..98e7ba24800d --- /dev/null +++ b/samples/client/petstore/perl/WWW/Swagger/Model/Category.pm @@ -0,0 +1,60 @@ + 'int', + 'name' => 'string' + ); + + static $attributeMap = array( + 'id' => 'id', + 'name' => 'name' + ); + + + public $id; /* int */ + public $name; /* string */ + + public function __construct(array $data) { + $this->id = $data["id"]; + $this->name = $data["name"]; + } + + public function offsetExists($offset) { + return isset($this->$offset); + } + + public function offsetGet($offset) { + return $this->$offset; + } + + public function offsetSet($offset, $value) { + $this->$offset = $value; + } + + public function offsetUnset($offset) { + unset($this->$offset); + } +} diff --git a/samples/client/petstore/perl/WWW/Swagger/Model/Order.pl b/samples/client/petstore/perl/WWW/Swagger/Model/Order.pl new file mode 100644 index 000000000000..2770e8bbbdf1 --- /dev/null +++ b/samples/client/petstore/perl/WWW/Swagger/Model/Order.pl @@ -0,0 +1,79 @@ + 'int', + 'pet_id' => 'int', + 'quantity' => 'int', + 'ship_date' => 'DateTime', + 'status' => 'string', + 'complete' => 'boolean' + ); + + static $attributeMap = array( + 'id' => 'id', + 'pet_id' => 'petId', + 'quantity' => 'quantity', + 'ship_date' => 'shipDate', + 'status' => 'status', + 'complete' => 'complete' + ); + + + public $id; /* int */ + public $pet_id; /* int */ + public $quantity; /* int */ + public $ship_date; /* DateTime */ + /** + * Order Status + */ + public $status; /* string */ + public $complete; /* boolean */ + + public function __construct(array $data) { + $this->id = $data["id"]; + $this->pet_id = $data["pet_id"]; + $this->quantity = $data["quantity"]; + $this->ship_date = $data["ship_date"]; + $this->status = $data["status"]; + $this->complete = $data["complete"]; + } + + public function offsetExists($offset) { + return isset($this->$offset); + } + + public function offsetGet($offset) { + return $this->$offset; + } + + public function offsetSet($offset, $value) { + $this->$offset = $value; + } + + public function offsetUnset($offset) { + unset($this->$offset); + } +} diff --git a/samples/client/petstore/perl/WWW/Swagger/Model/Order.pm b/samples/client/petstore/perl/WWW/Swagger/Model/Order.pm new file mode 100644 index 000000000000..2770e8bbbdf1 --- /dev/null +++ b/samples/client/petstore/perl/WWW/Swagger/Model/Order.pm @@ -0,0 +1,79 @@ + 'int', + 'pet_id' => 'int', + 'quantity' => 'int', + 'ship_date' => 'DateTime', + 'status' => 'string', + 'complete' => 'boolean' + ); + + static $attributeMap = array( + 'id' => 'id', + 'pet_id' => 'petId', + 'quantity' => 'quantity', + 'ship_date' => 'shipDate', + 'status' => 'status', + 'complete' => 'complete' + ); + + + public $id; /* int */ + public $pet_id; /* int */ + public $quantity; /* int */ + public $ship_date; /* DateTime */ + /** + * Order Status + */ + public $status; /* string */ + public $complete; /* boolean */ + + public function __construct(array $data) { + $this->id = $data["id"]; + $this->pet_id = $data["pet_id"]; + $this->quantity = $data["quantity"]; + $this->ship_date = $data["ship_date"]; + $this->status = $data["status"]; + $this->complete = $data["complete"]; + } + + public function offsetExists($offset) { + return isset($this->$offset); + } + + public function offsetGet($offset) { + return $this->$offset; + } + + public function offsetSet($offset, $value) { + $this->$offset = $value; + } + + public function offsetUnset($offset) { + unset($this->$offset); + } +} diff --git a/samples/client/petstore/perl/WWW/Swagger/Model/Pet.pl b/samples/client/petstore/perl/WWW/Swagger/Model/Pet.pl new file mode 100644 index 000000000000..eee7fa3784cd --- /dev/null +++ b/samples/client/petstore/perl/WWW/Swagger/Model/Pet.pl @@ -0,0 +1,79 @@ + 'int', + 'category' => 'Category', + 'name' => 'string', + 'photo_urls' => 'array[string]', + 'tags' => 'array[Tag]', + 'status' => 'string' + ); + + static $attributeMap = array( + 'id' => 'id', + 'category' => 'category', + 'name' => 'name', + 'photo_urls' => 'photoUrls', + 'tags' => 'tags', + 'status' => 'status' + ); + + + public $id; /* int */ + public $category; /* Category */ + public $name; /* string */ + public $photo_urls; /* array[string] */ + public $tags; /* array[Tag] */ + /** + * pet status in the store + */ + public $status; /* string */ + + public function __construct(array $data) { + $this->id = $data["id"]; + $this->category = $data["category"]; + $this->name = $data["name"]; + $this->photo_urls = $data["photo_urls"]; + $this->tags = $data["tags"]; + $this->status = $data["status"]; + } + + public function offsetExists($offset) { + return isset($this->$offset); + } + + public function offsetGet($offset) { + return $this->$offset; + } + + public function offsetSet($offset, $value) { + $this->$offset = $value; + } + + public function offsetUnset($offset) { + unset($this->$offset); + } +} diff --git a/samples/client/petstore/perl/WWW/Swagger/Model/Pet.pm b/samples/client/petstore/perl/WWW/Swagger/Model/Pet.pm new file mode 100644 index 000000000000..eee7fa3784cd --- /dev/null +++ b/samples/client/petstore/perl/WWW/Swagger/Model/Pet.pm @@ -0,0 +1,79 @@ + 'int', + 'category' => 'Category', + 'name' => 'string', + 'photo_urls' => 'array[string]', + 'tags' => 'array[Tag]', + 'status' => 'string' + ); + + static $attributeMap = array( + 'id' => 'id', + 'category' => 'category', + 'name' => 'name', + 'photo_urls' => 'photoUrls', + 'tags' => 'tags', + 'status' => 'status' + ); + + + public $id; /* int */ + public $category; /* Category */ + public $name; /* string */ + public $photo_urls; /* array[string] */ + public $tags; /* array[Tag] */ + /** + * pet status in the store + */ + public $status; /* string */ + + public function __construct(array $data) { + $this->id = $data["id"]; + $this->category = $data["category"]; + $this->name = $data["name"]; + $this->photo_urls = $data["photo_urls"]; + $this->tags = $data["tags"]; + $this->status = $data["status"]; + } + + public function offsetExists($offset) { + return isset($this->$offset); + } + + public function offsetGet($offset) { + return $this->$offset; + } + + public function offsetSet($offset, $value) { + $this->$offset = $value; + } + + public function offsetUnset($offset) { + unset($this->$offset); + } +} diff --git a/samples/client/petstore/perl/WWW/Swagger/Model/Tag.pl b/samples/client/petstore/perl/WWW/Swagger/Model/Tag.pl new file mode 100644 index 000000000000..f8efc998df66 --- /dev/null +++ b/samples/client/petstore/perl/WWW/Swagger/Model/Tag.pl @@ -0,0 +1,60 @@ + 'int', + 'name' => 'string' + ); + + static $attributeMap = array( + 'id' => 'id', + 'name' => 'name' + ); + + + public $id; /* int */ + public $name; /* string */ + + public function __construct(array $data) { + $this->id = $data["id"]; + $this->name = $data["name"]; + } + + public function offsetExists($offset) { + return isset($this->$offset); + } + + public function offsetGet($offset) { + return $this->$offset; + } + + public function offsetSet($offset, $value) { + $this->$offset = $value; + } + + public function offsetUnset($offset) { + unset($this->$offset); + } +} diff --git a/samples/client/petstore/perl/WWW/Swagger/Model/Tag.pm b/samples/client/petstore/perl/WWW/Swagger/Model/Tag.pm new file mode 100644 index 000000000000..f8efc998df66 --- /dev/null +++ b/samples/client/petstore/perl/WWW/Swagger/Model/Tag.pm @@ -0,0 +1,60 @@ + 'int', + 'name' => 'string' + ); + + static $attributeMap = array( + 'id' => 'id', + 'name' => 'name' + ); + + + public $id; /* int */ + public $name; /* string */ + + public function __construct(array $data) { + $this->id = $data["id"]; + $this->name = $data["name"]; + } + + public function offsetExists($offset) { + return isset($this->$offset); + } + + public function offsetGet($offset) { + return $this->$offset; + } + + public function offsetSet($offset, $value) { + $this->$offset = $value; + } + + public function offsetUnset($offset) { + unset($this->$offset); + } +} diff --git a/samples/client/petstore/perl/WWW/Swagger/Model/User.pl b/samples/client/petstore/perl/WWW/Swagger/Model/User.pl new file mode 100644 index 000000000000..d6b520eba51d --- /dev/null +++ b/samples/client/petstore/perl/WWW/Swagger/Model/User.pl @@ -0,0 +1,87 @@ + 'int', + 'username' => 'string', + 'first_name' => 'string', + 'last_name' => 'string', + 'email' => 'string', + 'password' => 'string', + 'phone' => 'string', + 'user_status' => 'int' + ); + + static $attributeMap = array( + 'id' => 'id', + 'username' => 'username', + 'first_name' => 'firstName', + 'last_name' => 'lastName', + 'email' => 'email', + 'password' => 'password', + 'phone' => 'phone', + 'user_status' => 'userStatus' + ); + + + public $id; /* int */ + public $username; /* string */ + public $first_name; /* string */ + public $last_name; /* string */ + public $email; /* string */ + public $password; /* string */ + public $phone; /* string */ + /** + * User Status + */ + public $user_status; /* int */ + + public function __construct(array $data) { + $this->id = $data["id"]; + $this->username = $data["username"]; + $this->first_name = $data["first_name"]; + $this->last_name = $data["last_name"]; + $this->email = $data["email"]; + $this->password = $data["password"]; + $this->phone = $data["phone"]; + $this->user_status = $data["user_status"]; + } + + public function offsetExists($offset) { + return isset($this->$offset); + } + + public function offsetGet($offset) { + return $this->$offset; + } + + public function offsetSet($offset, $value) { + $this->$offset = $value; + } + + public function offsetUnset($offset) { + unset($this->$offset); + } +} diff --git a/samples/client/petstore/perl/WWW/Swagger/Model/User.pm b/samples/client/petstore/perl/WWW/Swagger/Model/User.pm new file mode 100644 index 000000000000..d6b520eba51d --- /dev/null +++ b/samples/client/petstore/perl/WWW/Swagger/Model/User.pm @@ -0,0 +1,87 @@ + 'int', + 'username' => 'string', + 'first_name' => 'string', + 'last_name' => 'string', + 'email' => 'string', + 'password' => 'string', + 'phone' => 'string', + 'user_status' => 'int' + ); + + static $attributeMap = array( + 'id' => 'id', + 'username' => 'username', + 'first_name' => 'firstName', + 'last_name' => 'lastName', + 'email' => 'email', + 'password' => 'password', + 'phone' => 'phone', + 'user_status' => 'userStatus' + ); + + + public $id; /* int */ + public $username; /* string */ + public $first_name; /* string */ + public $last_name; /* string */ + public $email; /* string */ + public $password; /* string */ + public $phone; /* string */ + /** + * User Status + */ + public $user_status; /* int */ + + public function __construct(array $data) { + $this->id = $data["id"]; + $this->username = $data["username"]; + $this->first_name = $data["first_name"]; + $this->last_name = $data["last_name"]; + $this->email = $data["email"]; + $this->password = $data["password"]; + $this->phone = $data["phone"]; + $this->user_status = $data["user_status"]; + } + + public function offsetExists($offset) { + return isset($this->$offset); + } + + public function offsetGet($offset) { + return $this->$offset; + } + + public function offsetSet($offset, $value) { + $this->$offset = $value; + } + + public function offsetUnset($offset) { + unset($this->$offset); + } +} diff --git a/samples/client/petstore/perl/WWW/Swagger/PetApi.pl b/samples/client/petstore/perl/WWW/Swagger/PetApi.pl new file mode 100644 index 000000000000..5d876b4b61e7 --- /dev/null +++ b/samples/client/petstore/perl/WWW/Swagger/PetApi.pl @@ -0,0 +1,481 @@ +# +# 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. +# + +require 5.6.0; +use strict; +use warnings; + +use WWW::Swagger::Model::Category; +use WWW::Swagger::Model::Pet; + +package WWW::Swagger::PetApiAPI; + +our $VERSION = '2.09'; + + +sub new { + my $class = shift; + my $options = shift; + + croak("You must supply an API client") + unless $options->{api_client}; + + my $self = { + api_client = $option->{api_client} + } + + bless $self, $class; + +} + + + # + # updatePet + # + # Update an existing pet + # + # @param Pet $body Pet object that needs to be added to the store (required) + # @return void + # + sub updatePet { + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/pet"; + $resource_path =~ s/{format}/json/; + + my $method = "PUT"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = 'application/json,application/xml'; + + + + + + # body params + my $body; + if (isset($body)) { + $body = $body; + } + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # addPet + # + # Add a new pet to the store + # + # @param Pet $body Pet object that needs to be added to the store (required) + # @return void + # + sub addPet { + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/pet"; + $resource_path =~ s/{format}/json/; + + my $method = "POST"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = 'application/json,application/xml'; + + + + + + # body params + my $body; + if (isset($body)) { + $body = $body; + } + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # findPetsByStatus + # + # Finds Pets by status + # + # @param array[string] $status Status values that need to be considered for filter (required) + # @return array[Pet] + # + sub findPetsByStatus { + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/pet/findByStatus"; + $resource_path =~ s/{format}/json/; + + my $method = "GET"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + # query params + if($status !== null) { + $query_params['status'] = $this->api_client->to_query_value($status); + } + + + + + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + if(!$response) { + return; + } + + $response_object = $this->api_client->deserialize($response, 'array[Pet]'); + return $responseObject; + } + + # + # findPetsByTags + # + # Finds Pets by tags + # + # @param array[string] $tags Tags to filter by (required) + # @return array[Pet] + # + sub findPetsByTags { + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/pet/findByTags"; + $resource_path =~ s/{format}/json/; + + my $method = "GET"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + # query params + if($tags !== null) { + $query_params['tags'] = $this->api_client->to_query_value($tags); + } + + + + + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + if(!$response) { + return; + } + + $response_object = $this->api_client->deserialize($response, 'array[Pet]'); + return $responseObject; + } + + # + # getPetById + # + # Find pet by ID + # + # @param int $pet_id ID of pet that needs to be fetched (required) + # @return Pet + # + sub getPetById { + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/pet/{petId}"; + $resource_path =~ s/{format}/json/; + + my $method = "GET"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + # path params + if($pet_id !== null) { + my $base_variable = "{" + "petId" + "}"; + my $base_value = $this->api_client->to_path_value($pet_id); + $resource_path = s/$base_variable/$base_value/; + } + + + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + if(!$response) { + return; + } + + $response_object = $this->api_client->deserialize($response, 'Pet'); + return $responseObject; + } + + # + # updatePetWithForm + # + # 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 updatePetWithForm { + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/pet/{petId}"; + $resource_path =~ s/{format}/json/; + + my $method = "POST"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = 'application/x-www-form-urlencoded'; + + + + # path params + if($pet_id !== null) { + my $base_variable = "{" + "petId" + "}"; + my $base_value = $this->api_client->to_path_value($pet_id); + $resource_path = s/$base_variable/$base_value/; + } + # form params + if ($name !== null) { + $formParams->{'name'} = $this->api_client->to_form_value($name); + } # form params + if ($status !== null) { + $formParams->{'status'} = $this->api_client->to_form_value($status); + } + + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # deletePet + # + # Deletes a pet + # + # @param string $api_key (required) + # @param int $pet_id Pet id to delete (required) + # @return void + # + sub deletePet { + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/pet/{petId}"; + $resource_path =~ s/{format}/json/; + + my $method = "DELETE"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + # header params + if($api_key !== null) { + $headerParams['api_key'] = $this->apiClient->to_header_value($args[api_key]); + } + # path params + if($pet_id !== null) { + my $base_variable = "{" + "petId" + "}"; + my $base_value = $this->api_client->to_path_value($pet_id); + $resource_path = s/$base_variable/$base_value/; + } + + + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # uploadFile + # + # 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 uploadFile { + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/pet/{petId}/uploadImage"; + $resource_path =~ s/{format}/json/; + + my $method = "POST"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = 'multipart/form-data'; + + + + # path params + if($pet_id !== null) { + my $base_variable = "{" + "petId" + "}"; + my $base_value = $this->api_client->to_path_value($pet_id); + $resource_path = s/$base_variable/$base_value/; + } + # form params + if ($additional_metadata !== null) { + $formParams->{'additionalMetadata'} = $this->api_client->to_form_value($additional_metadata); + } # form params + if ($file !== null) { + $formParams->{'file'} = '@' . $this->api_client->to_form_value($file); + } + + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + +} + +1; diff --git a/samples/client/petstore/perl/WWW/Swagger/PetApi.pm b/samples/client/petstore/perl/WWW/Swagger/PetApi.pm new file mode 100644 index 000000000000..a76ed8054ba1 --- /dev/null +++ b/samples/client/petstore/perl/WWW/Swagger/PetApi.pm @@ -0,0 +1,486 @@ +# +# 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. +# + +require 5.6.0; +use strict; +use warnings; + +#use WWW::Swagger::Model::Category; +#use WWW::Swagger::Model::Pet; + +package WWW::Swagger::PetApi; + +our $VERSION = '2.09'; + + +sub new { + my $class = shift; + my $options = shift; + + croak("You must supply an API client") + unless $options->{api_client}; + + my $self = { + api_client => $options->{api_client} + }; + + bless $self, $class; + +} + + + # + # updatePet + # + # Update an existing pet + # + # @param Pet $body Pet object that needs to be added to the store (required) + # @return void + # + sub updatePet { + my $self = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/pet"; + $resource_path =~ s/{format}/json/; + + my $method = "PUT"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = 'application/json,application/xml'; + + + + + + my $body; + # body params + if (isset($body)) { + $body = $body; + } + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # addPet + # + # Add a new pet to the store + # + # @param Pet $body Pet object that needs to be added to the store (required) + # @return void + # + sub addPet { + my $self = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/pet"; + $resource_path =~ s/{format}/json/; + + my $method = "POST"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = 'application/json,application/xml'; + + + + + + my $body; + # body params + if (isset($body)) { + $body = $body; + } + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # findPetsByStatus + # + # Finds Pets by status + # + # @param array[string] $status Status values that need to be considered for filter (required) + # @return array[Pet] + # + sub findPetsByStatus { + my $self = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/pet/findByStatus"; + $resource_path =~ s/{format}/json/; + + my $method = "GET"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + # query params + if($args{ status }) { + $query_params->{'status'} = $self->api_client->to_query_value($args{ status }); + } + + + + my $body; + + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + if(!$response) { + return; + } + + my $response_object = $self->api_client->deserialize($response, 'array[Pet]'); + return $response_object; + } + + # + # findPetsByTags + # + # Finds Pets by tags + # + # @param array[string] $tags Tags to filter by (required) + # @return array[Pet] + # + sub findPetsByTags { + my $self = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/pet/findByTags"; + $resource_path =~ s/{format}/json/; + + my $method = "GET"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + # query params + if($args{ tags }) { + $query_params->{'tags'} = $self->api_client->to_query_value($args{ tags }); + } + + + + my $body; + + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + if(!$response) { + return; + } + + my $response_object = $self->api_client->deserialize($response, 'array[Pet]'); + return $response_object; + } + + # + # getPetById + # + # Find pet by ID + # + # @param int $pet_id ID of pet that needs to be fetched (required) + # @return Pet + # + sub getPetById { + my $self = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/pet/{petId}"; + $resource_path =~ s/{format}/json/; + + my $method = "GET"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + # path params + if( $args{ pet_id }) { + my $base_variable = "{" + "petId" + "}"; + my $base_value = $self->api_client->to_path_value($args{ pet_id }); + $resource_path = s/$base_variable/$base_value/; + } + + my $body; + + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + if(!$response) { + return; + } + + my $response_object = $self->api_client->deserialize($response, 'Pet'); + return $response_object; + } + + # + # updatePetWithForm + # + # 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 updatePetWithForm { + my $self = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/pet/{petId}"; + $resource_path =~ s/{format}/json/; + + my $method = "POST"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = 'application/x-www-form-urlencoded'; + + + + # path params + if( $args{ pet_id }) { + my $base_variable = "{" + "petId" + "}"; + my $base_value = $self->api_client->to_path_value($args{ pet_id }); + $resource_path = s/$base_variable/$base_value/; + } + # form params + if ($args{ name }) { + $form_params->{'name'} = $self->api_client->to_form_value($args{ name }); + } # form params + if ($args{ status }) { + $form_params->{'status'} = $self->api_client->to_form_value($args{ status }); + } + my $body; + + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # deletePet + # + # Deletes a pet + # + # @param string $api_key (required) + # @param int $pet_id Pet id to delete (required) + # @return void + # + sub deletePet { + my $self = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/pet/{petId}"; + $resource_path =~ s/{format}/json/; + + my $method = "DELETE"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + # header params + if($args{ api_key }) { + $header_params->{'api_key'} = $self->apiClient->to_header_value($args{ api_key }); + } + # path params + if( $args{ pet_id }) { + my $base_variable = "{" + "petId" + "}"; + my $base_value = $self->api_client->to_path_value($args{ pet_id }); + $resource_path = s/$base_variable/$base_value/; + } + + my $body; + + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # uploadFile + # + # 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 uploadFile { + my $self = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/pet/{petId}/uploadImage"; + $resource_path =~ s/{format}/json/; + + my $method = "POST"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = 'multipart/form-data'; + + + + # path params + if( $args{ pet_id }) { + my $base_variable = "{" + "petId" + "}"; + my $base_value = $self->api_client->to_path_value($args{ pet_id }); + $resource_path = s/$base_variable/$base_value/; + } + # form params + if ($args{ additional_metadata }) { + $form_params->{'additionalMetadata'} = $self->api_client->to_form_value($args{ additional_metadata }); + } # form params + if ($args{ file }) { + $form_params->{'file'} = '@' . $self->api_client->to_form_value($args{ file }); + } + my $body; + + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + + +1; diff --git a/samples/client/petstore/perl/WWW/Swagger/StoreApi.pl b/samples/client/petstore/perl/WWW/Swagger/StoreApi.pl new file mode 100644 index 000000000000..64c20c71a662 --- /dev/null +++ b/samples/client/petstore/perl/WWW/Swagger/StoreApi.pl @@ -0,0 +1,260 @@ +# +# 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. +# + +require 5.6.0; +use strict; +use warnings; + +use WWW::Swagger::Model::Category; +use WWW::Swagger::Model::Pet; + +package WWW::Swagger::StoreApiAPI; + +our $VERSION = '2.09'; + + +sub new { + my $class = shift; + my $options = shift; + + croak("You must supply an API client") + unless $options->{api_client}; + + my $self = { + api_client = $option->{api_client} + } + + bless $self, $class; + +} + + + # + # getInventory + # + # Returns pet inventories by status + # + # @return map[string,int] + # + sub getInventory { + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/store/inventory"; + $resource_path =~ s/{format}/json/; + + my $method = "GET"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + + + + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + if(!$response) { + return; + } + + $response_object = $this->api_client->deserialize($response, 'map[string,int]'); + return $responseObject; + } + + # + # placeOrder + # + # Place an order for a pet + # + # @param Order $body order placed for purchasing the pet (required) + # @return Order + # + sub placeOrder { + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/store/order"; + $resource_path =~ s/{format}/json/; + + my $method = "POST"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + + + # body params + my $body; + if (isset($body)) { + $body = $body; + } + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + if(!$response) { + return; + } + + $response_object = $this->api_client->deserialize($response, 'Order'); + return $responseObject; + } + + # + # getOrderById + # + # Find purchase order by ID + # + # @param string $order_id ID of pet that needs to be fetched (required) + # @return Order + # + sub getOrderById { + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/store/order/{orderId}"; + $resource_path =~ s/{format}/json/; + + my $method = "GET"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + # path params + if($order_id !== null) { + my $base_variable = "{" + "orderId" + "}"; + my $base_value = $this->api_client->to_path_value($order_id); + $resource_path = s/$base_variable/$base_value/; + } + + + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + if(!$response) { + return; + } + + $response_object = $this->api_client->deserialize($response, 'Order'); + return $responseObject; + } + + # + # deleteOrder + # + # Delete purchase order by ID + # + # @param string $order_id ID of the order that needs to be deleted (required) + # @return void + # + sub deleteOrder { + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/store/order/{orderId}"; + $resource_path =~ s/{format}/json/; + + my $method = "DELETE"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + # path params + if($order_id !== null) { + my $base_variable = "{" + "orderId" + "}"; + my $base_value = $this->api_client->to_path_value($order_id); + $resource_path = s/$base_variable/$base_value/; + } + + + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + +} + +1; diff --git a/samples/client/petstore/perl/WWW/Swagger/StoreApi.pm b/samples/client/petstore/perl/WWW/Swagger/StoreApi.pm new file mode 100644 index 000000000000..a9e412ba32c7 --- /dev/null +++ b/samples/client/petstore/perl/WWW/Swagger/StoreApi.pm @@ -0,0 +1,262 @@ +# +# 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. +# + +require 5.6.0; +use strict; +use warnings; + +#use WWW::Swagger::Model::Category; +#use WWW::Swagger::Model::Pet; + +package WWW::Swagger::StoreApi; + +our $VERSION = '2.09'; + + +sub new { + my $class = shift; + my $options = shift; + + croak("You must supply an API client") + unless $options->{api_client}; + + my $self = { + api_client => $options->{api_client} + }; + + bless $self, $class; + +} + + + # + # getInventory + # + # Returns pet inventories by status + # + # @return map[string,int] + # + sub getInventory { + my $self = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/store/inventory"; + $resource_path =~ s/{format}/json/; + + my $method = "GET"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + + + my $body; + + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + if(!$response) { + return; + } + + my $response_object = $self->api_client->deserialize($response, 'map[string,int]'); + return $response_object; + } + + # + # placeOrder + # + # Place an order for a pet + # + # @param Order $body order placed for purchasing the pet (required) + # @return Order + # + sub placeOrder { + my $self = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/store/order"; + $resource_path =~ s/{format}/json/; + + my $method = "POST"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + + + my $body; + # body params + if (isset($body)) { + $body = $body; + } + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + if(!$response) { + return; + } + + my $response_object = $self->api_client->deserialize($response, 'Order'); + return $response_object; + } + + # + # getOrderById + # + # Find purchase order by ID + # + # @param string $order_id ID of pet that needs to be fetched (required) + # @return Order + # + sub getOrderById { + my $self = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/store/order/{orderId}"; + $resource_path =~ s/{format}/json/; + + my $method = "GET"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + # path params + if( $args{ order_id }) { + my $base_variable = "{" + "orderId" + "}"; + my $base_value = $self->api_client->to_path_value($args{ order_id }); + $resource_path = s/$base_variable/$base_value/; + } + + my $body; + + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + if(!$response) { + return; + } + + my $response_object = $self->api_client->deserialize($response, 'Order'); + return $response_object; + } + + # + # deleteOrder + # + # Delete purchase order by ID + # + # @param string $order_id ID of the order that needs to be deleted (required) + # @return void + # + sub deleteOrder { + my $self = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/store/order/{orderId}"; + $resource_path =~ s/{format}/json/; + + my $method = "DELETE"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + # path params + if( $args{ order_id }) { + my $base_variable = "{" + "orderId" + "}"; + my $base_value = $self->api_client->to_path_value($args{ order_id }); + $resource_path = s/$base_variable/$base_value/; + } + + my $body; + + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + + +1; diff --git a/samples/client/petstore/perl/WWW/Swagger/UserApi.pl b/samples/client/petstore/perl/WWW/Swagger/UserApi.pl new file mode 100644 index 000000000000..ba2877560fb7 --- /dev/null +++ b/samples/client/petstore/perl/WWW/Swagger/UserApi.pl @@ -0,0 +1,460 @@ +# +# 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. +# + +require 5.6.0; +use strict; +use warnings; + +use WWW::Swagger::Model::Category; +use WWW::Swagger::Model::Pet; + +package WWW::Swagger::UserApiAPI; + +our $VERSION = '2.09'; + + +sub new { + my $class = shift; + my $options = shift; + + croak("You must supply an API client") + unless $options->{api_client}; + + my $self = { + api_client = $option->{api_client} + } + + bless $self, $class; + +} + + + # + # createUser + # + # Create user + # + # @param User $body Created user object (required) + # @return void + # + sub createUser { + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/user"; + $resource_path =~ s/{format}/json/; + + my $method = "POST"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + + + # body params + my $body; + if (isset($body)) { + $body = $body; + } + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # createUsersWithArrayInput + # + # Creates list of users with given input array + # + # @param array[User] $body List of user object (required) + # @return void + # + sub createUsersWithArrayInput { + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/user/createWithArray"; + $resource_path =~ s/{format}/json/; + + my $method = "POST"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + + + # body params + my $body; + if (isset($body)) { + $body = $body; + } + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # createUsersWithListInput + # + # Creates list of users with given input array + # + # @param array[User] $body List of user object (required) + # @return void + # + sub createUsersWithListInput { + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/user/createWithList"; + $resource_path =~ s/{format}/json/; + + my $method = "POST"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + + + # body params + my $body; + if (isset($body)) { + $body = $body; + } + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # loginUser + # + # 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 loginUser { + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/user/login"; + $resource_path =~ s/{format}/json/; + + my $method = "GET"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + # query params + if($username !== null) { + $query_params['username'] = $this->api_client->to_query_value($username); + } # query params + if($password !== null) { + $query_params['password'] = $this->api_client->to_query_value($password); + } + + + + + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + if(!$response) { + return; + } + + $response_object = $this->api_client->deserialize($response, 'string'); + return $responseObject; + } + + # + # logoutUser + # + # Logs out current logged in user session + # + # @return void + # + sub logoutUser { + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/user/logout"; + $resource_path =~ s/{format}/json/; + + my $method = "GET"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + + + + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # getUserByName + # + # Get user by user name + # + # @param string $username The name that needs to be fetched. Use user1 for testing. (required) + # @return User + # + sub getUserByName { + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/user/{username}"; + $resource_path =~ s/{format}/json/; + + my $method = "GET"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + # path params + if($username !== null) { + my $base_variable = "{" + "username" + "}"; + my $base_value = $this->api_client->to_path_value($username); + $resource_path = s/$base_variable/$base_value/; + } + + + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + if(!$response) { + return; + } + + $response_object = $this->api_client->deserialize($response, 'User'); + return $responseObject; + } + + # + # updateUser + # + # Updated user + # + # @param string $username name that need to be deleted (required) + # @param User $body Updated user object (required) + # @return void + # + sub updateUser { + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/user/{username}"; + $resource_path =~ s/{format}/json/; + + my $method = "PUT"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + # path params + if($username !== null) { + my $base_variable = "{" + "username" + "}"; + my $base_value = $this->api_client->to_path_value($username); + $resource_path = s/$base_variable/$base_value/; + } + + # body params + my $body; + if (isset($body)) { + $body = $body; + } + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # deleteUser + # + # Delete user + # + # @param string $username The name that needs to be deleted (required) + # @return void + # + sub deleteUser { + my $self = shift; + my %args = @_; + + // parse inputs + my $resource_path = "/user/{username}"; + $resource_path =~ s/{format}/json/; + + my $method = "DELETE"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + # path params + if($username !== null) { + my $base_variable = "{" + "username" + "}"; + my $base_value = $this->api_client->to_path_value($username); + $resource_path = s/$base_variable/$base_value/; + } + + + + # for HTTP post (form) + $body = $body ?: $formParams; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + +} + +1; diff --git a/samples/client/petstore/perl/WWW/Swagger/UserApi.pm b/samples/client/petstore/perl/WWW/Swagger/UserApi.pm new file mode 100644 index 000000000000..375f6eaf0c10 --- /dev/null +++ b/samples/client/petstore/perl/WWW/Swagger/UserApi.pm @@ -0,0 +1,463 @@ +# +# 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. +# + +require 5.6.0; +use strict; +use warnings; + +#use WWW::Swagger::Model::Category; +#use WWW::Swagger::Model::Pet; + +package WWW::Swagger::UserApi; + +our $VERSION = '2.09'; + + +sub new { + my $class = shift; + my $options = shift; + + croak("You must supply an API client") + unless $options->{api_client}; + + my $self = { + api_client => $options->{api_client} + }; + + bless $self, $class; + +} + + + # + # createUser + # + # Create user + # + # @param User $body Created user object (required) + # @return void + # + sub createUser { + my $self = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/user"; + $resource_path =~ s/{format}/json/; + + my $method = "POST"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + + + my $body; + # body params + if (isset($body)) { + $body = $body; + } + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # createUsersWithArrayInput + # + # Creates list of users with given input array + # + # @param array[User] $body List of user object (required) + # @return void + # + sub createUsersWithArrayInput { + my $self = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/user/createWithArray"; + $resource_path =~ s/{format}/json/; + + my $method = "POST"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + + + my $body; + # body params + if (isset($body)) { + $body = $body; + } + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # createUsersWithListInput + # + # Creates list of users with given input array + # + # @param array[User] $body List of user object (required) + # @return void + # + sub createUsersWithListInput { + my $self = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/user/createWithList"; + $resource_path =~ s/{format}/json/; + + my $method = "POST"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + + + my $body; + # body params + if (isset($body)) { + $body = $body; + } + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # loginUser + # + # 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 loginUser { + my $self = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/user/login"; + $resource_path =~ s/{format}/json/; + + my $method = "GET"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + # query params + if($args{ username }) { + $query_params->{'username'} = $self->api_client->to_query_value($args{ username }); + } # query params + if($args{ password }) { + $query_params->{'password'} = $self->api_client->to_query_value($args{ password }); + } + + + + my $body; + + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + if(!$response) { + return; + } + + my $response_object = $self->api_client->deserialize($response, 'string'); + return $response_object; + } + + # + # logoutUser + # + # Logs out current logged in user session + # + # @return void + # + sub logoutUser { + my $self = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/user/logout"; + $resource_path =~ s/{format}/json/; + + my $method = "GET"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + + + my $body; + + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # getUserByName + # + # Get user by user name + # + # @param string $username The name that needs to be fetched. Use user1 for testing. (required) + # @return User + # + sub getUserByName { + my $self = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/user/{username}"; + $resource_path =~ s/{format}/json/; + + my $method = "GET"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + # path params + if( $args{ username }) { + my $base_variable = "{" + "username" + "}"; + my $base_value = $self->api_client->to_path_value($args{ username }); + $resource_path = s/$base_variable/$base_value/; + } + + my $body; + + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + if(!$response) { + return; + } + + my $response_object = $self->api_client->deserialize($response, 'User'); + return $response_object; + } + + # + # updateUser + # + # Updated user + # + # @param string $username name that need to be deleted (required) + # @param User $body Updated user object (required) + # @return void + # + sub updateUser { + my $self = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/user/{username}"; + $resource_path =~ s/{format}/json/; + + my $method = "PUT"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + # path params + if( $args{ username }) { + my $base_variable = "{" + "username" + "}"; + my $base_value = $self->api_client->to_path_value($args{ username }); + $resource_path = s/$base_variable/$base_value/; + } + + my $body; + # body params + if (isset($body)) { + $body = $body; + } + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # deleteUser + # + # Delete user + # + # @param string $username The name that needs to be deleted (required) + # @return void + # + sub deleteUser { + my $self = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/user/{username}"; + $resource_path =~ s/{format}/json/; + + my $method = "DELETE"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + # path params + if( $args{ username }) { + my $base_variable = "{" + "username" + "}"; + my $base_value = $self->api_client->to_path_value($args{ username }); + $resource_path = s/$base_variable/$base_value/; + } + + my $body; + + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + + +1; diff --git a/samples/client/petstore/perl/models/Category.pl b/samples/client/petstore/perl/models/Category.pl new file mode 100644 index 000000000000..98e7ba24800d --- /dev/null +++ b/samples/client/petstore/perl/models/Category.pl @@ -0,0 +1,60 @@ + 'int', + 'name' => 'string' + ); + + static $attributeMap = array( + 'id' => 'id', + 'name' => 'name' + ); + + + public $id; /* int */ + public $name; /* string */ + + public function __construct(array $data) { + $this->id = $data["id"]; + $this->name = $data["name"]; + } + + public function offsetExists($offset) { + return isset($this->$offset); + } + + public function offsetGet($offset) { + return $this->$offset; + } + + public function offsetSet($offset, $value) { + $this->$offset = $value; + } + + public function offsetUnset($offset) { + unset($this->$offset); + } +} diff --git a/samples/client/petstore/perl/models/Order.pl b/samples/client/petstore/perl/models/Order.pl new file mode 100644 index 000000000000..2770e8bbbdf1 --- /dev/null +++ b/samples/client/petstore/perl/models/Order.pl @@ -0,0 +1,79 @@ + 'int', + 'pet_id' => 'int', + 'quantity' => 'int', + 'ship_date' => 'DateTime', + 'status' => 'string', + 'complete' => 'boolean' + ); + + static $attributeMap = array( + 'id' => 'id', + 'pet_id' => 'petId', + 'quantity' => 'quantity', + 'ship_date' => 'shipDate', + 'status' => 'status', + 'complete' => 'complete' + ); + + + public $id; /* int */ + public $pet_id; /* int */ + public $quantity; /* int */ + public $ship_date; /* DateTime */ + /** + * Order Status + */ + public $status; /* string */ + public $complete; /* boolean */ + + public function __construct(array $data) { + $this->id = $data["id"]; + $this->pet_id = $data["pet_id"]; + $this->quantity = $data["quantity"]; + $this->ship_date = $data["ship_date"]; + $this->status = $data["status"]; + $this->complete = $data["complete"]; + } + + public function offsetExists($offset) { + return isset($this->$offset); + } + + public function offsetGet($offset) { + return $this->$offset; + } + + public function offsetSet($offset, $value) { + $this->$offset = $value; + } + + public function offsetUnset($offset) { + unset($this->$offset); + } +} diff --git a/samples/client/petstore/perl/models/Pet.pl b/samples/client/petstore/perl/models/Pet.pl new file mode 100644 index 000000000000..eee7fa3784cd --- /dev/null +++ b/samples/client/petstore/perl/models/Pet.pl @@ -0,0 +1,79 @@ + 'int', + 'category' => 'Category', + 'name' => 'string', + 'photo_urls' => 'array[string]', + 'tags' => 'array[Tag]', + 'status' => 'string' + ); + + static $attributeMap = array( + 'id' => 'id', + 'category' => 'category', + 'name' => 'name', + 'photo_urls' => 'photoUrls', + 'tags' => 'tags', + 'status' => 'status' + ); + + + public $id; /* int */ + public $category; /* Category */ + public $name; /* string */ + public $photo_urls; /* array[string] */ + public $tags; /* array[Tag] */ + /** + * pet status in the store + */ + public $status; /* string */ + + public function __construct(array $data) { + $this->id = $data["id"]; + $this->category = $data["category"]; + $this->name = $data["name"]; + $this->photo_urls = $data["photo_urls"]; + $this->tags = $data["tags"]; + $this->status = $data["status"]; + } + + public function offsetExists($offset) { + return isset($this->$offset); + } + + public function offsetGet($offset) { + return $this->$offset; + } + + public function offsetSet($offset, $value) { + $this->$offset = $value; + } + + public function offsetUnset($offset) { + unset($this->$offset); + } +} diff --git a/samples/client/petstore/perl/models/Tag.pl b/samples/client/petstore/perl/models/Tag.pl new file mode 100644 index 000000000000..f8efc998df66 --- /dev/null +++ b/samples/client/petstore/perl/models/Tag.pl @@ -0,0 +1,60 @@ + 'int', + 'name' => 'string' + ); + + static $attributeMap = array( + 'id' => 'id', + 'name' => 'name' + ); + + + public $id; /* int */ + public $name; /* string */ + + public function __construct(array $data) { + $this->id = $data["id"]; + $this->name = $data["name"]; + } + + public function offsetExists($offset) { + return isset($this->$offset); + } + + public function offsetGet($offset) { + return $this->$offset; + } + + public function offsetSet($offset, $value) { + $this->$offset = $value; + } + + public function offsetUnset($offset) { + unset($this->$offset); + } +} diff --git a/samples/client/petstore/perl/models/User.pl b/samples/client/petstore/perl/models/User.pl new file mode 100644 index 000000000000..d6b520eba51d --- /dev/null +++ b/samples/client/petstore/perl/models/User.pl @@ -0,0 +1,87 @@ + 'int', + 'username' => 'string', + 'first_name' => 'string', + 'last_name' => 'string', + 'email' => 'string', + 'password' => 'string', + 'phone' => 'string', + 'user_status' => 'int' + ); + + static $attributeMap = array( + 'id' => 'id', + 'username' => 'username', + 'first_name' => 'firstName', + 'last_name' => 'lastName', + 'email' => 'email', + 'password' => 'password', + 'phone' => 'phone', + 'user_status' => 'userStatus' + ); + + + public $id; /* int */ + public $username; /* string */ + public $first_name; /* string */ + public $last_name; /* string */ + public $email; /* string */ + public $password; /* string */ + public $phone; /* string */ + /** + * User Status + */ + public $user_status; /* int */ + + public function __construct(array $data) { + $this->id = $data["id"]; + $this->username = $data["username"]; + $this->first_name = $data["first_name"]; + $this->last_name = $data["last_name"]; + $this->email = $data["email"]; + $this->password = $data["password"]; + $this->phone = $data["phone"]; + $this->user_status = $data["user_status"]; + } + + public function offsetExists($offset) { + return isset($this->$offset); + } + + public function offsetGet($offset) { + return $this->$offset; + } + + public function offsetSet($offset, $value) { + $this->$offset = $value; + } + + public function offsetUnset($offset) { + unset($this->$offset); + } +} From c5fcf3ba2c0b888827a8c15a9d7bc202af5269b8 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Wed, 1 Apr 2015 01:30:06 +0800 Subject: [PATCH 16/67] remove pl files --- samples/client/petstore/perl/PetApi.pl | 489 ------------------ samples/client/petstore/perl/StoreApi.pl | 264 ---------- samples/client/petstore/perl/Swagger.pl | 326 ------------ samples/client/petstore/perl/UserApi.pl | 468 ----------------- .../perl/WWW/Swagger/Model/Category.pl | 60 --- .../petstore/perl/WWW/Swagger/Model/Order.pl | 79 --- .../petstore/perl/WWW/Swagger/Model/Pet.pl | 79 --- .../petstore/perl/WWW/Swagger/Model/Tag.pl | 60 --- .../petstore/perl/WWW/Swagger/Model/User.pl | 87 ---- .../petstore/perl/WWW/Swagger/PetApi.pl | 481 ----------------- .../petstore/perl/WWW/Swagger/StoreApi.pl | 260 ---------- .../petstore/perl/WWW/Swagger/UserApi.pl | 460 ---------------- .../client/petstore/perl/models/Category.pl | 60 --- samples/client/petstore/perl/models/Order.pl | 79 --- samples/client/petstore/perl/models/Pet.pl | 79 --- samples/client/petstore/perl/models/Tag.pl | 60 --- samples/client/petstore/perl/models/User.pl | 87 ---- 17 files changed, 3478 deletions(-) delete mode 100644 samples/client/petstore/perl/PetApi.pl delete mode 100644 samples/client/petstore/perl/StoreApi.pl delete mode 100644 samples/client/petstore/perl/Swagger.pl delete mode 100644 samples/client/petstore/perl/UserApi.pl delete mode 100644 samples/client/petstore/perl/WWW/Swagger/Model/Category.pl delete mode 100644 samples/client/petstore/perl/WWW/Swagger/Model/Order.pl delete mode 100644 samples/client/petstore/perl/WWW/Swagger/Model/Pet.pl delete mode 100644 samples/client/petstore/perl/WWW/Swagger/Model/Tag.pl delete mode 100644 samples/client/petstore/perl/WWW/Swagger/Model/User.pl delete mode 100644 samples/client/petstore/perl/WWW/Swagger/PetApi.pl delete mode 100644 samples/client/petstore/perl/WWW/Swagger/StoreApi.pl delete mode 100644 samples/client/petstore/perl/WWW/Swagger/UserApi.pl delete mode 100644 samples/client/petstore/perl/models/Category.pl delete mode 100644 samples/client/petstore/perl/models/Order.pl delete mode 100644 samples/client/petstore/perl/models/Pet.pl delete mode 100644 samples/client/petstore/perl/models/Tag.pl delete mode 100644 samples/client/petstore/perl/models/User.pl diff --git a/samples/client/petstore/perl/PetApi.pl b/samples/client/petstore/perl/PetApi.pl deleted file mode 100644 index 7dc8261cd770..000000000000 --- a/samples/client/petstore/perl/PetApi.pl +++ /dev/null @@ -1,489 +0,0 @@ -# -# 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. -# - -require 5.6.0; -use strict; -use warnings; - -use WWW::Swagger::Model::Category; -use WWW::Swagger::Model::Pet; - -package WWW::Swagger::PetApiAPI; - -our $VERSION = '2.09'; - - -sub new { - my $class = shift; - my $options = shift; - - croak("You must supply an API client") - unless $options->{api_client}; - - my $self = { - api_client = $option->{api_client} - } - - bless $self, $class; - -} - - - # - # updatePet - # - # Update an existing pet - # - # @param Pet $body Pet object that needs to be added to the store (required) - # @return void - # - sub updatePet($body) { - - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/pet"; - $resource_path =~ s/{format}/json/; - - my $method = "PUT"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = 'application/json,application/xml'; - - - - - - # body params - my $body; - if (isset($body)) { - $body = $body; - } - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # addPet - # - # Add a new pet to the store - # - # @param Pet $body Pet object that needs to be added to the store (required) - # @return void - # - sub addPet($body) { - - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/pet"; - $resource_path =~ s/{format}/json/; - - my $method = "POST"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = 'application/json,application/xml'; - - - - - - # body params - my $body; - if (isset($body)) { - $body = $body; - } - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # findPetsByStatus - # - # Finds Pets by status - # - # @param array[string] $status Status values that need to be considered for filter (required) - # @return array[Pet] - # - sub findPetsByStatus($status) { - - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/pet/findByStatus"; - $resource_path =~ s/{format}/json/; - - my $method = "GET"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - # query params - if($status !== null) { - $query_params['status'] = $this->api_client->to_query_value($status); - } - - - - - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - if(!$response) { - return; - } - - $response_object = $this->api_client->deserialize($response, 'array[Pet]'); - return $responseObject; - } - - # - # findPetsByTags - # - # Finds Pets by tags - # - # @param array[string] $tags Tags to filter by (required) - # @return array[Pet] - # - sub findPetsByTags($tags) { - - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/pet/findByTags"; - $resource_path =~ s/{format}/json/; - - my $method = "GET"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - # query params - if($tags !== null) { - $query_params['tags'] = $this->api_client->to_query_value($tags); - } - - - - - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - if(!$response) { - return; - } - - $response_object = $this->api_client->deserialize($response, 'array[Pet]'); - return $responseObject; - } - - # - # getPetById - # - # Find pet by ID - # - # @param int $pet_id ID of pet that needs to be fetched (required) - # @return Pet - # - sub getPetById($pet_id) { - - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/pet/{petId}"; - $resource_path =~ s/{format}/json/; - - my $method = "GET"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - # path params - if($pet_id !== null) { - my $base_variable = "{" + "petId" + "}"; - my $base_value = $this->api_client->to_path_value($pet_id); - $resource_path = s/$base_variable/$base_value/; - } - - - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - if(!$response) { - return; - } - - $response_object = $this->api_client->deserialize($response, 'Pet'); - return $responseObject; - } - - # - # updatePetWithForm - # - # 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 updatePetWithForm($pet_id, $name, $status) { - - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/pet/{petId}"; - $resource_path =~ s/{format}/json/; - - my $method = "POST"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = 'application/x-www-form-urlencoded'; - - - - # path params - if($pet_id !== null) { - my $base_variable = "{" + "petId" + "}"; - my $base_value = $this->api_client->to_path_value($pet_id); - $resource_path = s/$base_variable/$base_value/; - } - # form params - if ($name !== null) { - $formParams->{'name'} = $this->api_client->to_form_value($name); - } # form params - if ($status !== null) { - $formParams->{'status'} = $this->api_client->to_form_value($status); - } - - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # deletePet - # - # Deletes a pet - # - # @param string $api_key (required) - # @param int $pet_id Pet id to delete (required) - # @return void - # - sub deletePet($api_key, $pet_id) { - - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/pet/{petId}"; - $resource_path =~ s/{format}/json/; - - my $method = "DELETE"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - # header params - if($api_key !== null) { - $headerParams['api_key'] = $this->apiClient->to_header_value($args[api_key]); - } - # path params - if($pet_id !== null) { - my $base_variable = "{" + "petId" + "}"; - my $base_value = $this->api_client->to_path_value($pet_id); - $resource_path = s/$base_variable/$base_value/; - } - - - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # uploadFile - # - # 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 uploadFile($pet_id, $additional_metadata, $file) { - - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/pet/{petId}/uploadImage"; - $resource_path =~ s/{format}/json/; - - my $method = "POST"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = 'multipart/form-data'; - - - - # path params - if($pet_id !== null) { - my $base_variable = "{" + "petId" + "}"; - my $base_value = $this->api_client->to_path_value($pet_id); - $resource_path = s/$base_variable/$base_value/; - } - # form params - if ($additional_metadata !== null) { - $formParams->{'additionalMetadata'} = $this->api_client->to_form_value($additional_metadata); - } # form params - if ($file !== null) { - $formParams->{'file'} = '@' . $this->api_client->to_form_value($file); - } - - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - -} - -1; diff --git a/samples/client/petstore/perl/StoreApi.pl b/samples/client/petstore/perl/StoreApi.pl deleted file mode 100644 index 6ab1b62758e4..000000000000 --- a/samples/client/petstore/perl/StoreApi.pl +++ /dev/null @@ -1,264 +0,0 @@ -# -# 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. -# - -require 5.6.0; -use strict; -use warnings; - -use WWW::Swagger::Model::Category; -use WWW::Swagger::Model::Pet; - -package WWW::Swagger::StoreApiAPI; - -our $VERSION = '2.09'; - - -sub new { - my $class = shift; - my $options = shift; - - croak("You must supply an API client") - unless $options->{api_client}; - - my $self = { - api_client = $option->{api_client} - } - - bless $self, $class; - -} - - - # - # getInventory - # - # Returns pet inventories by status - # - # @return map[string,int] - # - sub getInventory() { - - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/store/inventory"; - $resource_path =~ s/{format}/json/; - - my $method = "GET"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - - - - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - if(!$response) { - return; - } - - $response_object = $this->api_client->deserialize($response, 'map[string,int]'); - return $responseObject; - } - - # - # placeOrder - # - # Place an order for a pet - # - # @param Order $body order placed for purchasing the pet (required) - # @return Order - # - sub placeOrder($body) { - - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/store/order"; - $resource_path =~ s/{format}/json/; - - my $method = "POST"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - - - # body params - my $body; - if (isset($body)) { - $body = $body; - } - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - if(!$response) { - return; - } - - $response_object = $this->api_client->deserialize($response, 'Order'); - return $responseObject; - } - - # - # getOrderById - # - # Find purchase order by ID - # - # @param string $order_id ID of pet that needs to be fetched (required) - # @return Order - # - sub getOrderById($order_id) { - - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/store/order/{orderId}"; - $resource_path =~ s/{format}/json/; - - my $method = "GET"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - # path params - if($order_id !== null) { - my $base_variable = "{" + "orderId" + "}"; - my $base_value = $this->api_client->to_path_value($order_id); - $resource_path = s/$base_variable/$base_value/; - } - - - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - if(!$response) { - return; - } - - $response_object = $this->api_client->deserialize($response, 'Order'); - return $responseObject; - } - - # - # deleteOrder - # - # Delete purchase order by ID - # - # @param string $order_id ID of the order that needs to be deleted (required) - # @return void - # - sub deleteOrder($order_id) { - - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/store/order/{orderId}"; - $resource_path =~ s/{format}/json/; - - my $method = "DELETE"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - # path params - if($order_id !== null) { - my $base_variable = "{" + "orderId" + "}"; - my $base_value = $this->api_client->to_path_value($order_id); - $resource_path = s/$base_variable/$base_value/; - } - - - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - -} - -1; diff --git a/samples/client/petstore/perl/Swagger.pl b/samples/client/petstore/perl/Swagger.pl deleted file mode 100644 index 3d6b77d819e8..000000000000 --- a/samples/client/petstore/perl/Swagger.pl +++ /dev/null @@ -1,326 +0,0 @@ -host = $host; - $this->headerName = $headerName; - $this->headerValue = $headerValue; - } - - /** - * Set the user agent of the API client - * - * @param string $user_agent The user agent of the API client - */ - public function setUserAgent($user_agent) { - if (!is_string($user_agent)) { - throw new Exception('User-agent must be a string.'); - } - $this->user_agent= $user_agent; - } - - /** - * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] - */ - public function setTimeout($seconds) { - if (!is_numeric($seconds)) { - throw new Exception('Timeout variable must be numeric.'); - } - $this->curl_timout = $seconds; - } - - /** - * @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 - */ - public function callAPI($resourcePath, $method, $queryParams, $postData, - $headerParams) { - - $headers = array(); - - # Allow API key from $headerParams to override default - $added_api_key = False; - if ($headerParams != null) { - foreach ($headerParams as $key => $val) { - $headers[] = "$key: $val"; - if ($key == $this->headerName) { - $added_api_key = True; - } - } - } - if (! $added_api_key && $this->headerName != null) { - $headers[] = $this->headerName . ": " . $this->headerValue; - } - - if (strpos($headers['Content-Type'], "multipart/form-data") < 0 and (is_object($postData) or is_array($postData))) { - $postData = json_encode($this->sanitizeForSerialization($postData)); - } - - $url = $this->host . $resourcePath; - - $curl = curl_init(); - if ($this->curl_timout) { - curl_setopt($curl, CURLOPT_TIMEOUT, $this->curl_timout); - } - // return the result on success, rather than just TRUE - curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); - curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); - - if (! empty($queryParams)) { - $url = ($url . '?' . http_build_query($queryParams)); - } - - if ($method == self::$POST) { - curl_setopt($curl, CURLOPT_POST, true); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method == self::$PATCH) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method == self::$PUT) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method == self::$DELETE) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method != self::$GET) { - throw new Exception('Method ' . $method . ' is not recognized.'); - } - curl_setopt($curl, CURLOPT_URL, $url); - - // Set user agent - if ($this->user_agent) { - curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent); - } else { // use PHP-Swagger as the default user agent - curl_setopt($curl, CURLOPT_USERAGENT, 'PHP-Swagger'); - } - - // Make the request - $response = curl_exec($curl); - $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); - } 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) { - throw new APIClientException("Unauthorized API request to " . $url . - ": " . serialize($response), 0, $response_info, $response); - } else if ($response_info['http_code'] == 404) { - $data = null; - } else { - throw new APIClientException("Can't connect to the api: " . $url . - " response code: " . - $response_info['http_code'], 0, $response_info, $response); - } - return $data; - } - - /** - * Build a JSON POST object - */ - protected function sanitizeForSerialization($data) - { - 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 - */ - public static function toPathValue($value) { - return rawurlencode(toString($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 - */ - public static function toQueryValue($object) { - 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 - */ - public static function toHeaderValue($value) { - return toString($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 - */ - public static function toFormValue($value) { - return toString($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 - */ - public static function toString($value) { - if ($value instanceof \DateTime) { // datetime in ISO8601 format - return $value->format(\DateTime::ISO8601); - } - else { - return $value; - } - } - - /** - * Deserialize a JSON string into an object - * - * @param object $object object or primitive to be deserialized - * @param string $class class name is passed as a string - * @return object an instance of $class - */ - - public static function deserialize($data, $class) - { - if (null === $data) { - $deserialized = null; - } elseif (substr($class, 0, 4) == 'map[') { - $inner = substr($class, 4, -1); - $values = array(); - if(strrpos($inner, ",") !== false) { - $subClass_array = explode(',', $inner, 2); - $subClass = $subClass_array[1]; - foreach ($data as $key => $value) { - $values[] = array($key => self::deserialize($value, $subClass)); - } - } - $deserialized = $values; - } elseif (strcasecmp(substr($class, 0, 6),'array[') == 0) { - $subClass = substr($class, 6, -1); - $values = array(); - foreach ($data as $key => $value) { - $values[] = self::deserialize($value, $subClass); - } - $deserialized = $values; - } elseif ($class == 'DateTime') { - $deserialized = new \DateTime($data); - } elseif (in_array($class, array('string', 'int', 'float', 'bool'))) { - settype($data, $class); - $deserialized = $data; - } else { - $instance = new $class(); - foreach ($instance::$swaggerTypes as $property => $type) { - if (isset($data->$property)) { - $original_property_name = $instance::$attributeMap[$property]; - $instance->$property = self::deserialize($data->$original_property_name, $type); - } - } - $deserialized = $instance; - } - - return $deserialized; - } - -} - -class APIClientException extends Exception { - protected $response, $response_info; - - public function __construct($message="", $code=0, $response_info=null, $response=null) { - parent::__construct($message, $code); - $this->response_info = $response_info; - $this->response = $response; - } - - public function getResponse() { - return $this->response; - } - - public function getResponseInfo() { - return $this->response_info; - } -} diff --git a/samples/client/petstore/perl/UserApi.pl b/samples/client/petstore/perl/UserApi.pl deleted file mode 100644 index 49803ffa66b1..000000000000 --- a/samples/client/petstore/perl/UserApi.pl +++ /dev/null @@ -1,468 +0,0 @@ -# -# 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. -# - -require 5.6.0; -use strict; -use warnings; - -use WWW::Swagger::Model::Category; -use WWW::Swagger::Model::Pet; - -package WWW::Swagger::UserApiAPI; - -our $VERSION = '2.09'; - - -sub new { - my $class = shift; - my $options = shift; - - croak("You must supply an API client") - unless $options->{api_client}; - - my $self = { - api_client = $option->{api_client} - } - - bless $self, $class; - -} - - - # - # createUser - # - # Create user - # - # @param User $body Created user object (required) - # @return void - # - sub createUser($body) { - - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/user"; - $resource_path =~ s/{format}/json/; - - my $method = "POST"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - - - # body params - my $body; - if (isset($body)) { - $body = $body; - } - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # createUsersWithArrayInput - # - # Creates list of users with given input array - # - # @param array[User] $body List of user object (required) - # @return void - # - sub createUsersWithArrayInput($body) { - - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/user/createWithArray"; - $resource_path =~ s/{format}/json/; - - my $method = "POST"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - - - # body params - my $body; - if (isset($body)) { - $body = $body; - } - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # createUsersWithListInput - # - # Creates list of users with given input array - # - # @param array[User] $body List of user object (required) - # @return void - # - sub createUsersWithListInput($body) { - - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/user/createWithList"; - $resource_path =~ s/{format}/json/; - - my $method = "POST"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - - - # body params - my $body; - if (isset($body)) { - $body = $body; - } - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # loginUser - # - # 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 loginUser($username, $password) { - - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/user/login"; - $resource_path =~ s/{format}/json/; - - my $method = "GET"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - # query params - if($username !== null) { - $query_params['username'] = $this->api_client->to_query_value($username); - } # query params - if($password !== null) { - $query_params['password'] = $this->api_client->to_query_value($password); - } - - - - - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - if(!$response) { - return; - } - - $response_object = $this->api_client->deserialize($response, 'string'); - return $responseObject; - } - - # - # logoutUser - # - # Logs out current logged in user session - # - # @return void - # - sub logoutUser() { - - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/user/logout"; - $resource_path =~ s/{format}/json/; - - my $method = "GET"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - - - - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # getUserByName - # - # Get user by user name - # - # @param string $username The name that needs to be fetched. Use user1 for testing. (required) - # @return User - # - sub getUserByName($username) { - - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/user/{username}"; - $resource_path =~ s/{format}/json/; - - my $method = "GET"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - # path params - if($username !== null) { - my $base_variable = "{" + "username" + "}"; - my $base_value = $this->api_client->to_path_value($username); - $resource_path = s/$base_variable/$base_value/; - } - - - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - if(!$response) { - return; - } - - $response_object = $this->api_client->deserialize($response, 'User'); - return $responseObject; - } - - # - # updateUser - # - # Updated user - # - # @param string $username name that need to be deleted (required) - # @param User $body Updated user object (required) - # @return void - # - sub updateUser($username, $body) { - - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/user/{username}"; - $resource_path =~ s/{format}/json/; - - my $method = "PUT"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - # path params - if($username !== null) { - my $base_variable = "{" + "username" + "}"; - my $base_value = $this->api_client->to_path_value($username); - $resource_path = s/$base_variable/$base_value/; - } - - # body params - my $body; - if (isset($body)) { - $body = $body; - } - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # deleteUser - # - # Delete user - # - # @param string $username The name that needs to be deleted (required) - # @return void - # - sub deleteUser($username) { - - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/user/{username}"; - $resource_path =~ s/{format}/json/; - - my $method = "DELETE"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - # path params - if($username !== null) { - my $base_variable = "{" + "username" + "}"; - my $base_value = $this->api_client->to_path_value($username); - $resource_path = s/$base_variable/$base_value/; - } - - - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - -} - -1; diff --git a/samples/client/petstore/perl/WWW/Swagger/Model/Category.pl b/samples/client/petstore/perl/WWW/Swagger/Model/Category.pl deleted file mode 100644 index 98e7ba24800d..000000000000 --- a/samples/client/petstore/perl/WWW/Swagger/Model/Category.pl +++ /dev/null @@ -1,60 +0,0 @@ - 'int', - 'name' => 'string' - ); - - static $attributeMap = array( - 'id' => 'id', - 'name' => 'name' - ); - - - public $id; /* int */ - public $name; /* string */ - - public function __construct(array $data) { - $this->id = $data["id"]; - $this->name = $data["name"]; - } - - public function offsetExists($offset) { - return isset($this->$offset); - } - - public function offsetGet($offset) { - return $this->$offset; - } - - public function offsetSet($offset, $value) { - $this->$offset = $value; - } - - public function offsetUnset($offset) { - unset($this->$offset); - } -} diff --git a/samples/client/petstore/perl/WWW/Swagger/Model/Order.pl b/samples/client/petstore/perl/WWW/Swagger/Model/Order.pl deleted file mode 100644 index 2770e8bbbdf1..000000000000 --- a/samples/client/petstore/perl/WWW/Swagger/Model/Order.pl +++ /dev/null @@ -1,79 +0,0 @@ - 'int', - 'pet_id' => 'int', - 'quantity' => 'int', - 'ship_date' => 'DateTime', - 'status' => 'string', - 'complete' => 'boolean' - ); - - static $attributeMap = array( - 'id' => 'id', - 'pet_id' => 'petId', - 'quantity' => 'quantity', - 'ship_date' => 'shipDate', - 'status' => 'status', - 'complete' => 'complete' - ); - - - public $id; /* int */ - public $pet_id; /* int */ - public $quantity; /* int */ - public $ship_date; /* DateTime */ - /** - * Order Status - */ - public $status; /* string */ - public $complete; /* boolean */ - - public function __construct(array $data) { - $this->id = $data["id"]; - $this->pet_id = $data["pet_id"]; - $this->quantity = $data["quantity"]; - $this->ship_date = $data["ship_date"]; - $this->status = $data["status"]; - $this->complete = $data["complete"]; - } - - public function offsetExists($offset) { - return isset($this->$offset); - } - - public function offsetGet($offset) { - return $this->$offset; - } - - public function offsetSet($offset, $value) { - $this->$offset = $value; - } - - public function offsetUnset($offset) { - unset($this->$offset); - } -} diff --git a/samples/client/petstore/perl/WWW/Swagger/Model/Pet.pl b/samples/client/petstore/perl/WWW/Swagger/Model/Pet.pl deleted file mode 100644 index eee7fa3784cd..000000000000 --- a/samples/client/petstore/perl/WWW/Swagger/Model/Pet.pl +++ /dev/null @@ -1,79 +0,0 @@ - 'int', - 'category' => 'Category', - 'name' => 'string', - 'photo_urls' => 'array[string]', - 'tags' => 'array[Tag]', - 'status' => 'string' - ); - - static $attributeMap = array( - 'id' => 'id', - 'category' => 'category', - 'name' => 'name', - 'photo_urls' => 'photoUrls', - 'tags' => 'tags', - 'status' => 'status' - ); - - - public $id; /* int */ - public $category; /* Category */ - public $name; /* string */ - public $photo_urls; /* array[string] */ - public $tags; /* array[Tag] */ - /** - * pet status in the store - */ - public $status; /* string */ - - public function __construct(array $data) { - $this->id = $data["id"]; - $this->category = $data["category"]; - $this->name = $data["name"]; - $this->photo_urls = $data["photo_urls"]; - $this->tags = $data["tags"]; - $this->status = $data["status"]; - } - - public function offsetExists($offset) { - return isset($this->$offset); - } - - public function offsetGet($offset) { - return $this->$offset; - } - - public function offsetSet($offset, $value) { - $this->$offset = $value; - } - - public function offsetUnset($offset) { - unset($this->$offset); - } -} diff --git a/samples/client/petstore/perl/WWW/Swagger/Model/Tag.pl b/samples/client/petstore/perl/WWW/Swagger/Model/Tag.pl deleted file mode 100644 index f8efc998df66..000000000000 --- a/samples/client/petstore/perl/WWW/Swagger/Model/Tag.pl +++ /dev/null @@ -1,60 +0,0 @@ - 'int', - 'name' => 'string' - ); - - static $attributeMap = array( - 'id' => 'id', - 'name' => 'name' - ); - - - public $id; /* int */ - public $name; /* string */ - - public function __construct(array $data) { - $this->id = $data["id"]; - $this->name = $data["name"]; - } - - public function offsetExists($offset) { - return isset($this->$offset); - } - - public function offsetGet($offset) { - return $this->$offset; - } - - public function offsetSet($offset, $value) { - $this->$offset = $value; - } - - public function offsetUnset($offset) { - unset($this->$offset); - } -} diff --git a/samples/client/petstore/perl/WWW/Swagger/Model/User.pl b/samples/client/petstore/perl/WWW/Swagger/Model/User.pl deleted file mode 100644 index d6b520eba51d..000000000000 --- a/samples/client/petstore/perl/WWW/Swagger/Model/User.pl +++ /dev/null @@ -1,87 +0,0 @@ - 'int', - 'username' => 'string', - 'first_name' => 'string', - 'last_name' => 'string', - 'email' => 'string', - 'password' => 'string', - 'phone' => 'string', - 'user_status' => 'int' - ); - - static $attributeMap = array( - 'id' => 'id', - 'username' => 'username', - 'first_name' => 'firstName', - 'last_name' => 'lastName', - 'email' => 'email', - 'password' => 'password', - 'phone' => 'phone', - 'user_status' => 'userStatus' - ); - - - public $id; /* int */ - public $username; /* string */ - public $first_name; /* string */ - public $last_name; /* string */ - public $email; /* string */ - public $password; /* string */ - public $phone; /* string */ - /** - * User Status - */ - public $user_status; /* int */ - - public function __construct(array $data) { - $this->id = $data["id"]; - $this->username = $data["username"]; - $this->first_name = $data["first_name"]; - $this->last_name = $data["last_name"]; - $this->email = $data["email"]; - $this->password = $data["password"]; - $this->phone = $data["phone"]; - $this->user_status = $data["user_status"]; - } - - public function offsetExists($offset) { - return isset($this->$offset); - } - - public function offsetGet($offset) { - return $this->$offset; - } - - public function offsetSet($offset, $value) { - $this->$offset = $value; - } - - public function offsetUnset($offset) { - unset($this->$offset); - } -} diff --git a/samples/client/petstore/perl/WWW/Swagger/PetApi.pl b/samples/client/petstore/perl/WWW/Swagger/PetApi.pl deleted file mode 100644 index 5d876b4b61e7..000000000000 --- a/samples/client/petstore/perl/WWW/Swagger/PetApi.pl +++ /dev/null @@ -1,481 +0,0 @@ -# -# 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. -# - -require 5.6.0; -use strict; -use warnings; - -use WWW::Swagger::Model::Category; -use WWW::Swagger::Model::Pet; - -package WWW::Swagger::PetApiAPI; - -our $VERSION = '2.09'; - - -sub new { - my $class = shift; - my $options = shift; - - croak("You must supply an API client") - unless $options->{api_client}; - - my $self = { - api_client = $option->{api_client} - } - - bless $self, $class; - -} - - - # - # updatePet - # - # Update an existing pet - # - # @param Pet $body Pet object that needs to be added to the store (required) - # @return void - # - sub updatePet { - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/pet"; - $resource_path =~ s/{format}/json/; - - my $method = "PUT"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = 'application/json,application/xml'; - - - - - - # body params - my $body; - if (isset($body)) { - $body = $body; - } - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # addPet - # - # Add a new pet to the store - # - # @param Pet $body Pet object that needs to be added to the store (required) - # @return void - # - sub addPet { - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/pet"; - $resource_path =~ s/{format}/json/; - - my $method = "POST"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = 'application/json,application/xml'; - - - - - - # body params - my $body; - if (isset($body)) { - $body = $body; - } - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # findPetsByStatus - # - # Finds Pets by status - # - # @param array[string] $status Status values that need to be considered for filter (required) - # @return array[Pet] - # - sub findPetsByStatus { - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/pet/findByStatus"; - $resource_path =~ s/{format}/json/; - - my $method = "GET"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - # query params - if($status !== null) { - $query_params['status'] = $this->api_client->to_query_value($status); - } - - - - - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - if(!$response) { - return; - } - - $response_object = $this->api_client->deserialize($response, 'array[Pet]'); - return $responseObject; - } - - # - # findPetsByTags - # - # Finds Pets by tags - # - # @param array[string] $tags Tags to filter by (required) - # @return array[Pet] - # - sub findPetsByTags { - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/pet/findByTags"; - $resource_path =~ s/{format}/json/; - - my $method = "GET"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - # query params - if($tags !== null) { - $query_params['tags'] = $this->api_client->to_query_value($tags); - } - - - - - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - if(!$response) { - return; - } - - $response_object = $this->api_client->deserialize($response, 'array[Pet]'); - return $responseObject; - } - - # - # getPetById - # - # Find pet by ID - # - # @param int $pet_id ID of pet that needs to be fetched (required) - # @return Pet - # - sub getPetById { - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/pet/{petId}"; - $resource_path =~ s/{format}/json/; - - my $method = "GET"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - # path params - if($pet_id !== null) { - my $base_variable = "{" + "petId" + "}"; - my $base_value = $this->api_client->to_path_value($pet_id); - $resource_path = s/$base_variable/$base_value/; - } - - - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - if(!$response) { - return; - } - - $response_object = $this->api_client->deserialize($response, 'Pet'); - return $responseObject; - } - - # - # updatePetWithForm - # - # 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 updatePetWithForm { - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/pet/{petId}"; - $resource_path =~ s/{format}/json/; - - my $method = "POST"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = 'application/x-www-form-urlencoded'; - - - - # path params - if($pet_id !== null) { - my $base_variable = "{" + "petId" + "}"; - my $base_value = $this->api_client->to_path_value($pet_id); - $resource_path = s/$base_variable/$base_value/; - } - # form params - if ($name !== null) { - $formParams->{'name'} = $this->api_client->to_form_value($name); - } # form params - if ($status !== null) { - $formParams->{'status'} = $this->api_client->to_form_value($status); - } - - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # deletePet - # - # Deletes a pet - # - # @param string $api_key (required) - # @param int $pet_id Pet id to delete (required) - # @return void - # - sub deletePet { - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/pet/{petId}"; - $resource_path =~ s/{format}/json/; - - my $method = "DELETE"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - # header params - if($api_key !== null) { - $headerParams['api_key'] = $this->apiClient->to_header_value($args[api_key]); - } - # path params - if($pet_id !== null) { - my $base_variable = "{" + "petId" + "}"; - my $base_value = $this->api_client->to_path_value($pet_id); - $resource_path = s/$base_variable/$base_value/; - } - - - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # uploadFile - # - # 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 uploadFile { - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/pet/{petId}/uploadImage"; - $resource_path =~ s/{format}/json/; - - my $method = "POST"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = 'multipart/form-data'; - - - - # path params - if($pet_id !== null) { - my $base_variable = "{" + "petId" + "}"; - my $base_value = $this->api_client->to_path_value($pet_id); - $resource_path = s/$base_variable/$base_value/; - } - # form params - if ($additional_metadata !== null) { - $formParams->{'additionalMetadata'} = $this->api_client->to_form_value($additional_metadata); - } # form params - if ($file !== null) { - $formParams->{'file'} = '@' . $this->api_client->to_form_value($file); - } - - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - -} - -1; diff --git a/samples/client/petstore/perl/WWW/Swagger/StoreApi.pl b/samples/client/petstore/perl/WWW/Swagger/StoreApi.pl deleted file mode 100644 index 64c20c71a662..000000000000 --- a/samples/client/petstore/perl/WWW/Swagger/StoreApi.pl +++ /dev/null @@ -1,260 +0,0 @@ -# -# 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. -# - -require 5.6.0; -use strict; -use warnings; - -use WWW::Swagger::Model::Category; -use WWW::Swagger::Model::Pet; - -package WWW::Swagger::StoreApiAPI; - -our $VERSION = '2.09'; - - -sub new { - my $class = shift; - my $options = shift; - - croak("You must supply an API client") - unless $options->{api_client}; - - my $self = { - api_client = $option->{api_client} - } - - bless $self, $class; - -} - - - # - # getInventory - # - # Returns pet inventories by status - # - # @return map[string,int] - # - sub getInventory { - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/store/inventory"; - $resource_path =~ s/{format}/json/; - - my $method = "GET"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - - - - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - if(!$response) { - return; - } - - $response_object = $this->api_client->deserialize($response, 'map[string,int]'); - return $responseObject; - } - - # - # placeOrder - # - # Place an order for a pet - # - # @param Order $body order placed for purchasing the pet (required) - # @return Order - # - sub placeOrder { - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/store/order"; - $resource_path =~ s/{format}/json/; - - my $method = "POST"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - - - # body params - my $body; - if (isset($body)) { - $body = $body; - } - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - if(!$response) { - return; - } - - $response_object = $this->api_client->deserialize($response, 'Order'); - return $responseObject; - } - - # - # getOrderById - # - # Find purchase order by ID - # - # @param string $order_id ID of pet that needs to be fetched (required) - # @return Order - # - sub getOrderById { - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/store/order/{orderId}"; - $resource_path =~ s/{format}/json/; - - my $method = "GET"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - # path params - if($order_id !== null) { - my $base_variable = "{" + "orderId" + "}"; - my $base_value = $this->api_client->to_path_value($order_id); - $resource_path = s/$base_variable/$base_value/; - } - - - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - if(!$response) { - return; - } - - $response_object = $this->api_client->deserialize($response, 'Order'); - return $responseObject; - } - - # - # deleteOrder - # - # Delete purchase order by ID - # - # @param string $order_id ID of the order that needs to be deleted (required) - # @return void - # - sub deleteOrder { - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/store/order/{orderId}"; - $resource_path =~ s/{format}/json/; - - my $method = "DELETE"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - # path params - if($order_id !== null) { - my $base_variable = "{" + "orderId" + "}"; - my $base_value = $this->api_client->to_path_value($order_id); - $resource_path = s/$base_variable/$base_value/; - } - - - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - -} - -1; diff --git a/samples/client/petstore/perl/WWW/Swagger/UserApi.pl b/samples/client/petstore/perl/WWW/Swagger/UserApi.pl deleted file mode 100644 index ba2877560fb7..000000000000 --- a/samples/client/petstore/perl/WWW/Swagger/UserApi.pl +++ /dev/null @@ -1,460 +0,0 @@ -# -# 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. -# - -require 5.6.0; -use strict; -use warnings; - -use WWW::Swagger::Model::Category; -use WWW::Swagger::Model::Pet; - -package WWW::Swagger::UserApiAPI; - -our $VERSION = '2.09'; - - -sub new { - my $class = shift; - my $options = shift; - - croak("You must supply an API client") - unless $options->{api_client}; - - my $self = { - api_client = $option->{api_client} - } - - bless $self, $class; - -} - - - # - # createUser - # - # Create user - # - # @param User $body Created user object (required) - # @return void - # - sub createUser { - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/user"; - $resource_path =~ s/{format}/json/; - - my $method = "POST"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - - - # body params - my $body; - if (isset($body)) { - $body = $body; - } - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # createUsersWithArrayInput - # - # Creates list of users with given input array - # - # @param array[User] $body List of user object (required) - # @return void - # - sub createUsersWithArrayInput { - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/user/createWithArray"; - $resource_path =~ s/{format}/json/; - - my $method = "POST"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - - - # body params - my $body; - if (isset($body)) { - $body = $body; - } - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # createUsersWithListInput - # - # Creates list of users with given input array - # - # @param array[User] $body List of user object (required) - # @return void - # - sub createUsersWithListInput { - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/user/createWithList"; - $resource_path =~ s/{format}/json/; - - my $method = "POST"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - - - # body params - my $body; - if (isset($body)) { - $body = $body; - } - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # loginUser - # - # 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 loginUser { - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/user/login"; - $resource_path =~ s/{format}/json/; - - my $method = "GET"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - # query params - if($username !== null) { - $query_params['username'] = $this->api_client->to_query_value($username); - } # query params - if($password !== null) { - $query_params['password'] = $this->api_client->to_query_value($password); - } - - - - - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - if(!$response) { - return; - } - - $response_object = $this->api_client->deserialize($response, 'string'); - return $responseObject; - } - - # - # logoutUser - # - # Logs out current logged in user session - # - # @return void - # - sub logoutUser { - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/user/logout"; - $resource_path =~ s/{format}/json/; - - my $method = "GET"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - - - - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # getUserByName - # - # Get user by user name - # - # @param string $username The name that needs to be fetched. Use user1 for testing. (required) - # @return User - # - sub getUserByName { - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/user/{username}"; - $resource_path =~ s/{format}/json/; - - my $method = "GET"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - # path params - if($username !== null) { - my $base_variable = "{" + "username" + "}"; - my $base_value = $this->api_client->to_path_value($username); - $resource_path = s/$base_variable/$base_value/; - } - - - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - if(!$response) { - return; - } - - $response_object = $this->api_client->deserialize($response, 'User'); - return $responseObject; - } - - # - # updateUser - # - # Updated user - # - # @param string $username name that need to be deleted (required) - # @param User $body Updated user object (required) - # @return void - # - sub updateUser { - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/user/{username}"; - $resource_path =~ s/{format}/json/; - - my $method = "PUT"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - # path params - if($username !== null) { - my $base_variable = "{" + "username" + "}"; - my $base_value = $this->api_client->to_path_value($username); - $resource_path = s/$base_variable/$base_value/; - } - - # body params - my $body; - if (isset($body)) { - $body = $body; - } - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # deleteUser - # - # Delete user - # - # @param string $username The name that needs to be deleted (required) - # @return void - # - sub deleteUser { - my $self = shift; - my %args = @_; - - // parse inputs - my $resource_path = "/user/{username}"; - $resource_path =~ s/{format}/json/; - - my $method = "DELETE"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - # path params - if($username !== null) { - my $base_variable = "{" + "username" + "}"; - my $base_value = $this->api_client->to_path_value($username); - $resource_path = s/$base_variable/$base_value/; - } - - - - # for HTTP post (form) - $body = $body ?: $formParams; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - // make the API Call - $response = $this->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - -} - -1; diff --git a/samples/client/petstore/perl/models/Category.pl b/samples/client/petstore/perl/models/Category.pl deleted file mode 100644 index 98e7ba24800d..000000000000 --- a/samples/client/petstore/perl/models/Category.pl +++ /dev/null @@ -1,60 +0,0 @@ - 'int', - 'name' => 'string' - ); - - static $attributeMap = array( - 'id' => 'id', - 'name' => 'name' - ); - - - public $id; /* int */ - public $name; /* string */ - - public function __construct(array $data) { - $this->id = $data["id"]; - $this->name = $data["name"]; - } - - public function offsetExists($offset) { - return isset($this->$offset); - } - - public function offsetGet($offset) { - return $this->$offset; - } - - public function offsetSet($offset, $value) { - $this->$offset = $value; - } - - public function offsetUnset($offset) { - unset($this->$offset); - } -} diff --git a/samples/client/petstore/perl/models/Order.pl b/samples/client/petstore/perl/models/Order.pl deleted file mode 100644 index 2770e8bbbdf1..000000000000 --- a/samples/client/petstore/perl/models/Order.pl +++ /dev/null @@ -1,79 +0,0 @@ - 'int', - 'pet_id' => 'int', - 'quantity' => 'int', - 'ship_date' => 'DateTime', - 'status' => 'string', - 'complete' => 'boolean' - ); - - static $attributeMap = array( - 'id' => 'id', - 'pet_id' => 'petId', - 'quantity' => 'quantity', - 'ship_date' => 'shipDate', - 'status' => 'status', - 'complete' => 'complete' - ); - - - public $id; /* int */ - public $pet_id; /* int */ - public $quantity; /* int */ - public $ship_date; /* DateTime */ - /** - * Order Status - */ - public $status; /* string */ - public $complete; /* boolean */ - - public function __construct(array $data) { - $this->id = $data["id"]; - $this->pet_id = $data["pet_id"]; - $this->quantity = $data["quantity"]; - $this->ship_date = $data["ship_date"]; - $this->status = $data["status"]; - $this->complete = $data["complete"]; - } - - public function offsetExists($offset) { - return isset($this->$offset); - } - - public function offsetGet($offset) { - return $this->$offset; - } - - public function offsetSet($offset, $value) { - $this->$offset = $value; - } - - public function offsetUnset($offset) { - unset($this->$offset); - } -} diff --git a/samples/client/petstore/perl/models/Pet.pl b/samples/client/petstore/perl/models/Pet.pl deleted file mode 100644 index eee7fa3784cd..000000000000 --- a/samples/client/petstore/perl/models/Pet.pl +++ /dev/null @@ -1,79 +0,0 @@ - 'int', - 'category' => 'Category', - 'name' => 'string', - 'photo_urls' => 'array[string]', - 'tags' => 'array[Tag]', - 'status' => 'string' - ); - - static $attributeMap = array( - 'id' => 'id', - 'category' => 'category', - 'name' => 'name', - 'photo_urls' => 'photoUrls', - 'tags' => 'tags', - 'status' => 'status' - ); - - - public $id; /* int */ - public $category; /* Category */ - public $name; /* string */ - public $photo_urls; /* array[string] */ - public $tags; /* array[Tag] */ - /** - * pet status in the store - */ - public $status; /* string */ - - public function __construct(array $data) { - $this->id = $data["id"]; - $this->category = $data["category"]; - $this->name = $data["name"]; - $this->photo_urls = $data["photo_urls"]; - $this->tags = $data["tags"]; - $this->status = $data["status"]; - } - - public function offsetExists($offset) { - return isset($this->$offset); - } - - public function offsetGet($offset) { - return $this->$offset; - } - - public function offsetSet($offset, $value) { - $this->$offset = $value; - } - - public function offsetUnset($offset) { - unset($this->$offset); - } -} diff --git a/samples/client/petstore/perl/models/Tag.pl b/samples/client/petstore/perl/models/Tag.pl deleted file mode 100644 index f8efc998df66..000000000000 --- a/samples/client/petstore/perl/models/Tag.pl +++ /dev/null @@ -1,60 +0,0 @@ - 'int', - 'name' => 'string' - ); - - static $attributeMap = array( - 'id' => 'id', - 'name' => 'name' - ); - - - public $id; /* int */ - public $name; /* string */ - - public function __construct(array $data) { - $this->id = $data["id"]; - $this->name = $data["name"]; - } - - public function offsetExists($offset) { - return isset($this->$offset); - } - - public function offsetGet($offset) { - return $this->$offset; - } - - public function offsetSet($offset, $value) { - $this->$offset = $value; - } - - public function offsetUnset($offset) { - unset($this->$offset); - } -} diff --git a/samples/client/petstore/perl/models/User.pl b/samples/client/petstore/perl/models/User.pl deleted file mode 100644 index d6b520eba51d..000000000000 --- a/samples/client/petstore/perl/models/User.pl +++ /dev/null @@ -1,87 +0,0 @@ - 'int', - 'username' => 'string', - 'first_name' => 'string', - 'last_name' => 'string', - 'email' => 'string', - 'password' => 'string', - 'phone' => 'string', - 'user_status' => 'int' - ); - - static $attributeMap = array( - 'id' => 'id', - 'username' => 'username', - 'first_name' => 'firstName', - 'last_name' => 'lastName', - 'email' => 'email', - 'password' => 'password', - 'phone' => 'phone', - 'user_status' => 'userStatus' - ); - - - public $id; /* int */ - public $username; /* string */ - public $first_name; /* string */ - public $last_name; /* string */ - public $email; /* string */ - public $password; /* string */ - public $phone; /* string */ - /** - * User Status - */ - public $user_status; /* int */ - - public function __construct(array $data) { - $this->id = $data["id"]; - $this->username = $data["username"]; - $this->first_name = $data["first_name"]; - $this->last_name = $data["last_name"]; - $this->email = $data["email"]; - $this->password = $data["password"]; - $this->phone = $data["phone"]; - $this->user_status = $data["user_status"]; - } - - public function offsetExists($offset) { - return isset($this->$offset); - } - - public function offsetGet($offset) { - return $this->$offset; - } - - public function offsetSet($offset, $value) { - $this->$offset = $value; - } - - public function offsetUnset($offset) { - unset($this->$offset); - } -} From a7ef1262e5b61a679eb5e1843a8b1c0f67c25faf Mon Sep 17 00:00:00 2001 From: William Cheng Date: Sat, 2 May 2015 19:08:07 +0800 Subject: [PATCH 17/67] fix all swagger.pl syntax issue --- .../codegen/languages/PerlClientCodegen.java | 27 + .../src/main/resources/perl/Swagger.mustache | 523 +++++++----------- samples/client/petstore/perl/Swagger.pl | 229 ++++++++ .../petstore/perl/WWW/Swagger/PetApi.pm | 40 +- .../petstore/perl/WWW/Swagger/StoreApi.pm | 16 +- .../petstore/perl/WWW/Swagger/UserApi.pm | 32 +- .../petstore/perl/WWW/Swagger/pet_api.pm | 486 ++++++++++++++++ .../petstore/perl/WWW/Swagger/store_api.pm | 262 +++++++++ .../petstore/perl/WWW/Swagger/user_api.pm | 463 ++++++++++++++++ 9 files changed, 1724 insertions(+), 354 deletions(-) create mode 100644 samples/client/petstore/perl/Swagger.pl create mode 100644 samples/client/petstore/perl/WWW/Swagger/pet_api.pm create mode 100644 samples/client/petstore/perl/WWW/Swagger/store_api.pm create mode 100644 samples/client/petstore/perl/WWW/Swagger/user_api.pm 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 index 89afcd23b7ec..92f448729657 100644 --- 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 @@ -149,4 +149,31 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { 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/resources/perl/Swagger.mustache b/modules/swagger-codegen/src/main/resources/perl/Swagger.mustache index 3d6b77d819e8..e58f64107cd0 100644 --- a/modules/swagger-codegen/src/main/resources/perl/Swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/Swagger.mustache @@ -1,326 +1,229 @@ -new; +my $http_user_agent = 'Perl-Swagger'; # HTTP user-agent +my $http_timeout; #timeout +my $base_url; + + +sub new +{ + my $class = shift; + my %args = @_; + + return bless \%args, $class; } -spl_autoload_register('swagger_autoloader'); +# 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; +} -class APIClient { +# 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; +} - public static $POST = "POST"; - public static $GET = "GET"; - public static $PUT = "PUT"; - public static $DELETE = "DELETE"; +# 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) = @_; - /** - * @param string $host the address of the API server - * @param string $headerName a header to pass on requests - */ - function __construct($host, $headerName = null, $headerValue = null) { - $this->host = $host; - $this->headerName = $headerName; - $this->headerValue = $headerValue; + 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 }); } - /** - * Set the user agent of the API client - * - * @param string $user_agent The user agent of the API client - */ - public function setUserAgent($user_agent) { - if (!is_string($user_agent)) { - throw new Exception('User-agent must be a string.'); - } - $this->user_agent= $user_agent; - } - - /** - * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] - */ - public function setTimeout($seconds) { - if (!is_numeric($seconds)) { - throw new Exception('Timeout variable must be numeric.'); - } - $this->curl_timout = $seconds; - } - - /** - * @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 - */ - public function callAPI($resourcePath, $method, $queryParams, $postData, - $headerParams) { - - $headers = array(); - - # Allow API key from $headerParams to override default - $added_api_key = False; - if ($headerParams != null) { - foreach ($headerParams as $key => $val) { - $headers[] = "$key: $val"; - if ($key == $this->headerName) { - $added_api_key = True; - } - } - } - if (! $added_api_key && $this->headerName != null) { - $headers[] = $this->headerName . ": " . $this->headerValue; - } - - if (strpos($headers['Content-Type'], "multipart/form-data") < 0 and (is_object($postData) or is_array($postData))) { - $postData = json_encode($this->sanitizeForSerialization($postData)); - } - - $url = $this->host . $resourcePath; - - $curl = curl_init(); - if ($this->curl_timout) { - curl_setopt($curl, CURLOPT_TIMEOUT, $this->curl_timout); - } - // return the result on success, rather than just TRUE - curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); - curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); - - if (! empty($queryParams)) { - $url = ($url . '?' . http_build_query($queryParams)); - } - - if ($method == self::$POST) { - curl_setopt($curl, CURLOPT_POST, true); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method == self::$PATCH) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method == self::$PUT) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method == self::$DELETE) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method != self::$GET) { - throw new Exception('Method ' . $method . ' is not recognized.'); - } - curl_setopt($curl, CURLOPT_URL, $url); - - // Set user agent - if ($this->user_agent) { - curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent); - } else { // use PHP-Swagger as the default user agent - curl_setopt($curl, CURLOPT_USERAGENT, 'PHP-Swagger'); - } - - // Make the request - $response = curl_exec($curl); - $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); - } 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) { - throw new APIClientException("Unauthorized API request to " . $url . - ": " . serialize($response), 0, $response_info, $response); - } else if ($response_info['http_code'] == 404) { - $data = null; - } else { - throw new APIClientException("Can't connect to the api: " . $url . - " response code: " . - $response_info['http_code'], 0, $response_info, $response); - } - return $data; - } - - /** - * Build a JSON POST object - */ - protected function sanitizeForSerialization($data) - { - 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 - */ - public static function toPathValue($value) { - return rawurlencode(toString($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 - */ - public static function toQueryValue($object) { - 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 - */ - public static function toHeaderValue($value) { - return toString($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 - */ - public static function toFormValue($value) { - return toString($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 - */ - public static function toString($value) { - if ($value instanceof \DateTime) { // datetime in ISO8601 format - return $value->format(\DateTime::ISO8601); - } - else { - return $value; - } - } - - /** - * Deserialize a JSON string into an object - * - * @param object $object object or primitive to be deserialized - * @param string $class class name is passed as a string - * @return object an instance of $class - */ - - public static function deserialize($data, $class) - { - if (null === $data) { - $deserialized = null; - } elseif (substr($class, 0, 4) == 'map[') { - $inner = substr($class, 4, -1); - $values = array(); - if(strrpos($inner, ",") !== false) { - $subClass_array = explode(',', $inner, 2); - $subClass = $subClass_array[1]; - foreach ($data as $key => $value) { - $values[] = array($key => self::deserialize($value, $subClass)); - } - } - $deserialized = $values; - } elseif (strcasecmp(substr($class, 0, 6),'array[') == 0) { - $subClass = substr($class, 6, -1); - $values = array(); - foreach ($data as $key => $value) { - $values[] = self::deserialize($value, $subClass); - } - $deserialized = $values; - } elseif ($class == 'DateTime') { - $deserialized = new \DateTime($data); - } elseif (in_array($class, array('string', 'int', 'float', 'bool'))) { - settype($data, $class); - $deserialized = $data; - } else { - $instance = new $class(); - foreach ($instance::$swaggerTypes as $property => $type) { - if (isset($data->$property)) { - $original_property_name = $instance::$attributeMap[$property]; - $instance->$property = self::deserialize($data->$original_property_name, $type); - } - } - $deserialized = $instance; - } - - return $deserialized; + # body data + my $_body_data = $post_params ? $post_params : $body_data; + + # Make the HTTP request + my $_request = HTTP::Request->new( + $method, $_url, $headers, $_body_data + ); + + $ua->timeout($http_timeout); + $ua->agent($http_user_agent); + my $_response = $ua->request($_request); + + if (!$_response->is_success) { + #TODO croak("Can't connect ot the api ($_response{code}): $_response{message}"); } + + return $_response->content; } -class APIClientException extends Exception { - protected $response, $response_info; - public function __construct($message="", $code=0, $response_info=null, $response=null) { - parent::__construct($message, $code); - $this->response_info = $response_info; - $this->response = $response; +# 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(); } - - public function getResponse() { - return $this->response; - } - - public function getResponseInfo() { - return $this->response_info; + else { + return $value; } } + + +# Deserialize a JSON string into an object +# +# @param object $object object or primitive to be deserialized +# @param string $class class name is passed as a string +# @return object an instance of $class +#sub deserialize +#{ +# my ($data, $class) = @_; +# if (null === $data) { +# $deserialized = null; +# } elseif (substr($class, 0, 4) == 'map[') { +# $inner = substr($class, 4, -1); +# $values = array(); +# if(strrpos($inner, ",") !== false) { +# $subClass_array = explode(',', $inner, 2); +# $subClass = $subClass_array[1]; +# foreach ($data as $key => $value) { +# $values[] = array($key => self::deserialize($value, $subClass)); +# } +# } +# $deserialized = $values; +# } elseif (strcasecmp(substr($class, 0, 6),'array[') == 0) { +# $subClass = substr($class, 6, -1); +# $values = array(); +# foreach ($data as $key => $value) { +# $values[] = self::deserialize($value, $subClass); +# } +# $deserialized = $values; +# } elseif ($class == 'DateTime') { +# $deserialized = new \DateTime($data); +# } elseif (in_array($class, array('string', 'int', 'float', 'bool'))) { +# settype($data, $class); +# $deserialized = $data; +# } else { +# $instance = new $class(); +# foreach ($instance::$swaggerTypes as $property => $type) { +# if (isset($data->$property)) { +# $original_property_name = $instance::$attributeMap[$property]; +# $instance->$property = self::deserialize($data->$original_property_name, $type); +# } +# } +# $deserialized = $instance; +# } +# +# return $deserialized; +#} + +1; diff --git a/samples/client/petstore/perl/Swagger.pl b/samples/client/petstore/perl/Swagger.pl new file mode 100644 index 000000000000..e58f64107cd0 --- /dev/null +++ b/samples/client/petstore/perl/Swagger.pl @@ -0,0 +1,229 @@ +package WWW::Swagger::Swagger; + +use strict; +use warnings; +use utf8; + +use LWP::UserAgent; +use HTTP::Headers; +use HTTP::Response; +use HTTP::Status; +use URI::Query; +use JSON; + +use Scalar::Util; + +# class variables +my $ua = LWP::UserAgent->new; +my $http_user_agent = 'Perl-Swagger'; # HTTP user-agent +my $http_timeout; #timeout +my $base_url; + + +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 + my $_body_data = $post_params ? $post_params : $body_data; + + # Make the HTTP request + my $_request = HTTP::Request->new( + $method, $_url, $headers, $_body_data + ); + + $ua->timeout($http_timeout); + $ua->agent($http_user_agent); + my $_response = $ua->request($_request); + + if (!$_response->is_success) { + #TODO croak("Can't connect ot the api ($_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 object $object object or primitive to be deserialized +# @param string $class class name is passed as a string +# @return object an instance of $class +#sub deserialize +#{ +# my ($data, $class) = @_; +# if (null === $data) { +# $deserialized = null; +# } elseif (substr($class, 0, 4) == 'map[') { +# $inner = substr($class, 4, -1); +# $values = array(); +# if(strrpos($inner, ",") !== false) { +# $subClass_array = explode(',', $inner, 2); +# $subClass = $subClass_array[1]; +# foreach ($data as $key => $value) { +# $values[] = array($key => self::deserialize($value, $subClass)); +# } +# } +# $deserialized = $values; +# } elseif (strcasecmp(substr($class, 0, 6),'array[') == 0) { +# $subClass = substr($class, 6, -1); +# $values = array(); +# foreach ($data as $key => $value) { +# $values[] = self::deserialize($value, $subClass); +# } +# $deserialized = $values; +# } elseif ($class == 'DateTime') { +# $deserialized = new \DateTime($data); +# } elseif (in_array($class, array('string', 'int', 'float', 'bool'))) { +# settype($data, $class); +# $deserialized = $data; +# } else { +# $instance = new $class(); +# foreach ($instance::$swaggerTypes as $property => $type) { +# if (isset($data->$property)) { +# $original_property_name = $instance::$attributeMap[$property]; +# $instance->$property = self::deserialize($data->$original_property_name, $type); +# } +# } +# $deserialized = $instance; +# } +# +# return $deserialized; +#} + +1; diff --git a/samples/client/petstore/perl/WWW/Swagger/PetApi.pm b/samples/client/petstore/perl/WWW/Swagger/PetApi.pm index a76ed8054ba1..94c92c553743 100644 --- a/samples/client/petstore/perl/WWW/Swagger/PetApi.pm +++ b/samples/client/petstore/perl/WWW/Swagger/PetApi.pm @@ -47,14 +47,14 @@ sub new { # - # updatePet + # update_pet # # Update an existing pet # # @param Pet $body Pet object that needs to be added to the store (required) # @return void # - sub updatePet { + sub update_pet { my $self = shift; my %args = @_; @@ -68,7 +68,7 @@ sub new { my $form_params = {}; $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = 'application/json,application/xml,'; @@ -96,14 +96,14 @@ sub new { } # - # addPet + # 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 addPet { + sub add_pet { my $self = shift; my %args = @_; @@ -117,7 +117,7 @@ sub new { my $form_params = {}; $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = 'application/json,application/xml,'; @@ -145,14 +145,14 @@ sub new { } # - # findPetsByStatus + # 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 findPetsByStatus { + sub find_pets_by_status { my $self = shift; my %args = @_; @@ -199,14 +199,14 @@ sub new { } # - # findPetsByTags + # find_pets_by_tags # # Finds Pets by tags # # @param array[string] $tags Tags to filter by (required) # @return array[Pet] # - sub findPetsByTags { + sub find_pets_by_tags { my $self = shift; my %args = @_; @@ -253,14 +253,14 @@ sub new { } # - # getPetById + # get_pet_by_id # # Find pet by ID # # @param int $pet_id ID of pet that needs to be fetched (required) # @return Pet # - sub getPetById { + sub get_pet_by_id { my $self = shift; my %args = @_; @@ -309,7 +309,7 @@ sub new { } # - # updatePetWithForm + # update_pet_with_form # # Updates a pet in the store with form data # @@ -318,7 +318,7 @@ sub new { # @param string $status Updated status of the pet (required) # @return void # - sub updatePetWithForm { + sub update_pet_with_form { my $self = shift; my %args = @_; @@ -332,7 +332,7 @@ sub new { my $form_params = {}; $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = 'application/x-www-form-urlencoded'; + $header_params->{'Content-Type'} = 'application/x-www-form-urlencoded,'; @@ -368,7 +368,7 @@ sub new { } # - # deletePet + # delete_pet # # Deletes a pet # @@ -376,7 +376,7 @@ sub new { # @param int $pet_id Pet id to delete (required) # @return void # - sub deletePet { + sub delete_pet { my $self = shift; my %args = @_; @@ -423,7 +423,7 @@ sub new { } # - # uploadFile + # upload_file # # uploads an image # @@ -432,7 +432,7 @@ sub new { # @param file $file file to upload (required) # @return void # - sub uploadFile { + sub upload_file { my $self = shift; my %args = @_; @@ -446,7 +446,7 @@ sub new { my $form_params = {}; $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = 'multipart/form-data'; + $header_params->{'Content-Type'} = 'multipart/form-data,'; diff --git a/samples/client/petstore/perl/WWW/Swagger/StoreApi.pm b/samples/client/petstore/perl/WWW/Swagger/StoreApi.pm index a9e412ba32c7..cc355cd3b6b5 100644 --- a/samples/client/petstore/perl/WWW/Swagger/StoreApi.pm +++ b/samples/client/petstore/perl/WWW/Swagger/StoreApi.pm @@ -47,13 +47,13 @@ sub new { # - # getInventory + # get_inventory # # Returns pet inventories by status # # @return map[string,int] # - sub getInventory { + sub get_inventory { my $self = shift; my %args = @_; @@ -97,14 +97,14 @@ sub new { } # - # placeOrder + # place_order # # Place an order for a pet # # @param Order $body order placed for purchasing the pet (required) # @return Order # - sub placeOrder { + sub place_order { my $self = shift; my %args = @_; @@ -151,14 +151,14 @@ sub new { } # - # getOrderById + # 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 getOrderById { + sub get_order_by_id { my $self = shift; my %args = @_; @@ -207,14 +207,14 @@ sub new { } # - # deleteOrder + # delete_order # # Delete purchase order by ID # # @param string $order_id ID of the order that needs to be deleted (required) # @return void # - sub deleteOrder { + sub delete_order { my $self = shift; my %args = @_; diff --git a/samples/client/petstore/perl/WWW/Swagger/UserApi.pm b/samples/client/petstore/perl/WWW/Swagger/UserApi.pm index 375f6eaf0c10..316c6e8b99d3 100644 --- a/samples/client/petstore/perl/WWW/Swagger/UserApi.pm +++ b/samples/client/petstore/perl/WWW/Swagger/UserApi.pm @@ -47,14 +47,14 @@ sub new { # - # createUser + # create_user # # Create user # # @param User $body Created user object (required) # @return void # - sub createUser { + sub create_user { my $self = shift; my %args = @_; @@ -96,14 +96,14 @@ sub new { } # - # createUsersWithArrayInput + # 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 createUsersWithArrayInput { + sub create_users_with_array_input { my $self = shift; my %args = @_; @@ -145,14 +145,14 @@ sub new { } # - # createUsersWithListInput + # 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 createUsersWithListInput { + sub create_users_with_list_input { my $self = shift; my %args = @_; @@ -194,7 +194,7 @@ sub new { } # - # loginUser + # login_user # # Logs user into the system # @@ -202,7 +202,7 @@ sub new { # @param string $password The password for login in clear text (required) # @return string # - sub loginUser { + sub login_user { my $self = shift; my %args = @_; @@ -252,13 +252,13 @@ sub new { } # - # logoutUser + # logout_user # # Logs out current logged in user session # # @return void # - sub logoutUser { + sub logout_user { my $self = shift; my %args = @_; @@ -297,14 +297,14 @@ sub new { } # - # getUserByName + # 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 getUserByName { + sub get_user_by_name { my $self = shift; my %args = @_; @@ -353,7 +353,7 @@ sub new { } # - # updateUser + # update_user # # Updated user # @@ -361,7 +361,7 @@ sub new { # @param User $body Updated user object (required) # @return void # - sub updateUser { + sub update_user { my $self = shift; my %args = @_; @@ -408,14 +408,14 @@ sub new { } # - # deleteUser + # delete_user # # Delete user # # @param string $username The name that needs to be deleted (required) # @return void # - sub deleteUser { + sub delete_user { my $self = shift; my %args = @_; diff --git a/samples/client/petstore/perl/WWW/Swagger/pet_api.pm b/samples/client/petstore/perl/WWW/Swagger/pet_api.pm new file mode 100644 index 000000000000..94c92c553743 --- /dev/null +++ b/samples/client/petstore/perl/WWW/Swagger/pet_api.pm @@ -0,0 +1,486 @@ +# +# 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. +# + +require 5.6.0; +use strict; +use warnings; + +#use WWW::Swagger::Model::Category; +#use WWW::Swagger::Model::Pet; + +package WWW::Swagger::PetApi; + +our $VERSION = '2.09'; + + +sub new { + my $class = shift; + my $options = shift; + + croak("You must supply an API client") + unless $options->{api_client}; + + my $self = { + api_client => $options->{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 = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/pet"; + $resource_path =~ s/{format}/json/; + + my $method = "PUT"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = 'application/json,application/xml,'; + + + + + + my $body; + # body params + if (isset($body)) { + $body = $body; + } + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # 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 = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/pet"; + $resource_path =~ s/{format}/json/; + + my $method = "POST"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = 'application/json,application/xml,'; + + + + + + my $body; + # body params + if (isset($body)) { + $body = $body; + } + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # 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 = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/pet/findByStatus"; + $resource_path =~ s/{format}/json/; + + my $method = "GET"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + # query params + if($args{ status }) { + $query_params->{'status'} = $self->api_client->to_query_value($args{ status }); + } + + + + my $body; + + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + if(!$response) { + return; + } + + my $response_object = $self->api_client->deserialize($response, 'array[Pet]'); + 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 = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/pet/findByTags"; + $resource_path =~ s/{format}/json/; + + my $method = "GET"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + # query params + if($args{ tags }) { + $query_params->{'tags'} = $self->api_client->to_query_value($args{ tags }); + } + + + + my $body; + + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + if(!$response) { + return; + } + + my $response_object = $self->api_client->deserialize($response, 'array[Pet]'); + 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 = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/pet/{petId}"; + $resource_path =~ s/{format}/json/; + + my $method = "GET"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + # path params + if( $args{ pet_id }) { + my $base_variable = "{" + "petId" + "}"; + my $base_value = $self->api_client->to_path_value($args{ pet_id }); + $resource_path = s/$base_variable/$base_value/; + } + + my $body; + + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + if(!$response) { + return; + } + + my $response_object = $self->api_client->deserialize($response, 'Pet'); + 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 = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/pet/{petId}"; + $resource_path =~ s/{format}/json/; + + my $method = "POST"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = 'application/x-www-form-urlencoded,'; + + + + # path params + if( $args{ pet_id }) { + my $base_variable = "{" + "petId" + "}"; + my $base_value = $self->api_client->to_path_value($args{ pet_id }); + $resource_path = s/$base_variable/$base_value/; + } + # form params + if ($args{ name }) { + $form_params->{'name'} = $self->api_client->to_form_value($args{ name }); + } # form params + if ($args{ status }) { + $form_params->{'status'} = $self->api_client->to_form_value($args{ status }); + } + my $body; + + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # 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 = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/pet/{petId}"; + $resource_path =~ s/{format}/json/; + + my $method = "DELETE"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + # header params + if($args{ api_key }) { + $header_params->{'api_key'} = $self->apiClient->to_header_value($args{ api_key }); + } + # path params + if( $args{ pet_id }) { + my $base_variable = "{" + "petId" + "}"; + my $base_value = $self->api_client->to_path_value($args{ pet_id }); + $resource_path = s/$base_variable/$base_value/; + } + + my $body; + + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # 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 = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/pet/{petId}/uploadImage"; + $resource_path =~ s/{format}/json/; + + my $method = "POST"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = 'multipart/form-data,'; + + + + # path params + if( $args{ pet_id }) { + my $base_variable = "{" + "petId" + "}"; + my $base_value = $self->api_client->to_path_value($args{ pet_id }); + $resource_path = s/$base_variable/$base_value/; + } + # form params + if ($args{ additional_metadata }) { + $form_params->{'additionalMetadata'} = $self->api_client->to_form_value($args{ additional_metadata }); + } # form params + if ($args{ file }) { + $form_params->{'file'} = '@' . $self->api_client->to_form_value($args{ file }); + } + my $body; + + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + + +1; diff --git a/samples/client/petstore/perl/WWW/Swagger/store_api.pm b/samples/client/petstore/perl/WWW/Swagger/store_api.pm new file mode 100644 index 000000000000..cc355cd3b6b5 --- /dev/null +++ b/samples/client/petstore/perl/WWW/Swagger/store_api.pm @@ -0,0 +1,262 @@ +# +# 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. +# + +require 5.6.0; +use strict; +use warnings; + +#use WWW::Swagger::Model::Category; +#use WWW::Swagger::Model::Pet; + +package WWW::Swagger::StoreApi; + +our $VERSION = '2.09'; + + +sub new { + my $class = shift; + my $options = shift; + + croak("You must supply an API client") + unless $options->{api_client}; + + my $self = { + api_client => $options->{api_client} + }; + + bless $self, $class; + +} + + + # + # get_inventory + # + # Returns pet inventories by status + # + # @return map[string,int] + # + sub get_inventory { + my $self = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/store/inventory"; + $resource_path =~ s/{format}/json/; + + my $method = "GET"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + + + my $body; + + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + if(!$response) { + return; + } + + my $response_object = $self->api_client->deserialize($response, 'map[string,int]'); + 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 = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/store/order"; + $resource_path =~ s/{format}/json/; + + my $method = "POST"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + + + my $body; + # body params + if (isset($body)) { + $body = $body; + } + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + if(!$response) { + return; + } + + my $response_object = $self->api_client->deserialize($response, 'Order'); + 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 = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/store/order/{orderId}"; + $resource_path =~ s/{format}/json/; + + my $method = "GET"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + # path params + if( $args{ order_id }) { + my $base_variable = "{" + "orderId" + "}"; + my $base_value = $self->api_client->to_path_value($args{ order_id }); + $resource_path = s/$base_variable/$base_value/; + } + + my $body; + + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + if(!$response) { + return; + } + + my $response_object = $self->api_client->deserialize($response, 'Order'); + 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 = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/store/order/{orderId}"; + $resource_path =~ s/{format}/json/; + + my $method = "DELETE"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + # path params + if( $args{ order_id }) { + my $base_variable = "{" + "orderId" + "}"; + my $base_value = $self->api_client->to_path_value($args{ order_id }); + $resource_path = s/$base_variable/$base_value/; + } + + my $body; + + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + + +1; diff --git a/samples/client/petstore/perl/WWW/Swagger/user_api.pm b/samples/client/petstore/perl/WWW/Swagger/user_api.pm new file mode 100644 index 000000000000..316c6e8b99d3 --- /dev/null +++ b/samples/client/petstore/perl/WWW/Swagger/user_api.pm @@ -0,0 +1,463 @@ +# +# 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. +# + +require 5.6.0; +use strict; +use warnings; + +#use WWW::Swagger::Model::Category; +#use WWW::Swagger::Model::Pet; + +package WWW::Swagger::UserApi; + +our $VERSION = '2.09'; + + +sub new { + my $class = shift; + my $options = shift; + + croak("You must supply an API client") + unless $options->{api_client}; + + my $self = { + api_client => $options->{api_client} + }; + + bless $self, $class; + +} + + + # + # create_user + # + # Create user + # + # @param User $body Created user object (required) + # @return void + # + sub create_user { + my $self = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/user"; + $resource_path =~ s/{format}/json/; + + my $method = "POST"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + + + my $body; + # body params + if (isset($body)) { + $body = $body; + } + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # 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 = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/user/createWithArray"; + $resource_path =~ s/{format}/json/; + + my $method = "POST"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + + + my $body; + # body params + if (isset($body)) { + $body = $body; + } + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # 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 = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/user/createWithList"; + $resource_path =~ s/{format}/json/; + + my $method = "POST"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + + + my $body; + # body params + if (isset($body)) { + $body = $body; + } + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # 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 = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/user/login"; + $resource_path =~ s/{format}/json/; + + my $method = "GET"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + # query params + if($args{ username }) { + $query_params->{'username'} = $self->api_client->to_query_value($args{ username }); + } # query params + if($args{ password }) { + $query_params->{'password'} = $self->api_client->to_query_value($args{ password }); + } + + + + my $body; + + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + if(!$response) { + return; + } + + my $response_object = $self->api_client->deserialize($response, 'string'); + return $response_object; + } + + # + # logout_user + # + # Logs out current logged in user session + # + # @return void + # + sub logout_user { + my $self = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/user/logout"; + $resource_path =~ s/{format}/json/; + + my $method = "GET"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + + + my $body; + + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # 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 = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/user/{username}"; + $resource_path =~ s/{format}/json/; + + my $method = "GET"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + # path params + if( $args{ username }) { + my $base_variable = "{" + "username" + "}"; + my $base_value = $self->api_client->to_path_value($args{ username }); + $resource_path = s/$base_variable/$base_value/; + } + + my $body; + + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + if(!$response) { + return; + } + + my $response_object = $self->api_client->deserialize($response, 'User'); + 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 = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/user/{username}"; + $resource_path =~ s/{format}/json/; + + my $method = "PUT"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + # path params + if( $args{ username }) { + my $base_variable = "{" + "username" + "}"; + my $base_value = $self->api_client->to_path_value($args{ username }); + $resource_path = s/$base_variable/$base_value/; + } + + my $body; + # body params + if (isset($body)) { + $body = $body; + } + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + # + # delete_user + # + # Delete user + # + # @param string $username The name that needs to be deleted (required) + # @return void + # + sub delete_user { + my $self = shift; + my %args = @_; + + # parse inputs + my $resource_path = "/user/{username}"; + $resource_path =~ s/{format}/json/; + + my $method = "DELETE"; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + $header_params->{'Accept'} = 'application/json,application/xml'; + $header_params->{'Content-Type'} = ''; + + + + # path params + if( $args{ username }) { + my $base_variable = "{" + "username" + "}"; + my $base_value = $self->api_client->to_path_value($args{ username }); + $resource_path = s/$base_variable/$base_value/; + } + + my $body; + + + # for HTTP post (form) + $body = $body ? undef : $form_params; + + if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { + $body = http_build_query($body); + } + + # make the API Call + my $response = $self->api_client->call_api($resource_path, $method, + $query_params, $body, + $header_params); + + + } + + + +1; From 07cd23edac7cfbfa4d3a1918bb4e3598c5efc92b Mon Sep 17 00:00:00 2001 From: William Cheng Date: Wed, 6 May 2015 18:46:31 +0800 Subject: [PATCH 18/67] seralization and deserialization work, get_pet_by_id and update_pet_with_form work --- .../codegen/languages/PerlClientCodegen.java | 8 +- .../src/main/resources/perl/api.mustache | 112 ++-- .../src/main/resources/perl/model.mustache | 134 +++-- .../perl/WWW/Swagger/Model/Category.pm | 60 -- .../petstore/perl/WWW/Swagger/Model/Order.pm | 79 --- .../petstore/perl/WWW/Swagger/Model/Pet.pm | 79 --- .../petstore/perl/WWW/Swagger/Model/Tag.pm | 60 -- .../petstore/perl/WWW/Swagger/Model/User.pm | 87 --- .../petstore/perl/WWW/Swagger/PetApi.pm | 486 ---------------- .../petstore/perl/WWW/Swagger/StoreApi.pm | 262 --------- .../petstore/perl/WWW/Swagger/UserApi.pm | 463 --------------- .../petstore/perl/WWW/Swagger/pet_api.pm | 486 ---------------- .../petstore/perl/WWW/Swagger/store_api.pm | 262 --------- .../petstore/perl/WWW/Swagger/user_api.pm | 463 --------------- samples/client/petstore/perl/http.pl | 25 + .../perl/lib/WWW/SwaggerClient/APIClient.pm | 239 ++++++++ .../lib/WWW/SwaggerClient/Model/Category.pm | 97 ++++ .../perl/lib/WWW/SwaggerClient/Model/Order.pm | 113 ++++ .../perl/lib/WWW/SwaggerClient/Model/Pet.pm | 113 ++++ .../perl/lib/WWW/SwaggerClient/Model/Tag.pm | 97 ++++ .../perl/lib/WWW/SwaggerClient/Model/User.pm | 121 ++++ .../perl/lib/WWW/SwaggerClient/PetApi.pm | 538 ++++++++++++++++++ .../perl/lib/WWW/SwaggerClient/StoreApi.pm | 292 ++++++++++ .../{ => lib/WWW/SwaggerClient}/Swagger.pl | 3 +- .../perl/lib/WWW/SwaggerClient/Swagger.pm | 17 +- .../perl/lib/WWW/SwaggerClient/UserApi.pm | 512 +++++++++++++++++ samples/client/petstore/perl/test.pl | 42 ++ 27 files changed, 2356 insertions(+), 2894 deletions(-) delete mode 100644 samples/client/petstore/perl/WWW/Swagger/Model/Category.pm delete mode 100644 samples/client/petstore/perl/WWW/Swagger/Model/Order.pm delete mode 100644 samples/client/petstore/perl/WWW/Swagger/Model/Pet.pm delete mode 100644 samples/client/petstore/perl/WWW/Swagger/Model/Tag.pm delete mode 100644 samples/client/petstore/perl/WWW/Swagger/Model/User.pm delete mode 100644 samples/client/petstore/perl/WWW/Swagger/PetApi.pm delete mode 100644 samples/client/petstore/perl/WWW/Swagger/StoreApi.pm delete mode 100644 samples/client/petstore/perl/WWW/Swagger/UserApi.pm delete mode 100644 samples/client/petstore/perl/WWW/Swagger/pet_api.pm delete mode 100644 samples/client/petstore/perl/WWW/Swagger/store_api.pm delete mode 100644 samples/client/petstore/perl/WWW/Swagger/user_api.pm create mode 100644 samples/client/petstore/perl/http.pl create mode 100644 samples/client/petstore/perl/lib/WWW/SwaggerClient/APIClient.pm create mode 100644 samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/Category.pm create mode 100644 samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/Order.pm create mode 100644 samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/Pet.pm create mode 100644 samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/Tag.pm create mode 100644 samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/User.pm create mode 100644 samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm create mode 100644 samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm rename samples/client/petstore/perl/{ => lib/WWW/SwaggerClient}/Swagger.pl (99%) rename modules/swagger-codegen/src/main/resources/perl/Swagger.mustache => samples/client/petstore/perl/lib/WWW/SwaggerClient/Swagger.pm (97%) create mode 100644 samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm create mode 100644 samples/client/petstore/perl/test.pl 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 index 92f448729657..d187bcd90117 100644 --- 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 @@ -8,7 +8,7 @@ import java.util.*; import java.io.File; public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String invokerPackage = "com.wordnik.client"; + protected String invokerPackage = "SwaggerClient"; protected String groupId = "com.wordnik"; protected String artifactId = "swagger-client"; protected String artifactVersion = "1.0.0"; @@ -59,7 +59,7 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("List", "array"); typeMapping.put("map", "map"); - supportingFiles.add(new SupportingFile("Swagger.mustache", "", "Swagger.pl")); + supportingFiles.add(new SupportingFile("APIClient.mustache", "lib/WWW/" + invokerPackage, "APIClient.pm")); } @Override @@ -69,11 +69,11 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String apiFileFolder() { - return outputFolder + "/WWW/Swagger/" + apiPackage().replace('.', File.separatorChar); + return outputFolder + "/lib/WWW/" + invokerPackage + apiPackage().replace('.', File.separatorChar); } public String modelFileFolder() { - return outputFolder + "/WWW/Swagger/" + modelPackage().replace('.', File.separatorChar); + return outputFolder + "/lib/WWW/" + invokerPackage + "/" + modelPackage().replace('.', File.separatorChar); } @Override diff --git a/modules/swagger-codegen/src/main/resources/perl/api.mustache b/modules/swagger-codegen/src/main/resources/perl/api.mustache index 76f7b31aa0b5..56596c5733d1 100644 --- a/modules/swagger-codegen/src/main/resources/perl/api.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/api.mustache @@ -17,29 +17,44 @@ # 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}} -package WWW::Swagger::{{classname}}; -our $VERSION = '2.09'; +use WWW::{{invokerPackage}}::APIClient; +our @EXPORT_OK = qw( + {{#operation}}{{{nickname}}} + {{/operation}} +); sub new { my $class = shift; - my $options = shift; + my $default_api_client = WWW::{{invokerPackage}}::APIClient->new; + #TODO fix default + #my (%arg) = ( + # 'api_client' => $default_api_client, + # @_ + #); - croak("You must supply an API client") - unless $options->{api_client}; + #croak("You must supply an API client") + # unless $options->{api_client}; my $self = { - api_client => $options->{api_client} + #api_client => $options->{api_client} + api_client => $default_api_client }; bless $self, $class; @@ -56,63 +71,72 @@ sub new { {{/allParams}} # @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} # sub {{nickname}} { - my $self = shift; - my %args = @_; + my ($self, $args) = @_; - # parse inputs - my $resource_path = "{{path}}"; - $resource_path =~ s/{format}/json/; + {{#allParams}}{{#required}} + # verify the required parameter '{{paramName}}' is set + unless (exists $args->{'{{paramName}}'}) { + croak("Missing the required parameter '{{paramName}}' when calling {{nickname}}"); + } + {{/required}}{{/allParams}} - my $method = "{{httpMethod}}"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = '{{#produces}}{{mediaType}}{{#hasMore}},{{/hasMore}}{{/produces}}'; - $header_params->{'Content-Type'} = '{{#consumes}}{{mediaType}}{{#hasMore}},{{/hasMore}}{{/consumes}}'; + # 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 = {}; + + my $_header_accept = '{{#produces}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/produces}}'; + if ($_header_accept ne '') { + $header_params->{'Accept'} = $_header_accept; + } + my @_header_content_type = ({{#consumes}}'{{mediaType}}'{{#hasMore}},{{/hasMore}}{{/consumes}}); + $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; {{#queryParams}} # query params - if($args{ {{paramName}} }) { - $query_params->{'{{baseName}}'} = $self->api_client->to_query_value($args{ {{paramName}} }); + if ( exists $args->{'{{paramName}}'}) { + $query_params->{'{{baseName}}'} = WWW::SwaggerClient::APIClient::to_query_value($args->{'{{paramName}}'}); }{{/queryParams}} {{#headerParams}} # header params - if($args{ {{paramName}} }) { - $header_params->{'{{baseName}}'} = $self->apiClient->to_header_value($args{ {{paramName}} }); + if ( exists $args->{'{{paramName}}'}) { + $header_params->{'{{baseName}}'} = WWW::SwaggerClient::APIClient::to_header_value($args->{'{{paramName}}'}); }{{/headerParams}} {{#pathParams}} # path params - if( $args{ {{paramName}} }) { - my $base_variable = "{" + "{{baseName}}" + "}"; - my $base_value = $self->api_client->to_path_value($args{ {{paramName}} }); - $resource_path = s/$base_variable/$base_value/; + if ( exists $args->{'{{paramName}}'}) { + my $_base_variable = "{" . "{{baseName}}" . "}"; + my $_base_value = WWW::SwaggerClient::APIClient::to_path_value($args->{'{{paramName}}'}); + $_resource_path =~ s/$_base_variable/$_base_value/g; }{{/pathParams}} {{#formParams}} # form params - if ($args{ {{paramName}} }) { - $form_params->{'{{baseName}}'} = {{#isFile}}'@' . {{/isFile}}$self->api_client->to_form_value($args{ {{paramName}} }); + if ( exists $args->{'{{paramName}}'} ) { + $form_params->{'{{baseName}}'} = {{#isFile}}'@' . {{/isFile}}WWW::SwaggerClient::APIClient::to_form_value($args->{'{{paramName}}'}); }{{/formParams}} - my $body; + my $_body_data; {{#bodyParams}} # body params - if (isset(${{paramName}})) { - $body = ${{paramName}}; + if ( exists $args->{'{{paramName}}'}) { + $_body_data = $args->{'{{paramName}}'}; }{{/bodyParams}} # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } + #$_body_data = $_body ? undef : $form_params; # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - {{#returnType}}if(!$response) { + {{#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($response, '{{returnType}}'); - return $response_object;{{/returnType}} + 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}} diff --git a/modules/swagger-codegen/src/main/resources/perl/model.mustache b/modules/swagger-codegen/src/main/resources/perl/model.mustache index 4540f973633f..3612ed1050a3 100644 --- a/modules/swagger-codegen/src/main/resources/perl/model.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/model.mustache @@ -1,66 +1,100 @@ - '{{{datatype}}}'{{#hasMore}}, {{/hasMore}}{{/vars}} - ); +}; - static $attributeMap = array( +my $attribute_map = { {{#vars}}'{{name}}' => '{{baseName}}'{{#hasMore}}, {{/hasMore}}{{/vars}} - ); +}; - {{#vars}}{{#description}} - /** - * {{{description}}} - */{{/description}} - public ${{name}}; /* {{{datatype}}} */{{/vars}} +# new object +sub new { + my ($class, $args) = @_; + my $self = { + {{#vars}}#{{#description}}{{{description}}}{{/description}} + '{{name}}' => $args->{'{{baseName}}'}{{#hasMore}}, + {{/hasMore}}{{/vars}} + }; - public function __construct(array $data) { - {{#vars}}$this->{{name}} = $data["{{name}}"];{{#hasMore}} - {{/hasMore}}{{/vars}} + return bless $self, $class; +} + +# 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 $attribute_map) { + if (defined $self->{$attribute_map->{$_key}}) { + $_data->{$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 $swagger_types) { + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$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); + } } - public function offsetExists($offset) { - return isset($this->$offset); - } - - public function offsetGet($offset) { - return $this->$offset; - } - - public function offsetSet($offset, $value) { - $this->$offset = $value; - } - - public function offsetUnset($offset) { - unset($this->$offset); + 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$/, ('string', 'int', 'float', 'bool')) ) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Model::$type->new()"; + return $_instance->from_hash($data); } } + {{/model}} {{/models}} + +1; diff --git a/samples/client/petstore/perl/WWW/Swagger/Model/Category.pm b/samples/client/petstore/perl/WWW/Swagger/Model/Category.pm deleted file mode 100644 index 98e7ba24800d..000000000000 --- a/samples/client/petstore/perl/WWW/Swagger/Model/Category.pm +++ /dev/null @@ -1,60 +0,0 @@ - 'int', - 'name' => 'string' - ); - - static $attributeMap = array( - 'id' => 'id', - 'name' => 'name' - ); - - - public $id; /* int */ - public $name; /* string */ - - public function __construct(array $data) { - $this->id = $data["id"]; - $this->name = $data["name"]; - } - - public function offsetExists($offset) { - return isset($this->$offset); - } - - public function offsetGet($offset) { - return $this->$offset; - } - - public function offsetSet($offset, $value) { - $this->$offset = $value; - } - - public function offsetUnset($offset) { - unset($this->$offset); - } -} diff --git a/samples/client/petstore/perl/WWW/Swagger/Model/Order.pm b/samples/client/petstore/perl/WWW/Swagger/Model/Order.pm deleted file mode 100644 index 2770e8bbbdf1..000000000000 --- a/samples/client/petstore/perl/WWW/Swagger/Model/Order.pm +++ /dev/null @@ -1,79 +0,0 @@ - 'int', - 'pet_id' => 'int', - 'quantity' => 'int', - 'ship_date' => 'DateTime', - 'status' => 'string', - 'complete' => 'boolean' - ); - - static $attributeMap = array( - 'id' => 'id', - 'pet_id' => 'petId', - 'quantity' => 'quantity', - 'ship_date' => 'shipDate', - 'status' => 'status', - 'complete' => 'complete' - ); - - - public $id; /* int */ - public $pet_id; /* int */ - public $quantity; /* int */ - public $ship_date; /* DateTime */ - /** - * Order Status - */ - public $status; /* string */ - public $complete; /* boolean */ - - public function __construct(array $data) { - $this->id = $data["id"]; - $this->pet_id = $data["pet_id"]; - $this->quantity = $data["quantity"]; - $this->ship_date = $data["ship_date"]; - $this->status = $data["status"]; - $this->complete = $data["complete"]; - } - - public function offsetExists($offset) { - return isset($this->$offset); - } - - public function offsetGet($offset) { - return $this->$offset; - } - - public function offsetSet($offset, $value) { - $this->$offset = $value; - } - - public function offsetUnset($offset) { - unset($this->$offset); - } -} diff --git a/samples/client/petstore/perl/WWW/Swagger/Model/Pet.pm b/samples/client/petstore/perl/WWW/Swagger/Model/Pet.pm deleted file mode 100644 index eee7fa3784cd..000000000000 --- a/samples/client/petstore/perl/WWW/Swagger/Model/Pet.pm +++ /dev/null @@ -1,79 +0,0 @@ - 'int', - 'category' => 'Category', - 'name' => 'string', - 'photo_urls' => 'array[string]', - 'tags' => 'array[Tag]', - 'status' => 'string' - ); - - static $attributeMap = array( - 'id' => 'id', - 'category' => 'category', - 'name' => 'name', - 'photo_urls' => 'photoUrls', - 'tags' => 'tags', - 'status' => 'status' - ); - - - public $id; /* int */ - public $category; /* Category */ - public $name; /* string */ - public $photo_urls; /* array[string] */ - public $tags; /* array[Tag] */ - /** - * pet status in the store - */ - public $status; /* string */ - - public function __construct(array $data) { - $this->id = $data["id"]; - $this->category = $data["category"]; - $this->name = $data["name"]; - $this->photo_urls = $data["photo_urls"]; - $this->tags = $data["tags"]; - $this->status = $data["status"]; - } - - public function offsetExists($offset) { - return isset($this->$offset); - } - - public function offsetGet($offset) { - return $this->$offset; - } - - public function offsetSet($offset, $value) { - $this->$offset = $value; - } - - public function offsetUnset($offset) { - unset($this->$offset); - } -} diff --git a/samples/client/petstore/perl/WWW/Swagger/Model/Tag.pm b/samples/client/petstore/perl/WWW/Swagger/Model/Tag.pm deleted file mode 100644 index f8efc998df66..000000000000 --- a/samples/client/petstore/perl/WWW/Swagger/Model/Tag.pm +++ /dev/null @@ -1,60 +0,0 @@ - 'int', - 'name' => 'string' - ); - - static $attributeMap = array( - 'id' => 'id', - 'name' => 'name' - ); - - - public $id; /* int */ - public $name; /* string */ - - public function __construct(array $data) { - $this->id = $data["id"]; - $this->name = $data["name"]; - } - - public function offsetExists($offset) { - return isset($this->$offset); - } - - public function offsetGet($offset) { - return $this->$offset; - } - - public function offsetSet($offset, $value) { - $this->$offset = $value; - } - - public function offsetUnset($offset) { - unset($this->$offset); - } -} diff --git a/samples/client/petstore/perl/WWW/Swagger/Model/User.pm b/samples/client/petstore/perl/WWW/Swagger/Model/User.pm deleted file mode 100644 index d6b520eba51d..000000000000 --- a/samples/client/petstore/perl/WWW/Swagger/Model/User.pm +++ /dev/null @@ -1,87 +0,0 @@ - 'int', - 'username' => 'string', - 'first_name' => 'string', - 'last_name' => 'string', - 'email' => 'string', - 'password' => 'string', - 'phone' => 'string', - 'user_status' => 'int' - ); - - static $attributeMap = array( - 'id' => 'id', - 'username' => 'username', - 'first_name' => 'firstName', - 'last_name' => 'lastName', - 'email' => 'email', - 'password' => 'password', - 'phone' => 'phone', - 'user_status' => 'userStatus' - ); - - - public $id; /* int */ - public $username; /* string */ - public $first_name; /* string */ - public $last_name; /* string */ - public $email; /* string */ - public $password; /* string */ - public $phone; /* string */ - /** - * User Status - */ - public $user_status; /* int */ - - public function __construct(array $data) { - $this->id = $data["id"]; - $this->username = $data["username"]; - $this->first_name = $data["first_name"]; - $this->last_name = $data["last_name"]; - $this->email = $data["email"]; - $this->password = $data["password"]; - $this->phone = $data["phone"]; - $this->user_status = $data["user_status"]; - } - - public function offsetExists($offset) { - return isset($this->$offset); - } - - public function offsetGet($offset) { - return $this->$offset; - } - - public function offsetSet($offset, $value) { - $this->$offset = $value; - } - - public function offsetUnset($offset) { - unset($this->$offset); - } -} diff --git a/samples/client/petstore/perl/WWW/Swagger/PetApi.pm b/samples/client/petstore/perl/WWW/Swagger/PetApi.pm deleted file mode 100644 index 94c92c553743..000000000000 --- a/samples/client/petstore/perl/WWW/Swagger/PetApi.pm +++ /dev/null @@ -1,486 +0,0 @@ -# -# 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. -# - -require 5.6.0; -use strict; -use warnings; - -#use WWW::Swagger::Model::Category; -#use WWW::Swagger::Model::Pet; - -package WWW::Swagger::PetApi; - -our $VERSION = '2.09'; - - -sub new { - my $class = shift; - my $options = shift; - - croak("You must supply an API client") - unless $options->{api_client}; - - my $self = { - api_client => $options->{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 = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/pet"; - $resource_path =~ s/{format}/json/; - - my $method = "PUT"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = 'application/json,application/xml,'; - - - - - - my $body; - # body params - if (isset($body)) { - $body = $body; - } - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # 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 = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/pet"; - $resource_path =~ s/{format}/json/; - - my $method = "POST"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = 'application/json,application/xml,'; - - - - - - my $body; - # body params - if (isset($body)) { - $body = $body; - } - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # 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 = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/pet/findByStatus"; - $resource_path =~ s/{format}/json/; - - my $method = "GET"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - # query params - if($args{ status }) { - $query_params->{'status'} = $self->api_client->to_query_value($args{ status }); - } - - - - my $body; - - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - if(!$response) { - return; - } - - my $response_object = $self->api_client->deserialize($response, 'array[Pet]'); - 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 = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/pet/findByTags"; - $resource_path =~ s/{format}/json/; - - my $method = "GET"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - # query params - if($args{ tags }) { - $query_params->{'tags'} = $self->api_client->to_query_value($args{ tags }); - } - - - - my $body; - - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - if(!$response) { - return; - } - - my $response_object = $self->api_client->deserialize($response, 'array[Pet]'); - 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 = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/pet/{petId}"; - $resource_path =~ s/{format}/json/; - - my $method = "GET"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - # path params - if( $args{ pet_id }) { - my $base_variable = "{" + "petId" + "}"; - my $base_value = $self->api_client->to_path_value($args{ pet_id }); - $resource_path = s/$base_variable/$base_value/; - } - - my $body; - - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - if(!$response) { - return; - } - - my $response_object = $self->api_client->deserialize($response, 'Pet'); - 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 = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/pet/{petId}"; - $resource_path =~ s/{format}/json/; - - my $method = "POST"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = 'application/x-www-form-urlencoded,'; - - - - # path params - if( $args{ pet_id }) { - my $base_variable = "{" + "petId" + "}"; - my $base_value = $self->api_client->to_path_value($args{ pet_id }); - $resource_path = s/$base_variable/$base_value/; - } - # form params - if ($args{ name }) { - $form_params->{'name'} = $self->api_client->to_form_value($args{ name }); - } # form params - if ($args{ status }) { - $form_params->{'status'} = $self->api_client->to_form_value($args{ status }); - } - my $body; - - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # 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 = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/pet/{petId}"; - $resource_path =~ s/{format}/json/; - - my $method = "DELETE"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - # header params - if($args{ api_key }) { - $header_params->{'api_key'} = $self->apiClient->to_header_value($args{ api_key }); - } - # path params - if( $args{ pet_id }) { - my $base_variable = "{" + "petId" + "}"; - my $base_value = $self->api_client->to_path_value($args{ pet_id }); - $resource_path = s/$base_variable/$base_value/; - } - - my $body; - - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # 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 = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/pet/{petId}/uploadImage"; - $resource_path =~ s/{format}/json/; - - my $method = "POST"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = 'multipart/form-data,'; - - - - # path params - if( $args{ pet_id }) { - my $base_variable = "{" + "petId" + "}"; - my $base_value = $self->api_client->to_path_value($args{ pet_id }); - $resource_path = s/$base_variable/$base_value/; - } - # form params - if ($args{ additional_metadata }) { - $form_params->{'additionalMetadata'} = $self->api_client->to_form_value($args{ additional_metadata }); - } # form params - if ($args{ file }) { - $form_params->{'file'} = '@' . $self->api_client->to_form_value($args{ file }); - } - my $body; - - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - - -1; diff --git a/samples/client/petstore/perl/WWW/Swagger/StoreApi.pm b/samples/client/petstore/perl/WWW/Swagger/StoreApi.pm deleted file mode 100644 index cc355cd3b6b5..000000000000 --- a/samples/client/petstore/perl/WWW/Swagger/StoreApi.pm +++ /dev/null @@ -1,262 +0,0 @@ -# -# 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. -# - -require 5.6.0; -use strict; -use warnings; - -#use WWW::Swagger::Model::Category; -#use WWW::Swagger::Model::Pet; - -package WWW::Swagger::StoreApi; - -our $VERSION = '2.09'; - - -sub new { - my $class = shift; - my $options = shift; - - croak("You must supply an API client") - unless $options->{api_client}; - - my $self = { - api_client => $options->{api_client} - }; - - bless $self, $class; - -} - - - # - # get_inventory - # - # Returns pet inventories by status - # - # @return map[string,int] - # - sub get_inventory { - my $self = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/store/inventory"; - $resource_path =~ s/{format}/json/; - - my $method = "GET"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - - - my $body; - - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - if(!$response) { - return; - } - - my $response_object = $self->api_client->deserialize($response, 'map[string,int]'); - 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 = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/store/order"; - $resource_path =~ s/{format}/json/; - - my $method = "POST"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - - - my $body; - # body params - if (isset($body)) { - $body = $body; - } - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - if(!$response) { - return; - } - - my $response_object = $self->api_client->deserialize($response, 'Order'); - 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 = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/store/order/{orderId}"; - $resource_path =~ s/{format}/json/; - - my $method = "GET"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - # path params - if( $args{ order_id }) { - my $base_variable = "{" + "orderId" + "}"; - my $base_value = $self->api_client->to_path_value($args{ order_id }); - $resource_path = s/$base_variable/$base_value/; - } - - my $body; - - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - if(!$response) { - return; - } - - my $response_object = $self->api_client->deserialize($response, 'Order'); - 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 = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/store/order/{orderId}"; - $resource_path =~ s/{format}/json/; - - my $method = "DELETE"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - # path params - if( $args{ order_id }) { - my $base_variable = "{" + "orderId" + "}"; - my $base_value = $self->api_client->to_path_value($args{ order_id }); - $resource_path = s/$base_variable/$base_value/; - } - - my $body; - - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - - -1; diff --git a/samples/client/petstore/perl/WWW/Swagger/UserApi.pm b/samples/client/petstore/perl/WWW/Swagger/UserApi.pm deleted file mode 100644 index 316c6e8b99d3..000000000000 --- a/samples/client/petstore/perl/WWW/Swagger/UserApi.pm +++ /dev/null @@ -1,463 +0,0 @@ -# -# 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. -# - -require 5.6.0; -use strict; -use warnings; - -#use WWW::Swagger::Model::Category; -#use WWW::Swagger::Model::Pet; - -package WWW::Swagger::UserApi; - -our $VERSION = '2.09'; - - -sub new { - my $class = shift; - my $options = shift; - - croak("You must supply an API client") - unless $options->{api_client}; - - my $self = { - api_client => $options->{api_client} - }; - - bless $self, $class; - -} - - - # - # create_user - # - # Create user - # - # @param User $body Created user object (required) - # @return void - # - sub create_user { - my $self = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/user"; - $resource_path =~ s/{format}/json/; - - my $method = "POST"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - - - my $body; - # body params - if (isset($body)) { - $body = $body; - } - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # 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 = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/user/createWithArray"; - $resource_path =~ s/{format}/json/; - - my $method = "POST"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - - - my $body; - # body params - if (isset($body)) { - $body = $body; - } - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # 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 = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/user/createWithList"; - $resource_path =~ s/{format}/json/; - - my $method = "POST"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - - - my $body; - # body params - if (isset($body)) { - $body = $body; - } - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # 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 = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/user/login"; - $resource_path =~ s/{format}/json/; - - my $method = "GET"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - # query params - if($args{ username }) { - $query_params->{'username'} = $self->api_client->to_query_value($args{ username }); - } # query params - if($args{ password }) { - $query_params->{'password'} = $self->api_client->to_query_value($args{ password }); - } - - - - my $body; - - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - if(!$response) { - return; - } - - my $response_object = $self->api_client->deserialize($response, 'string'); - return $response_object; - } - - # - # logout_user - # - # Logs out current logged in user session - # - # @return void - # - sub logout_user { - my $self = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/user/logout"; - $resource_path =~ s/{format}/json/; - - my $method = "GET"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - - - my $body; - - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # 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 = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/user/{username}"; - $resource_path =~ s/{format}/json/; - - my $method = "GET"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - # path params - if( $args{ username }) { - my $base_variable = "{" + "username" + "}"; - my $base_value = $self->api_client->to_path_value($args{ username }); - $resource_path = s/$base_variable/$base_value/; - } - - my $body; - - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - if(!$response) { - return; - } - - my $response_object = $self->api_client->deserialize($response, 'User'); - 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 = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/user/{username}"; - $resource_path =~ s/{format}/json/; - - my $method = "PUT"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - # path params - if( $args{ username }) { - my $base_variable = "{" + "username" + "}"; - my $base_value = $self->api_client->to_path_value($args{ username }); - $resource_path = s/$base_variable/$base_value/; - } - - my $body; - # body params - if (isset($body)) { - $body = $body; - } - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # delete_user - # - # Delete user - # - # @param string $username The name that needs to be deleted (required) - # @return void - # - sub delete_user { - my $self = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/user/{username}"; - $resource_path =~ s/{format}/json/; - - my $method = "DELETE"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - # path params - if( $args{ username }) { - my $base_variable = "{" + "username" + "}"; - my $base_value = $self->api_client->to_path_value($args{ username }); - $resource_path = s/$base_variable/$base_value/; - } - - my $body; - - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - - -1; diff --git a/samples/client/petstore/perl/WWW/Swagger/pet_api.pm b/samples/client/petstore/perl/WWW/Swagger/pet_api.pm deleted file mode 100644 index 94c92c553743..000000000000 --- a/samples/client/petstore/perl/WWW/Swagger/pet_api.pm +++ /dev/null @@ -1,486 +0,0 @@ -# -# 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. -# - -require 5.6.0; -use strict; -use warnings; - -#use WWW::Swagger::Model::Category; -#use WWW::Swagger::Model::Pet; - -package WWW::Swagger::PetApi; - -our $VERSION = '2.09'; - - -sub new { - my $class = shift; - my $options = shift; - - croak("You must supply an API client") - unless $options->{api_client}; - - my $self = { - api_client => $options->{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 = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/pet"; - $resource_path =~ s/{format}/json/; - - my $method = "PUT"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = 'application/json,application/xml,'; - - - - - - my $body; - # body params - if (isset($body)) { - $body = $body; - } - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # 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 = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/pet"; - $resource_path =~ s/{format}/json/; - - my $method = "POST"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = 'application/json,application/xml,'; - - - - - - my $body; - # body params - if (isset($body)) { - $body = $body; - } - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # 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 = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/pet/findByStatus"; - $resource_path =~ s/{format}/json/; - - my $method = "GET"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - # query params - if($args{ status }) { - $query_params->{'status'} = $self->api_client->to_query_value($args{ status }); - } - - - - my $body; - - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - if(!$response) { - return; - } - - my $response_object = $self->api_client->deserialize($response, 'array[Pet]'); - 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 = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/pet/findByTags"; - $resource_path =~ s/{format}/json/; - - my $method = "GET"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - # query params - if($args{ tags }) { - $query_params->{'tags'} = $self->api_client->to_query_value($args{ tags }); - } - - - - my $body; - - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - if(!$response) { - return; - } - - my $response_object = $self->api_client->deserialize($response, 'array[Pet]'); - 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 = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/pet/{petId}"; - $resource_path =~ s/{format}/json/; - - my $method = "GET"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - # path params - if( $args{ pet_id }) { - my $base_variable = "{" + "petId" + "}"; - my $base_value = $self->api_client->to_path_value($args{ pet_id }); - $resource_path = s/$base_variable/$base_value/; - } - - my $body; - - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - if(!$response) { - return; - } - - my $response_object = $self->api_client->deserialize($response, 'Pet'); - 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 = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/pet/{petId}"; - $resource_path =~ s/{format}/json/; - - my $method = "POST"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = 'application/x-www-form-urlencoded,'; - - - - # path params - if( $args{ pet_id }) { - my $base_variable = "{" + "petId" + "}"; - my $base_value = $self->api_client->to_path_value($args{ pet_id }); - $resource_path = s/$base_variable/$base_value/; - } - # form params - if ($args{ name }) { - $form_params->{'name'} = $self->api_client->to_form_value($args{ name }); - } # form params - if ($args{ status }) { - $form_params->{'status'} = $self->api_client->to_form_value($args{ status }); - } - my $body; - - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # 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 = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/pet/{petId}"; - $resource_path =~ s/{format}/json/; - - my $method = "DELETE"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - # header params - if($args{ api_key }) { - $header_params->{'api_key'} = $self->apiClient->to_header_value($args{ api_key }); - } - # path params - if( $args{ pet_id }) { - my $base_variable = "{" + "petId" + "}"; - my $base_value = $self->api_client->to_path_value($args{ pet_id }); - $resource_path = s/$base_variable/$base_value/; - } - - my $body; - - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # 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 = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/pet/{petId}/uploadImage"; - $resource_path =~ s/{format}/json/; - - my $method = "POST"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = 'multipart/form-data,'; - - - - # path params - if( $args{ pet_id }) { - my $base_variable = "{" + "petId" + "}"; - my $base_value = $self->api_client->to_path_value($args{ pet_id }); - $resource_path = s/$base_variable/$base_value/; - } - # form params - if ($args{ additional_metadata }) { - $form_params->{'additionalMetadata'} = $self->api_client->to_form_value($args{ additional_metadata }); - } # form params - if ($args{ file }) { - $form_params->{'file'} = '@' . $self->api_client->to_form_value($args{ file }); - } - my $body; - - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - - -1; diff --git a/samples/client/petstore/perl/WWW/Swagger/store_api.pm b/samples/client/petstore/perl/WWW/Swagger/store_api.pm deleted file mode 100644 index cc355cd3b6b5..000000000000 --- a/samples/client/petstore/perl/WWW/Swagger/store_api.pm +++ /dev/null @@ -1,262 +0,0 @@ -# -# 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. -# - -require 5.6.0; -use strict; -use warnings; - -#use WWW::Swagger::Model::Category; -#use WWW::Swagger::Model::Pet; - -package WWW::Swagger::StoreApi; - -our $VERSION = '2.09'; - - -sub new { - my $class = shift; - my $options = shift; - - croak("You must supply an API client") - unless $options->{api_client}; - - my $self = { - api_client => $options->{api_client} - }; - - bless $self, $class; - -} - - - # - # get_inventory - # - # Returns pet inventories by status - # - # @return map[string,int] - # - sub get_inventory { - my $self = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/store/inventory"; - $resource_path =~ s/{format}/json/; - - my $method = "GET"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - - - my $body; - - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - if(!$response) { - return; - } - - my $response_object = $self->api_client->deserialize($response, 'map[string,int]'); - 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 = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/store/order"; - $resource_path =~ s/{format}/json/; - - my $method = "POST"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - - - my $body; - # body params - if (isset($body)) { - $body = $body; - } - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - if(!$response) { - return; - } - - my $response_object = $self->api_client->deserialize($response, 'Order'); - 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 = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/store/order/{orderId}"; - $resource_path =~ s/{format}/json/; - - my $method = "GET"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - # path params - if( $args{ order_id }) { - my $base_variable = "{" + "orderId" + "}"; - my $base_value = $self->api_client->to_path_value($args{ order_id }); - $resource_path = s/$base_variable/$base_value/; - } - - my $body; - - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - if(!$response) { - return; - } - - my $response_object = $self->api_client->deserialize($response, 'Order'); - 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 = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/store/order/{orderId}"; - $resource_path =~ s/{format}/json/; - - my $method = "DELETE"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - # path params - if( $args{ order_id }) { - my $base_variable = "{" + "orderId" + "}"; - my $base_value = $self->api_client->to_path_value($args{ order_id }); - $resource_path = s/$base_variable/$base_value/; - } - - my $body; - - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - - -1; diff --git a/samples/client/petstore/perl/WWW/Swagger/user_api.pm b/samples/client/petstore/perl/WWW/Swagger/user_api.pm deleted file mode 100644 index 316c6e8b99d3..000000000000 --- a/samples/client/petstore/perl/WWW/Swagger/user_api.pm +++ /dev/null @@ -1,463 +0,0 @@ -# -# 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. -# - -require 5.6.0; -use strict; -use warnings; - -#use WWW::Swagger::Model::Category; -#use WWW::Swagger::Model::Pet; - -package WWW::Swagger::UserApi; - -our $VERSION = '2.09'; - - -sub new { - my $class = shift; - my $options = shift; - - croak("You must supply an API client") - unless $options->{api_client}; - - my $self = { - api_client => $options->{api_client} - }; - - bless $self, $class; - -} - - - # - # create_user - # - # Create user - # - # @param User $body Created user object (required) - # @return void - # - sub create_user { - my $self = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/user"; - $resource_path =~ s/{format}/json/; - - my $method = "POST"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - - - my $body; - # body params - if (isset($body)) { - $body = $body; - } - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # 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 = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/user/createWithArray"; - $resource_path =~ s/{format}/json/; - - my $method = "POST"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - - - my $body; - # body params - if (isset($body)) { - $body = $body; - } - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # 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 = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/user/createWithList"; - $resource_path =~ s/{format}/json/; - - my $method = "POST"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - - - my $body; - # body params - if (isset($body)) { - $body = $body; - } - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # 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 = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/user/login"; - $resource_path =~ s/{format}/json/; - - my $method = "GET"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - # query params - if($args{ username }) { - $query_params->{'username'} = $self->api_client->to_query_value($args{ username }); - } # query params - if($args{ password }) { - $query_params->{'password'} = $self->api_client->to_query_value($args{ password }); - } - - - - my $body; - - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - if(!$response) { - return; - } - - my $response_object = $self->api_client->deserialize($response, 'string'); - return $response_object; - } - - # - # logout_user - # - # Logs out current logged in user session - # - # @return void - # - sub logout_user { - my $self = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/user/logout"; - $resource_path =~ s/{format}/json/; - - my $method = "GET"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - - - my $body; - - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # 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 = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/user/{username}"; - $resource_path =~ s/{format}/json/; - - my $method = "GET"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - # path params - if( $args{ username }) { - my $base_variable = "{" + "username" + "}"; - my $base_value = $self->api_client->to_path_value($args{ username }); - $resource_path = s/$base_variable/$base_value/; - } - - my $body; - - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - if(!$response) { - return; - } - - my $response_object = $self->api_client->deserialize($response, 'User'); - 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 = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/user/{username}"; - $resource_path =~ s/{format}/json/; - - my $method = "PUT"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - # path params - if( $args{ username }) { - my $base_variable = "{" + "username" + "}"; - my $base_value = $self->api_client->to_path_value($args{ username }); - $resource_path = s/$base_variable/$base_value/; - } - - my $body; - # body params - if (isset($body)) { - $body = $body; - } - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - # - # delete_user - # - # Delete user - # - # @param string $username The name that needs to be deleted (required) - # @return void - # - sub delete_user { - my $self = shift; - my %args = @_; - - # parse inputs - my $resource_path = "/user/{username}"; - $resource_path =~ s/{format}/json/; - - my $method = "DELETE"; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - $header_params->{'Accept'} = 'application/json,application/xml'; - $header_params->{'Content-Type'} = ''; - - - - # path params - if( $args{ username }) { - my $base_variable = "{" + "username" + "}"; - my $base_value = $self->api_client->to_path_value($args{ username }); - $resource_path = s/$base_variable/$base_value/; - } - - my $body; - - - # for HTTP post (form) - $body = $body ? undef : $form_params; - - if ($header_params->{'Content-Type'} eq "application/x-www-form-urlencoded") { - $body = http_build_query($body); - } - - # make the API Call - my $response = $self->api_client->call_api($resource_path, $method, - $query_params, $body, - $header_params); - - - } - - - -1; diff --git a/samples/client/petstore/perl/http.pl b/samples/client/petstore/perl/http.pl new file mode 100644 index 000000000000..282b06ba3e52 --- /dev/null +++ b/samples/client/petstore/perl/http.pl @@ -0,0 +1,25 @@ +use LWP::UserAgent; + +my $ua = LWP::UserAgent->new; + +my $server_endpoint = "http://petstore.swagger.io/v2/pet/10002"; + +# set custom HTTP request header fields +my $req = HTTP::Request->new(GET => $server_endpoint); +$req->header('content-type' => 'application/json'); + +use Data::Dumper; +print Dumper($req); + +my $resp = $ua->request($req); +if ($resp->is_success) { + my $message = $resp->decoded_content; + print "Received reply: $message\n"; +} +else { + print "HTTP GET error code: ", $resp->code, "\n"; + print "HTTP GET error message: ", $resp->message, "\n"; +} + + + 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..cf9e85119fdc --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/APIClient.pm @@ -0,0 +1,239 @@ +package WWW::SwaggerClient::APIClient; + +use strict; +use warnings; +use utf8; + +use LWP::UserAgent; +use HTTP::Headers; +use HTTP::Response; +use HTTP::Request::Common; +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 + my $_body_data = $post_params ? $post_params : $body_data; + + # Make the HTTP request + my $_request; + switch ($method) { + case 'POST' { + #TODO: multipart + $_request = POST($_url, Accept => $header_params->{Accept}, + Content_Type => $header_params->{'Content-Type'}, Content => $_body_data); + } + case 'GET' { + $_request = GET($_url, Accept => $header_params->{'Accept'}, + Content_Type => $header_params->{'Content-Type'}); + } + case 'PUT' { + + } + } + + $ua->timeout($http_timeout); + $ua->agent($http_user_agent); + + my $_response = $ua->request($_request); + + unless ($_response->is_success) { + croak("Can't connect to the server"); + #croak("Can't connect to the api ($_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 object $object object or primitive to be deserialized +# @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 (substr($class, 0, 4) eq 'map[') { #TODO map + $_result = $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::Model::$class")->new; + $_result = $_instance->from_hash(decode_json $data); + } + + return $_result; + +} + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/Category.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/Category.pm new file mode 100644 index 000000000000..03e22e073a2f --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/Category.pm @@ -0,0 +1,97 @@ +package WWW::SwaggerClient::Model::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); + + +# +# +# +#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; +} + +# 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 $attribute_map) { + if (defined $self->{$attribute_map->{$_key}}) { + $_data->{$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 $swagger_types) { + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$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$/, ('string', 'int', 'float', 'bool')) ) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Model::$type->new()"; + return $_instance->from_hash($data); + } +} + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/Order.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/Order.pm new file mode 100644 index 000000000000..7bfc8e4a85c2 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/Order.pm @@ -0,0 +1,113 @@ +package WWW::SwaggerClient::Model::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); + + +# +# +# +#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; +} + +# 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 $attribute_map) { + if (defined $self->{$attribute_map->{$_key}}) { + $_data->{$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 $swagger_types) { + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$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$/, ('string', 'int', 'float', 'bool')) ) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Model::$type->new()"; + return $_instance->from_hash($data); + } +} + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/Pet.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/Pet.pm new file mode 100644 index 000000000000..1b41f6fd88c3 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/Pet.pm @@ -0,0 +1,113 @@ +package WWW::SwaggerClient::Model::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); + + +# +# +# +#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; +} + +# 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 $attribute_map) { + if (defined $self->{$attribute_map->{$_key}}) { + $_data->{$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 $swagger_types) { + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$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$/, ('string', 'int', 'float', 'bool')) ) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Model::$type->new()"; + return $_instance->from_hash($data); + } +} + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/Tag.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/Tag.pm new file mode 100644 index 000000000000..eb838d1d7ec4 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/Tag.pm @@ -0,0 +1,97 @@ +package WWW::SwaggerClient::Model::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); + + +# +# +# +#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; +} + +# 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 $attribute_map) { + if (defined $self->{$attribute_map->{$_key}}) { + $_data->{$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 $swagger_types) { + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$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$/, ('string', 'int', 'float', 'bool')) ) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Model::$type->new()"; + return $_instance->from_hash($data); + } +} + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/User.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/User.pm new file mode 100644 index 000000000000..4a431457ab7a --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/User.pm @@ -0,0 +1,121 @@ +package WWW::SwaggerClient::Model::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); + + +# +# +# +#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; +} + +# 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 $attribute_map) { + if (defined $self->{$attribute_map->{$_key}}) { + $_data->{$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 $swagger_types) { + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$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$/, ('string', 'int', 'float', 'bool')) ) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Model::$type->new()"; + return $_instance->from_hash($data); + } +} + + +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..4771c5598876 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm @@ -0,0 +1,538 @@ +# +# 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; + #TODO fix default + #my (%arg) = ( + # 'api_client' => $default_api_client, + # @_ + #); + + #croak("You must supply an API client") + # unless $options->{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 = {}; + + my $_header_accept = 'application/json, application/xml'; + if ($_header_accept ne '') { + $header_params->{'Accept'} = $_header_accept; + } + my @_header_content_type = ('application/json','application/xml',); + $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + + + + + + 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 = {}; + + my $_header_accept = 'application/json, application/xml'; + if ($_header_accept ne '') { + $header_params->{'Accept'} = $_header_accept; + } + my @_header_content_type = ('application/json','application/xml',); + $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + + + + + + 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 = {}; + + my $_header_accept = 'application/json, application/xml'; + if ($_header_accept ne '') { + $header_params->{'Accept'} = $_header_accept; + } + my @_header_content_type = (); + $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + + # query params + if ( exists $args->{'status'}) { + $query_params->{'status'} = WWW::SwaggerClient::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 = {}; + + my $_header_accept = 'application/json, application/xml'; + if ($_header_accept ne '') { + $header_params->{'Accept'} = $_header_accept; + } + my @_header_content_type = (); + $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + + # query params + if ( exists $args->{'tags'}) { + $query_params->{'tags'} = WWW::SwaggerClient::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 = {}; + + my $_header_accept = 'application/json, application/xml'; + if ($_header_accept ne '') { + $header_params->{'Accept'} = $_header_accept; + } + my @_header_content_type = (); + $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + + + + # 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 = {}; + + my $_header_accept = 'application/json, application/xml'; + if ($_header_accept ne '') { + $header_params->{'Accept'} = $_header_accept; + } + my @_header_content_type = ('application/x-www-form-urlencoded',); + $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + + + + # 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 = {}; + + my $_header_accept = 'application/json, application/xml'; + if ($_header_accept ne '') { + $header_params->{'Accept'} = $_header_accept; + } + my @_header_content_type = (); + $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + + + # 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 = {}; + + my $_header_accept = 'application/json, application/xml'; + if ($_header_accept ne '') { + $header_params->{'Accept'} = $_header_accept; + } + my @_header_content_type = ('multipart/form-data',); + $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + + + + # 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'} = '@' . WWW::SwaggerClient::APIClient::to_form_value($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..eaf819a16d04 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm @@ -0,0 +1,292 @@ +# +# 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; + #TODO fix default + #my (%arg) = ( + # 'api_client' => $default_api_client, + # @_ + #); + + #croak("You must supply an API client") + # unless $options->{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 map[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 = {}; + + my $_header_accept = 'application/json, application/xml'; + if ($_header_accept ne '') { + $header_params->{'Accept'} = $_header_accept; + } + my @_header_content_type = (); + $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + + + + + + 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('map[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 = {}; + + my $_header_accept = 'application/json, application/xml'; + if ($_header_accept ne '') { + $header_params->{'Accept'} = $_header_accept; + } + my @_header_content_type = (); + $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + + + + + + 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 = {}; + + my $_header_accept = 'application/json, application/xml'; + if ($_header_accept ne '') { + $header_params->{'Accept'} = $_header_accept; + } + my @_header_content_type = (); + $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + + + + # 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 = {}; + + my $_header_accept = 'application/json, application/xml'; + if ($_header_accept ne '') { + $header_params->{'Accept'} = $_header_accept; + } + my @_header_content_type = (); + $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + + + + # 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/Swagger.pl b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Swagger.pl similarity index 99% rename from samples/client/petstore/perl/Swagger.pl rename to samples/client/petstore/perl/lib/WWW/SwaggerClient/Swagger.pl index e58f64107cd0..a5a82fcbd3f2 100644 --- a/samples/client/petstore/perl/Swagger.pl +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Swagger.pl @@ -1,4 +1,4 @@ -package WWW::Swagger::Swagger; +package WWW::SwaggerClient::Swagger; use strict; use warnings; @@ -79,6 +79,7 @@ sub call_api { $ua->timeout($http_timeout); $ua->agent($http_user_agent); + my $_response = $ua->request($_request); if (!$_response->is_success) { diff --git a/modules/swagger-codegen/src/main/resources/perl/Swagger.mustache b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Swagger.pm similarity index 97% rename from modules/swagger-codegen/src/main/resources/perl/Swagger.mustache rename to samples/client/petstore/perl/lib/WWW/SwaggerClient/Swagger.pm index e58f64107cd0..6f7e645bfd03 100644 --- a/modules/swagger-codegen/src/main/resources/perl/Swagger.mustache +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Swagger.pm @@ -1,4 +1,4 @@ -package WWW::Swagger::Swagger; +package WWW::SwaggerClient::Swagger; use strict; use warnings; @@ -17,7 +17,7 @@ use Scalar::Util; my $ua = LWP::UserAgent->new; my $http_user_agent = 'Perl-Swagger'; # HTTP user-agent my $http_timeout; #timeout -my $base_url; +my $base_url = "http://petstore.swagger.io/v2"; sub new @@ -79,6 +79,7 @@ sub call_api { $ua->timeout($http_timeout); $ua->agent($http_user_agent); + my $_response = $ua->request($_request); if (!$_response->is_success) { @@ -91,8 +92,8 @@ sub call_api { # Build a JSON POST object -#sub sanitize_for_serialization -#{ +sub sanitize_for_serialization +{ # my $data = shift; # if (is_scalar($data) || null === $data) { # $sanitized = $data; @@ -114,7 +115,7 @@ sub call_api { # } # # return $sanitized; -#} +} # Take value and turn it into a string suitable for inclusion in @@ -184,8 +185,8 @@ sub to_string { # @param object $object object or primitive to be deserialized # @param string $class class name is passed as a string # @return object an instance of $class -#sub deserialize -#{ +sub deserialize +{ # my ($data, $class) = @_; # if (null === $data) { # $deserialized = null; @@ -224,6 +225,6 @@ sub to_string { # } # # return $deserialized; -#} +} 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..3582520cd5c4 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm @@ -0,0 +1,512 @@ +# +# 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; + #TODO fix default + #my (%arg) = ( + # 'api_client' => $default_api_client, + # @_ + #); + + #croak("You must supply an API client") + # unless $options->{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 = {}; + + my $_header_accept = 'application/json, application/xml'; + if ($_header_accept ne '') { + $header_params->{'Accept'} = $_header_accept; + } + my @_header_content_type = (); + $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + + + + + + 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 = {}; + + my $_header_accept = 'application/json, application/xml'; + if ($_header_accept ne '') { + $header_params->{'Accept'} = $_header_accept; + } + my @_header_content_type = (); + $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + + + + + + 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 = {}; + + my $_header_accept = 'application/json, application/xml'; + if ($_header_accept ne '') { + $header_params->{'Accept'} = $_header_accept; + } + my @_header_content_type = (); + $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + + + + + + 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 = {}; + + my $_header_accept = 'application/json, application/xml'; + if ($_header_accept ne '') { + $header_params->{'Accept'} = $_header_accept; + } + my @_header_content_type = (); + $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + + # query params + if ( exists $args->{'username'}) { + $query_params->{'username'} = WWW::SwaggerClient::APIClient::to_query_value($args->{'username'}); + } # query params + if ( exists $args->{'password'}) { + $query_params->{'password'} = WWW::SwaggerClient::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 = {}; + + my $_header_accept = 'application/json, application/xml'; + if ($_header_accept ne '') { + $header_params->{'Accept'} = $_header_accept; + } + my @_header_content_type = (); + $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + + + + + + 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 = {}; + + my $_header_accept = 'application/json, application/xml'; + if ($_header_accept ne '') { + $header_params->{'Accept'} = $_header_accept; + } + my @_header_content_type = (); + $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + + + + # 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 = {}; + + my $_header_accept = 'application/json, application/xml'; + if ($_header_accept ne '') { + $header_params->{'Accept'} = $_header_accept; + } + my @_header_content_type = (); + $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + + + + # 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 = {}; + + my $_header_accept = 'application/json, application/xml'; + if ($_header_accept ne '') { + $header_params->{'Accept'} = $_header_accept; + } + my @_header_content_type = (); + $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + + + + # 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/test.pl b/samples/client/petstore/perl/test.pl new file mode 100644 index 000000000000..f415dc36c09d --- /dev/null +++ b/samples/client/petstore/perl/test.pl @@ -0,0 +1,42 @@ +#!/usr/bin/perl +# +# + +use strict; +use warnings; +use WWW::SwaggerClient::PetApi; +use WWW::SwaggerClient::APIClient; +use WWW::SwaggerClient::Model::Pet; +use WWW::SwaggerClient::Model::Tag; +use WWW::SwaggerClient::Model::Category; +use JSON; +use Data::Dumper; + +my $api = WWW::SwaggerClient::PetApi->new(); + +print WWW::SwaggerClient::APIClient::to_form_value('testing 123'); + +my $pet_id = 5; + +my $tag = WWW::SwaggerClient::Model::Tag->new({'id' => 'tag1', 'name' => 'just kidding', + "photoUrls" => ['123', 'oop']}); +my $pet = WWW::SwaggerClient::Model::Pet->new({'id' => 5, 'name' => 'haha', + "photoUrls" => ['123', 'oop'], 'tags' => [$tag]}); + +##print Dumper $pet; + +my $json = JSON->new->convert_blessed; + +#print $json->convert_blessed->encode($pet); +#print $json->get_convert_blessed; +##print Dumper($pet->to_hash); + + +#my $pet2 = WWW::SwaggerClient::Model::Pet->from_json($pet->to_hash); +my $pet2 = WWW::SwaggerClient::Model::Pet->new(); +$pet2 = $pet2->from_hash($pet->to_hash); +#$pet2->from_json($pet->to_hash); +##print Dumper($pet2->to_hash); +print "============================\n"; +print Dumper $api->get_pet_by_id({pet_id => $pet_id}); +print Dumper $api->update_pet_with_form({pet_id => $pet_id, name => 'test_name', status => 'test status'}); From 0a34793f5abc3462ccd36754e94b37a8e2a2a189 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Thu, 7 May 2015 10:03:30 +0800 Subject: [PATCH 19/67] add inheritance to object (model) --- .../codegen/languages/PerlClientCodegen.java | 5 +- .../main/resources/perl/APIClient.mustache | 106 ++++---- .../main/resources/perl/BaseObject.mustache | 76 ++++++ .../src/main/resources/perl/api.mustache | 8 +- .../perl/{model.mustache => object.mustache} | 7 +- .../perl/lib/WWW/SwaggerClient/APIClient.pm | 7 +- .../WWW/SwaggerClient/Object/BaseObject.pm | 76 ++++++ .../{Model => Object}/Category.pm | 7 +- .../SwaggerClient/{Model => Object}/Order.pm | 7 +- .../SwaggerClient/{Model => Object}/Pet.pm | 7 +- .../SwaggerClient/{Model => Object}/Tag.pm | 7 +- .../SwaggerClient/{Model => Object}/User.pm | 7 +- .../perl/lib/WWW/SwaggerClient/PetApi.pm | 4 +- .../perl/lib/WWW/SwaggerClient/Swagger.pl | 230 ------------------ .../perl/lib/WWW/SwaggerClient/UserApi.pm | 4 +- samples/client/petstore/perl/test.pl | 20 +- 16 files changed, 262 insertions(+), 316 deletions(-) rename samples/client/petstore/perl/lib/WWW/SwaggerClient/Swagger.pm => modules/swagger-codegen/src/main/resources/perl/APIClient.mustache (71%) create mode 100644 modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache rename modules/swagger-codegen/src/main/resources/perl/{model.mustache => object.mustache} (91%) create mode 100644 samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/BaseObject.pm rename samples/client/petstore/perl/lib/WWW/SwaggerClient/{Model => Object}/Category.pm (91%) rename samples/client/petstore/perl/lib/WWW/SwaggerClient/{Model => Object}/Order.pm (93%) rename samples/client/petstore/perl/lib/WWW/SwaggerClient/{Model => Object}/Pet.pm (93%) rename samples/client/petstore/perl/lib/WWW/SwaggerClient/{Model => Object}/Tag.pm (91%) rename samples/client/petstore/perl/lib/WWW/SwaggerClient/{Model => Object}/User.pm (93%) delete mode 100644 samples/client/petstore/perl/lib/WWW/SwaggerClient/Swagger.pl 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 index d187bcd90117..4edead804d51 100644 --- 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 @@ -27,9 +27,9 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { public PerlClientCodegen() { super(); - modelPackage = "Model"; + modelPackage = "Object"; outputFolder = "generated-code/perl"; - modelTemplateFiles.put("model.mustache", ".pm"); + modelTemplateFiles.put("object.mustache", ".pm"); apiTemplateFiles.put("api.mustache", ".pm"); templateDir = "perl"; @@ -60,6 +60,7 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("map", "map"); supportingFiles.add(new SupportingFile("APIClient.mustache", "lib/WWW/" + invokerPackage, "APIClient.pm")); + supportingFiles.add(new SupportingFile("BaseObject.mustache", "lib/WWW/" + invokerPackage, "Object/BaseObject.pm")); } @Override diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Swagger.pm b/modules/swagger-codegen/src/main/resources/perl/APIClient.mustache similarity index 71% rename from samples/client/petstore/perl/lib/WWW/SwaggerClient/Swagger.pm rename to modules/swagger-codegen/src/main/resources/perl/APIClient.mustache index 6f7e645bfd03..44d5b60b21e8 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Swagger.pm +++ b/modules/swagger-codegen/src/main/resources/perl/APIClient.mustache @@ -1,4 +1,4 @@ -package WWW::SwaggerClient::Swagger; +package WWW::{{invokerPackage}}::APIClient; use strict; use warnings; @@ -7,17 +7,22 @@ use utf8; use LWP::UserAgent; use HTTP::Headers; use HTTP::Response; +use HTTP::Request::Common; 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"; +my $base_url = "{{basePath}}"; sub new @@ -65,7 +70,7 @@ sub call_api { my $_url = $base_url . $resource_path; # build query - if ($query_params) { + if (%$query_params) { $_url = ($_url . '?' . eval { URI::Query->new($query_params)->stringify }); } @@ -73,17 +78,30 @@ sub call_api { my $_body_data = $post_params ? $post_params : $body_data; # Make the HTTP request - my $_request = HTTP::Request->new( - $method, $_url, $headers, $_body_data - ); + my $_request; + switch ($method) { + case 'POST' { + #TODO: multipart + $_request = POST($_url, Accept => $header_params->{Accept}, + Content_Type => $header_params->{'Content-Type'}, Content => $_body_data); + } + case 'GET' { + $_request = GET($_url, Accept => $header_params->{'Accept'}, + Content_Type => $header_params->{'Content-Type'}); + } + case 'PUT' { + + } + } $ua->timeout($http_timeout); $ua->agent($http_user_agent); my $_response = $ua->request($_request); - if (!$_response->is_success) { - #TODO croak("Can't connect ot the api ($_response{code}): $_response{message}"); + unless ($_response->is_success) { + croak("Can't connect to the server"); + #croak("Can't connect to the api ($_response{code}): $_response{message}"); } return $_response->content; @@ -179,52 +197,42 @@ sub to_string { } } - # Deserialize a JSON string into an object # -# @param object $object object or primitive to be deserialized # @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 ($data, $class) = @_; -# if (null === $data) { -# $deserialized = null; -# } elseif (substr($class, 0, 4) == 'map[') { -# $inner = substr($class, 4, -1); -# $values = array(); -# if(strrpos($inner, ",") !== false) { -# $subClass_array = explode(',', $inner, 2); -# $subClass = $subClass_array[1]; -# foreach ($data as $key => $value) { -# $values[] = array($key => self::deserialize($value, $subClass)); -# } -# } -# $deserialized = $values; -# } elseif (strcasecmp(substr($class, 0, 6),'array[') == 0) { -# $subClass = substr($class, 6, -1); -# $values = array(); -# foreach ($data as $key => $value) { -# $values[] = self::deserialize($value, $subClass); -# } -# $deserialized = $values; -# } elseif ($class == 'DateTime') { -# $deserialized = new \DateTime($data); -# } elseif (in_array($class, array('string', 'int', 'float', 'bool'))) { -# settype($data, $class); -# $deserialized = $data; -# } else { -# $instance = new $class(); -# foreach ($instance::$swaggerTypes as $property => $type) { -# if (isset($data->$property)) { -# $original_property_name = $instance::$attributeMap[$property]; -# $instance->$property = self::deserialize($data->$original_property_name, $type); -# } -# } -# $deserialized = $instance; -# } -# -# return $deserialized; + 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; + } 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..be8937a16f0d --- /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->{attribute_map}) { + if (defined $self->{$self->{attribute_map}->{$_key}}) { + $_data->{$self->{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->{swagger_types}) { + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$self->{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$/, ('string', 'int', 'float', 'bool')) ) { + 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 index 56596c5733d1..7eb16b8a1a5f 100644 --- a/modules/swagger-codegen/src/main/resources/perl/api.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/api.mustache @@ -98,21 +98,21 @@ sub new { {{#queryParams}} # query params if ( exists $args->{'{{paramName}}'}) { - $query_params->{'{{baseName}}'} = WWW::SwaggerClient::APIClient::to_query_value($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::SwaggerClient::APIClient::to_header_value($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::SwaggerClient::APIClient::to_path_value($args->{'{{paramName}}'}); + 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}}'} ) { - $form_params->{'{{baseName}}'} = {{#isFile}}'@' . {{/isFile}}WWW::SwaggerClient::APIClient::to_form_value($args->{'{{paramName}}'}); + $form_params->{'{{baseName}}'} = {{#isFile}}'@' . {{/isFile}}WWW::{{invokerPackage}}::APIClient::to_form_value($args->{'{{paramName}}'}); }{{/formParams}} my $_body_data; {{#bodyParams}} # body params diff --git a/modules/swagger-codegen/src/main/resources/perl/model.mustache b/modules/swagger-codegen/src/main/resources/perl/object.mustache similarity index 91% rename from modules/swagger-codegen/src/main/resources/perl/model.mustache rename to modules/swagger-codegen/src/main/resources/perl/object.mustache index 3612ed1050a3..73b2e749ea33 100644 --- a/modules/swagger-codegen/src/main/resources/perl/model.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/object.mustache @@ -1,6 +1,6 @@ {{#models}} {{#model}} -package WWW::{{invokerPackage}}::Model::{{classname}}; +package WWW::{{invokerPackage}}::Object::{{classname}}; require 5.6.0; use strict; @@ -10,7 +10,10 @@ 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}} @@ -89,7 +92,7 @@ sub _deserialize { } elsif ( grep( /^$type$/, ('string', 'int', 'float', 'bool')) ) { return $data; } else { # hash(model) - my $_instance = eval "WWW::SwaggerClient::Model::$type->new()"; + my $_instance = eval "WWW::{{invokerPackage}}::Object::$type->new()"; return $_instance->from_hash($data); } } diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/APIClient.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/APIClient.pm index cf9e85119fdc..18246004781d 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/APIClient.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/APIClient.pm @@ -199,7 +199,6 @@ sub to_string { # Deserialize a JSON string into an object # -# @param object $object object or primitive to be deserialized # @param string $class class name is passed as a string # @param string $data data of the body # @return object an instance of $class @@ -211,8 +210,8 @@ sub deserialize if (not defined $data) { return undef; - } elsif (substr($class, 0, 4) eq 'map[') { #TODO map - $_result = $data; + } 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 @@ -228,7 +227,7 @@ sub deserialize } elsif (grep /^$data$/, ('string', 'int', 'float', 'bool')) { #TODO revise the primitive type $_result= $data; } else { # model - my $_instance = use_module("WWW::SwaggerClient::Model::$class")->new; + my $_instance = use_module("WWW::SwaggerClient::Object::$class")->new; $_result = $_instance->from_hash(decode_json $data); } 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..276b3f46f0f2 --- /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->{attribute_map}) { + if (defined $self->{$self->{attribute_map}->{$_key}}) { + $_data->{$self->{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->{swagger_types}) { + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$self->{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$/, ('string', 'int', 'float', 'bool')) ) { + 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/Model/Category.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm similarity index 91% rename from samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/Category.pm rename to samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm index 03e22e073a2f..b82bd5f82a2f 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/Category.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm @@ -1,4 +1,4 @@ -package WWW::SwaggerClient::Model::Category; +package WWW::SwaggerClient::Object::Category; require 5.6.0; use strict; @@ -8,7 +8,10 @@ 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"; # # @@ -88,7 +91,7 @@ sub _deserialize { } elsif ( grep( /^$type$/, ('string', 'int', 'float', 'bool')) ) { return $data; } else { # hash(model) - my $_instance = eval "WWW::SwaggerClient::Model::$type->new()"; + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; return $_instance->from_hash($data); } } diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/Order.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm similarity index 93% rename from samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/Order.pm rename to samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm index 7bfc8e4a85c2..35a6e96fac81 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/Order.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm @@ -1,4 +1,4 @@ -package WWW::SwaggerClient::Model::Order; +package WWW::SwaggerClient::Object::Order; require 5.6.0; use strict; @@ -8,7 +8,10 @@ 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"; # # @@ -104,7 +107,7 @@ sub _deserialize { } elsif ( grep( /^$type$/, ('string', 'int', 'float', 'bool')) ) { return $data; } else { # hash(model) - my $_instance = eval "WWW::SwaggerClient::Model::$type->new()"; + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; return $_instance->from_hash($data); } } diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/Pet.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm similarity index 93% rename from samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/Pet.pm rename to samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm index 1b41f6fd88c3..1e692d7bb51e 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/Pet.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm @@ -1,4 +1,4 @@ -package WWW::SwaggerClient::Model::Pet; +package WWW::SwaggerClient::Object::Pet; require 5.6.0; use strict; @@ -8,7 +8,10 @@ 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"; # # @@ -104,7 +107,7 @@ sub _deserialize { } elsif ( grep( /^$type$/, ('string', 'int', 'float', 'bool')) ) { return $data; } else { # hash(model) - my $_instance = eval "WWW::SwaggerClient::Model::$type->new()"; + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; return $_instance->from_hash($data); } } diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/Tag.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm similarity index 91% rename from samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/Tag.pm rename to samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm index eb838d1d7ec4..b46b44927f80 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/Tag.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm @@ -1,4 +1,4 @@ -package WWW::SwaggerClient::Model::Tag; +package WWW::SwaggerClient::Object::Tag; require 5.6.0; use strict; @@ -8,7 +8,10 @@ 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"; # # @@ -88,7 +91,7 @@ sub _deserialize { } elsif ( grep( /^$type$/, ('string', 'int', 'float', 'bool')) ) { return $data; } else { # hash(model) - my $_instance = eval "WWW::SwaggerClient::Model::$type->new()"; + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; return $_instance->from_hash($data); } } diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/User.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm similarity index 93% rename from samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/User.pm rename to samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm index 4a431457ab7a..08d9ff6b0801 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Model/User.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm @@ -1,4 +1,4 @@ -package WWW::SwaggerClient::Model::User; +package WWW::SwaggerClient::Object::User; require 5.6.0; use strict; @@ -8,7 +8,10 @@ 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"; # # @@ -112,7 +115,7 @@ sub _deserialize { } elsif ( grep( /^$type$/, ('string', 'int', 'float', 'bool')) ) { return $data; } else { # hash(model) - my $_instance = eval "WWW::SwaggerClient::Model::$type->new()"; + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; return $_instance->from_hash($data); } } diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm index 4771c5598876..8b02083e6371 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm @@ -201,7 +201,7 @@ sub new { # query params if ( exists $args->{'status'}) { - $query_params->{'status'} = WWW::SwaggerClient::APIClient::to_query_value($args->{'status'}); + $query_params->{'status'} = WWW::::APIClient::to_query_value($args->{'status'}); } @@ -255,7 +255,7 @@ sub new { # query params if ( exists $args->{'tags'}) { - $query_params->{'tags'} = WWW::SwaggerClient::APIClient::to_query_value($args->{'tags'}); + $query_params->{'tags'} = WWW::::APIClient::to_query_value($args->{'tags'}); } diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Swagger.pl b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Swagger.pl deleted file mode 100644 index a5a82fcbd3f2..000000000000 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Swagger.pl +++ /dev/null @@ -1,230 +0,0 @@ -package WWW::SwaggerClient::Swagger; - -use strict; -use warnings; -use utf8; - -use LWP::UserAgent; -use HTTP::Headers; -use HTTP::Response; -use HTTP::Status; -use URI::Query; -use JSON; - -use Scalar::Util; - -# class variables -my $ua = LWP::UserAgent->new; -my $http_user_agent = 'Perl-Swagger'; # HTTP user-agent -my $http_timeout; #timeout -my $base_url; - - -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 - my $_body_data = $post_params ? $post_params : $body_data; - - # Make the HTTP request - my $_request = HTTP::Request->new( - $method, $_url, $headers, $_body_data - ); - - $ua->timeout($http_timeout); - $ua->agent($http_user_agent); - - my $_response = $ua->request($_request); - - if (!$_response->is_success) { - #TODO croak("Can't connect ot the api ($_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 object $object object or primitive to be deserialized -# @param string $class class name is passed as a string -# @return object an instance of $class -#sub deserialize -#{ -# my ($data, $class) = @_; -# if (null === $data) { -# $deserialized = null; -# } elseif (substr($class, 0, 4) == 'map[') { -# $inner = substr($class, 4, -1); -# $values = array(); -# if(strrpos($inner, ",") !== false) { -# $subClass_array = explode(',', $inner, 2); -# $subClass = $subClass_array[1]; -# foreach ($data as $key => $value) { -# $values[] = array($key => self::deserialize($value, $subClass)); -# } -# } -# $deserialized = $values; -# } elseif (strcasecmp(substr($class, 0, 6),'array[') == 0) { -# $subClass = substr($class, 6, -1); -# $values = array(); -# foreach ($data as $key => $value) { -# $values[] = self::deserialize($value, $subClass); -# } -# $deserialized = $values; -# } elseif ($class == 'DateTime') { -# $deserialized = new \DateTime($data); -# } elseif (in_array($class, array('string', 'int', 'float', 'bool'))) { -# settype($data, $class); -# $deserialized = $data; -# } else { -# $instance = new $class(); -# foreach ($instance::$swaggerTypes as $property => $type) { -# if (isset($data->$property)) { -# $original_property_name = $instance::$attributeMap[$property]; -# $instance->$property = self::deserialize($data->$original_property_name, $type); -# } -# } -# $deserialized = $instance; -# } -# -# return $deserialized; -#} - -1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm index 3582520cd5c4..a8a52ae48add 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm @@ -253,10 +253,10 @@ sub new { # query params if ( exists $args->{'username'}) { - $query_params->{'username'} = WWW::SwaggerClient::APIClient::to_query_value($args->{'username'}); + $query_params->{'username'} = WWW::::APIClient::to_query_value($args->{'username'}); } # query params if ( exists $args->{'password'}) { - $query_params->{'password'} = WWW::SwaggerClient::APIClient::to_query_value($args->{'password'}); + $query_params->{'password'} = WWW::::APIClient::to_query_value($args->{'password'}); } diff --git a/samples/client/petstore/perl/test.pl b/samples/client/petstore/perl/test.pl index f415dc36c09d..25ac786166cf 100644 --- a/samples/client/petstore/perl/test.pl +++ b/samples/client/petstore/perl/test.pl @@ -6,22 +6,22 @@ use strict; use warnings; use WWW::SwaggerClient::PetApi; use WWW::SwaggerClient::APIClient; -use WWW::SwaggerClient::Model::Pet; -use WWW::SwaggerClient::Model::Tag; -use WWW::SwaggerClient::Model::Category; +use WWW::SwaggerClient::Object::Pet; +use WWW::SwaggerClient::Object::Tag; +use WWW::SwaggerClient::Object::Category; use JSON; use Data::Dumper; my $api = WWW::SwaggerClient::PetApi->new(); -print WWW::SwaggerClient::APIClient::to_form_value('testing 123'); +#print WWW::SwaggerClient::APIClient::to_form_value('testing 123'); my $pet_id = 5; -my $tag = WWW::SwaggerClient::Model::Tag->new({'id' => 'tag1', 'name' => 'just kidding', +my $tag = WWW::SwaggerClient::Object::Tag->new({'id' => 'tag1', 'name' => 'just kidding', "photoUrls" => ['123', 'oop']}); -my $pet = WWW::SwaggerClient::Model::Pet->new({'id' => 5, 'name' => 'haha', - "photoUrls" => ['123', 'oop'], 'tags' => [$tag]}); +my $pet = WWW::SwaggerClient::Object::Pet->new({'id' => 5, 'name' => 'haha', + "photoUrls" => ['123', 'oop'], 'tags' => [$tag], 'created' => '2003-04-05 02:58:00'}); ##print Dumper $pet; @@ -29,11 +29,9 @@ my $json = JSON->new->convert_blessed; #print $json->convert_blessed->encode($pet); #print $json->get_convert_blessed; -##print Dumper($pet->to_hash); - - +print Dumper($pet->to_hash); #my $pet2 = WWW::SwaggerClient::Model::Pet->from_json($pet->to_hash); -my $pet2 = WWW::SwaggerClient::Model::Pet->new(); +my $pet2 = WWW::SwaggerClient::Object::Pet->new(); $pet2 = $pet2->from_hash($pet->to_hash); #$pet2->from_json($pet->to_hash); ##print Dumper($pet2->to_hash); From f69fb40c71bd5c432a359b7dd59083ade779ecba Mon Sep 17 00:00:00 2001 From: William Cheng Date: Thu, 7 May 2015 14:41:58 +0800 Subject: [PATCH 20/67] add methods for static variable --- .../main/resources/perl/BaseObject.mustache | 10 +-- .../src/main/resources/perl/object.mustache | 61 +++---------------- .../WWW/SwaggerClient/Object/BaseObject.pm | 10 +-- .../lib/WWW/SwaggerClient/Object/Category.pm | 57 ++--------------- .../lib/WWW/SwaggerClient/Object/Order.pm | 57 ++--------------- .../perl/lib/WWW/SwaggerClient/Object/Pet.pm | 57 ++--------------- .../perl/lib/WWW/SwaggerClient/Object/Tag.pm | 57 ++--------------- .../perl/lib/WWW/SwaggerClient/Object/User.pm | 57 ++--------------- samples/client/petstore/perl/test.pl | 22 ++++++- 9 files changed, 67 insertions(+), 321 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache b/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache index be8937a16f0d..4a0be0aaea05 100644 --- a/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache @@ -28,9 +28,9 @@ sub to_hash { sub TO_JSON { my $self = shift; my $_data = {}; - foreach my $_key (keys $self->{attribute_map}) { - if (defined $self->{$self->{attribute_map}->{$_key}}) { - $_data->{$self->{attribute_map}->{$_key}} = $self->{$_key}; + foreach my $_key (keys $self->get_attribute_map) { + if (defined $self->{$self->get_attribute_map->{$_key}}) { + $_data->{$self->get_attribute_map->{$_key}} = $self->{$_key}; } } return $_data; @@ -40,11 +40,11 @@ sub TO_JSON { sub from_hash { my ($self, $hash) = @_; # loop through attributes and use swagger_types to deserialize the data - while ( my ($_key, $_type) = each $self->{swagger_types}) { + 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->{attribute_map}->{$_key}}}) { + foreach my $_element (@{$hash->{$self->get_attribute_map->{$_key}}}) { push @_array, $self->_deserialize($_subclass, $_element); } $self->{$_key} = \@_array; diff --git a/modules/swagger-codegen/src/main/resources/perl/object.mustache b/modules/swagger-codegen/src/main/resources/perl/object.mustache index 73b2e749ea33..34e504819a0d 100644 --- a/modules/swagger-codegen/src/main/resources/perl/object.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/object.mustache @@ -43,61 +43,16 @@ sub new { return bless $self, $class; } -# return json string -sub to_hash { - return decode_json(JSON->new->convert_blessed->encode( shift )); +# get swagger type of the attribute +sub get_swagger_types { + return $swagger_types; } -# used by JSON for serialization -sub TO_JSON { - my $self = shift; - my $_data = {}; - foreach my $_key (keys $attribute_map) { - if (defined $self->{$attribute_map->{$_key}}) { - $_data->{$attribute_map->{$_key}} = $self->{$_key}; - } - } - return $_data; +# get attribute mappping +sub get_attribute_map { + return $attribute_map; } -# 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 $swagger_types) { - if ($_type =~ /^array\[/i) { # array - my $_subclass = substr($_type, 6, -1); - my @_array = (); - foreach my $_element (@{$hash->{$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$/, ('string', 'int', 'float', 'bool')) ) { - return $data; - } else { # hash(model) - my $_instance = eval "WWW::{{invokerPackage}}::Object::$type->new()"; - return $_instance->from_hash($data); - } -} - -{{/model}} -{{/models}} - 1; +{{/model}} +{{/models}} diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/BaseObject.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/BaseObject.pm index 276b3f46f0f2..584710238adf 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/BaseObject.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/BaseObject.pm @@ -28,9 +28,9 @@ sub to_hash { sub TO_JSON { my $self = shift; my $_data = {}; - foreach my $_key (keys $self->{attribute_map}) { - if (defined $self->{$self->{attribute_map}->{$_key}}) { - $_data->{$self->{attribute_map}->{$_key}} = $self->{$_key}; + foreach my $_key (keys $self->get_attribute_map) { + if (defined $self->{$self->get_attribute_map->{$_key}}) { + $_data->{$self->get_attribute_map->{$_key}} = $self->{$_key}; } } return $_data; @@ -40,11 +40,11 @@ sub TO_JSON { sub from_hash { my ($self, $hash) = @_; # loop through attributes and use swagger_types to deserialize the data - while ( my ($_key, $_type) = each $self->{swagger_types}) { + 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->{attribute_map}->{$_key}}}) { + foreach my $_element (@{$hash->{$self->get_attribute_map->{$_key}}}) { push @_array, $self->_deserialize($_subclass, $_element); } $self->{$_key} = \@_array; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm index b82bd5f82a2f..2ae61e3a7faa 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm @@ -42,59 +42,14 @@ sub new { return bless $self, $class; } -# return json string -sub to_hash { - return decode_json(JSON->new->convert_blessed->encode( shift )); +# get swagger type of the attribute +sub get_swagger_types { + return $swagger_types; } -# used by JSON for serialization -sub TO_JSON { - my $self = shift; - my $_data = {}; - foreach my $_key (keys $attribute_map) { - if (defined $self->{$attribute_map->{$_key}}) { - $_data->{$attribute_map->{$_key}} = $self->{$_key}; - } - } - return $_data; +# get attribute mappping +sub get_attribute_map { + return $attribute_map; } -# 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 $swagger_types) { - if ($_type =~ /^array\[/i) { # array - my $_subclass = substr($_type, 6, -1); - my @_array = (); - foreach my $_element (@{$hash->{$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$/, ('string', 'int', 'float', 'bool')) ) { - 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/Order.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm index 35a6e96fac81..5693ecd2177c 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm @@ -58,59 +58,14 @@ sub new { return bless $self, $class; } -# return json string -sub to_hash { - return decode_json(JSON->new->convert_blessed->encode( shift )); +# get swagger type of the attribute +sub get_swagger_types { + return $swagger_types; } -# used by JSON for serialization -sub TO_JSON { - my $self = shift; - my $_data = {}; - foreach my $_key (keys $attribute_map) { - if (defined $self->{$attribute_map->{$_key}}) { - $_data->{$attribute_map->{$_key}} = $self->{$_key}; - } - } - return $_data; +# get attribute mappping +sub get_attribute_map { + return $attribute_map; } -# 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 $swagger_types) { - if ($_type =~ /^array\[/i) { # array - my $_subclass = substr($_type, 6, -1); - my @_array = (); - foreach my $_element (@{$hash->{$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$/, ('string', 'int', 'float', 'bool')) ) { - 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/Pet.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm index 1e692d7bb51e..6c31afb5b913 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm @@ -58,59 +58,14 @@ sub new { return bless $self, $class; } -# return json string -sub to_hash { - return decode_json(JSON->new->convert_blessed->encode( shift )); +# get swagger type of the attribute +sub get_swagger_types { + return $swagger_types; } -# used by JSON for serialization -sub TO_JSON { - my $self = shift; - my $_data = {}; - foreach my $_key (keys $attribute_map) { - if (defined $self->{$attribute_map->{$_key}}) { - $_data->{$attribute_map->{$_key}} = $self->{$_key}; - } - } - return $_data; +# get attribute mappping +sub get_attribute_map { + return $attribute_map; } -# 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 $swagger_types) { - if ($_type =~ /^array\[/i) { # array - my $_subclass = substr($_type, 6, -1); - my @_array = (); - foreach my $_element (@{$hash->{$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$/, ('string', 'int', 'float', 'bool')) ) { - 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/Tag.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm index b46b44927f80..45c570a75069 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm @@ -42,59 +42,14 @@ sub new { return bless $self, $class; } -# return json string -sub to_hash { - return decode_json(JSON->new->convert_blessed->encode( shift )); +# get swagger type of the attribute +sub get_swagger_types { + return $swagger_types; } -# used by JSON for serialization -sub TO_JSON { - my $self = shift; - my $_data = {}; - foreach my $_key (keys $attribute_map) { - if (defined $self->{$attribute_map->{$_key}}) { - $_data->{$attribute_map->{$_key}} = $self->{$_key}; - } - } - return $_data; +# get attribute mappping +sub get_attribute_map { + return $attribute_map; } -# 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 $swagger_types) { - if ($_type =~ /^array\[/i) { # array - my $_subclass = substr($_type, 6, -1); - my @_array = (); - foreach my $_element (@{$hash->{$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$/, ('string', 'int', 'float', 'bool')) ) { - 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/User.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm index 08d9ff6b0801..f5d7c1dbce2b 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm @@ -66,59 +66,14 @@ sub new { return bless $self, $class; } -# return json string -sub to_hash { - return decode_json(JSON->new->convert_blessed->encode( shift )); +# get swagger type of the attribute +sub get_swagger_types { + return $swagger_types; } -# used by JSON for serialization -sub TO_JSON { - my $self = shift; - my $_data = {}; - foreach my $_key (keys $attribute_map) { - if (defined $self->{$attribute_map->{$_key}}) { - $_data->{$attribute_map->{$_key}} = $self->{$_key}; - } - } - return $_data; +# get attribute mappping +sub get_attribute_map { + return $attribute_map; } -# 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 $swagger_types) { - if ($_type =~ /^array\[/i) { # array - my $_subclass = substr($_type, 6, -1); - my @_array = (); - foreach my $_element (@{$hash->{$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$/, ('string', 'int', 'float', 'bool')) ) { - 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/test.pl b/samples/client/petstore/perl/test.pl index 25ac786166cf..ed7dff0b33c2 100644 --- a/samples/client/petstore/perl/test.pl +++ b/samples/client/petstore/perl/test.pl @@ -11,20 +11,35 @@ use WWW::SwaggerClient::Object::Tag; use WWW::SwaggerClient::Object::Category; use JSON; use Data::Dumper; +use DateTime; my $api = WWW::SwaggerClient::PetApi->new(); #print WWW::SwaggerClient::APIClient::to_form_value('testing 123'); my $pet_id = 5; +my $dt = DateTime->new( + year => 1972, + month => 12, + day => 31, + hour => 23, + minute => 59, + second => 30, + time_zone => 'UTC' +); + +print "dt = $dt\n"; +print "dt = ".$dt->datetime()."\n"; + my $tag = WWW::SwaggerClient::Object::Tag->new({'id' => 'tag1', 'name' => 'just kidding', "photoUrls" => ['123', 'oop']}); my $pet = WWW::SwaggerClient::Object::Pet->new({'id' => 5, 'name' => 'haha', - "photoUrls" => ['123', 'oop'], 'tags' => [$tag], 'created' => '2003-04-05 02:58:00'}); + "photoUrls" => ['123', 'oop'], 'tags' => [$tag], 'created' => $dt}); ##print Dumper $pet; - +print "pet ref=".ref($pet)."\n"; +print "tag ref=".ref($tag)."\n"; my $json = JSON->new->convert_blessed; #print $json->convert_blessed->encode($pet); @@ -34,7 +49,8 @@ print Dumper($pet->to_hash); my $pet2 = WWW::SwaggerClient::Object::Pet->new(); $pet2 = $pet2->from_hash($pet->to_hash); #$pet2->from_json($pet->to_hash); -##print Dumper($pet2->to_hash); +print Dumper($pet2->to_hash); +#exit; print "============================\n"; print Dumper $api->get_pet_by_id({pet_id => $pet_id}); print Dumper $api->update_pet_with_form({pet_id => $pet_id, name => 'test_name', status => 'test status'}); From 48844442fc4a604b24ebf16487519f864f6ebedf Mon Sep 17 00:00:00 2001 From: William Cheng Date: Thu, 7 May 2015 15:46:43 +0800 Subject: [PATCH 21/67] test post body (model), fix to_hash attribute mapping --- .../main/resources/perl/APIClient.mustache | 15 +++++++++--- .../main/resources/perl/BaseObject.mustache | 2 +- .../perl/lib/WWW/SwaggerClient/APIClient.pm | 15 +++++++++--- .../WWW/SwaggerClient/Object/BaseObject.pm | 2 +- samples/client/petstore/perl/test.pl | 23 +++++++++++-------- 5 files changed, 40 insertions(+), 17 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/perl/APIClient.mustache b/modules/swagger-codegen/src/main/resources/perl/APIClient.mustache index 44d5b60b21e8..04f0a006356e 100644 --- a/modules/swagger-codegen/src/main/resources/perl/APIClient.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/APIClient.mustache @@ -75,15 +75,24 @@ sub call_api { } # body data - my $_body_data = $post_params ? $post_params : $body_data; + my $_body_data = %$post_params ? $post_params : to_json($body_data->to_hash); # Make the HTTP request my $_request; switch ($method) { case 'POST' { - #TODO: multipart + # 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 => $header_params->{'Content-Type'}, Content => $_body_data); + 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'}, diff --git a/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache b/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache index 4a0be0aaea05..9fab6611593a 100644 --- a/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache @@ -29,7 +29,7 @@ sub TO_JSON { my $self = shift; my $_data = {}; foreach my $_key (keys $self->get_attribute_map) { - if (defined $self->{$self->get_attribute_map->{$_key}}) { + if (defined $self->{$_key}) { $_data->{$self->get_attribute_map->{$_key}} = $self->{$_key}; } } diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/APIClient.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/APIClient.pm index 18246004781d..577bd23003f9 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/APIClient.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/APIClient.pm @@ -75,15 +75,24 @@ sub call_api { } # body data - my $_body_data = $post_params ? $post_params : $body_data; + my $_body_data = %$post_params ? $post_params : to_json($body_data->to_hash); # Make the HTTP request my $_request; switch ($method) { case 'POST' { - #TODO: multipart + # 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 => $header_params->{'Content-Type'}, Content => $_body_data); + 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'}, diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/BaseObject.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/BaseObject.pm index 584710238adf..a5be613d472d 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/BaseObject.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/BaseObject.pm @@ -29,7 +29,7 @@ sub TO_JSON { my $self = shift; my $_data = {}; foreach my $_key (keys $self->get_attribute_map) { - if (defined $self->{$self->get_attribute_map->{$_key}}) { + if (defined $self->{$_key}) { $_data->{$self->get_attribute_map->{$_key}} = $self->{$_key}; } } diff --git a/samples/client/petstore/perl/test.pl b/samples/client/petstore/perl/test.pl index ed7dff0b33c2..3fb7c3e0a08c 100644 --- a/samples/client/petstore/perl/test.pl +++ b/samples/client/petstore/perl/test.pl @@ -17,7 +17,7 @@ my $api = WWW::SwaggerClient::PetApi->new(); #print WWW::SwaggerClient::APIClient::to_form_value('testing 123'); -my $pet_id = 5; +my $pet_id = 88; my $dt = DateTime->new( year => 1972, month => 12, @@ -32,14 +32,13 @@ print "dt = $dt\n"; print "dt = ".$dt->datetime()."\n"; -my $tag = WWW::SwaggerClient::Object::Tag->new({'id' => 'tag1', 'name' => 'just kidding', +my $category = WWW::SwaggerClient::Object::Category->new({'id' => '2', 'name' => 'pending'}); +my $tag = WWW::SwaggerClient::Object::Tag->new({'id' => '1', 'name' => 'just kidding', "photoUrls" => ['123', 'oop']}); -my $pet = WWW::SwaggerClient::Object::Pet->new({'id' => 5, 'name' => 'haha', - "photoUrls" => ['123', 'oop'], 'tags' => [$tag], 'created' => $dt}); +my $pet = WWW::SwaggerClient::Object::Pet->new({'id' => $pet_id, 'name' => 'perl test', + "photoUrls" => ['123', 'oop'], 'tags' => [$tag], 'status' => 'pending'}); -##print Dumper $pet; -print "pet ref=".ref($pet)."\n"; -print "tag ref=".ref($tag)."\n"; +print Dumper $pet; my $json = JSON->new->convert_blessed; #print $json->convert_blessed->encode($pet); @@ -52,5 +51,11 @@ $pet2 = $pet2->from_hash($pet->to_hash); print Dumper($pet2->to_hash); #exit; print "============================\n"; -print Dumper $api->get_pet_by_id({pet_id => $pet_id}); -print Dumper $api->update_pet_with_form({pet_id => $pet_id, name => 'test_name', status => 'test status'}); +print Dumper $api->add_pet({body => $pet}); +#print Dumper $api->get_pet_by_id({pet_id => $pet_id}); +#print Dumper $api->update_pet_with_form({pet_id => $pet_id, name => 'test_name', status => 'test status'}); +#print Dumper $api->delete_pet({pet_id => $pet_id}); + + + + From c03250132d9d325217d681bcbea3560ec8b60784 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Thu, 7 May 2015 18:01:56 +0800 Subject: [PATCH 22/67] update error message, update test script --- .../main/resources/perl/APIClient.mustache | 21 +++++--- .../src/main/resources/perl/api.mustache | 6 ++- samples/client/petstore/perl/http.pl | 25 ---------- .../perl/lib/WWW/SwaggerClient/APIClient.pm | 21 +++++--- .../perl/lib/WWW/SwaggerClient/PetApi.pm | 11 +++- samples/client/petstore/perl/test.pl | 50 ++++++------------- 6 files changed, 60 insertions(+), 74 deletions(-) delete mode 100644 samples/client/petstore/perl/http.pl diff --git a/modules/swagger-codegen/src/main/resources/perl/APIClient.mustache b/modules/swagger-codegen/src/main/resources/perl/APIClient.mustache index 04f0a006356e..b0c3c9b5d39f 100644 --- a/modules/swagger-codegen/src/main/resources/perl/APIClient.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/APIClient.mustache @@ -7,7 +7,7 @@ use utf8; use LWP::UserAgent; use HTTP::Headers; use HTTP::Response; -use HTTP::Request::Common; +use HTTP::Request::Common qw(DELETE POST GET HEAD PUT); use HTTP::Status; use URI::Query; use JSON; @@ -75,7 +75,8 @@ sub call_api { } # body data - my $_body_data = %$post_params ? $post_params : to_json($body_data->to_hash); + $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; @@ -84,6 +85,7 @@ sub call_api { # 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); } @@ -98,9 +100,17 @@ sub call_api { $_request = GET($_url, Accept => $header_params->{'Accept'}, Content_Type => $header_params->{'Content-Type'}); } - case 'PUT' { - + 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); @@ -109,8 +119,7 @@ sub call_api { my $_response = $ua->request($_request); unless ($_response->is_success) { - croak("Can't connect to the server"); - #croak("Can't connect to the api ($_response{code}): $_response{message}"); + croak("API Exception(".$_response->code."): ".$_response->message); } return $_response->content; diff --git a/modules/swagger-codegen/src/main/resources/perl/api.mustache b/modules/swagger-codegen/src/main/resources/perl/api.mustache index 7eb16b8a1a5f..25c0d80fb952 100644 --- a/modules/swagger-codegen/src/main/resources/perl/api.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/api.mustache @@ -112,7 +112,11 @@ sub new { }{{/pathParams}} {{#formParams}} # form params if ( exists $args->{'{{paramName}}'} ) { - $form_params->{'{{baseName}}'} = {{#isFile}}'@' . {{/isFile}}WWW::{{invokerPackage}}::APIClient::to_form_value($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 diff --git a/samples/client/petstore/perl/http.pl b/samples/client/petstore/perl/http.pl deleted file mode 100644 index 282b06ba3e52..000000000000 --- a/samples/client/petstore/perl/http.pl +++ /dev/null @@ -1,25 +0,0 @@ -use LWP::UserAgent; - -my $ua = LWP::UserAgent->new; - -my $server_endpoint = "http://petstore.swagger.io/v2/pet/10002"; - -# set custom HTTP request header fields -my $req = HTTP::Request->new(GET => $server_endpoint); -$req->header('content-type' => 'application/json'); - -use Data::Dumper; -print Dumper($req); - -my $resp = $ua->request($req); -if ($resp->is_success) { - my $message = $resp->decoded_content; - print "Received reply: $message\n"; -} -else { - print "HTTP GET error code: ", $resp->code, "\n"; - print "HTTP GET error message: ", $resp->message, "\n"; -} - - - diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/APIClient.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/APIClient.pm index 577bd23003f9..6d0ecc44dc69 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/APIClient.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/APIClient.pm @@ -7,7 +7,7 @@ use utf8; use LWP::UserAgent; use HTTP::Headers; use HTTP::Response; -use HTTP::Request::Common; +use HTTP::Request::Common qw(DELETE POST GET HEAD PUT); use HTTP::Status; use URI::Query; use JSON; @@ -75,7 +75,8 @@ sub call_api { } # body data - my $_body_data = %$post_params ? $post_params : to_json($body_data->to_hash); + $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; @@ -84,6 +85,7 @@ sub call_api { # 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); } @@ -98,9 +100,17 @@ sub call_api { $_request = GET($_url, Accept => $header_params->{'Accept'}, Content_Type => $header_params->{'Content-Type'}); } - case 'PUT' { - + 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); @@ -109,8 +119,7 @@ sub call_api { my $_response = $ua->request($_request); unless ($_response->is_success) { - croak("Can't connect to the server"); - #croak("Can't connect to the api ($_response{code}): $_response{message}"); + croak("API Exception(".$_response->code."): ".$_response->message); } return $_response->content; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm index 8b02083e6371..bd7c0b5fc6ba 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm @@ -385,10 +385,14 @@ sub new { } # 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; @@ -513,10 +517,15 @@ sub new { } # 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'} = '@' . WWW::SwaggerClient::APIClient::to_form_value($args->{'file'}); + $form_params->{'file'} = [] unless defined $form_params->{'file'}; + push $form_params->{'file'}, $args->{'file'}; + + } my $_body_data; diff --git a/samples/client/petstore/perl/test.pl b/samples/client/petstore/perl/test.pl index 3fb7c3e0a08c..504461710cdd 100644 --- a/samples/client/petstore/perl/test.pl +++ b/samples/client/petstore/perl/test.pl @@ -1,7 +1,7 @@ #!/usr/bin/perl # # - +use lib 'lib'; use strict; use warnings; use WWW::SwaggerClient::PetApi; @@ -15,46 +15,26 @@ use DateTime; my $api = WWW::SwaggerClient::PetApi->new(); -#print WWW::SwaggerClient::APIClient::to_form_value('testing 123'); - my $pet_id = 88; -my $dt = DateTime->new( - year => 1972, - month => 12, - day => 31, - hour => 23, - minute => 59, - second => 30, - time_zone => 'UTC' -); -print "dt = $dt\n"; -print "dt = ".$dt->datetime()."\n"; - - -my $category = WWW::SwaggerClient::Object::Category->new({'id' => '2', 'name' => 'pending'}); -my $tag = WWW::SwaggerClient::Object::Tag->new({'id' => '1', 'name' => 'just kidding', - "photoUrls" => ['123', 'oop']}); +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'}); + "photoUrls" => ['123', 'oop'], 'tags' => [$tag], 'status' => 'pending', 'category' => $category}); -print Dumper $pet; +print "\npet(object)=".Dumper $pet; my $json = JSON->new->convert_blessed; -#print $json->convert_blessed->encode($pet); -#print $json->get_convert_blessed; -print Dumper($pet->to_hash); -#my $pet2 = WWW::SwaggerClient::Model::Pet->from_json($pet->to_hash); -my $pet2 = WWW::SwaggerClient::Object::Pet->new(); -$pet2 = $pet2->from_hash($pet->to_hash); -#$pet2->from_json($pet->to_hash); -print Dumper($pet2->to_hash); -#exit; -print "============================\n"; -print Dumper $api->add_pet({body => $pet}); -#print Dumper $api->get_pet_by_id({pet_id => $pet_id}); -#print Dumper $api->update_pet_with_form({pet_id => $pet_id, name => 'test_name', status => 'test status'}); -#print Dumper $api->delete_pet({pet_id => $pet_id}); +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 => '/var/tmp/f5.jpg'}); +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}); From 1d4735f76d973b78538184448e6aaacc3c94c981 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Thu, 7 May 2015 20:49:35 +0800 Subject: [PATCH 23/67] update subroutine argument --- .../src/main/resources/perl/api.mustache | 48 +++++---- .../src/main/resources/perl/object.mustache | 4 +- .../lib/WWW/SwaggerClient/Object/Category.pm | 6 +- .../lib/WWW/SwaggerClient/Object/Order.pm | 14 +-- .../perl/lib/WWW/SwaggerClient/Object/Pet.pm | 14 +-- .../perl/lib/WWW/SwaggerClient/Object/Tag.pm | 6 +- .../perl/lib/WWW/SwaggerClient/Object/User.pm | 18 ++-- .../perl/lib/WWW/SwaggerClient/PetApi.pm | 98 +++++++++---------- .../perl/lib/WWW/SwaggerClient/StoreApi.pm | 46 ++++----- .../perl/lib/WWW/SwaggerClient/UserApi.pm | 80 +++++++-------- samples/client/petstore/perl/test.pl | 18 ++-- 11 files changed, 168 insertions(+), 184 deletions(-) mode change 100644 => 100755 samples/client/petstore/perl/test.pl diff --git a/modules/swagger-codegen/src/main/resources/perl/api.mustache b/modules/swagger-codegen/src/main/resources/perl/api.mustache index 25c0d80fb952..7b7d9d98a4ed 100644 --- a/modules/swagger-codegen/src/main/resources/perl/api.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/api.mustache @@ -43,21 +43,17 @@ our @EXPORT_OK = qw( sub new { my $class = shift; my $default_api_client = WWW::{{invokerPackage}}::APIClient->new; - #TODO fix default - #my (%arg) = ( - # 'api_client' => $default_api_client, - # @_ - #); + my (%self) = ( + 'api_client' => $default_api_client, + @_ + ); - #croak("You must supply an API client") - # unless $options->{api_client}; + #my $self = { + # #api_client => $options->{api_client} + # api_client => $default_api_client + #}; - my $self = { - #api_client => $options->{api_client} - api_client => $default_api_client - }; - - bless $self, $class; + bless \%self, $class; } @@ -71,11 +67,11 @@ sub new { {{/allParams}} # @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} # sub {{nickname}} { - my ($self, $args) = @_; + my ($self, %args) = @_; {{#allParams}}{{#required}} # verify the required parameter '{{paramName}}' is set - unless (exists $args->{'{{paramName}}'}) { + unless (exists $args{'{{paramName}}'}) { croak("Missing the required parameter '{{paramName}}' when calling {{nickname}}"); } {{/required}}{{/allParams}} @@ -97,31 +93,31 @@ sub new { $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; {{#queryParams}} # query params - if ( exists $args->{'{{paramName}}'}) { - $query_params->{'{{baseName}}'} = WWW::{{invokerPacakge}}::APIClient::to_query_value($args->{'{{paramName}}'}); + 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}}'}); + if ( exists $args{'{{paramName}}'}) { + $header_params->{'{{baseName}}'} = WWW::{{invokerPackage}}::APIClient::to_header_value($args{'{{paramName}}'}); }{{/headerParams}} {{#pathParams}} # path params - if ( exists $args->{'{{paramName}}'}) { + if ( exists $args{'{{paramName}}'}) { my $_base_variable = "{" . "{{baseName}}" . "}"; - my $_base_value = WWW::{{invokerPackage}}::APIClient::to_path_value($args->{'{{paramName}}'}); + 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}}'} ) { + if ( exists $args{'{{paramName}}'} ) { {{#isFile}}$form_params->{'{{baseName}}'} = [] unless defined $form_params->{'{{baseName}}'}; - push $form_params->{'{{baseName}}'}, $args->{'{{paramName}}'}; + push $form_params->{'{{baseName}}'}, $args{'{{paramName}}'}; {{/isFile}} - {{^isFile}}$form_params->{'{{baseName}}'} = WWW::{{invokerPackage}}::APIClient::to_form_value($args->{'{{paramName}}'}); + {{^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}}'}; + if ( exists $args{'{{paramName}}'}) { + $_body_data = $args{'{{paramName}}'}; }{{/bodyParams}} # for HTTP post (form) diff --git a/modules/swagger-codegen/src/main/resources/perl/object.mustache b/modules/swagger-codegen/src/main/resources/perl/object.mustache index 34e504819a0d..c527957a9b10 100644 --- a/modules/swagger-codegen/src/main/resources/perl/object.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/object.mustache @@ -33,10 +33,10 @@ my $attribute_map = { # new object sub new { - my ($class, $args) = @_; + my ($class, %args) = @_; my $self = { {{#vars}}#{{#description}}{{{description}}}{{/description}} - '{{name}}' => $args->{'{{baseName}}'}{{#hasMore}}, + '{{name}}' => $args{'{{baseName}}'}{{#hasMore}}, {{/hasMore}}{{/vars}} }; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm index 2ae61e3a7faa..857dccdce5a0 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm @@ -31,12 +31,12 @@ my $attribute_map = { # new object sub new { - my ($class, $args) = @_; + my ($class, %args) = @_; my $self = { # - 'id' => $args->{'id'}, + 'id' => $args{'id'}, # - 'name' => $args->{'name'} + 'name' => $args{'name'} }; return bless $self, $class; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm index 5693ecd2177c..35449647e132 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm @@ -39,20 +39,20 @@ my $attribute_map = { # new object sub new { - my ($class, $args) = @_; + my ($class, %args) = @_; my $self = { # - 'id' => $args->{'id'}, + 'id' => $args{'id'}, # - 'pet_id' => $args->{'petId'}, + 'pet_id' => $args{'petId'}, # - 'quantity' => $args->{'quantity'}, + 'quantity' => $args{'quantity'}, # - 'ship_date' => $args->{'shipDate'}, + 'ship_date' => $args{'shipDate'}, #Order Status - 'status' => $args->{'status'}, + 'status' => $args{'status'}, # - 'complete' => $args->{'complete'} + 'complete' => $args{'complete'} }; return bless $self, $class; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm index 6c31afb5b913..f53aacdf0d33 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm @@ -39,20 +39,20 @@ my $attribute_map = { # new object sub new { - my ($class, $args) = @_; + my ($class, %args) = @_; my $self = { # - 'id' => $args->{'id'}, + 'id' => $args{'id'}, # - 'category' => $args->{'category'}, + 'category' => $args{'category'}, # - 'name' => $args->{'name'}, + 'name' => $args{'name'}, # - 'photo_urls' => $args->{'photoUrls'}, + 'photo_urls' => $args{'photoUrls'}, # - 'tags' => $args->{'tags'}, + 'tags' => $args{'tags'}, #pet status in the store - 'status' => $args->{'status'} + 'status' => $args{'status'} }; return bless $self, $class; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm index 45c570a75069..35850032d5c2 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm @@ -31,12 +31,12 @@ my $attribute_map = { # new object sub new { - my ($class, $args) = @_; + my ($class, %args) = @_; my $self = { # - 'id' => $args->{'id'}, + 'id' => $args{'id'}, # - 'name' => $args->{'name'} + 'name' => $args{'name'} }; return bless $self, $class; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm index f5d7c1dbce2b..88a396ece3a7 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm @@ -43,24 +43,24 @@ my $attribute_map = { # new object sub new { - my ($class, $args) = @_; + my ($class, %args) = @_; my $self = { # - 'id' => $args->{'id'}, + 'id' => $args{'id'}, # - 'username' => $args->{'username'}, + 'username' => $args{'username'}, # - 'first_name' => $args->{'firstName'}, + 'first_name' => $args{'firstName'}, # - 'last_name' => $args->{'lastName'}, + 'last_name' => $args{'lastName'}, # - 'email' => $args->{'email'}, + 'email' => $args{'email'}, # - 'password' => $args->{'password'}, + 'password' => $args{'password'}, # - 'phone' => $args->{'phone'}, + 'phone' => $args{'phone'}, #User Status - 'user_status' => $args->{'userStatus'} + 'user_status' => $args{'userStatus'} }; return bless $self, $class; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm index bd7c0b5fc6ba..9dbceba42912 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm @@ -49,21 +49,17 @@ our @EXPORT_OK = qw( sub new { my $class = shift; my $default_api_client = WWW::SwaggerClient::APIClient->new; - #TODO fix default - #my (%arg) = ( - # 'api_client' => $default_api_client, - # @_ - #); + my (%self) = ( + 'api_client' => $default_api_client, + @_ + ); - #croak("You must supply an API client") - # unless $options->{api_client}; + #my $self = { + # #api_client => $options->{api_client} + # api_client => $default_api_client + #}; - my $self = { - #api_client => $options->{api_client} - api_client => $default_api_client - }; - - bless $self, $class; + bless \%self, $class; } @@ -77,7 +73,7 @@ sub new { # @return void # sub update_pet { - my ($self, $args) = @_; + my ($self, %args) = @_; @@ -103,8 +99,8 @@ sub new { my $_body_data; # body params - if ( exists $args->{'body'}) { - $_body_data = $args->{'body'}; + if ( exists $args{'body'}) { + $_body_data = $args{'body'}; } # for HTTP post (form) @@ -128,7 +124,7 @@ sub new { # @return void # sub add_pet { - my ($self, $args) = @_; + my ($self, %args) = @_; @@ -154,8 +150,8 @@ sub new { my $_body_data; # body params - if ( exists $args->{'body'}) { - $_body_data = $args->{'body'}; + if ( exists $args{'body'}) { + $_body_data = $args{'body'}; } # for HTTP post (form) @@ -179,7 +175,7 @@ sub new { # @return array[Pet] # sub find_pets_by_status { - my ($self, $args) = @_; + my ($self, %args) = @_; @@ -200,8 +196,8 @@ sub new { $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; # query params - if ( exists $args->{'status'}) { - $query_params->{'status'} = WWW::::APIClient::to_query_value($args->{'status'}); + if ( exists $args{'status'}) { + $query_params->{'status'} = WWW::::APIClient::to_query_value($args{'status'}); } @@ -233,7 +229,7 @@ sub new { # @return array[Pet] # sub find_pets_by_tags { - my ($self, $args) = @_; + my ($self, %args) = @_; @@ -254,8 +250,8 @@ sub new { $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; # query params - if ( exists $args->{'tags'}) { - $query_params->{'tags'} = WWW::::APIClient::to_query_value($args->{'tags'}); + if ( exists $args{'tags'}) { + $query_params->{'tags'} = WWW::::APIClient::to_query_value($args{'tags'}); } @@ -287,11 +283,11 @@ sub new { # @return Pet # sub get_pet_by_id { - my ($self, $args) = @_; + my ($self, %args) = @_; # verify the required parameter 'pet_id' is set - unless (exists $args->{'pet_id'}) { + unless (exists $args{'pet_id'}) { croak("Missing the required parameter 'pet_id' when calling get_pet_by_id"); } @@ -315,9 +311,9 @@ sub new { # path params - if ( exists $args->{'pet_id'}) { + if ( exists $args{'pet_id'}) { my $_base_variable = "{" . "petId" . "}"; - my $_base_value = WWW::SwaggerClient::APIClient::to_path_value($args->{'pet_id'}); + my $_base_value = WWW::SwaggerClient::APIClient::to_path_value($args{'pet_id'}); $_resource_path =~ s/$_base_variable/$_base_value/g; } @@ -350,11 +346,11 @@ sub new { # @return void # sub update_pet_with_form { - my ($self, $args) = @_; + my ($self, %args) = @_; # verify the required parameter 'pet_id' is set - unless (exists $args->{'pet_id'}) { + unless (exists $args{'pet_id'}) { croak("Missing the required parameter 'pet_id' when calling update_pet_with_form"); } @@ -378,20 +374,20 @@ sub new { # path params - if ( exists $args->{'pet_id'}) { + if ( exists $args{'pet_id'}) { my $_base_variable = "{" . "petId" . "}"; - my $_base_value = WWW::SwaggerClient::APIClient::to_path_value($args->{'pet_id'}); + 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'} ) { + if ( exists $args{'name'} ) { - $form_params->{'name'} = WWW::SwaggerClient::APIClient::to_form_value($args->{'name'}); + $form_params->{'name'} = WWW::SwaggerClient::APIClient::to_form_value($args{'name'}); } # form params - if ( exists $args->{'status'} ) { + if ( exists $args{'status'} ) { - $form_params->{'status'} = WWW::SwaggerClient::APIClient::to_form_value($args->{'status'}); + $form_params->{'status'} = WWW::SwaggerClient::APIClient::to_form_value($args{'status'}); } my $_body_data; @@ -419,11 +415,11 @@ sub new { # @return void # sub delete_pet { - my ($self, $args) = @_; + my ($self, %args) = @_; # verify the required parameter 'pet_id' is set - unless (exists $args->{'pet_id'}) { + unless (exists $args{'pet_id'}) { croak("Missing the required parameter 'pet_id' when calling delete_pet"); } @@ -446,13 +442,13 @@ sub new { # header params - if ( exists $args->{'api_key'}) { - $header_params->{'api_key'} = WWW::SwaggerClient::APIClient::to_header_value($args->{'api_key'}); + 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'}) { + if ( exists $args{'pet_id'}) { my $_base_variable = "{" . "petId" . "}"; - my $_base_value = WWW::SwaggerClient::APIClient::to_path_value($args->{'pet_id'}); + my $_base_value = WWW::SwaggerClient::APIClient::to_path_value($args{'pet_id'}); $_resource_path =~ s/$_base_variable/$_base_value/g; } @@ -482,11 +478,11 @@ sub new { # @return void # sub upload_file { - my ($self, $args) = @_; + my ($self, %args) = @_; # verify the required parameter 'pet_id' is set - unless (exists $args->{'pet_id'}) { + unless (exists $args{'pet_id'}) { croak("Missing the required parameter 'pet_id' when calling upload_file"); } @@ -510,20 +506,20 @@ sub new { # path params - if ( exists $args->{'pet_id'}) { + if ( exists $args{'pet_id'}) { my $_base_variable = "{" . "petId" . "}"; - my $_base_value = WWW::SwaggerClient::APIClient::to_path_value($args->{'pet_id'}); + 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'} ) { + if ( exists $args{'additional_metadata'} ) { - $form_params->{'additionalMetadata'} = WWW::SwaggerClient::APIClient::to_form_value($args->{'additional_metadata'}); + $form_params->{'additionalMetadata'} = WWW::SwaggerClient::APIClient::to_form_value($args{'additional_metadata'}); } # form params - if ( exists $args->{'file'} ) { + if ( exists $args{'file'} ) { $form_params->{'file'} = [] unless defined $form_params->{'file'}; - push $form_params->{'file'}, $args->{'file'}; + push $form_params->{'file'}, $args{'file'}; } diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm index eaf819a16d04..6ef684893254 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm @@ -45,21 +45,17 @@ our @EXPORT_OK = qw( sub new { my $class = shift; my $default_api_client = WWW::SwaggerClient::APIClient->new; - #TODO fix default - #my (%arg) = ( - # 'api_client' => $default_api_client, - # @_ - #); + my (%self) = ( + 'api_client' => $default_api_client, + @_ + ); - #croak("You must supply an API client") - # unless $options->{api_client}; + #my $self = { + # #api_client => $options->{api_client} + # api_client => $default_api_client + #}; - my $self = { - #api_client => $options->{api_client} - api_client => $default_api_client - }; - - bless $self, $class; + bless \%self, $class; } @@ -72,7 +68,7 @@ sub new { # @return map[string,int] # sub get_inventory { - my ($self, $args) = @_; + my ($self, %args) = @_; @@ -123,7 +119,7 @@ sub new { # @return Order # sub place_order { - my ($self, $args) = @_; + my ($self, %args) = @_; @@ -149,8 +145,8 @@ sub new { my $_body_data; # body params - if ( exists $args->{'body'}) { - $_body_data = $args->{'body'}; + if ( exists $args{'body'}) { + $_body_data = $args{'body'}; } # for HTTP post (form) @@ -177,11 +173,11 @@ sub new { # @return Order # sub get_order_by_id { - my ($self, $args) = @_; + my ($self, %args) = @_; # verify the required parameter 'order_id' is set - unless (exists $args->{'order_id'}) { + unless (exists $args{'order_id'}) { croak("Missing the required parameter 'order_id' when calling get_order_by_id"); } @@ -205,9 +201,9 @@ sub new { # path params - if ( exists $args->{'order_id'}) { + if ( exists $args{'order_id'}) { my $_base_variable = "{" . "orderId" . "}"; - my $_base_value = WWW::SwaggerClient::APIClient::to_path_value($args->{'order_id'}); + my $_base_value = WWW::SwaggerClient::APIClient::to_path_value($args{'order_id'}); $_resource_path =~ s/$_base_variable/$_base_value/g; } @@ -238,11 +234,11 @@ sub new { # @return void # sub delete_order { - my ($self, $args) = @_; + my ($self, %args) = @_; # verify the required parameter 'order_id' is set - unless (exists $args->{'order_id'}) { + unless (exists $args{'order_id'}) { croak("Missing the required parameter 'order_id' when calling delete_order"); } @@ -266,9 +262,9 @@ sub new { # path params - if ( exists $args->{'order_id'}) { + if ( exists $args{'order_id'}) { my $_base_variable = "{" . "orderId" . "}"; - my $_base_value = WWW::SwaggerClient::APIClient::to_path_value($args->{'order_id'}); + my $_base_value = WWW::SwaggerClient::APIClient::to_path_value($args{'order_id'}); $_resource_path =~ s/$_base_variable/$_base_value/g; } diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm index a8a52ae48add..a3955b7d4f88 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm @@ -49,21 +49,17 @@ our @EXPORT_OK = qw( sub new { my $class = shift; my $default_api_client = WWW::SwaggerClient::APIClient->new; - #TODO fix default - #my (%arg) = ( - # 'api_client' => $default_api_client, - # @_ - #); + my (%self) = ( + 'api_client' => $default_api_client, + @_ + ); - #croak("You must supply an API client") - # unless $options->{api_client}; + #my $self = { + # #api_client => $options->{api_client} + # api_client => $default_api_client + #}; - my $self = { - #api_client => $options->{api_client} - api_client => $default_api_client - }; - - bless $self, $class; + bless \%self, $class; } @@ -77,7 +73,7 @@ sub new { # @return void # sub create_user { - my ($self, $args) = @_; + my ($self, %args) = @_; @@ -103,8 +99,8 @@ sub new { my $_body_data; # body params - if ( exists $args->{'body'}) { - $_body_data = $args->{'body'}; + if ( exists $args{'body'}) { + $_body_data = $args{'body'}; } # for HTTP post (form) @@ -128,7 +124,7 @@ sub new { # @return void # sub create_users_with_array_input { - my ($self, $args) = @_; + my ($self, %args) = @_; @@ -154,8 +150,8 @@ sub new { my $_body_data; # body params - if ( exists $args->{'body'}) { - $_body_data = $args->{'body'}; + if ( exists $args{'body'}) { + $_body_data = $args{'body'}; } # for HTTP post (form) @@ -179,7 +175,7 @@ sub new { # @return void # sub create_users_with_list_input { - my ($self, $args) = @_; + my ($self, %args) = @_; @@ -205,8 +201,8 @@ sub new { my $_body_data; # body params - if ( exists $args->{'body'}) { - $_body_data = $args->{'body'}; + if ( exists $args{'body'}) { + $_body_data = $args{'body'}; } # for HTTP post (form) @@ -231,7 +227,7 @@ sub new { # @return string # sub login_user { - my ($self, $args) = @_; + my ($self, %args) = @_; @@ -252,11 +248,11 @@ sub new { $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; # query params - if ( exists $args->{'username'}) { - $query_params->{'username'} = WWW::::APIClient::to_query_value($args->{'username'}); + 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'}); + if ( exists $args{'password'}) { + $query_params->{'password'} = WWW::::APIClient::to_query_value($args{'password'}); } @@ -287,7 +283,7 @@ sub new { # @return void # sub logout_user { - my ($self, $args) = @_; + my ($self, %args) = @_; @@ -335,11 +331,11 @@ sub new { # @return User # sub get_user_by_name { - my ($self, $args) = @_; + my ($self, %args) = @_; # verify the required parameter 'username' is set - unless (exists $args->{'username'}) { + unless (exists $args{'username'}) { croak("Missing the required parameter 'username' when calling get_user_by_name"); } @@ -363,9 +359,9 @@ sub new { # path params - if ( exists $args->{'username'}) { + if ( exists $args{'username'}) { my $_base_variable = "{" . "username" . "}"; - my $_base_value = WWW::SwaggerClient::APIClient::to_path_value($args->{'username'}); + my $_base_value = WWW::SwaggerClient::APIClient::to_path_value($args{'username'}); $_resource_path =~ s/$_base_variable/$_base_value/g; } @@ -397,11 +393,11 @@ sub new { # @return void # sub update_user { - my ($self, $args) = @_; + my ($self, %args) = @_; # verify the required parameter 'username' is set - unless (exists $args->{'username'}) { + unless (exists $args{'username'}) { croak("Missing the required parameter 'username' when calling update_user"); } @@ -425,16 +421,16 @@ sub new { # path params - if ( exists $args->{'username'}) { + if ( exists $args{'username'}) { my $_base_variable = "{" . "username" . "}"; - my $_base_value = WWW::SwaggerClient::APIClient::to_path_value($args->{'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'}; + if ( exists $args{'body'}) { + $_body_data = $args{'body'}; } # for HTTP post (form) @@ -458,11 +454,11 @@ sub new { # @return void # sub delete_user { - my ($self, $args) = @_; + my ($self, %args) = @_; # verify the required parameter 'username' is set - unless (exists $args->{'username'}) { + unless (exists $args{'username'}) { croak("Missing the required parameter 'username' when calling delete_user"); } @@ -486,9 +482,9 @@ sub new { # path params - if ( exists $args->{'username'}) { + if ( exists $args{'username'}) { my $_base_variable = "{" . "username" . "}"; - my $_base_value = WWW::SwaggerClient::APIClient::to_path_value($args->{'username'}); + my $_base_value = WWW::SwaggerClient::APIClient::to_path_value($args{'username'}); $_resource_path =~ s/$_base_variable/$_base_value/g; } diff --git a/samples/client/petstore/perl/test.pl b/samples/client/petstore/perl/test.pl old mode 100644 new mode 100755 index 504461710cdd..b92e4cfcff14 --- a/samples/client/petstore/perl/test.pl +++ b/samples/client/petstore/perl/test.pl @@ -17,10 +17,10 @@ my $api = WWW::SwaggerClient::PetApi->new(); my $pet_id = 88; -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}); +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; @@ -30,11 +30,11 @@ $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 => '/var/tmp/f5.jpg'}); -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}); +print "\nupload_file:".Dumper $api->upload_file(pet_id => $pet_id, additional_metadata => 'testabc', file => '/var/tmp/f5.jpg'); +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); From 063a1ffd3645b2f593be3f60ea9d73565fc529c2 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Thu, 7 May 2015 22:41:50 +0800 Subject: [PATCH 24/67] update type list in deserialize --- .../codegen/languages/PerlClientCodegen.java | 34 ++++++++++++++----- .../main/resources/perl/BaseObject.mustache | 2 +- .../WWW/SwaggerClient/Object/BaseObject.pm | 2 +- .../lib/WWW/SwaggerClient/Object/Category.pm | 2 +- .../lib/WWW/SwaggerClient/Object/Order.pm | 4 +-- .../perl/lib/WWW/SwaggerClient/Object/Pet.pm | 6 ++-- .../perl/lib/WWW/SwaggerClient/Object/Tag.pm | 2 +- .../perl/lib/WWW/SwaggerClient/Object/User.pm | 2 +- .../perl/lib/WWW/SwaggerClient/PetApi.pm | 18 +++++----- .../perl/lib/WWW/SwaggerClient/StoreApi.pm | 4 +-- .../perl/lib/WWW/SwaggerClient/UserApi.pm | 4 +-- samples/client/petstore/perl/test.pl | 2 -- 12 files changed, 49 insertions(+), 33 deletions(-) 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 index 4edead804d51..9062c2722d72 100644 --- 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 @@ -38,7 +38,17 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { 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") + "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); @@ -47,17 +57,25 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { additionalProperties.put("artifactVersion", artifactVersion); languageSpecificPrimitives.add("int"); - languageSpecificPrimitives.add("array"); - languageSpecificPrimitives.add("map"); + languageSpecificPrimitives.add("Math::BigInt"); + languageSpecificPrimitives.add("double"); languageSpecificPrimitives.add("string"); + languageSpecificPrimitives.add("boolean"); languageSpecificPrimitives.add("DateTime"); + languageSpecificPrimitives.add("ARRAY"); + languageSpecificPrimitives.add("HASH"); - typeMapping.put("long", "int"); typeMapping.put("integer", "int"); - typeMapping.put("Array", "array"); - typeMapping.put("String", "string"); - typeMapping.put("List", "array"); - typeMapping.put("map", "map"); + typeMapping.put("long", "Math::BigInt"); + 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")); diff --git a/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache b/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache index 9fab6611593a..7ae05c075859 100644 --- a/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache @@ -65,7 +65,7 @@ sub _deserialize { if ($type eq 'DateTime') { return DateTime->from_epoch(epoch => str2time($data)); - } elsif ( grep( /^$type$/, ('string', 'int', 'float', 'bool')) ) { + } elsif ( grep( /^$type$/, ('int', 'Math::BigInt', 'double', 'string', 'boolean'))) { return $data; } else { # hash(model) my $_instance = eval "WWW::{{invokerPackage}}::Object::$type->new()"; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/BaseObject.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/BaseObject.pm index a5be613d472d..d1146ec45366 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/BaseObject.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/BaseObject.pm @@ -65,7 +65,7 @@ sub _deserialize { if ($type eq 'DateTime') { return DateTime->from_epoch(epoch => str2time($data)); - } elsif ( grep( /^$type$/, ('string', 'int', 'float', 'bool')) ) { + } elsif ( grep( /^$type$/, ('int', 'Math::BigInt', 'double', 'string', 'boolean'))) { return $data; } else { # hash(model) my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm index 857dccdce5a0..d72dc2c78c75 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm @@ -20,7 +20,7 @@ use base "WWW::SwaggerClient::Object::BaseObject"; # my $swagger_types = { - 'id' => 'int', + 'id' => 'Math::BigInt', 'name' => 'string' }; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm index 35449647e132..d76d03d8d3bc 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm @@ -20,8 +20,8 @@ use base "WWW::SwaggerClient::Object::BaseObject"; # my $swagger_types = { - 'id' => 'int', - 'pet_id' => 'int', + 'id' => 'Math::BigInt', + 'pet_id' => 'Math::BigInt', 'quantity' => 'int', 'ship_date' => 'DateTime', 'status' => 'string', diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm index f53aacdf0d33..ddcc0793f23b 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm @@ -20,11 +20,11 @@ use base "WWW::SwaggerClient::Object::BaseObject"; # my $swagger_types = { - 'id' => 'int', + 'id' => 'Math::BigInt', 'category' => 'Category', 'name' => 'string', - 'photo_urls' => 'array[string]', - 'tags' => 'array[Tag]', + 'photo_urls' => 'ARRAY[string]', + 'tags' => 'ARRAY[Tag]', 'status' => 'string' }; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm index 35850032d5c2..79f259340baa 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm @@ -20,7 +20,7 @@ use base "WWW::SwaggerClient::Object::BaseObject"; # my $swagger_types = { - 'id' => 'int', + 'id' => 'Math::BigInt', 'name' => 'string' }; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm index 88a396ece3a7..bc8971fb5e29 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm @@ -20,7 +20,7 @@ use base "WWW::SwaggerClient::Object::BaseObject"; # my $swagger_types = { - 'id' => 'int', + 'id' => 'Math::BigInt', 'username' => 'string', 'first_name' => 'string', 'last_name' => 'string', diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm index 9dbceba42912..b1985703ddda 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm @@ -171,8 +171,8 @@ sub new { # # Finds Pets by status # - # @param array[string] $status Status values that need to be considered for filter (required) - # @return array[Pet] + # @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) = @_; @@ -215,7 +215,7 @@ sub new { if (!$response) { return; } - my $_response_object = $self->{api_client}->deserialize('array[Pet]', $response); + my $_response_object = $self->{api_client}->deserialize('ARRAY[Pet]', $response); return $_response_object; } @@ -225,8 +225,8 @@ sub new { # # Finds Pets by tags # - # @param array[string] $tags Tags to filter by (required) - # @return array[Pet] + # @param ARRAY[string] $tags Tags to filter by (required) + # @return ARRAY[Pet] # sub find_pets_by_tags { my ($self, %args) = @_; @@ -269,7 +269,7 @@ sub new { if (!$response) { return; } - my $_response_object = $self->{api_client}->deserialize('array[Pet]', $response); + my $_response_object = $self->{api_client}->deserialize('ARRAY[Pet]', $response); return $_response_object; } @@ -279,7 +279,7 @@ sub new { # # Find pet by ID # - # @param int $pet_id ID of pet that needs to be fetched (required) + # @param Math::BigInt $pet_id ID of pet that needs to be fetched (required) # @return Pet # sub get_pet_by_id { @@ -411,7 +411,7 @@ sub new { # Deletes a pet # # @param string $api_key (required) - # @param int $pet_id Pet id to delete (required) + # @param Math::BigInt $pet_id Pet id to delete (required) # @return void # sub delete_pet { @@ -472,7 +472,7 @@ sub new { # # uploads an image # - # @param int $pet_id ID of pet to update (required) + # @param Math::BigInt $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 diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm index 6ef684893254..bb361d05a43d 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm @@ -65,7 +65,7 @@ sub new { # # Returns pet inventories by status # - # @return map[string,int] + # @return HASH[string,int] # sub get_inventory { my ($self, %args) = @_; @@ -105,7 +105,7 @@ sub new { if (!$response) { return; } - my $_response_object = $self->{api_client}->deserialize('map[string,int]', $response); + my $_response_object = $self->{api_client}->deserialize('HASH[string,int]', $response); return $_response_object; } diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm index a3955b7d4f88..d3869b625550 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm @@ -120,7 +120,7 @@ sub new { # # Creates list of users with given input array # - # @param array[User] $body List of user object (required) + # @param ARRAY[User] $body List of user object (required) # @return void # sub create_users_with_array_input { @@ -171,7 +171,7 @@ sub new { # # Creates list of users with given input array # - # @param array[User] $body List of user object (required) + # @param ARRAY[User] $body List of user object (required) # @return void # sub create_users_with_list_input { diff --git a/samples/client/petstore/perl/test.pl b/samples/client/petstore/perl/test.pl index b92e4cfcff14..2c545c7aac90 100755 --- a/samples/client/petstore/perl/test.pl +++ b/samples/client/petstore/perl/test.pl @@ -37,5 +37,3 @@ print "\nupdate_pet_with_form:".Dumper $api->update_pet_with_form(pet_id => $pet print "\ndelete_pet:".Dumper $api->delete_pet(pet_id => $pet_id); - - From fc43828c20b4a002e016fe655af4d5e5243cb7dc Mon Sep 17 00:00:00 2001 From: William Cheng Date: Fri, 8 May 2015 03:56:35 +0800 Subject: [PATCH 25/67] update type mapping, update test.pl to use local file for testing upload --- .../swagger/codegen/languages/PerlClientCodegen.java | 3 +-- .../src/main/resources/perl/BaseObject.mustache | 2 +- .../perl/lib/WWW/SwaggerClient/Object/BaseObject.pm | 2 +- .../petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm | 2 +- .../petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm | 4 ++-- .../petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm | 2 +- .../petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm | 2 +- .../petstore/perl/lib/WWW/SwaggerClient/Object/User.pm | 2 +- .../client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm | 6 +++--- samples/client/petstore/perl/test.pl | 4 ++-- 10 files changed, 14 insertions(+), 15 deletions(-) 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 index 9062c2722d72..b25e4490e856 100644 --- 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 @@ -57,7 +57,6 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { additionalProperties.put("artifactVersion", artifactVersion); languageSpecificPrimitives.add("int"); - languageSpecificPrimitives.add("Math::BigInt"); languageSpecificPrimitives.add("double"); languageSpecificPrimitives.add("string"); languageSpecificPrimitives.add("boolean"); @@ -66,7 +65,7 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { languageSpecificPrimitives.add("HASH"); typeMapping.put("integer", "int"); - typeMapping.put("long", "Math::BigInt"); + typeMapping.put("long", "int"); typeMapping.put("float", "double"); typeMapping.put("double", "double"); typeMapping.put("boolean", "boolean"); diff --git a/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache b/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache index 7ae05c075859..b4a7885a7987 100644 --- a/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache @@ -65,7 +65,7 @@ sub _deserialize { if ($type eq 'DateTime') { return DateTime->from_epoch(epoch => str2time($data)); - } elsif ( grep( /^$type$/, ('int', 'Math::BigInt', 'double', 'string', 'boolean'))) { + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { return $data; } else { # hash(model) my $_instance = eval "WWW::{{invokerPackage}}::Object::$type->new()"; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/BaseObject.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/BaseObject.pm index d1146ec45366..c4fd4e6aece3 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/BaseObject.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/BaseObject.pm @@ -65,7 +65,7 @@ sub _deserialize { if ($type eq 'DateTime') { return DateTime->from_epoch(epoch => str2time($data)); - } elsif ( grep( /^$type$/, ('int', 'Math::BigInt', 'double', 'string', 'boolean'))) { + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { return $data; } else { # hash(model) my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm index d72dc2c78c75..857dccdce5a0 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm @@ -20,7 +20,7 @@ use base "WWW::SwaggerClient::Object::BaseObject"; # my $swagger_types = { - 'id' => 'Math::BigInt', + 'id' => 'int', 'name' => 'string' }; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm index d76d03d8d3bc..35449647e132 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm @@ -20,8 +20,8 @@ use base "WWW::SwaggerClient::Object::BaseObject"; # my $swagger_types = { - 'id' => 'Math::BigInt', - 'pet_id' => 'Math::BigInt', + 'id' => 'int', + 'pet_id' => 'int', 'quantity' => 'int', 'ship_date' => 'DateTime', 'status' => 'string', diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm index ddcc0793f23b..df32665e8266 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm @@ -20,7 +20,7 @@ use base "WWW::SwaggerClient::Object::BaseObject"; # my $swagger_types = { - 'id' => 'Math::BigInt', + 'id' => 'int', 'category' => 'Category', 'name' => 'string', 'photo_urls' => 'ARRAY[string]', diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm index 79f259340baa..35850032d5c2 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm @@ -20,7 +20,7 @@ use base "WWW::SwaggerClient::Object::BaseObject"; # my $swagger_types = { - 'id' => 'Math::BigInt', + 'id' => 'int', 'name' => 'string' }; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm index bc8971fb5e29..88a396ece3a7 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm @@ -20,7 +20,7 @@ use base "WWW::SwaggerClient::Object::BaseObject"; # my $swagger_types = { - 'id' => 'Math::BigInt', + 'id' => 'int', 'username' => 'string', 'first_name' => 'string', 'last_name' => 'string', diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm index b1985703ddda..930bd52102be 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm @@ -279,7 +279,7 @@ sub new { # # Find pet by ID # - # @param Math::BigInt $pet_id ID of pet that needs to be fetched (required) + # @param int $pet_id ID of pet that needs to be fetched (required) # @return Pet # sub get_pet_by_id { @@ -411,7 +411,7 @@ sub new { # Deletes a pet # # @param string $api_key (required) - # @param Math::BigInt $pet_id Pet id to delete (required) + # @param int $pet_id Pet id to delete (required) # @return void # sub delete_pet { @@ -472,7 +472,7 @@ sub new { # # uploads an image # - # @param Math::BigInt $pet_id ID of pet to update (required) + # @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 diff --git a/samples/client/petstore/perl/test.pl b/samples/client/petstore/perl/test.pl index 2c545c7aac90..eb06f786f98e 100755 --- a/samples/client/petstore/perl/test.pl +++ b/samples/client/petstore/perl/test.pl @@ -15,7 +15,7 @@ use DateTime; my $api = WWW::SwaggerClient::PetApi->new(); -my $pet_id = 88; +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'); @@ -30,7 +30,7 @@ $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 => '/var/tmp/f5.jpg'); +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'); From 66dea18b615b5148ca8f23b6688803e2e08c5897 Mon Sep 17 00:00:00 2001 From: Alexey Nechaev Date: Fri, 8 May 2015 12:47:35 +0000 Subject: [PATCH 26/67] Reverted JsonUtil.mustache after PR #726. --- .../src/main/resources/Java/JsonUtil.mustache | 26 ++++++++++++------- 1 file changed, 16 insertions(+), 10 deletions(-) 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; + } +} From 5a1fa6ee65fc157c52fea545f76280b898322fe9 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 12 May 2015 05:56:12 -0400 Subject: [PATCH 27/67] added qt5 c++ templates --- .../codegen/languages/Qt5CPPGenerator.java | 306 ++++++++++++++++++ .../src/main/resources/qt5cpp/HttpRequest.cpp | 297 +++++++++++++++++ .../src/main/resources/qt5cpp/HttpRequest.h | 76 +++++ .../main/resources/qt5cpp/api-body.mustache | 107 ++++++ .../main/resources/qt5cpp/api-header.mustache | 34 ++ .../resources/qt5cpp/helpers-body.mustache | 161 +++++++++ .../resources/qt5cpp/helpers-header.mustache | 16 + .../main/resources/qt5cpp/model-body.mustache | 109 +++++++ .../resources/qt5cpp/model-header.mustache | 47 +++ .../src/main/resources/qt5cpp/model.mustache | 58 ++++ .../resources/qt5cpp/modelFactory.mustache | 18 ++ .../src/main/resources/qt5cpp/object.mustache | 24 ++ 12 files changed, 1253 insertions(+) create mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/Qt5CPPGenerator.java create mode 100644 modules/swagger-codegen/src/main/resources/qt5cpp/HttpRequest.cpp create mode 100644 modules/swagger-codegen/src/main/resources/qt5cpp/HttpRequest.h create mode 100644 modules/swagger-codegen/src/main/resources/qt5cpp/api-body.mustache create mode 100644 modules/swagger-codegen/src/main/resources/qt5cpp/api-header.mustache create mode 100644 modules/swagger-codegen/src/main/resources/qt5cpp/helpers-body.mustache create mode 100644 modules/swagger-codegen/src/main/resources/qt5cpp/helpers-header.mustache create mode 100644 modules/swagger-codegen/src/main/resources/qt5cpp/model-body.mustache create mode 100644 modules/swagger-codegen/src/main/resources/qt5cpp/model-header.mustache create mode 100644 modules/swagger-codegen/src/main/resources/qt5cpp/model.mustache create mode 100644 modules/swagger-codegen/src/main/resources/qt5cpp/modelFactory.mustache create mode 100644 modules/swagger-codegen/src/main/resources/qt5cpp/object.mustache 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..b3adeb19a321 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/Qt5CPPGenerator.java @@ -0,0 +1,306 @@ +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("number", "Long"); + typeMapping.put("object", PREFIX + "Object"); + + importMapping = new HashMap(); + + 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 "NULL"; + } + 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/resources/qt5cpp/HttpRequest.cpp b/modules/swagger-codegen/src/main/resources/qt5cpp/HttpRequest.cpp new file mode 100644 index 000000000000..fed94e8dddb6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/HttpRequest.cpp @@ -0,0 +1,297 @@ +#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) { + HttpRequestInputFileElement 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 = ""; + + + // 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; + 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) { + 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..260ccb206792 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/HttpRequest.h @@ -0,0 +1,76 @@ +/** + * 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 HttpRequestInputFileElement { + +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..a7a1d2646dd4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/api-body.mustache @@ -0,0 +1,107 @@ +#include "{{classname}}.h" +#include "{{prefix}}Helpers.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}}if(fullPath.compare("?") > 0) fullPath.append("?"); + else fullPath.append("&"); + fullPath.append(QUrl::toPercentEncoding("{{paramName}}")) + .append("=") + .append(QUrl::toPercentEncoding(stringValue({{paramName}}))); + {{/queryParams}} + + // qDebug() << fullPath; + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "{{httpMethod}}"); + + {{#bodyParams}} + // body + input.request_body.append({{paramName}}.asJson()); + {{/bodyParams}} + + {{#headerParams}} + input.headers + {{/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; + } + + // return type: {{{returnType}}} + + {{#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); + } + + + // void toJsonArray(QList* value, QJsonArray* output, QString innerName, QString innerType); + {{/isListContainer}} + + {{^isListContainer}}{{#returnTypeIsPrimitive}} + {{returnType}} output; // TODO + + {{/returnTypeIsPrimitive}} + {{^returnTypeIsPrimitive}}QString json(worker->response); + {{returnType}} output = new {{returnBaseType}}(&json); + + {{/returnTypeIsPrimitive}} + {{/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..364dc9b8e476 --- /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..01e205a07733 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-body.mustache @@ -0,0 +1,161 @@ +#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(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..988e6480da81 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-header.mustache @@ -0,0 +1,16 @@ +#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(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..f3cd5c8e2f0f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/modelFactory.mustache @@ -0,0 +1,18 @@ +#ifndef ModelFactory_H_ +#define ModelFactory_H_ + +{{#models}}{{#model}} +#include "{{classname}}.h"{{/model}}{{/models}} + +namespace Swagger { + void* + create(QString type) { + {{#models}}{{#model}}if(QString("{{classname}}").compare(type) == 0) { + return new {{classname}}(); + } + {{/model}}{{/models}} + 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_ */ From e703fc7982c36351998ccf9dfd4153205748a141 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 12 May 2015 06:03:37 -0400 Subject: [PATCH 28/67] fixed version --- .../swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache index d9e3b90bc95a..1bd168af7476 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache @@ -129,7 +129,7 @@ - 2.1.1-M2-SNAPSHOT + 1.5.2-M2-SNAPSHOT 9.2.9.v20150224 1.13 1.6.3 From c2ee64e669b5399b370f67380e39902cd849f3bb Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 12 May 2015 06:03:45 -0400 Subject: [PATCH 29/67] fixed version --- samples/server/petstore/jaxrs/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 From 037a00720f031c0b96e09c4f910e14c5c8d3c0b3 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 12 May 2015 06:04:10 -0400 Subject: [PATCH 30/67] added qt5 samples, script --- bin/qt5-petstore.sh | 31 ++ .../petstore/qt5cpp/client/SWGCategory.cpp | 105 ++++ .../petstore/qt5cpp/client/SWGCategory.h | 47 ++ .../petstore/qt5cpp/client/SWGHelpers.cpp | 161 +++++++ .../petstore/qt5cpp/client/SWGHelpers.h | 16 + .../petstore/qt5cpp/client/SWGHttpRequest.cpp | 297 ++++++++++++ .../petstore/qt5cpp/client/SWGHttpRequest.h | 76 +++ .../petstore/qt5cpp/client/SWGModelFactory.h | 34 ++ .../client/petstore/qt5cpp/client/SWGObject.h | 24 + .../petstore/qt5cpp/client/SWGOrder.cpp | 164 +++++++ .../client/petstore/qt5cpp/client/SWGOrder.h | 60 +++ .../client/petstore/qt5cpp/client/SWGPet.cpp | 199 ++++++++ .../client/petstore/qt5cpp/client/SWGPet.h | 62 +++ .../petstore/qt5cpp/client/SWGPetApi.cpp | 455 ++++++++++++++++++ .../client/petstore/qt5cpp/client/SWGPetApi.h | 56 +++ .../petstore/qt5cpp/client/SWGStoreApi.cpp | 230 +++++++++ .../petstore/qt5cpp/client/SWGStoreApi.h | 44 ++ .../client/petstore/qt5cpp/client/SWGTag.cpp | 105 ++++ .../client/petstore/qt5cpp/client/SWGTag.h | 47 ++ .../client/petstore/qt5cpp/client/SWGUser.cpp | 218 +++++++++ .../client/petstore/qt5cpp/client/SWGUser.h | 65 +++ .../petstore/qt5cpp/client/SWGUserApi.cpp | 424 ++++++++++++++++ .../petstore/qt5cpp/client/SWGUserApi.h | 56 +++ 23 files changed, 2976 insertions(+) create mode 100755 bin/qt5-petstore.sh create mode 100644 samples/client/petstore/qt5cpp/client/SWGCategory.cpp create mode 100644 samples/client/petstore/qt5cpp/client/SWGCategory.h create mode 100644 samples/client/petstore/qt5cpp/client/SWGHelpers.cpp create mode 100644 samples/client/petstore/qt5cpp/client/SWGHelpers.h create mode 100644 samples/client/petstore/qt5cpp/client/SWGHttpRequest.cpp create mode 100644 samples/client/petstore/qt5cpp/client/SWGHttpRequest.h create mode 100644 samples/client/petstore/qt5cpp/client/SWGModelFactory.h create mode 100644 samples/client/petstore/qt5cpp/client/SWGObject.h create mode 100644 samples/client/petstore/qt5cpp/client/SWGOrder.cpp create mode 100644 samples/client/petstore/qt5cpp/client/SWGOrder.h create mode 100644 samples/client/petstore/qt5cpp/client/SWGPet.cpp create mode 100644 samples/client/petstore/qt5cpp/client/SWGPet.h create mode 100644 samples/client/petstore/qt5cpp/client/SWGPetApi.cpp create mode 100644 samples/client/petstore/qt5cpp/client/SWGPetApi.h create mode 100644 samples/client/petstore/qt5cpp/client/SWGStoreApi.cpp create mode 100644 samples/client/petstore/qt5cpp/client/SWGStoreApi.h create mode 100644 samples/client/petstore/qt5cpp/client/SWGTag.cpp create mode 100644 samples/client/petstore/qt5cpp/client/SWGTag.h create mode 100644 samples/client/petstore/qt5cpp/client/SWGUser.cpp create mode 100644 samples/client/petstore/qt5cpp/client/SWGUser.h create mode 100644 samples/client/petstore/qt5cpp/client/SWGUserApi.cpp create mode 100644 samples/client/petstore/qt5cpp/client/SWGUserApi.h diff --git a/bin/qt5-petstore.sh b/bin/qt5-petstore.sh new file mode 100755 index 000000000000..d79dd513dede --- /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 -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/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..01e205a07733 --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/SWGHelpers.cpp @@ -0,0 +1,161 @@ +#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(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..988e6480da81 --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/SWGHelpers.h @@ -0,0 +1,16 @@ +#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(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..fed94e8dddb6 --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/SWGHttpRequest.cpp @@ -0,0 +1,297 @@ +#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) { + HttpRequestInputFileElement 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 = ""; + + + // 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; + 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) { + 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..260ccb206792 --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/SWGHttpRequest.h @@ -0,0 +1,76 @@ +/** + * 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 HttpRequestInputFileElement { + +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..3eaf51ab0a91 --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/SWGModelFactory.h @@ -0,0 +1,34 @@ +#ifndef ModelFactory_H_ +#define ModelFactory_H_ + + +#include "SWGUser.h" +#include "SWGCategory.h" +#include "SWGPet.h" +#include "SWGTag.h" +#include "SWGOrder.h" + +namespace Swagger { + 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; + } +} /* 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..e9cb4d082331 --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/SWGPet.h @@ -0,0 +1,62 @@ +/* + * SWGPet.h + * + * + */ + +#ifndef SWGPet_H_ +#define SWGPet_H_ + +#include + + +#include "SWGTag.h" +#include +#include "SWGCategory.h" +#include + +#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..312791e4b0f0 --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/SWGPetApi.cpp @@ -0,0 +1,455 @@ +#include "SWGPetApi.h" +#include "SWGHelpers.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"); + + + + + + // qDebug() << fullPath; + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "PUT"); + + + // body + input.request_body.append(body.asJson()); + + + + + 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; + } + + // return type: + + + + worker->deleteLater(); + + + emit updatePetSignal(); +} +void +SWGPetApi::addPet(SWGPet body) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/pet"); + + + + + + // qDebug() << fullPath; + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "POST"); + + + // body + input.request_body.append(body.asJson()); + + + + + 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; + } + + // return type: + + + + worker->deleteLater(); + + + emit addPetSignal(); +} +void +SWGPetApi::findPetsByStatus(QList<QString*>* status) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/pet/findByStatus"); + + + + if(fullPath.compare("?") > 0) fullPath.append("?"); + else fullPath.append("&"); + fullPath.append(QUrl::toPercentEncoding("status")) + .append("=") + .append(QUrl::toPercentEncoding(stringValue(status))); + + + // qDebug() << fullPath; + + 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; + } + + // return type: QList* + + + + 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); + } + + + // void toJsonArray(QList* value, QJsonArray* output, QString innerName, QString innerType); + + + + + worker->deleteLater(); + + emit findPetsByStatusSignal(output); + +} +void +SWGPetApi::findPetsByTags(QList<QString*>* tags) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/pet/findByTags"); + + + + if(fullPath.compare("?") > 0) fullPath.append("?"); + else fullPath.append("&"); + fullPath.append(QUrl::toPercentEncoding("tags")) + .append("=") + .append(QUrl::toPercentEncoding(stringValue(tags))); + + + // qDebug() << fullPath; + + 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; + } + + // return type: QList* + + + + 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); + } + + + // void toJsonArray(QList* value, QJsonArray* output, QString innerName, QString innerType); + + + + + 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)); + + + + + // qDebug() << fullPath; + + 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; + } + + // return type: SWGPet* + + + + + + QString json(worker->response); + SWGPet* output = new SWGPet(&json); + + + + + 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)); + + + + + // qDebug() << fullPath; + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "POST"); + + + + + + 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; + } + + // return type: + + + + 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)); + + + + + // qDebug() << fullPath; + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "DELETE"); + + + + + input.headers + + + 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; + } + + // return type: + + + + worker->deleteLater(); + + + emit deletePetSignal(); +} +void +SWGPetApi::uploadFile(qint64 petId, QString* additionalMetadata, SWGFile* 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)); + + + + + // qDebug() << fullPath; + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "POST"); + + + + + + 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; + } + + // return type: + + + + 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..41aac089a4ff --- /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 "SWGFile.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<QString*>* status); + void findPetsByTags(QList<QString*>* 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, SWGFile* 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..a973c7c99fd0 --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/SWGStoreApi.cpp @@ -0,0 +1,230 @@ +#include "SWGStoreApi.h" +#include "SWGHelpers.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"); + + + + + + // qDebug() << fullPath; + + 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; + } + + // return type: QMap* + + + + + + QString json(worker->response); + QMap<String, qint32>* output = new QMap(&json); + + + + + worker->deleteLater(); + + emit getInventorySignal(output); + +} +void +SWGStoreApi::placeOrder(SWGOrder body) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/store/order"); + + + + + + // qDebug() << fullPath; + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "POST"); + + + // body + input.request_body.append(body.asJson()); + + + + + 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; + } + + // return type: SWGOrder* + + + + + + QString json(worker->response); + SWGOrder* output = new SWGOrder(&json); + + + + + 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)); + + + + + // qDebug() << fullPath; + + 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; + } + + // return type: SWGOrder* + + + + + + QString json(worker->response); + SWGOrder* output = new SWGOrder(&json); + + + + + 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)); + + + + + // qDebug() << fullPath; + + 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; + } + + // return type: + + + + 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..6b7755c7d5e4 --- /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..21bba60e7d18 --- /dev/null +++ b/samples/client/petstore/qt5cpp/client/SWGUserApi.cpp @@ -0,0 +1,424 @@ +#include "SWGUserApi.h" +#include "SWGHelpers.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"); + + + + + + // qDebug() << fullPath; + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "POST"); + + + // body + input.request_body.append(body.asJson()); + + + + + 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; + } + + // return type: + + + + worker->deleteLater(); + + + emit createUserSignal(); +} +void +SWGUserApi::createUsersWithArrayInput(QList<SWGUser*>* body) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/user/createWithArray"); + + + + + + // qDebug() << fullPath; + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "POST"); + + + // body + input.request_body.append(body.asJson()); + + + + + 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; + } + + // return type: + + + + worker->deleteLater(); + + + emit createUsersWithArrayInputSignal(); +} +void +SWGUserApi::createUsersWithListInput(QList<SWGUser*>* body) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/user/createWithList"); + + + + + + // qDebug() << fullPath; + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "POST"); + + + // body + input.request_body.append(body.asJson()); + + + + + 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; + } + + // return type: + + + + 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.compare("?") > 0) fullPath.append("?"); + else fullPath.append("&"); + fullPath.append(QUrl::toPercentEncoding("username")) + .append("=") + .append(QUrl::toPercentEncoding(stringValue(username))); + if(fullPath.compare("?") > 0) fullPath.append("?"); + else fullPath.append("&"); + fullPath.append(QUrl::toPercentEncoding("password")) + .append("=") + .append(QUrl::toPercentEncoding(stringValue(password))); + + + // qDebug() << fullPath; + + 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; + } + + // return type: QString* + + + + + + QString json(worker->response); + QString* output = new QString(&json); + + + + + worker->deleteLater(); + + emit loginUserSignal(output); + +} +void +SWGUserApi::logoutUser() { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/user/logout"); + + + + + + // qDebug() << fullPath; + + 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; + } + + // return type: + + + + 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)); + + + + + // qDebug() << fullPath; + + 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; + } + + // return type: SWGUser* + + + + + + QString json(worker->response); + SWGUser* output = new SWGUser(&json); + + + + + 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)); + + + + + // qDebug() << fullPath; + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "PUT"); + + + // body + input.request_body.append(body.asJson()); + + + + + 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; + } + + // return type: + + + + 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)); + + + + + // qDebug() << fullPath; + + 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; + } + + // return type: + + + + 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..cc6ed57bf349 --- /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<SWGUser*>* body); + void createUsersWithListInput(QList<SWGUser*>* 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 From 1912973d36ee9c585fc3cf1720bf45567cbb78be Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 12 May 2015 06:04:23 -0400 Subject: [PATCH 31/67] enabled qt5 --- .../META-INF/services/com.wordnik.swagger.codegen.CodegenConfig | 1 + 1 file changed, 1 insertion(+) 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 8cb09dcfc111..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 @@ -9,6 +9,7 @@ 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 From dae01b50432f04a4f018fe9c88822d83bcd92d61 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 12 May 2015 06:04:44 -0400 Subject: [PATCH 32/67] template update --- .../spring-mvc/src/main/java/io/swagger/api/PetApi.java | 4 ++-- .../spring-mvc/src/main/java/io/swagger/api/UserApi.java | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) 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); From 0b2eced6a3c29e57897d794623a5356105512d89 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 12 May 2015 06:05:00 -0400 Subject: [PATCH 33/67] rebuilt --- samples/html/index.html | 638 +++++++++++++++++++++------------------- 1 file changed, 334 insertions(+), 304 deletions(-) diff --git a/samples/html/index.html b/samples/html/index.html index bab16472c309..7ce9ee130e2b 100644 --- a/samples/html/index.html +++ b/samples/html/index.html @@ -18,8 +18,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 +353,7 @@
post: /user/createWithArray
+
User
createUsersWithArrayInput Creates list of users with given input array
@@ -60,6 +374,7 @@
post: /user/createWithList
+
User
createUsersWithListInput Creates list of users with given input array
@@ -80,6 +395,7 @@
get: /user/login
+
User
loginUser Logs user into the system
@@ -111,6 +427,7 @@
get: /user/logout
+
User
logoutUser Logs out current logged in user session
@@ -128,6 +445,7 @@
get: /user/{username}
+
User
getUserByName Get user by user name
@@ -156,6 +474,7 @@
put: /user/{username}
+
User
updateUser Updated user
This can only be done by the logged in user.
@@ -179,6 +498,7 @@
delete: /user/{username}
+
User
deleteUser Delete user
This can only be done by the logged in user.
@@ -198,310 +518,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 +647,7 @@ hr { pre { padding: 10px; + margin-bottom: 2px; } pre.get { @@ -712,6 +729,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 From f9db729e7564c8df1be6fabc00e27759d9362d89 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 12 May 2015 06:05:09 -0400 Subject: [PATCH 34/67] added qt5 --- bin/all-petstore.sh | 1 + 1 file changed, 1 insertion(+) 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 From 8519480f2c443c0addabfbdc9b47671d00ceb0c4 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 12 May 2015 06:50:45 -0400 Subject: [PATCH 35/67] removed some cruft --- .../main/resources/qt5cpp/api-body.mustache | 10 +---- .../petstore/qt5cpp/client/SWGPetApi.cpp | 41 ------------------- .../petstore/qt5cpp/client/SWGStoreApi.cpp | 19 --------- .../petstore/qt5cpp/client/SWGUserApi.cpp | 34 --------------- 4 files changed, 1 insertion(+), 103 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/api-body.mustache b/modules/swagger-codegen/src/main/resources/qt5cpp/api-body.mustache index a7a1d2646dd4..9103cb5e16f2 100644 --- a/modules/swagger-codegen/src/main/resources/qt5cpp/api-body.mustache +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/api-body.mustache @@ -33,8 +33,6 @@ void .append(QUrl::toPercentEncoding(stringValue({{paramName}}))); {{/queryParams}} - // qDebug() << fullPath; - HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "{{httpMethod}}"); @@ -65,10 +63,7 @@ void msg = "Error: " + worker->error_str; } - // return type: {{{returnType}}} - - {{#returnType}} - {{#isListContainer}} + {{#returnType}}{{#isListContainer}} {{{returnType}}} output = {{{defaultResponse}}}; QString json(worker->response); QByteArray array (json.toStdString().c_str()); @@ -82,9 +77,6 @@ void o->fromJsonObject(*ptr); output->append(o); } - - - // void toJsonArray(QList* value, QJsonArray* output, QString innerName, QString innerType); {{/isListContainer}} {{^isListContainer}}{{#returnTypeIsPrimitive}} diff --git a/samples/client/petstore/qt5cpp/client/SWGPetApi.cpp b/samples/client/petstore/qt5cpp/client/SWGPetApi.cpp index 312791e4b0f0..4405b0e4d240 100644 --- a/samples/client/petstore/qt5cpp/client/SWGPetApi.cpp +++ b/samples/client/petstore/qt5cpp/client/SWGPetApi.cpp @@ -23,8 +23,6 @@ SWGPetApi::updatePet(SWGPet body) { - // qDebug() << fullPath; - HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "PUT"); @@ -53,8 +51,6 @@ SWGPetApi::updatePetCallback(HttpRequestWorker * worker) { msg = "Error: " + worker->error_str; } - // return type: - worker->deleteLater(); @@ -71,8 +67,6 @@ SWGPetApi::addPet(SWGPet body) { - // qDebug() << fullPath; - HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "POST"); @@ -101,8 +95,6 @@ SWGPetApi::addPetCallback(HttpRequestWorker * worker) { msg = "Error: " + worker->error_str; } - // return type: - worker->deleteLater(); @@ -124,8 +116,6 @@ SWGPetApi::findPetsByStatus(QList<QString*>* status) { .append(QUrl::toPercentEncoding(stringValue(status))); - // qDebug() << fullPath; - HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "GET"); @@ -151,9 +141,6 @@ SWGPetApi::findPetsByStatusCallback(HttpRequestWorker * worker) { msg = "Error: " + worker->error_str; } - // return type: QList* - - QList* output = new QList(); QString json(worker->response); @@ -168,9 +155,6 @@ SWGPetApi::findPetsByStatusCallback(HttpRequestWorker * worker) { o->fromJsonObject(*ptr); output->append(o); } - - - // void toJsonArray(QList* value, QJsonArray* output, QString innerName, QString innerType); @@ -194,8 +178,6 @@ SWGPetApi::findPetsByTags(QList<QString*>* tags) { .append(QUrl::toPercentEncoding(stringValue(tags))); - // qDebug() << fullPath; - HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "GET"); @@ -221,9 +203,6 @@ SWGPetApi::findPetsByTagsCallback(HttpRequestWorker * worker) { msg = "Error: " + worker->error_str; } - // return type: QList* - - QList* output = new QList(); QString json(worker->response); @@ -238,9 +217,6 @@ SWGPetApi::findPetsByTagsCallback(HttpRequestWorker * worker) { o->fromJsonObject(*ptr); output->append(o); } - - - // void toJsonArray(QList* value, QJsonArray* output, QString innerName, QString innerType); @@ -262,8 +238,6 @@ SWGPetApi::getPetById(qint64 petId) { - // qDebug() << fullPath; - HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "GET"); @@ -289,9 +263,6 @@ SWGPetApi::getPetByIdCallback(HttpRequestWorker * worker) { msg = "Error: " + worker->error_str; } - // return type: SWGPet* - - @@ -318,8 +289,6 @@ SWGPetApi::updatePetWithForm(QString* petId, QString* name, QString* status) { - // qDebug() << fullPath; - HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "POST"); @@ -345,8 +314,6 @@ SWGPetApi::updatePetWithFormCallback(HttpRequestWorker * worker) { msg = "Error: " + worker->error_str; } - // return type: - worker->deleteLater(); @@ -366,8 +333,6 @@ SWGPetApi::deletePet(QString* api_key, qint64 petId) { - // qDebug() << fullPath; - HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "DELETE"); @@ -395,8 +360,6 @@ SWGPetApi::deletePetCallback(HttpRequestWorker * worker) { msg = "Error: " + worker->error_str; } - // return type: - worker->deleteLater(); @@ -416,8 +379,6 @@ SWGPetApi::uploadFile(qint64 petId, QString* additionalMetadata, SWGFile* file) - // qDebug() << fullPath; - HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "POST"); @@ -443,8 +404,6 @@ SWGPetApi::uploadFileCallback(HttpRequestWorker * worker) { msg = "Error: " + worker->error_str; } - // return type: - worker->deleteLater(); diff --git a/samples/client/petstore/qt5cpp/client/SWGStoreApi.cpp b/samples/client/petstore/qt5cpp/client/SWGStoreApi.cpp index a973c7c99fd0..8602eb009fda 100644 --- a/samples/client/petstore/qt5cpp/client/SWGStoreApi.cpp +++ b/samples/client/petstore/qt5cpp/client/SWGStoreApi.cpp @@ -23,8 +23,6 @@ SWGStoreApi::getInventory() { - // qDebug() << fullPath; - HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "GET"); @@ -50,9 +48,6 @@ SWGStoreApi::getInventoryCallback(HttpRequestWorker * worker) { msg = "Error: " + worker->error_str; } - // return type: QMap* - - @@ -76,8 +71,6 @@ SWGStoreApi::placeOrder(SWGOrder body) { - // qDebug() << fullPath; - HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "POST"); @@ -106,9 +99,6 @@ SWGStoreApi::placeOrderCallback(HttpRequestWorker * worker) { msg = "Error: " + worker->error_str; } - // return type: SWGOrder* - - @@ -135,8 +125,6 @@ SWGStoreApi::getOrderById(QString* orderId) { - // qDebug() << fullPath; - HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "GET"); @@ -162,9 +150,6 @@ SWGStoreApi::getOrderByIdCallback(HttpRequestWorker * worker) { msg = "Error: " + worker->error_str; } - // return type: SWGOrder* - - @@ -191,8 +176,6 @@ SWGStoreApi::deleteOrder(QString* orderId) { - // qDebug() << fullPath; - HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "DELETE"); @@ -218,8 +201,6 @@ SWGStoreApi::deleteOrderCallback(HttpRequestWorker * worker) { msg = "Error: " + worker->error_str; } - // return type: - worker->deleteLater(); diff --git a/samples/client/petstore/qt5cpp/client/SWGUserApi.cpp b/samples/client/petstore/qt5cpp/client/SWGUserApi.cpp index 21bba60e7d18..9d17e9067e33 100644 --- a/samples/client/petstore/qt5cpp/client/SWGUserApi.cpp +++ b/samples/client/petstore/qt5cpp/client/SWGUserApi.cpp @@ -23,8 +23,6 @@ SWGUserApi::createUser(SWGUser body) { - // qDebug() << fullPath; - HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "POST"); @@ -53,8 +51,6 @@ SWGUserApi::createUserCallback(HttpRequestWorker * worker) { msg = "Error: " + worker->error_str; } - // return type: - worker->deleteLater(); @@ -71,8 +67,6 @@ SWGUserApi::createUsersWithArrayInput(QList<SWGUser*>* body) { - // qDebug() << fullPath; - HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "POST"); @@ -101,8 +95,6 @@ SWGUserApi::createUsersWithArrayInputCallback(HttpRequestWorker * worker) { msg = "Error: " + worker->error_str; } - // return type: - worker->deleteLater(); @@ -119,8 +111,6 @@ SWGUserApi::createUsersWithListInput(QList<SWGUser*>* body) { - // qDebug() << fullPath; - HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "POST"); @@ -149,8 +139,6 @@ SWGUserApi::createUsersWithListInputCallback(HttpRequestWorker * worker) { msg = "Error: " + worker->error_str; } - // return type: - worker->deleteLater(); @@ -177,8 +165,6 @@ SWGUserApi::loginUser(QString* username, QString* password) { .append(QUrl::toPercentEncoding(stringValue(password))); - // qDebug() << fullPath; - HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "GET"); @@ -204,9 +190,6 @@ SWGUserApi::loginUserCallback(HttpRequestWorker * worker) { msg = "Error: " + worker->error_str; } - // return type: QString* - - @@ -230,8 +213,6 @@ SWGUserApi::logoutUser() { - // qDebug() << fullPath; - HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "GET"); @@ -257,8 +238,6 @@ SWGUserApi::logoutUserCallback(HttpRequestWorker * worker) { msg = "Error: " + worker->error_str; } - // return type: - worker->deleteLater(); @@ -278,8 +257,6 @@ SWGUserApi::getUserByName(QString* username) { - // qDebug() << fullPath; - HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "GET"); @@ -305,9 +282,6 @@ SWGUserApi::getUserByNameCallback(HttpRequestWorker * worker) { msg = "Error: " + worker->error_str; } - // return type: SWGUser* - - @@ -334,8 +308,6 @@ SWGUserApi::updateUser(QString* username, SWGUser body) { - // qDebug() << fullPath; - HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "PUT"); @@ -364,8 +336,6 @@ SWGUserApi::updateUserCallback(HttpRequestWorker * worker) { msg = "Error: " + worker->error_str; } - // return type: - worker->deleteLater(); @@ -385,8 +355,6 @@ SWGUserApi::deleteUser(QString* username) { - // qDebug() << fullPath; - HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "DELETE"); @@ -412,8 +380,6 @@ SWGUserApi::deleteUserCallback(HttpRequestWorker * worker) { msg = "Error: " + worker->error_str; } - // return type: - worker->deleteLater(); From 622d883344c283eccdb8fec2509202b765c59b80 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 12 May 2015 06:57:37 -0400 Subject: [PATCH 36/67] fixed input type --- .../src/main/resources/qt5cpp/api-header.mustache | 2 +- samples/client/petstore/qt5cpp/client/SWGPetApi.h | 4 ++-- samples/client/petstore/qt5cpp/client/SWGUserApi.h | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/api-header.mustache b/modules/swagger-codegen/src/main/resources/qt5cpp/api-header.mustache index 364dc9b8e476..4260ba6ff865 100644 --- a/modules/swagger-codegen/src/main/resources/qt5cpp/api-header.mustache +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/api-header.mustache @@ -21,7 +21,7 @@ public: QString host; QString basePath; - {{#operations}}{{#operation}}void {{nickname}}({{#allParams}}{{dataType}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{#operations}}{{#operation}}void {{nickname}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); {{/operation}}{{/operations}} private: {{#operations}}{{#operation}}void {{nickname}}Callback (HttpRequestWorker * worker); diff --git a/samples/client/petstore/qt5cpp/client/SWGPetApi.h b/samples/client/petstore/qt5cpp/client/SWGPetApi.h index 41aac089a4ff..1067265656b9 100644 --- a/samples/client/petstore/qt5cpp/client/SWGPetApi.h +++ b/samples/client/petstore/qt5cpp/client/SWGPetApi.h @@ -24,8 +24,8 @@ public: void updatePet(SWGPet body); void addPet(SWGPet body); - void findPetsByStatus(QList<QString*>* status); - void findPetsByTags(QList<QString*>* tags); + 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); diff --git a/samples/client/petstore/qt5cpp/client/SWGUserApi.h b/samples/client/petstore/qt5cpp/client/SWGUserApi.h index cc6ed57bf349..2e3e119dc780 100644 --- a/samples/client/petstore/qt5cpp/client/SWGUserApi.h +++ b/samples/client/petstore/qt5cpp/client/SWGUserApi.h @@ -23,8 +23,8 @@ public: QString basePath; void createUser(SWGUser body); - void createUsersWithArrayInput(QList<SWGUser*>* body); - void createUsersWithListInput(QList<SWGUser*>* body); + void createUsersWithArrayInput(QList* body); + void createUsersWithListInput(QList* body); void loginUser(QString* username, QString* password); void logoutUser(); void getUserByName(QString* username); From 4466b6e15eda803b7dac0d686c633fedc712ede8 Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 15 May 2015 11:08:33 +0800 Subject: [PATCH 37/67] add test case for upload file, improve error handling --- .../php/SwaggerClient-php/lib/APIClient.php | 11 +++---- .../SwaggerClient-php/tests/PetApiTest.php | 32 +++++++++++++++++-- 2 files changed, 35 insertions(+), 8 deletions(-) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php index d3fe07aa911d..d6d14c72527f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php @@ -142,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/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index f50fd1a8fc42..d2d398ae1406 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -9,15 +9,26 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public static function setUpBeforeClass() { // initialize the API client $api_client = new SwaggerClient\APIClient('http://petstore.swagger.io/v2'); + // new pet $new_pet_id = 10005; $new_pet = new SwaggerClient\models\Pet; $new_pet->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); - // return nothing (void) - //$this->assertSame($add_response, NULL); } // test getPetById with a Pet object (id 10005) @@ -31,6 +42,10 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $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 @@ -112,6 +127,19 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $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); + } + } ?> From 3544136ab15105f5af368384abc6ef0170701067 Mon Sep 17 00:00:00 2001 From: Josh Ponelat Date: Fri, 15 May 2015 09:10:03 +0200 Subject: [PATCH 38/67] dynamic-html: make sure clicking on return type works --- .../resources/swagger-static/assets/js/main.js | 13 ++++--------- .../resources/swagger-static/operation.mustache | 2 +- samples/dynamic-html/docs/assets/js/main.js | 13 ++++--------- samples/dynamic-html/docs/operations/PetApi.html | 16 ++++++++-------- .../dynamic-html/docs/operations/StoreApi.html | 8 ++++---- .../dynamic-html/docs/operations/UserApi.html | 16 ++++++++-------- 6 files changed, 29 insertions(+), 39 deletions(-) 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..e84542d1b725 100644 --- a/modules/swagger-codegen/src/main/resources/swagger-static/operation.mustache +++ b/modules/swagger-codegen/src/main/resources/swagger-static/operation.mustache @@ -13,7 +13,7 @@

HTTP Method

{{httpMethod}}

Response Type

- +

Parameters

    {{#allParams}} 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..f14f68db0cac 100644 --- a/samples/dynamic-html/docs/operations/PetApi.html +++ b/samples/dynamic-html/docs/operations/PetApi.html @@ -13,7 +13,7 @@

    HTTP Method

    PUT

    Response Type

    -
    +

    Parameters

      @@ -36,7 +36,7 @@

      HTTP Method

      POST

      Response Type

      -
      +

      Parameters

        @@ -59,7 +59,7 @@

        HTTP Method

        GET

        Response Type

        - +

        Parameters

          @@ -82,7 +82,7 @@

          HTTP Method

          GET

          Response Type

          - +

          Parameters

            @@ -105,7 +105,7 @@

            HTTP Method

            GET

            Response Type

            - +

            Parameters

              @@ -128,7 +128,7 @@

              HTTP Method

              POST

              Response Type

              -
              +

              Parameters

                @@ -167,7 +167,7 @@

                HTTP Method

                DELETE

                Response Type

                -
                +

                Parameters

                  @@ -198,7 +198,7 @@

                  HTTP Method

                  POST

                  Response Type

                  -
                  +

                  Parameters

                    diff --git a/samples/dynamic-html/docs/operations/StoreApi.html b/samples/dynamic-html/docs/operations/StoreApi.html index 798372217f04..5e20fd2d10b9 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,7 +28,7 @@

                      HTTP Method

                      POST

                      Response Type

                      - +

                      Parameters

                        @@ -51,7 +51,7 @@

                        HTTP Method

                        GET

                        Response Type

                        - +

                        Parameters

                          @@ -74,7 +74,7 @@

                          HTTP Method

                          DELETE

                          Response Type

                          -
                          +

                          Parameters

                            diff --git a/samples/dynamic-html/docs/operations/UserApi.html b/samples/dynamic-html/docs/operations/UserApi.html index cc573089bceb..79fe6410e5e3 100644 --- a/samples/dynamic-html/docs/operations/UserApi.html +++ b/samples/dynamic-html/docs/operations/UserApi.html @@ -13,7 +13,7 @@

                            HTTP Method

                            POST

                            Response Type

                            -
                            +

                            Parameters

                              @@ -36,7 +36,7 @@

                              HTTP Method

                              POST

                              Response Type

                              -
                              +

                              Parameters

                                @@ -62,7 +62,7 @@

                                HTTP Method

                                POST

                                Response Type

                                -
                                +

                                Parameters

                                  @@ -88,7 +88,7 @@

                                  HTTP Method

                                  GET

                                  Response Type

                                  - +

                                  Parameters

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

                                    HTTP Method

                                    GET

                                    Response Type

                                    -
                                    +

                                    Parameters

                                      @@ -134,7 +134,7 @@

                                      HTTP Method

                                      GET

                                      Response Type

                                      - +

                                      Parameters

                                        @@ -157,7 +157,7 @@

                                        HTTP Method

                                        PUT

                                        Response Type

                                        -
                                        +

                                        Parameters

                                          @@ -188,7 +188,7 @@

                                          HTTP Method

                                          DELETE

                                          Response Type

                                          -
                                          +

                                          Parameters

                                            From 30496ffdc3ae9863849d4690a3404874a572ea44 Mon Sep 17 00:00:00 2001 From: Josh Ponelat Date: Fri, 15 May 2015 08:59:08 +0200 Subject: [PATCH 39/67] html: remove dead css line --- .../swagger-codegen/src/main/resources/htmlDocs/index.mustache | 1 - samples/html/index.html | 1 - 2 files changed, 2 deletions(-) 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/samples/html/index.html b/samples/html/index.html index 7ce9ee130e2b..1025186dc4b6 100644 --- a/samples/html/index.html +++ b/samples/html/index.html @@ -2,7 +2,6 @@ API Reference -

                                            Swagger Petstore

                                            From 3bc319d534b8e11ae8a146e47ee0f77e6ca7033d Mon Sep 17 00:00:00 2001 From: Josh Ponelat Date: Fri, 15 May 2015 09:25:24 +0200 Subject: [PATCH 40/67] dynamic-html: refactor parameters view --- .../swagger-static/assets/css/style.css | 28 +++- .../swagger-static/operation.mustache | 41 ++--- .../dynamic-html/docs/assets/css/style.css | 28 +++- .../dynamic-html/docs/operations/PetApi.html | 158 ++++++++++++------ .../docs/operations/StoreApi.html | 38 +++-- .../dynamic-html/docs/operations/UserApi.html | 116 ++++++++----- 6 files changed, 259 insertions(+), 150 deletions(-) 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/operation.mustache b/modules/swagger-codegen/src/main/resources/swagger-static/operation.mustache index d0e35f1b2963..a1789a60dadc 100644 --- a/modules/swagger-codegen/src/main/resources/swagger-static/operation.mustache +++ b/modules/swagger-codegen/src/main/resources/swagger-static/operation.mustache @@ -17,36 +17,19 @@

                                            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/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/operations/PetApi.html b/samples/dynamic-html/docs/operations/PetApi.html index 11ca041d8d8b..b01e28de36d8 100644 --- a/samples/dynamic-html/docs/operations/PetApi.html +++ b/samples/dynamic-html/docs/operations/PetApi.html @@ -17,13 +17,17 @@

    Parameters

      -
      +
    • - -

      Pet object that needs to be added to the store

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

      Pet object that needs to be added to the store

      +
    @@ -40,13 +44,17 @@

    Parameters

      -
      +
    • - -

      Pet object that needs to be added to the store

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

      Pet object that needs to be added to the store

      +
    @@ -63,13 +71,17 @@

    Parameters

      -
      +
    • + + Query: - -

      Status values that need to be considered for filter

      -
    • + status + List(String) + +

      Status values that need to be considered for filter

      +
    @@ -86,13 +98,17 @@

    Parameters

      -
      +
    • + + Query: - -

      Tags to filter by

      -
    • + tags + List(String) + +

      Tags to filter by

      +
    @@ -109,13 +125,17 @@

    Parameters

      -
      +
    • - + Path: -

      ID of pet that needs to be fetched

      -
    • + + petId + Long + +

      ID of pet that needs to be fetched

      +
    @@ -132,29 +152,41 @@

    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

      +
    @@ -171,21 +203,29 @@

    Parameters

      -
      +
    • - -

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

      + -
      +
    • - + Path: -

      Pet id to delete

      -
    • + + petId + Long + +

      Pet id to delete

      +
    @@ -202,31 +242,43 @@

    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..c2f8b942dbef 100644 --- a/samples/dynamic-html/docs/operations/StoreApi.html +++ b/samples/dynamic-html/docs/operations/StoreApi.html @@ -32,13 +32,17 @@

    Parameters

      -
      +
    • - -

      order placed for purchasing the pet

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

      order placed for purchasing the pet

      +
    @@ -55,13 +59,17 @@

    Parameters

      -
      +
    • - + Path: -

      ID of pet that needs to be fetched

      -
    • + + orderId + String + +

      ID of pet that needs to be fetched

      +
    @@ -78,15 +86,19 @@

    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..20ee0e086eab 100644 --- a/samples/dynamic-html/docs/operations/UserApi.html +++ b/samples/dynamic-html/docs/operations/UserApi.html @@ -17,13 +17,17 @@

    Parameters

      -
      +
    • - -

      Created user object

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

      Created user object

      +
    @@ -40,16 +44,17 @@

    Parameters

      -
      - - - +
    • - -

      List of user object

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

      List of user object

      +
    @@ -66,16 +71,17 @@

    Parameters

      -
      - - - +
    • - -

      List of user object

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

      List of user object

      +
    @@ -92,21 +98,29 @@

    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

      +
    @@ -138,13 +152,17 @@

    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.

      +
    @@ -161,21 +179,29 @@

    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

      +
    @@ -192,15 +218,19 @@

    Parameters

      -
      +
    • - + Path: -

      The name that needs to be deleted

      -
    • + + username + String + +

      The name that needs to be deleted

      +
    - \ No newline at end of file + From 1f6a19b684e6a556859142d781acf886d396964b Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 15 May 2015 20:58:59 +0800 Subject: [PATCH 41/67] minor improvement to ruby api client accept and content-type header --- .../src/main/resources/ruby/api.mustache | 8 ++- .../resources/ruby/swagger/request.mustache | 26 ++++++++ samples/client/petstore/ruby/lib/pet_api.rb | 64 ++++++++++++------- samples/client/petstore/ruby/lib/store_api.rb | 32 ++++++---- .../petstore/ruby/lib/swagger/request.rb | 26 ++++++++ samples/client/petstore/ruby/lib/user_api.rb | 64 ++++++++++++------- 6 files changed, 157 insertions(+), 63 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index 210c7d819bac..528c772f1fbe 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -29,11 +29,13 @@ class {{classname}} # 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 + # HTTP header 'Content-Type' _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['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}} 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..70f75d71c4ff 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache @@ -208,5 +208,31 @@ module Swagger @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 + end end diff --git a/samples/client/petstore/ruby/lib/pet_api.rb b/samples/client/petstore/ruby/lib/pet_api.rb index 7cab0c8eb008..96ddb14bd949 100644 --- a/samples/client/petstore/ruby/lib/pet_api.rb +++ b/samples/client/petstore/ruby/lib/pet_api.rb @@ -21,11 +21,13 @@ class PetApi # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -73,11 +75,13 @@ class PetApi # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -126,11 +130,13 @@ class PetApi # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -160,11 +166,13 @@ class PetApi # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -196,11 +204,13 @@ class PetApi # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -234,11 +244,13 @@ class PetApi # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -272,11 +284,13 @@ class PetApi # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + 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 @@ -310,11 +324,13 @@ class PetApi # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} diff --git a/samples/client/petstore/ruby/lib/store_api.rb b/samples/client/petstore/ruby/lib/store_api.rb index 1ce553cde9a9..a14d0f7c2733 100644 --- a/samples/client/petstore/ruby/lib/store_api.rb +++ b/samples/client/petstore/ruby/lib/store_api.rb @@ -20,11 +20,13 @@ class StoreApi # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -53,11 +55,13 @@ class StoreApi # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -109,11 +113,13 @@ class StoreApi # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -145,11 +151,13 @@ class StoreApi # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} diff --git a/samples/client/petstore/ruby/lib/swagger/request.rb b/samples/client/petstore/ruby/lib/swagger/request.rb index fbd70eeb9f54..70f75d71c4ff 100644 --- a/samples/client/petstore/ruby/lib/swagger/request.rb +++ b/samples/client/petstore/ruby/lib/swagger/request.rb @@ -208,5 +208,31 @@ module Swagger @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 + end end diff --git a/samples/client/petstore/ruby/lib/user_api.rb b/samples/client/petstore/ruby/lib/user_api.rb index fa900d3d0059..7e14c5cb4aa3 100644 --- a/samples/client/petstore/ruby/lib/user_api.rb +++ b/samples/client/petstore/ruby/lib/user_api.rb @@ -21,11 +21,13 @@ class UserApi # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -73,11 +75,13 @@ class UserApi # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -125,11 +129,13 @@ class UserApi # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -180,11 +186,13 @@ class UserApi # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -212,11 +220,13 @@ class UserApi # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -247,11 +257,13 @@ class UserApi # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -284,11 +296,13 @@ class UserApi # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -339,11 +353,13 @@ class UserApi # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} From b4674d6fc557e20ac95cec945fe44c99ce4dcce8 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 15 May 2015 11:27:03 -0700 Subject: [PATCH 42/67] template updates, tests --- bin/qt5-petstore.sh | 2 +- .../codegen/languages/Qt5CPPGenerator.java | 8 +- .../src/main/resources/qt5cpp/HttpRequest.cpp | 4 +- .../src/main/resources/qt5cpp/HttpRequest.h | 5 +- .../main/resources/qt5cpp/api-body.mustache | 114 +++++++- .../resources/qt5cpp/helpers-body.mustache | 5 + .../resources/qt5cpp/helpers-header.mustache | 1 + .../resources/qt5cpp/modelFactory.mustache | 15 +- .../petstore/qt5cpp/PetStore/PetApiTests.cpp | 274 ++++++++++++++++++ .../petstore/qt5cpp/PetStore/PetApiTests.h | 35 +++ .../petstore/qt5cpp/PetStore/PetStore.pro | 46 +++ .../qt5cpp/PetStore/PetStore.pro.user | 269 +++++++++++++++++ .../client/petstore/qt5cpp/PetStore/main.cpp | 12 + .../petstore/qt5cpp/client/SWGHelpers.cpp | 5 + .../petstore/qt5cpp/client/SWGHelpers.h | 1 + .../petstore/qt5cpp/client/SWGHttpRequest.cpp | 4 +- .../petstore/qt5cpp/client/SWGHttpRequest.h | 5 +- .../petstore/qt5cpp/client/SWGModelFactory.h | 15 +- .../petstore/qt5cpp/client/SWGPetApi.cpp | 207 ++++++++++--- .../client/petstore/qt5cpp/client/SWGPetApi.h | 4 +- .../petstore/qt5cpp/client/SWGStoreApi.cpp | 69 +++-- .../petstore/qt5cpp/client/SWGStoreApi.h | 2 +- .../petstore/qt5cpp/client/SWGUserApi.cpp | 139 ++++++--- 23 files changed, 1088 insertions(+), 153 deletions(-) create mode 100644 samples/client/petstore/qt5cpp/PetStore/PetApiTests.cpp create mode 100644 samples/client/petstore/qt5cpp/PetStore/PetApiTests.h create mode 100644 samples/client/petstore/qt5cpp/PetStore/PetStore.pro create mode 100644 samples/client/petstore/qt5cpp/PetStore/PetStore.pro.user create mode 100644 samples/client/petstore/qt5cpp/PetStore/main.cpp diff --git a/bin/qt5-petstore.sh b/bin/qt5-petstore.sh index d79dd513dede..7959785de34a 100755 --- a/bin/qt5-petstore.sh +++ b/bin/qt5-petstore.sh @@ -26,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l qt5cpp -o samples/client/petstore/qt5cpp" +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/languages/Qt5CPPGenerator.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/Qt5CPPGenerator.java index b3adeb19a321..35d9bf58bbb2 100644 --- 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 @@ -130,11 +130,13 @@ public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig { typeMapping.put("boolean", "bool"); typeMapping.put("array", "QList"); typeMapping.put("map", "QMap"); - // typeMapping.put("number", "Long"); + 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"); @@ -210,7 +212,7 @@ public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig { else if (p instanceof MapProperty) { MapProperty mp = (MapProperty) p; Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + "*"; + return getSwaggerType(p) + "*"; } if(foundationClasses.contains(swaggerType)) return swaggerType + "*"; @@ -243,7 +245,7 @@ public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig { else if (p instanceof MapProperty) { MapProperty ap = (MapProperty) p; String inner = getSwaggerType(ap.getAdditionalProperties()); - return "NULL"; + return "new QMap()"; } else if (p instanceof ArrayProperty) { ArrayProperty ap = (ArrayProperty) p; diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/HttpRequest.cpp b/modules/swagger-codegen/src/main/resources/qt5cpp/HttpRequest.cpp index fed94e8dddb6..b56004e8f510 100644 --- a/modules/swagger-codegen/src/main/resources/qt5cpp/HttpRequest.cpp +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/HttpRequest.cpp @@ -26,7 +26,7 @@ void HttpRequestInput::add_var(QString key, QString value) { } void HttpRequestInput::add_file(QString variable_name, QString local_filename, QString request_filename, QString mime_type) { - HttpRequestInputFileElement file; + SWGHttpRequestInputFileElement file; file.variable_name = variable_name; file.local_filename = local_filename; file.request_filename = request_filename; @@ -173,7 +173,7 @@ void HttpRequestWorker::execute(HttpRequestInput *input) { } // add files - for (QList::iterator file_info = input->files.begin(); file_info != input->files.end(); file_info++) { + 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 diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/HttpRequest.h b/modules/swagger-codegen/src/main/resources/qt5cpp/HttpRequest.h index 260ccb206792..a2e91a0765ee 100644 --- a/modules/swagger-codegen/src/main/resources/qt5cpp/HttpRequest.h +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/HttpRequest.h @@ -13,11 +13,10 @@ #include #include - enum HttpRequestVarLayout {NOT_SET, ADDRESS, URL_ENCODED, MULTIPART}; -class HttpRequestInputFileElement { +class SWGHttpRequestInputFileElement { public: QString variable_name; @@ -36,7 +35,7 @@ public: HttpRequestVarLayout var_layout; QMap vars; QMap headers; - QList files; + QList files; QByteArray request_body; HttpRequestInput(); diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/api-body.mustache b/modules/swagger-codegen/src/main/resources/qt5cpp/api-body.mustache index 9103cb5e16f2..592c4158aeb9 100644 --- a/modules/swagger-codegen/src/main/resources/qt5cpp/api-body.mustache +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/api-body.mustache @@ -1,5 +1,6 @@ #include "{{classname}}.h" #include "{{prefix}}Helpers.h" +#include "{{prefix}}ModelFactory.h" #include #include @@ -17,32 +18,97 @@ namespace Swagger { {{#operations}} {{#operation}} void -{{classname}}::{{nickname}}({{#allParams}}{{dataType}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { +{{classname}}::{{nickname}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("{{path}}"); + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "{{httpMethod}}"); + {{#pathParams}} QString {{paramName}}PathParam("{"); {{paramName}}PathParam.append("{{paramName}}").append("}"); fullPath.replace({{paramName}}PathParam, stringValue({{paramName}})); {{/pathParams}} - {{#queryParams}}if(fullPath.compare("?") > 0) fullPath.append("?"); - else fullPath.append("&"); + {{#formParams}}{{^isFile}} + if({{paramName}} != NULL) { + input.add_var("{{paramName}}", *{{paramName}}); + } + {{/isFile}}{{/formParams}} + + {{#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}}"); - {{#bodyParams}} - // body - input.request_body.append({{paramName}}.asJson()); - {{/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}} - input.headers + // TODO: add header support {{/headerParams}} connect(worker, @@ -71,7 +137,7 @@ void QJsonArray jsonArray = doc.array(); foreach(QJsonValue obj, jsonArray) { - {{returnBaseType}}* o = new {{returnBaseType}}(); + {{{returnBaseType}}}* o = new {{returnBaseType}}(); QJsonObject jv = obj.toObject(); QJsonObject * ptr = (QJsonObject*)&jv; o->fromJsonObject(*ptr); @@ -80,13 +146,29 @@ void {{/isListContainer}} {{^isListContainer}}{{#returnTypeIsPrimitive}} - {{returnType}} output; // TODO - + {{{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 = new {{returnBaseType}}(&json); - + {{{returnType}}} output = static_cast<{{{returnType}}}>(create(json, QString("{{{returnBaseType}}}"))); {{/returnTypeIsPrimitive}} + {{/isMapContainer}} {{/isListContainer}}{{/returnType}} worker->deleteLater(); diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-body.mustache b/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-body.mustache index 01e205a07733..7f4d748c2dce 100644 --- a/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-body.mustache +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-body.mustache @@ -154,6 +154,11 @@ stringValue(qint32 value) { return QString::number(value); } +QString +stringValue(qint64 value) { + return QString::number(value); +} + QString stringValue(bool value) { return QString(value ? "true" : "false"); diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-header.mustache b/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-header.mustache index 988e6480da81..3a02c0952d55 100644 --- a/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-header.mustache +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-header.mustache @@ -10,6 +10,7 @@ namespace Swagger { bool isCompatibleJsonValue(QString type); QString stringValue(QString* value); QString stringValue(qint32 value); + QString stringValue(qint64 value); QString stringValue(bool value); } diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/modelFactory.mustache b/modules/swagger-codegen/src/main/resources/qt5cpp/modelFactory.mustache index f3cd5c8e2f0f..4ec9e6f74113 100644 --- a/modules/swagger-codegen/src/main/resources/qt5cpp/modelFactory.mustache +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/modelFactory.mustache @@ -5,14 +5,25 @@ #include "{{classname}}.h"{{/model}}{{/models}} namespace Swagger { - void* - create(QString type) { + 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/samples/client/petstore/qt5cpp/PetStore/PetApiTests.cpp b/samples/client/petstore/qt5cpp/PetStore/PetApiTests.cpp new file mode 100644 index 000000000000..e5670fa4e001 --- /dev/null +++ b/samples/client/petstore/qt5cpp/PetStore/PetApiTests.cpp @@ -0,0 +1,274 @@ +#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) { + qDebug() << pet->asJson(); + 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/SWGHelpers.cpp b/samples/client/petstore/qt5cpp/client/SWGHelpers.cpp index 01e205a07733..7f4d748c2dce 100644 --- a/samples/client/petstore/qt5cpp/client/SWGHelpers.cpp +++ b/samples/client/petstore/qt5cpp/client/SWGHelpers.cpp @@ -154,6 +154,11 @@ stringValue(qint32 value) { return QString::number(value); } +QString +stringValue(qint64 value) { + return QString::number(value); +} + QString stringValue(bool value) { return QString(value ? "true" : "false"); diff --git a/samples/client/petstore/qt5cpp/client/SWGHelpers.h b/samples/client/petstore/qt5cpp/client/SWGHelpers.h index 988e6480da81..3a02c0952d55 100644 --- a/samples/client/petstore/qt5cpp/client/SWGHelpers.h +++ b/samples/client/petstore/qt5cpp/client/SWGHelpers.h @@ -10,6 +10,7 @@ namespace Swagger { bool isCompatibleJsonValue(QString type); QString stringValue(QString* value); QString stringValue(qint32 value); + QString stringValue(qint64 value); QString stringValue(bool value); } diff --git a/samples/client/petstore/qt5cpp/client/SWGHttpRequest.cpp b/samples/client/petstore/qt5cpp/client/SWGHttpRequest.cpp index fed94e8dddb6..b56004e8f510 100644 --- a/samples/client/petstore/qt5cpp/client/SWGHttpRequest.cpp +++ b/samples/client/petstore/qt5cpp/client/SWGHttpRequest.cpp @@ -26,7 +26,7 @@ void HttpRequestInput::add_var(QString key, QString value) { } void HttpRequestInput::add_file(QString variable_name, QString local_filename, QString request_filename, QString mime_type) { - HttpRequestInputFileElement file; + SWGHttpRequestInputFileElement file; file.variable_name = variable_name; file.local_filename = local_filename; file.request_filename = request_filename; @@ -173,7 +173,7 @@ void HttpRequestWorker::execute(HttpRequestInput *input) { } // add files - for (QList::iterator file_info = input->files.begin(); file_info != input->files.end(); file_info++) { + 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 diff --git a/samples/client/petstore/qt5cpp/client/SWGHttpRequest.h b/samples/client/petstore/qt5cpp/client/SWGHttpRequest.h index 260ccb206792..a2e91a0765ee 100644 --- a/samples/client/petstore/qt5cpp/client/SWGHttpRequest.h +++ b/samples/client/petstore/qt5cpp/client/SWGHttpRequest.h @@ -13,11 +13,10 @@ #include #include - enum HttpRequestVarLayout {NOT_SET, ADDRESS, URL_ENCODED, MULTIPART}; -class HttpRequestInputFileElement { +class SWGHttpRequestInputFileElement { public: QString variable_name; @@ -36,7 +35,7 @@ public: HttpRequestVarLayout var_layout; QMap vars; QMap headers; - QList files; + QList files; QByteArray request_body; HttpRequestInput(); diff --git a/samples/client/petstore/qt5cpp/client/SWGModelFactory.h b/samples/client/petstore/qt5cpp/client/SWGModelFactory.h index 3eaf51ab0a91..588a7ad952b1 100644 --- a/samples/client/petstore/qt5cpp/client/SWGModelFactory.h +++ b/samples/client/petstore/qt5cpp/client/SWGModelFactory.h @@ -9,8 +9,7 @@ #include "SWGOrder.h" namespace Swagger { - void* - create(QString type) { + inline void* create(QString type) { if(QString("SWGUser").compare(type) == 0) { return new SWGUser(); } @@ -29,6 +28,18 @@ namespace Swagger { 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/SWGPetApi.cpp b/samples/client/petstore/qt5cpp/client/SWGPetApi.cpp index 4405b0e4d240..eae6eb4e760b 100644 --- a/samples/client/petstore/qt5cpp/client/SWGPetApi.cpp +++ b/samples/client/petstore/qt5cpp/client/SWGPetApi.cpp @@ -1,5 +1,6 @@ #include "SWGPetApi.h" #include "SWGHelpers.h" +#include "SWGModelFactory.h" #include #include @@ -19,16 +20,20 @@ SWGPetApi::updatePet(SWGPet body) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/pet"); - - - - HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "PUT"); - // body - input.request_body.append(body.asJson()); + + + + + + + + QString output = body.asJson(); + input.request_body.append(output); + @@ -63,16 +68,20 @@ SWGPetApi::addPet(SWGPet body) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/pet"); - - - - HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "POST"); - // body - input.request_body.append(body.asJson()); + + + + + + + + QString output = body.asJson(); + input.request_body.append(output); + @@ -103,19 +112,10 @@ SWGPetApi::addPetCallback(HttpRequestWorker * worker) { emit addPetSignal(); } void -SWGPetApi::findPetsByStatus(QList<QString*>* status) { +SWGPetApi::findPetsByStatus(QList* status) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/pet/findByStatus"); - - - if(fullPath.compare("?") > 0) fullPath.append("?"); - else fullPath.append("&"); - fullPath.append(QUrl::toPercentEncoding("status")) - .append("=") - .append(QUrl::toPercentEncoding(stringValue(status))); - - HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "GET"); @@ -123,6 +123,57 @@ SWGPetApi::findPetsByStatus(QList<QString*>* status) { + + + + + + 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)); + } + } + } + + + + + + + connect(worker, &HttpRequestWorker::on_execution_finished, this, @@ -165,19 +216,10 @@ SWGPetApi::findPetsByStatusCallback(HttpRequestWorker * worker) { } void -SWGPetApi::findPetsByTags(QList<QString*>* tags) { +SWGPetApi::findPetsByTags(QList* tags) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/pet/findByTags"); - - - if(fullPath.compare("?") > 0) fullPath.append("?"); - else fullPath.append("&"); - fullPath.append(QUrl::toPercentEncoding("tags")) - .append("=") - .append(QUrl::toPercentEncoding(stringValue(tags))); - - HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "GET"); @@ -185,6 +227,57 @@ SWGPetApi::findPetsByTags(QList<QString*>* tags) { + + + + + + 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)); + } + } + } + + + + + + + connect(worker, &HttpRequestWorker::on_execution_finished, this, @@ -231,6 +324,9 @@ SWGPetApi::getPetById(qint64 petId) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/pet/{petId}"); + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "GET"); + QString petIdPathParam("{"); petIdPathParam.append("petId").append("}"); fullPath.replace(petIdPathParam, stringValue(petId)); @@ -238,9 +334,7 @@ SWGPetApi::getPetById(qint64 petId) { - HttpRequestWorker *worker = new HttpRequestWorker(); - HttpRequestInput input(fullPath, "GET"); - + @@ -266,9 +360,11 @@ SWGPetApi::getPetByIdCallback(HttpRequestWorker * worker) { + + QString json(worker->response); - SWGPet* output = new SWGPet(&json); - + SWGPet* output = static_cast(create(json, QString("SWGPet"))); + @@ -282,16 +378,25 @@ SWGPetApi::updatePetWithForm(QString* petId, QString* name, QString* status) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/pet/{petId}"); + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "POST"); + QString petIdPathParam("{"); petIdPathParam.append("petId").append("}"); fullPath.replace(petIdPathParam, stringValue(petId)); + if(name != NULL) { + input.add_var("name", *name); + } + + if(status != NULL) { + input.add_var("status", *status); + } + - HttpRequestWorker *worker = new HttpRequestWorker(); - HttpRequestInput input(fullPath, "POST"); - + @@ -326,6 +431,9 @@ SWGPetApi::deletePet(QString* api_key, qint64 petId) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/pet/{petId}"); + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "DELETE"); + QString petIdPathParam("{"); petIdPathParam.append("petId").append("}"); fullPath.replace(petIdPathParam, stringValue(petId)); @@ -333,13 +441,11 @@ SWGPetApi::deletePet(QString* api_key, qint64 petId) { - HttpRequestWorker *worker = new HttpRequestWorker(); - HttpRequestInput input(fullPath, "DELETE"); - + - input.headers + // TODO: add header support connect(worker, @@ -368,20 +474,25 @@ SWGPetApi::deletePetCallback(HttpRequestWorker * worker) { emit deletePetSignal(); } void -SWGPetApi::uploadFile(qint64 petId, QString* additionalMetadata, SWGFile* file) { +SWGPetApi::uploadFile(qint64 petId, QString* additionalMetadata, SWGHttpRequestInputFileElement* file) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/pet/{petId}/uploadImage"); + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "POST"); + QString petIdPathParam("{"); petIdPathParam.append("petId").append("}"); fullPath.replace(petIdPathParam, stringValue(petId)); + if(additionalMetadata != NULL) { + input.add_var("additionalMetadata", *additionalMetadata); + } + - HttpRequestWorker *worker = new HttpRequestWorker(); - HttpRequestInput input(fullPath, "POST"); - + diff --git a/samples/client/petstore/qt5cpp/client/SWGPetApi.h b/samples/client/petstore/qt5cpp/client/SWGPetApi.h index 1067265656b9..2f65cade2c47 100644 --- a/samples/client/petstore/qt5cpp/client/SWGPetApi.h +++ b/samples/client/petstore/qt5cpp/client/SWGPetApi.h @@ -5,7 +5,7 @@ #include "SWGPet.h" #include -#include "SWGFile.h" +#include "SWGHttpRequest.h" #include @@ -29,7 +29,7 @@ public: 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, SWGFile* file); + void uploadFile(qint64 petId, QString* additionalMetadata, SWGHttpRequestInputFileElement* file); private: void updatePetCallback (HttpRequestWorker * worker); diff --git a/samples/client/petstore/qt5cpp/client/SWGStoreApi.cpp b/samples/client/petstore/qt5cpp/client/SWGStoreApi.cpp index 8602eb009fda..49906842199e 100644 --- a/samples/client/petstore/qt5cpp/client/SWGStoreApi.cpp +++ b/samples/client/petstore/qt5cpp/client/SWGStoreApi.cpp @@ -1,5 +1,6 @@ #include "SWGStoreApi.h" #include "SWGHelpers.h" +#include "SWGModelFactory.h" #include #include @@ -19,10 +20,6 @@ SWGStoreApi::getInventory() { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/store/inventory"); - - - - HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "GET"); @@ -30,6 +27,11 @@ SWGStoreApi::getInventory() { + + + + + connect(worker, &HttpRequestWorker::on_execution_finished, this, @@ -51,9 +53,22 @@ SWGStoreApi::getInventoryCallback(HttpRequestWorker * worker) { - QString json(worker->response); - QMap<String, qint32>* output = new QMap(&json); + + 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); + } + + + @@ -67,16 +82,20 @@ SWGStoreApi::placeOrder(SWGOrder body) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/store/order"); - - - - HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "POST"); - // body - input.request_body.append(body.asJson()); + + + + + + + + QString output = body.asJson(); + input.request_body.append(output); + @@ -102,9 +121,11 @@ SWGStoreApi::placeOrderCallback(HttpRequestWorker * worker) { + + QString json(worker->response); - SWGOrder* output = new SWGOrder(&json); - + SWGOrder* output = static_cast(create(json, QString("SWGOrder"))); + @@ -118,6 +139,9 @@ SWGStoreApi::getOrderById(QString* orderId) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/store/order/{orderId}"); + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "GET"); + QString orderIdPathParam("{"); orderIdPathParam.append("orderId").append("}"); fullPath.replace(orderIdPathParam, stringValue(orderId)); @@ -125,9 +149,7 @@ SWGStoreApi::getOrderById(QString* orderId) { - HttpRequestWorker *worker = new HttpRequestWorker(); - HttpRequestInput input(fullPath, "GET"); - + @@ -153,9 +175,11 @@ SWGStoreApi::getOrderByIdCallback(HttpRequestWorker * worker) { + + QString json(worker->response); - SWGOrder* output = new SWGOrder(&json); - + SWGOrder* output = static_cast(create(json, QString("SWGOrder"))); + @@ -169,6 +193,9 @@ SWGStoreApi::deleteOrder(QString* orderId) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/store/order/{orderId}"); + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "DELETE"); + QString orderIdPathParam("{"); orderIdPathParam.append("orderId").append("}"); fullPath.replace(orderIdPathParam, stringValue(orderId)); @@ -176,9 +203,7 @@ SWGStoreApi::deleteOrder(QString* orderId) { - HttpRequestWorker *worker = new HttpRequestWorker(); - HttpRequestInput input(fullPath, "DELETE"); - + diff --git a/samples/client/petstore/qt5cpp/client/SWGStoreApi.h b/samples/client/petstore/qt5cpp/client/SWGStoreApi.h index 6b7755c7d5e4..7bbe8e5f92ae 100644 --- a/samples/client/petstore/qt5cpp/client/SWGStoreApi.h +++ b/samples/client/petstore/qt5cpp/client/SWGStoreApi.h @@ -34,7 +34,7 @@ private: void deleteOrderCallback (HttpRequestWorker * worker); signals: - void getInventorySignal(QMap* summary); + void getInventorySignal(QMap* summary); void placeOrderSignal(SWGOrder* summary); void getOrderByIdSignal(SWGOrder* summary); void deleteOrderSignal(); diff --git a/samples/client/petstore/qt5cpp/client/SWGUserApi.cpp b/samples/client/petstore/qt5cpp/client/SWGUserApi.cpp index 9d17e9067e33..6f56ef2ebbbb 100644 --- a/samples/client/petstore/qt5cpp/client/SWGUserApi.cpp +++ b/samples/client/petstore/qt5cpp/client/SWGUserApi.cpp @@ -1,5 +1,6 @@ #include "SWGUserApi.h" #include "SWGHelpers.h" +#include "SWGModelFactory.h" #include #include @@ -19,16 +20,20 @@ SWGUserApi::createUser(SWGUser body) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/user"); - - - - HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "POST"); - // body - input.request_body.append(body.asJson()); + + + + + + + + QString output = body.asJson(); + input.request_body.append(output); + @@ -59,20 +64,28 @@ SWGUserApi::createUserCallback(HttpRequestWorker * worker) { emit createUserSignal(); } void -SWGUserApi::createUsersWithArrayInput(QList<SWGUser*>* body) { +SWGUserApi::createUsersWithArrayInput(QList* body) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/user/createWithArray"); - - - - HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "POST"); - // body - input.request_body.append(body.asJson()); + + + + + + + QJsonArray* bodyArray = new QJsonArray(); + toJsonArray((QList*)body, bodyArray, QString("body"), QString("SWGUser*")); + + QJsonDocument doc(*bodyArray); + QByteArray bytes = doc.toJson(); + + input.request_body.append(bytes); + @@ -103,20 +116,28 @@ SWGUserApi::createUsersWithArrayInputCallback(HttpRequestWorker * worker) { emit createUsersWithArrayInputSignal(); } void -SWGUserApi::createUsersWithListInput(QList<SWGUser*>* body) { +SWGUserApi::createUsersWithListInput(QList* body) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/user/createWithList"); - - - - HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "POST"); - // body - input.request_body.append(body.asJson()); + + + + + + + QJsonArray* bodyArray = new QJsonArray(); + toJsonArray((QList*)body, bodyArray, QString("body"), QString("SWGUser*")); + + QJsonDocument doc(*bodyArray); + QByteArray bytes = doc.toJson(); + + input.request_body.append(bytes); + @@ -151,23 +172,38 @@ SWGUserApi::loginUser(QString* username, QString* password) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/user/login"); + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "GET"); + - if(fullPath.compare("?") > 0) fullPath.append("?"); - else fullPath.append("&"); + + + + + if(fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); fullPath.append(QUrl::toPercentEncoding("username")) .append("=") .append(QUrl::toPercentEncoding(stringValue(username))); - if(fullPath.compare("?") > 0) fullPath.append("?"); - else fullPath.append("&"); + + + + + + 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"); - + + @@ -193,9 +229,11 @@ SWGUserApi::loginUserCallback(HttpRequestWorker * worker) { + + QString json(worker->response); - QString* output = new QString(&json); - + QString* output = static_cast(create(json, QString("QString"))); + @@ -209,10 +247,6 @@ SWGUserApi::logoutUser() { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/user/logout"); - - - - HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "GET"); @@ -220,6 +254,11 @@ SWGUserApi::logoutUser() { + + + + + connect(worker, &HttpRequestWorker::on_execution_finished, this, @@ -250,6 +289,9 @@ SWGUserApi::getUserByName(QString* username) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/user/{username}"); + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "GET"); + QString usernamePathParam("{"); usernamePathParam.append("username").append("}"); fullPath.replace(usernamePathParam, stringValue(username)); @@ -257,9 +299,7 @@ SWGUserApi::getUserByName(QString* username) { - HttpRequestWorker *worker = new HttpRequestWorker(); - HttpRequestInput input(fullPath, "GET"); - + @@ -285,9 +325,11 @@ SWGUserApi::getUserByNameCallback(HttpRequestWorker * worker) { + + QString json(worker->response); - SWGUser* output = new SWGUser(&json); - + SWGUser* output = static_cast(create(json, QString("SWGUser"))); + @@ -301,6 +343,9 @@ SWGUserApi::updateUser(QString* username, SWGUser body) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/user/{username}"); + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "PUT"); + QString usernamePathParam("{"); usernamePathParam.append("username").append("}"); fullPath.replace(usernamePathParam, stringValue(username)); @@ -308,12 +353,13 @@ SWGUserApi::updateUser(QString* username, SWGUser body) { - HttpRequestWorker *worker = new HttpRequestWorker(); - HttpRequestInput input(fullPath, "PUT"); - - // body - input.request_body.append(body.asJson()); + + + + QString output = body.asJson(); + input.request_body.append(output); + @@ -348,6 +394,9 @@ SWGUserApi::deleteUser(QString* username) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/user/{username}"); + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "DELETE"); + QString usernamePathParam("{"); usernamePathParam.append("username").append("}"); fullPath.replace(usernamePathParam, stringValue(username)); @@ -355,9 +404,7 @@ SWGUserApi::deleteUser(QString* username) { - HttpRequestWorker *worker = new HttpRequestWorker(); - HttpRequestInput input(fullPath, "DELETE"); - + From 9904c0e09fc6fbb502223ef0028eaed1f9acc529 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Sat, 16 May 2015 15:37:58 +0800 Subject: [PATCH 43/67] add unit testing for pet --- samples/client/petstore/perl/t/01_pet_api.t | 59 +++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 samples/client/petstore/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..02a10544c57a --- /dev/null +++ b/samples/client/petstore/perl/t/01_pet_api.t @@ -0,0 +1,59 @@ +use Test::More tests => 25; +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(); + +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'; + From f4cbd88e2c4e90a704ae280407e67e1ae0db67f7 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Sat, 16 May 2015 00:45:42 -0700 Subject: [PATCH 44/67] fixed ordering --- .../main/resources/qt5cpp/api-body.mustache | 20 +++--- .../client/petstore/qt5cpp/client/SWGPet.h | 6 +- .../petstore/qt5cpp/client/SWGPetApi.cpp | 70 ++++++++++--------- .../petstore/qt5cpp/client/SWGStoreApi.cpp | 29 ++++---- .../petstore/qt5cpp/client/SWGUserApi.cpp | 62 ++++++++-------- 5 files changed, 101 insertions(+), 86 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/api-body.mustache b/modules/swagger-codegen/src/main/resources/qt5cpp/api-body.mustache index 592c4158aeb9..b63411041881 100644 --- a/modules/swagger-codegen/src/main/resources/qt5cpp/api-body.mustache +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/api-body.mustache @@ -22,20 +22,11 @@ void QString fullPath; fullPath.append(this->host).append(this->basePath).append("{{path}}"); - HttpRequestWorker *worker = new HttpRequestWorker(); - HttpRequestInput input(fullPath, "{{httpMethod}}"); - {{#pathParams}} QString {{paramName}}PathParam("{"); {{paramName}}PathParam.append("{{paramName}}").append("}"); fullPath.replace({{paramName}}PathParam, stringValue({{paramName}})); {{/pathParams}} - {{#formParams}}{{^isFile}} - if({{paramName}} != NULL) { - input.add_var("{{paramName}}", *{{paramName}}); - } - {{/isFile}}{{/formParams}} - {{#queryParams}} {{^collectionFormat}} if(fullPath.indexOf("?") > 0) @@ -91,6 +82,16 @@ void {{/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(); @@ -104,7 +105,6 @@ void {{^isContainer}} QString output = {{paramName}}.asJson(); input.request_body.append(output); - {{/isContainer}}{{/bodyParams}} {{#headerParams}} diff --git a/samples/client/petstore/qt5cpp/client/SWGPet.h b/samples/client/petstore/qt5cpp/client/SWGPet.h index e9cb4d082331..3f9320f15074 100644 --- a/samples/client/petstore/qt5cpp/client/SWGPet.h +++ b/samples/client/petstore/qt5cpp/client/SWGPet.h @@ -10,10 +10,10 @@ #include -#include "SWGTag.h" -#include -#include "SWGCategory.h" #include +#include "SWGCategory.h" +#include +#include "SWGTag.h" #include "SWGObject.h" diff --git a/samples/client/petstore/qt5cpp/client/SWGPetApi.cpp b/samples/client/petstore/qt5cpp/client/SWGPetApi.cpp index eae6eb4e760b..af7b2371ebcc 100644 --- a/samples/client/petstore/qt5cpp/client/SWGPetApi.cpp +++ b/samples/client/petstore/qt5cpp/client/SWGPetApi.cpp @@ -20,20 +20,20 @@ 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); - @@ -68,20 +68,20 @@ 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); - @@ -116,11 +116,6 @@ SWGPetApi::findPetsByStatus(QList* status) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/pet/findByStatus"); - HttpRequestWorker *worker = new HttpRequestWorker(); - HttpRequestInput input(fullPath, "GET"); - - - @@ -170,6 +165,12 @@ SWGPetApi::findPetsByStatus(QList* status) { + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "GET"); + + + @@ -220,11 +221,6 @@ SWGPetApi::findPetsByTags(QList* tags) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/pet/findByTags"); - HttpRequestWorker *worker = new HttpRequestWorker(); - HttpRequestInput input(fullPath, "GET"); - - - @@ -274,6 +270,12 @@ SWGPetApi::findPetsByTags(QList* tags) { + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "GET"); + + + @@ -324,9 +326,6 @@ SWGPetApi::getPetById(qint64 petId) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/pet/{petId}"); - HttpRequestWorker *worker = new HttpRequestWorker(); - HttpRequestInput input(fullPath, "GET"); - QString petIdPathParam("{"); petIdPathParam.append("petId").append("}"); fullPath.replace(petIdPathParam, stringValue(petId)); @@ -334,7 +333,11 @@ SWGPetApi::getPetById(qint64 petId) { + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "GET"); + + @@ -378,15 +381,17 @@ SWGPetApi::updatePetWithForm(QString* petId, QString* name, QString* status) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/pet/{petId}"); - HttpRequestWorker *worker = new HttpRequestWorker(); - HttpRequestInput input(fullPath, "POST"); - 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); } @@ -397,7 +402,6 @@ SWGPetApi::updatePetWithForm(QString* petId, QString* name, QString* status) { - @@ -431,9 +435,6 @@ SWGPetApi::deletePet(QString* api_key, qint64 petId) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/pet/{petId}"); - HttpRequestWorker *worker = new HttpRequestWorker(); - HttpRequestInput input(fullPath, "DELETE"); - QString petIdPathParam("{"); petIdPathParam.append("petId").append("}"); fullPath.replace(petIdPathParam, stringValue(petId)); @@ -441,7 +442,11 @@ SWGPetApi::deletePet(QString* api_key, qint64 petId) { + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "DELETE"); + + @@ -478,22 +483,23 @@ SWGPetApi::uploadFile(qint64 petId, QString* additionalMetadata, SWGHttpRequestI QString fullPath; fullPath.append(this->host).append(this->basePath).append("/pet/{petId}/uploadImage"); - HttpRequestWorker *worker = new HttpRequestWorker(); - HttpRequestInput input(fullPath, "POST"); - 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); } - diff --git a/samples/client/petstore/qt5cpp/client/SWGStoreApi.cpp b/samples/client/petstore/qt5cpp/client/SWGStoreApi.cpp index 49906842199e..be603573f621 100644 --- a/samples/client/petstore/qt5cpp/client/SWGStoreApi.cpp +++ b/samples/client/petstore/qt5cpp/client/SWGStoreApi.cpp @@ -20,6 +20,10 @@ SWGStoreApi::getInventory() { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/store/inventory"); + + + + HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "GET"); @@ -28,9 +32,6 @@ SWGStoreApi::getInventory() { - - - connect(worker, &HttpRequestWorker::on_execution_finished, @@ -82,20 +83,20 @@ 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); - @@ -139,9 +140,6 @@ SWGStoreApi::getOrderById(QString* orderId) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/store/order/{orderId}"); - HttpRequestWorker *worker = new HttpRequestWorker(); - HttpRequestInput input(fullPath, "GET"); - QString orderIdPathParam("{"); orderIdPathParam.append("orderId").append("}"); fullPath.replace(orderIdPathParam, stringValue(orderId)); @@ -149,7 +147,11 @@ SWGStoreApi::getOrderById(QString* orderId) { + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "GET"); + + @@ -193,9 +195,6 @@ SWGStoreApi::deleteOrder(QString* orderId) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/store/order/{orderId}"); - HttpRequestWorker *worker = new HttpRequestWorker(); - HttpRequestInput input(fullPath, "DELETE"); - QString orderIdPathParam("{"); orderIdPathParam.append("orderId").append("}"); fullPath.replace(orderIdPathParam, stringValue(orderId)); @@ -203,7 +202,11 @@ SWGStoreApi::deleteOrder(QString* orderId) { + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "DELETE"); + + diff --git a/samples/client/petstore/qt5cpp/client/SWGUserApi.cpp b/samples/client/petstore/qt5cpp/client/SWGUserApi.cpp index 6f56ef2ebbbb..6341231a8840 100644 --- a/samples/client/petstore/qt5cpp/client/SWGUserApi.cpp +++ b/samples/client/petstore/qt5cpp/client/SWGUserApi.cpp @@ -20,20 +20,20 @@ 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); - @@ -68,15 +68,16 @@ 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*")); @@ -120,15 +121,16 @@ 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*")); @@ -172,11 +174,6 @@ SWGUserApi::loginUser(QString* username, QString* password) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/user/login"); - HttpRequestWorker *worker = new HttpRequestWorker(); - HttpRequestInput input(fullPath, "GET"); - - - @@ -204,6 +201,12 @@ SWGUserApi::loginUser(QString* username, QString* password) { + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "GET"); + + + @@ -247,6 +250,10 @@ SWGUserApi::logoutUser() { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/user/logout"); + + + + HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestInput input(fullPath, "GET"); @@ -255,9 +262,6 @@ SWGUserApi::logoutUser() { - - - connect(worker, &HttpRequestWorker::on_execution_finished, @@ -289,9 +293,6 @@ SWGUserApi::getUserByName(QString* username) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/user/{username}"); - HttpRequestWorker *worker = new HttpRequestWorker(); - HttpRequestInput input(fullPath, "GET"); - QString usernamePathParam("{"); usernamePathParam.append("username").append("}"); fullPath.replace(usernamePathParam, stringValue(username)); @@ -299,7 +300,11 @@ SWGUserApi::getUserByName(QString* username) { + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "GET"); + + @@ -343,9 +348,6 @@ SWGUserApi::updateUser(QString* username, SWGUser body) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/user/{username}"); - HttpRequestWorker *worker = new HttpRequestWorker(); - HttpRequestInput input(fullPath, "PUT"); - QString usernamePathParam("{"); usernamePathParam.append("username").append("}"); fullPath.replace(usernamePathParam, stringValue(username)); @@ -353,13 +355,16 @@ SWGUserApi::updateUser(QString* username, SWGUser body) { + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "PUT"); + + QString output = body.asJson(); input.request_body.append(output); - @@ -394,9 +399,6 @@ SWGUserApi::deleteUser(QString* username) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/user/{username}"); - HttpRequestWorker *worker = new HttpRequestWorker(); - HttpRequestInput input(fullPath, "DELETE"); - QString usernamePathParam("{"); usernamePathParam.append("username").append("}"); fullPath.replace(usernamePathParam, stringValue(username)); @@ -404,7 +406,11 @@ SWGUserApi::deleteUser(QString* username) { + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "DELETE"); + + From 6ec7cf5a9d8ed9f000be7bf55f8675ad713896a4 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Sat, 16 May 2015 01:09:01 -0700 Subject: [PATCH 45/67] updated request process --- .../swagger-codegen/src/main/resources/qt5cpp/HttpRequest.cpp | 4 +++- samples/client/petstore/qt5cpp/PetStore/PetApiTests.cpp | 1 - samples/client/petstore/qt5cpp/client/SWGHttpRequest.cpp | 4 +++- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/HttpRequest.cpp b/modules/swagger-codegen/src/main/resources/qt5cpp/HttpRequest.cpp index b56004e8f510..f1e79c4d1975 100644 --- a/modules/swagger-codegen/src/main/resources/qt5cpp/HttpRequest.cpp +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/HttpRequest.cpp @@ -103,6 +103,7 @@ void HttpRequestWorker::execute(HttpRequestInput *input) { response = ""; error_type = QNetworkReply::NoError; error_str = ""; + bool isFormData = false; // decide on the variable layout @@ -124,6 +125,7 @@ void HttpRequestWorker::execute(HttpRequestInput *input) { if (input->vars.count() > 0) { bool first = true; + isFormData = true; foreach (QString key, input->vars.keys()) { if (!first) { request_content.append("&"); @@ -250,7 +252,7 @@ void HttpRequestWorker::execute(HttpRequestInput *input) { request.setRawHeader(key.toStdString().c_str(), input->headers.value(key).toStdString().c_str()); } - if (request_content.size() > 0) { + if (request_content.size() > 0 && !isFormData) { request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); } else if (input->var_layout == URL_ENCODED) { diff --git a/samples/client/petstore/qt5cpp/PetStore/PetApiTests.cpp b/samples/client/petstore/qt5cpp/PetStore/PetApiTests.cpp index e5670fa4e001..829fbe926409 100644 --- a/samples/client/petstore/qt5cpp/PetStore/PetApiTests.cpp +++ b/samples/client/petstore/qt5cpp/PetStore/PetApiTests.cpp @@ -44,7 +44,6 @@ void PetApiTests::getPetByIdTest() { timer.setSingleShot(true); auto validator = [](SWGPet* pet) { - qDebug() << pet->asJson(); QVERIFY(pet->getId() == 3); loop.quit(); }; diff --git a/samples/client/petstore/qt5cpp/client/SWGHttpRequest.cpp b/samples/client/petstore/qt5cpp/client/SWGHttpRequest.cpp index b56004e8f510..f1e79c4d1975 100644 --- a/samples/client/petstore/qt5cpp/client/SWGHttpRequest.cpp +++ b/samples/client/petstore/qt5cpp/client/SWGHttpRequest.cpp @@ -103,6 +103,7 @@ void HttpRequestWorker::execute(HttpRequestInput *input) { response = ""; error_type = QNetworkReply::NoError; error_str = ""; + bool isFormData = false; // decide on the variable layout @@ -124,6 +125,7 @@ void HttpRequestWorker::execute(HttpRequestInput *input) { if (input->vars.count() > 0) { bool first = true; + isFormData = true; foreach (QString key, input->vars.keys()) { if (!first) { request_content.append("&"); @@ -250,7 +252,7 @@ void HttpRequestWorker::execute(HttpRequestInput *input) { request.setRawHeader(key.toStdString().c_str(), input->headers.value(key).toStdString().c_str()); } - if (request_content.size() > 0) { + if (request_content.size() > 0 && !isFormData) { request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); } else if (input->var_layout == URL_ENCODED) { From 7a5db5e6659ba40c98b86f460600d1690add78ee Mon Sep 17 00:00:00 2001 From: William Cheng Date: Sat, 16 May 2015 16:44:32 +0800 Subject: [PATCH 46/67] add pom.xml for perl integration test --- samples/client/petstore/perl/pom.xml | 46 ++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 samples/client/petstore/perl/pom.xml 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 + + + + + + + + From 8710fbfde7a77cd10ab6289786065ee78c506b4c Mon Sep 17 00:00:00 2001 From: William Cheng Date: Sat, 16 May 2015 03:51:21 +0800 Subject: [PATCH 47/67] add base object --- .../codegen/languages/RubyClientCodegen.java | 1 + .../main/resources/ruby/base_object.mustache | 83 ++++++++ .../src/main/resources/ruby/model.mustache | 120 ++++++++++-- .../petstore/ruby/lib/model/base_object.rb | 83 ++++++++ samples/client/petstore/ruby/lib/pet_api.rb | 24 ++- .../petstore/ruby/models/base_object.rb | 86 +++++++++ .../client/petstore/ruby/models/category.rb | 123 ++++++++++-- samples/client/petstore/ruby/models/order.rb | 159 +++++++++++++--- samples/client/petstore/ruby/models/pet.rb | 162 +++++++++++++--- samples/client/petstore/ruby/models/tag.rb | 123 ++++++++++-- samples/client/petstore/ruby/models/user.rb | 177 ++++++++++++++---- samples/client/petstore/ruby/spec/pet_spec.rb | 43 +++++ .../client/petstore/ruby/spec/spec_helper.rb | 5 +- 13 files changed, 1033 insertions(+), 156 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/ruby/base_object.mustache create mode 100644 samples/client/petstore/ruby/lib/model/base_object.rb create mode 100644 samples/client/petstore/ruby/models/base_object.rb 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..962f7ea692c1 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 @@ -72,6 +72,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { 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")); + supportingFiles.add(new SupportingFile("base_object.mustache", "", "lib/model/base_object.rb")); } @Override 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..b8ff6dc3a355 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache @@ -0,0 +1,83 @@ +# 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 + 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 = Object.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 diff --git a/modules/swagger-codegen/src/main/resources/ruby/model.mustache b/modules/swagger-codegen/src/main/resources/ruby/model.mustache index 397a64f6471f..f3c1b85f2997 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/model.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/model.mustache @@ -1,35 +1,119 @@ -{{#models}} +require_relative 'base_object' -{{#model}} -class {{classname}} +{{#models}}#{{description}} +{{#model}}class {{classname}} < BaseObject attr_accessor {{#vars}}:{{{name}}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{newline}} - # :internal => :external + # attribute mapping from ruby-style variable name to JSON key def self.attribute_map { - {{#vars}}:{{{name}}} => :'{{{baseName}}}'{{#hasMore}},{{/hasMore}} + {{#vars}} + # {{description}} + :'{{{name}}}' => :'{{{baseName}}}'{{#hasMore}},{{/hasMore}} + {{/vars}} + } + end + + # attribute type + def self.swagger_types + { + {{#vars}}:'{{{name}}}' => :'{{{datatype}}}'{{#hasMore}},{{/hasMore}} {{/vars}} } end def initialize(attributes = {}) - return if attributes.empty? - # Morph attribute keys into undescored rubyish style + 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 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}} + if attributes[:'{{{baseName}}}'] + {{#isContainer}}if (value = attributes[:'{{{baseName}}}']).is_a?(Array) + @{{{name}}} = value + 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 +# # 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) +# 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 +# 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 = Object.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 {{/model}} {{/models}} diff --git a/samples/client/petstore/ruby/lib/model/base_object.rb b/samples/client/petstore/ruby/lib/model/base_object.rb new file mode 100644 index 000000000000..b8ff6dc3a355 --- /dev/null +++ b/samples/client/petstore/ruby/lib/model/base_object.rb @@ -0,0 +1,83 @@ +# 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 + 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 = Object.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 diff --git a/samples/client/petstore/ruby/lib/pet_api.rb b/samples/client/petstore/ruby/lib/pet_api.rb index 96ddb14bd949..c00b605e6074 100644 --- a/samples/client/petstore/ruby/lib/pet_api.rb +++ b/samples/client/petstore/ruby/lib/pet_api.rb @@ -37,18 +37,24 @@ class PetApi _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 + #_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.map{ |v| + if v.respond_to?(:to_hash) + v.to_hash else - _array.push item + v end - end - post_body = _array + } else - if _body_param.respond_to?(:to_body) - post_body = _body_param.to_body + if _body_param.respond_to?(:to_hash) + post_body = _body_param.to_hash else post_body = _body_param end diff --git a/samples/client/petstore/ruby/models/base_object.rb b/samples/client/petstore/ruby/models/base_object.rb new file mode 100644 index 000000000000..efa21abdfe4f --- /dev/null +++ b/samples/client/petstore/ruby/models/base_object.rb @@ -0,0 +1,86 @@ +require 'json' +# +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) + 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 + + # deserialize value based on type + def _deserialize(type, value) + case type + 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 = Object.const_get(type).new + _model.build_from_hash(value) + end + end + + #def to_json + # self.to_hash.to_json + #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 diff --git a/samples/client/petstore/ruby/models/category.rb b/samples/client/petstore/ruby/models/category.rb index 64ca857e17e6..b8ef8b6106a3 100644 --- a/samples/client/petstore/ruby/models/category.rb +++ b/samples/client/petstore/ruby/models/category.rb @@ -1,34 +1,123 @@ +require_relative 'base_object' -class Category +# +class Category < BaseObject attr_accessor :id, :name - # :internal => :external + # attribute mapping from ruby-style variable name to JSON key def self.attribute_map { - :id => :'id', - :name => :'name' + + # + :'id' => :'id', + + # + :'name' => :'name' + + } + end + + # attribute type + def self.swagger_types + { + :'id' => :'int', + :'name' => :'string' } end def initialize(attributes = {}) - return if attributes.empty? - # Morph attribute keys into undescored rubyish style + 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 self.class.attribute_map[:"id"] - @id = attributes["id"] + if attributes[:'id'] + @id = attributes[:'id'] end - if self.class.attribute_map[:"name"] - @name = attributes["name"] + if attributes[:'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 +# # 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) +# 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 +# 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 = Object.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 diff --git a/samples/client/petstore/ruby/models/order.rb b/samples/client/petstore/ruby/models/order.rb index 5434fbd8e2d8..ade8fea251f7 100644 --- a/samples/client/petstore/ruby/models/order.rb +++ b/samples/client/petstore/ruby/models/order.rb @@ -1,54 +1,155 @@ +require_relative 'base_object' -class Order +# +class Order < BaseObject attr_accessor :id, :pet_id, :quantity, :ship_date, :status, :complete - # :internal => :external + # attribute mapping from ruby-style variable name to JSON key def self.attribute_map { - :id => :'id', - :pet_id => :'petId', - :quantity => :'quantity', - :ship_date => :'shipDate', - :status => :'status', - :complete => :'complete' + + # + :'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.empty? - # Morph attribute keys into undescored rubyish style + 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 self.class.attribute_map[:"id"] - @id = attributes["id"] + if attributes[:'id'] + @id = attributes[:'id'] end - if self.class.attribute_map[:"pet_id"] - @pet_id = attributes["petId"] + if attributes[:'petId'] + @pet_id = attributes[:'petId'] end - if self.class.attribute_map[:"quantity"] - @quantity = attributes["quantity"] + if attributes[:'quantity'] + @quantity = attributes[:'quantity'] end - if self.class.attribute_map[:"ship_date"] - @ship_date = attributes["shipDate"] + if attributes[:'shipDate'] + @ship_date = attributes[:'shipDate'] end - if self.class.attribute_map[:"status"] - @status = attributes["status"] + if attributes[:'status'] + @status = attributes[:'status'] end - if self.class.attribute_map[:"complete"] - @complete = attributes["complete"] + if attributes[:'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 +# # 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) +# 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 +# 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 = Object.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 diff --git a/samples/client/petstore/ruby/models/pet.rb b/samples/client/petstore/ruby/models/pet.rb index 38767b46dd7a..472302daff8f 100644 --- a/samples/client/petstore/ruby/models/pet.rb +++ b/samples/client/petstore/ruby/models/pet.rb @@ -1,58 +1,160 @@ +require_relative 'base_object' -class Pet +# +class Pet < BaseObject attr_accessor :id, :category, :name, :photo_urls, :tags, :status - # :internal => :external + # 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', - :status => :'status' + + # + :'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.empty? - # Morph attribute keys into undescored rubyish style + 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 self.class.attribute_map[:"id"] - @id = attributes["id"] + if attributes[:'id'] + @id = attributes[:'id'] end - if self.class.attribute_map[:"category"] - @category = attributes["category"] + if attributes[:'category'] + @category = attributes[:'category'] end - if self.class.attribute_map[:"name"] - @name = attributes["name"] + if attributes[:'name'] + @name = attributes[:'name'] end - if self.class.attribute_map[:"photo_urls"] - if (value = attributes["photoUrls"]).is_a?(Array) + if attributes[:'photoUrls'] + 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) } + if attributes[:'tags'] + if (value = attributes[:'tags']).is_a?(Array) + #@tags = value.map{ |v| Tag.new(v) } + @tags = value end end - if self.class.attribute_map[:"status"] - @status = attributes["status"] + if attributes[:'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 +# # 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) +# 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 +# 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 = Object.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 diff --git a/samples/client/petstore/ruby/models/tag.rb b/samples/client/petstore/ruby/models/tag.rb index 24e3d1d0706e..dc4611953e65 100644 --- a/samples/client/petstore/ruby/models/tag.rb +++ b/samples/client/petstore/ruby/models/tag.rb @@ -1,34 +1,123 @@ +require_relative 'base_object' -class Tag +# +class Tag < BaseObject attr_accessor :id, :name - # :internal => :external + # attribute mapping from ruby-style variable name to JSON key def self.attribute_map { - :id => :'id', - :name => :'name' + + # + :'id' => :'id', + + # + :'name' => :'name' + + } + end + + # attribute type + def self.swagger_types + { + :'id' => :'int', + :'name' => :'string' } end def initialize(attributes = {}) - return if attributes.empty? - # Morph attribute keys into undescored rubyish style + 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 self.class.attribute_map[:"id"] - @id = attributes["id"] + if attributes[:'id'] + @id = attributes[:'id'] end - if self.class.attribute_map[:"name"] - @name = attributes["name"] + if attributes[:'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 +# # 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) +# 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 +# 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 = Object.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 diff --git a/samples/client/petstore/ruby/models/user.rb b/samples/client/petstore/ruby/models/user.rb index e270392a3b89..376c5a20f0a0 100644 --- a/samples/client/petstore/ruby/models/user.rb +++ b/samples/client/petstore/ruby/models/user.rb @@ -1,64 +1,171 @@ +require_relative 'base_object' -class User +# +class User < BaseObject attr_accessor :id, :username, :first_name, :last_name, :email, :password, :phone, :user_status - # :internal => :external + # 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 => :'userStatus' + + # + :'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.empty? - # Morph attribute keys into undescored rubyish style + 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 self.class.attribute_map[:"id"] - @id = attributes["id"] + if attributes[:'id'] + @id = attributes[:'id'] end - if self.class.attribute_map[:"username"] - @username = attributes["username"] + if attributes[:'username'] + @username = attributes[:'username'] end - if self.class.attribute_map[:"first_name"] - @first_name = attributes["firstName"] + if attributes[:'firstName'] + @first_name = attributes[:'firstName'] end - if self.class.attribute_map[:"last_name"] - @last_name = attributes["lastName"] + if attributes[:'lastName'] + @last_name = attributes[:'lastName'] end - if self.class.attribute_map[:"email"] - @email = attributes["email"] + if attributes[:'email'] + @email = attributes[:'email'] end - if self.class.attribute_map[:"password"] - @password = attributes["password"] + if attributes[:'password'] + @password = attributes[:'password'] end - if self.class.attribute_map[:"phone"] - @phone = attributes["phone"] + if attributes[:'phone'] + @phone = attributes[:'phone'] end - if self.class.attribute_map[:"user_status"] - @user_status = attributes["userStatus"] + if attributes[:'userStatus'] + @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 +# # 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) +# 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 +# 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 = Object.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 diff --git a/samples/client/petstore/ruby/spec/pet_spec.rb b/samples/client/petstore/ruby/spec/pet_spec.rb index 67cee70c1ee5..91750e770eb6 100644 --- a/samples/client/petstore/ruby/spec/pet_spec.rb +++ b/samples/client/petstore/ruby/spec/pet_spec.rb @@ -1,4 +1,5 @@ require 'spec_helper' +require 'json' describe "Pet" do before do @@ -7,11 +8,53 @@ describe "Pet" do end describe "pet methods" do + it "should construct a new pet object" do + tag1 = Tag.new({'id' => 1, 'name'=> 'tag1'}) + tag2 = Tag.new({'id' => 2, 'name'=> 'tag2'}) + category1 = 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 = 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 = 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 + + puts pet.to_json + pet_array = [pet, pet2] + puts pet_array.map{ |v| + if v.respond_to?(:to_hash) + v.to_hash + else + v + end + }.to_json + + end + it "should fetch a pet object" do pet = PetApi.get_pet_by_id(10002) + print pet.inspect pet.should be_a(Pet) pet.id.should == 10002 pet.name.should == "RUBY UNIT TESTING" + pet.tags[0].name.should == "RUBY UNIT TESTING" + pet.category.name.should == "RUBY UNIT TESTING" end it "should find pets by status" do diff --git a/samples/client/petstore/ruby/spec/spec_helper.rb b/samples/client/petstore/ruby/spec/spec_helper.rb index 71725a45a6c9..dd24eeca3800 100644 --- a/samples/client/petstore/ruby/spec/spec_helper.rb +++ b/samples/client/petstore/ruby/spec/spec_helper.rb @@ -49,7 +49,10 @@ def prepare_pet # remove the pet PetApi.delete_pet(10002) # recreate the pet - pet = Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING") + category = Category.new('id' => 20002, 'name' => 'category test') + tag = Tag.new('id' => 30002, 'name' => 'tag test') + pet = Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING", 'photo_urls' => 'photo url', + 'category' => category, 'tags' => [tag], 'status' => 'pending') PetApi.add_pet(:body => pet) end From 92a20112074b23d2696707fd9f03049168e74473 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Sun, 17 May 2015 23:18:55 +0800 Subject: [PATCH 48/67] fix post model, update rspec --- .../src/main/resources/ruby/api.mustache | 29 +---- .../main/resources/ruby/base_object.mustache | 2 +- .../src/main/resources/ruby/swagger.mustache | 28 ++++- .../resources/ruby/swagger/request.mustache | 25 ++++ .../resources/ruby/swagger/response.mustache | 4 +- .../petstore/ruby/lib/model/base_object.rb | 2 +- samples/client/petstore/ruby/lib/pet_api.rb | 74 +++--------- samples/client/petstore/ruby/lib/store_api.rb | 34 ++---- samples/client/petstore/ruby/lib/swagger.rb | 28 ++++- .../petstore/ruby/lib/swagger/request.rb | 25 ++++ .../petstore/ruby/lib/swagger/response.rb | 4 +- samples/client/petstore/ruby/lib/user_api.rb | 112 ++++-------------- .../petstore/ruby/models/base_object.rb | 2 +- samples/client/petstore/ruby/models/pet.rb | 1 - samples/client/petstore/ruby/spec/pet_spec.rb | 16 +-- .../petstore/ruby/spec/response_spec.rb | 2 +- .../client/petstore/ruby/spec/spec_helper.rb | 3 +- 17 files changed, 168 insertions(+), 223 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index 528c772f1fbe..038a40f66ea4 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -45,31 +45,12 @@ class {{classname}} 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}} + {{^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 diff --git a/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache index b8ff6dc3a355..398e434e9bd2 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache @@ -31,7 +31,7 @@ class BaseObject end def _deserialize(type, value) - case type + case type.to_s when :DateTime DateTime.parse(value) when :string diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache index fff098e96fcc..273d8d343d99 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache @@ -4,6 +4,7 @@ require 'swagger/request' require 'swagger/response' require 'swagger/version' require 'logger' +require 'json' module Swagger @@ -74,6 +75,31 @@ module Swagger Swagger.configuration.auth_token = response_body['token'] 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 @@ -82,4 +108,4 @@ class ServerError < StandardError end class ClientError < StandardError -end \ No newline at end of file +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 70f75d71c4ff..4ec071b93d5e 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache @@ -234,5 +234,30 @@ module Swagger 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 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..641b7ccc7565 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache @@ -28,7 +28,7 @@ module Swagger # If body is JSON, parse it # Otherwise return raw string def body - JSON.parse raw.body + JSON.parse(raw.body, :symbolize_names => true) rescue raw.body end @@ -67,4 +67,4 @@ module Swagger end end -end \ No newline at end of file +end diff --git a/samples/client/petstore/ruby/lib/model/base_object.rb b/samples/client/petstore/ruby/lib/model/base_object.rb index b8ff6dc3a355..398e434e9bd2 100644 --- a/samples/client/petstore/ruby/lib/model/base_object.rb +++ b/samples/client/petstore/ruby/lib/model/base_object.rb @@ -31,7 +31,7 @@ class BaseObject end def _deserialize(type, value) - case type + case type.to_s when :DateTime DateTime.parse(value) when :string diff --git a/samples/client/petstore/ruby/lib/pet_api.rb b/samples/client/petstore/ruby/lib/pet_api.rb index c00b605e6074..b15198588aad 100644 --- a/samples/client/petstore/ruby/lib/pet_api.rb +++ b/samples/client/petstore/ruby/lib/pet_api.rb @@ -33,35 +33,10 @@ class PetApi 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.map{ |v| - if v.respond_to?(:to_hash) - v.to_hash - else - v - end - } - else - if _body_param.respond_to?(:to_hash) - post_body = _body_param.to_hash - else - post_body = _body_param - end - end - end + 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 + 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 @@ -93,29 +68,10 @@ class PetApi 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 + 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 + Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make end # Finds Pets by status @@ -149,9 +105,10 @@ class PetApi # 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) } + response.map {|response| obj = Pet.new() and obj.build_from_hash(response) } end # Finds Pets by tags @@ -185,9 +142,10 @@ class PetApi # 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) } + response.map {|response| obj = Pet.new() and obj.build_from_hash(response) } end # Find pet by ID @@ -223,9 +181,10 @@ class PetApi # 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) + obj = Pet.new() and obj.build_from_hash(response) end # Updates a pet in the store with form data @@ -265,8 +224,9 @@ class PetApi # 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 + Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make end # Deletes a pet @@ -304,8 +264,9 @@ class PetApi # 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 + Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make end # uploads an image @@ -345,7 +306,8 @@ class PetApi # 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 + 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 index a14d0f7c2733..c6d670cd8c04 100644 --- a/samples/client/petstore/ruby/lib/store_api.rb +++ b/samples/client/petstore/ruby/lib/store_api.rb @@ -33,9 +33,10 @@ class StoreApi # 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) } + response.map {|response| obj = map.new() and obj.build_from_hash(response) } end # Place an order for a pet @@ -67,30 +68,11 @@ class StoreApi 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 + 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 - Order.new(response) + obj = Order.new() and obj.build_from_hash(response) end # Find purchase order by ID @@ -126,9 +108,10 @@ class StoreApi # 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) + obj = Order.new() and obj.build_from_hash(response) end # Delete purchase order by ID @@ -164,7 +147,8 @@ class StoreApi # 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 + 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.rb b/samples/client/petstore/ruby/lib/swagger.rb index fff098e96fcc..273d8d343d99 100644 --- a/samples/client/petstore/ruby/lib/swagger.rb +++ b/samples/client/petstore/ruby/lib/swagger.rb @@ -4,6 +4,7 @@ require 'swagger/request' require 'swagger/response' require 'swagger/version' require 'logger' +require 'json' module Swagger @@ -74,6 +75,31 @@ module Swagger Swagger.configuration.auth_token = response_body['token'] 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 @@ -82,4 +108,4 @@ class ServerError < StandardError end class ClientError < StandardError -end \ No newline at end of file +end diff --git a/samples/client/petstore/ruby/lib/swagger/request.rb b/samples/client/petstore/ruby/lib/swagger/request.rb index 70f75d71c4ff..4ec071b93d5e 100644 --- a/samples/client/petstore/ruby/lib/swagger/request.rb +++ b/samples/client/petstore/ruby/lib/swagger/request.rb @@ -234,5 +234,30 @@ module Swagger 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 diff --git a/samples/client/petstore/ruby/lib/swagger/response.rb b/samples/client/petstore/ruby/lib/swagger/response.rb index 02a1a458eb4c..641b7ccc7565 100644 --- a/samples/client/petstore/ruby/lib/swagger/response.rb +++ b/samples/client/petstore/ruby/lib/swagger/response.rb @@ -28,7 +28,7 @@ module Swagger # If body is JSON, parse it # Otherwise return raw string def body - JSON.parse raw.body + JSON.parse(raw.body, :symbolize_names => true) rescue raw.body end @@ -67,4 +67,4 @@ module Swagger end end -end \ No newline at end of file +end diff --git a/samples/client/petstore/ruby/lib/user_api.rb b/samples/client/petstore/ruby/lib/user_api.rb index 7e14c5cb4aa3..e7d0644d3204 100644 --- a/samples/client/petstore/ruby/lib/user_api.rb +++ b/samples/client/petstore/ruby/lib/user_api.rb @@ -33,29 +33,10 @@ class UserApi 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 + 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 + 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 @@ -87,29 +68,10 @@ class UserApi 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 + 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 + 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 @@ -141,29 +103,10 @@ class UserApi 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 + 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 + 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 @@ -199,9 +142,10 @@ class UserApi # 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) + obj = string.new() and obj.build_from_hash(response) end # Logs out current logged in user session @@ -233,8 +177,9 @@ class UserApi # 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 + 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 @@ -270,9 +215,10 @@ class UserApi # 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) + obj = User.new() and obj.build_from_hash(response) end # Updated user @@ -308,29 +254,10 @@ class UserApi 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 + 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 + Swagger::Request.new(:PUT, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make end # Delete user @@ -366,7 +293,8 @@ class UserApi # 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 + 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/base_object.rb b/samples/client/petstore/ruby/models/base_object.rb index efa21abdfe4f..337ca7f822ed 100644 --- a/samples/client/petstore/ruby/models/base_object.rb +++ b/samples/client/petstore/ruby/models/base_object.rb @@ -32,7 +32,7 @@ class BaseObject # deserialize value based on type def _deserialize(type, value) - case type + case type.to_sym when :DateTime DateTime.parse(value) when :string diff --git a/samples/client/petstore/ruby/models/pet.rb b/samples/client/petstore/ruby/models/pet.rb index 472302daff8f..4e41eb451ff8 100644 --- a/samples/client/petstore/ruby/models/pet.rb +++ b/samples/client/petstore/ruby/models/pet.rb @@ -68,7 +68,6 @@ class Pet < BaseObject if attributes[:'tags'] if (value = attributes[:'tags']).is_a?(Array) - #@tags = value.map{ |v| Tag.new(v) } @tags = value end end diff --git a/samples/client/petstore/ruby/spec/pet_spec.rb b/samples/client/petstore/ruby/spec/pet_spec.rb index 91750e770eb6..90df1cd821b6 100644 --- a/samples/client/petstore/ruby/spec/pet_spec.rb +++ b/samples/client/petstore/ruby/spec/pet_spec.rb @@ -34,27 +34,15 @@ describe "Pet" do 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 - - puts pet.to_json - pet_array = [pet, pet2] - puts pet_array.map{ |v| - if v.respond_to?(:to_hash) - v.to_hash - else - v - end - }.to_json - end it "should fetch a pet object" do pet = PetApi.get_pet_by_id(10002) - print pet.inspect pet.should be_a(Pet) pet.id.should == 10002 pet.name.should == "RUBY UNIT TESTING" - pet.tags[0].name.should == "RUBY UNIT TESTING" - pet.category.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 diff --git a/samples/client/petstore/ruby/spec/response_spec.rb b/samples/client/petstore/ruby/spec/response_spec.rb index c0542005cb09..f29a0d2a62fb 100644 --- a/samples/client/petstore/ruby/spec/response_spec.rb +++ b/samples/client/petstore/ruby/spec/response_spec.rb @@ -19,7 +19,7 @@ describe Swagger::Response do 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 diff --git a/samples/client/petstore/ruby/spec/spec_helper.rb b/samples/client/petstore/ruby/spec/spec_helper.rb index dd24eeca3800..d247ba5cbec0 100644 --- a/samples/client/petstore/ruby/spec/spec_helper.rb +++ b/samples/client/petstore/ruby/spec/spec_helper.rb @@ -53,7 +53,8 @@ def prepare_pet tag = Tag.new('id' => 30002, 'name' => 'tag test') pet = Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING", 'photo_urls' => 'photo url', 'category' => category, 'tags' => [tag], 'status' => 'pending') - PetApi.add_pet(:body => pet) + + PetApi.add_pet(:'body'=> pet) end # always delete and then re-create the store order From 3de9b4bfc84ba973aec6492d408e3752eaa3b8e7 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Sun, 17 May 2015 23:47:55 +0800 Subject: [PATCH 49/67] remove (duplicated) object_to_http_body and object_to_hash from swagger.rb --- .../src/main/resources/ruby/swagger.mustache | 25 ------------------- samples/client/petstore/ruby/lib/swagger.rb | 25 ------------------- 2 files changed, 50 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache index 273d8d343d99..f393330b148a 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache @@ -75,31 +75,6 @@ module Swagger Swagger.configuration.auth_token = response_body['token'] 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 diff --git a/samples/client/petstore/ruby/lib/swagger.rb b/samples/client/petstore/ruby/lib/swagger.rb index 273d8d343d99..f393330b148a 100644 --- a/samples/client/petstore/ruby/lib/swagger.rb +++ b/samples/client/petstore/ruby/lib/swagger.rb @@ -75,31 +75,6 @@ module Swagger Swagger.configuration.auth_token = response_body['token'] 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 From 05ac516ffa25613e43e5320e020134750f3754f6 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Mon, 18 May 2015 04:30:26 +0800 Subject: [PATCH 50/67] clean up ruby sample, remove commented code, bug fix --- .../codegen/languages/RubyClientCodegen.java | 2 +- .../main/resources/ruby/base_object.mustache | 2 +- .../src/main/resources/ruby/model.mustache | 78 ----------------- .../petstore/ruby/lib/model/base_object.rb | 83 ------------------- .../petstore/ruby/models/base_object.rb | 11 +-- .../client/petstore/ruby/models/category.rb | 78 ----------------- samples/client/petstore/ruby/models/order.rb | 78 ----------------- samples/client/petstore/ruby/models/pet.rb | 78 ----------------- samples/client/petstore/ruby/models/tag.rb | 78 ----------------- samples/client/petstore/ruby/models/user.rb | 78 ----------------- 10 files changed, 6 insertions(+), 560 deletions(-) delete mode 100644 samples/client/petstore/ruby/lib/model/base_object.rb 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 962f7ea692c1..99f56bf5d415 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 @@ -72,7 +72,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { 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")); - supportingFiles.add(new SupportingFile("base_object.mustache", "", "lib/model/base_object.rb")); + supportingFiles.add(new SupportingFile("base_object.mustache", "", "models/base_object.rb")); } @Override diff --git a/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache index 398e434e9bd2..ecad551c77b0 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache @@ -31,7 +31,7 @@ class BaseObject end def _deserialize(type, value) - case type.to_s + case type.to_sym when :DateTime DateTime.parse(value) when :string diff --git a/modules/swagger-codegen/src/main/resources/ruby/model.mustache b/modules/swagger-codegen/src/main/resources/ruby/model.mustache index f3c1b85f2997..362664aa2b76 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/model.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/model.mustache @@ -36,84 +36,6 @@ require_relative 'base_object' {{/vars}} end -# # 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) -# 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 -# 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 = Object.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 {{/model}} {{/models}} diff --git a/samples/client/petstore/ruby/lib/model/base_object.rb b/samples/client/petstore/ruby/lib/model/base_object.rb deleted file mode 100644 index 398e434e9bd2..000000000000 --- a/samples/client/petstore/ruby/lib/model/base_object.rb +++ /dev/null @@ -1,83 +0,0 @@ -# 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_s - 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 = Object.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 diff --git a/samples/client/petstore/ruby/models/base_object.rb b/samples/client/petstore/ruby/models/base_object.rb index 337ca7f822ed..ecad551c77b0 100644 --- a/samples/client/petstore/ruby/models/base_object.rb +++ b/samples/client/petstore/ruby/models/base_object.rb @@ -1,7 +1,6 @@ -require 'json' -# +# 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 = {} @@ -13,6 +12,7 @@ class BaseObject # 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) @@ -30,7 +30,6 @@ class BaseObject self end - # deserialize value based on type def _deserialize(type, value) case type.to_sym when :DateTime @@ -53,9 +52,7 @@ class BaseObject end end - #def to_json - # self.to_hash.to_json - #end + # to_body is an alias to to_body (backward compatibility) def to_hash diff --git a/samples/client/petstore/ruby/models/category.rb b/samples/client/petstore/ruby/models/category.rb index b8ef8b6106a3..c1da69482e02 100644 --- a/samples/client/petstore/ruby/models/category.rb +++ b/samples/client/petstore/ruby/models/category.rb @@ -42,82 +42,4 @@ class Category < BaseObject end -# # 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) -# 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 -# 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 = Object.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 diff --git a/samples/client/petstore/ruby/models/order.rb b/samples/client/petstore/ruby/models/order.rb index ade8fea251f7..6347167c860e 100644 --- a/samples/client/petstore/ruby/models/order.rb +++ b/samples/client/petstore/ruby/models/order.rb @@ -74,82 +74,4 @@ class Order < BaseObject end -# # 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) -# 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 -# 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 = Object.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 diff --git a/samples/client/petstore/ruby/models/pet.rb b/samples/client/petstore/ruby/models/pet.rb index 4e41eb451ff8..9accf4d1c818 100644 --- a/samples/client/petstore/ruby/models/pet.rb +++ b/samples/client/petstore/ruby/models/pet.rb @@ -78,82 +78,4 @@ class Pet < BaseObject end -# # 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) -# 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 -# 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 = Object.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 diff --git a/samples/client/petstore/ruby/models/tag.rb b/samples/client/petstore/ruby/models/tag.rb index dc4611953e65..7eb332a32182 100644 --- a/samples/client/petstore/ruby/models/tag.rb +++ b/samples/client/petstore/ruby/models/tag.rb @@ -42,82 +42,4 @@ class Tag < BaseObject end -# # 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) -# 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 -# 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 = Object.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 diff --git a/samples/client/petstore/ruby/models/user.rb b/samples/client/petstore/ruby/models/user.rb index 376c5a20f0a0..20420e1c69b7 100644 --- a/samples/client/petstore/ruby/models/user.rb +++ b/samples/client/petstore/ruby/models/user.rb @@ -90,82 +90,4 @@ class User < BaseObject end -# # 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) -# 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 -# 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 = Object.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 From abbea5ec4c1d53884d31e027496138fd3fe393ed Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 18 May 2015 16:23:46 +0800 Subject: [PATCH 51/67] better logic for accept and content-type, added test cases --- .../main/resources/perl/APIClient.mustache | 35 ++++++++ .../src/main/resources/perl/api.mustache | 10 ++- .../perl/lib/WWW/SwaggerClient/APIClient.pm | 35 ++++++++ .../perl/lib/WWW/SwaggerClient/PetApi.pm | 80 +++++++++++-------- .../perl/lib/WWW/SwaggerClient/StoreApi.pm | 40 ++++++---- .../perl/lib/WWW/SwaggerClient/UserApi.pm | 80 +++++++++++-------- samples/client/petstore/perl/t/01_pet_api.t | 12 ++- 7 files changed, 207 insertions(+), 85 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/perl/APIClient.mustache b/modules/swagger-codegen/src/main/resources/perl/APIClient.mustache index b0c3c9b5d39f..19079a079223 100644 --- a/modules/swagger-codegen/src/main/resources/perl/APIClient.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/APIClient.mustache @@ -253,4 +253,39 @@ sub deserialize } +# 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/api.mustache b/modules/swagger-codegen/src/main/resources/perl/api.mustache index 7b7d9d98a4ed..c88364ff7d72 100644 --- a/modules/swagger-codegen/src/main/resources/perl/api.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/api.mustache @@ -85,12 +85,14 @@ sub new { my $header_params = {}; my $form_params = {}; - my $_header_accept = '{{#produces}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/produces}}'; - if ($_header_accept ne '') { + # '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; } - my @_header_content_type = ({{#consumes}}'{{mediaType}}'{{#hasMore}},{{/hasMore}}{{/consumes}}); - $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + #my @_header_content_type = ({{#consumes}}'{{mediaType}}'{{#hasMore}},{{/hasMore}}{{/consumes}}); + #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type({{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}); {{#queryParams}} # query params if ( exists $args{'{{paramName}}'}) { diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/APIClient.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/APIClient.pm index 6d0ecc44dc69..0f0fea793e36 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/APIClient.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/APIClient.pm @@ -253,4 +253,39 @@ sub deserialize } +# 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/PetApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm index 930bd52102be..7ee7dfce8747 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm @@ -86,12 +86,14 @@ sub new { my $header_params = {}; my $form_params = {}; - my $_header_accept = 'application/json, application/xml'; - if ($_header_accept ne '') { + # '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; } - my @_header_content_type = ('application/json','application/xml',); - $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + #my @_header_content_type = ('application/json','application/xml',); + #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json', 'application/xml', ); @@ -137,12 +139,14 @@ sub new { my $header_params = {}; my $form_params = {}; - my $_header_accept = 'application/json, application/xml'; - if ($_header_accept ne '') { + # '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; } - my @_header_content_type = ('application/json','application/xml',); - $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + #my @_header_content_type = ('application/json','application/xml',); + #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json', 'application/xml', ); @@ -188,12 +192,14 @@ sub new { my $header_params = {}; my $form_params = {}; - my $_header_accept = 'application/json, application/xml'; - if ($_header_accept ne '') { + # '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; } - my @_header_content_type = (); - $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + #my @_header_content_type = (); + #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); # query params if ( exists $args{'status'}) { @@ -242,12 +248,14 @@ sub new { my $header_params = {}; my $form_params = {}; - my $_header_accept = 'application/json, application/xml'; - if ($_header_accept ne '') { + # '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; } - my @_header_content_type = (); - $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + #my @_header_content_type = (); + #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); # query params if ( exists $args{'tags'}) { @@ -301,12 +309,14 @@ sub new { my $header_params = {}; my $form_params = {}; - my $_header_accept = 'application/json, application/xml'; - if ($_header_accept ne '') { + # '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; } - my @_header_content_type = (); - $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + #my @_header_content_type = (); + #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); @@ -364,12 +374,14 @@ sub new { my $header_params = {}; my $form_params = {}; - my $_header_accept = 'application/json, application/xml'; - if ($_header_accept ne '') { + # '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; } - my @_header_content_type = ('application/x-www-form-urlencoded',); - $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + #my @_header_content_type = ('application/x-www-form-urlencoded',); + #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/x-www-form-urlencoded', ); @@ -433,12 +445,14 @@ sub new { my $header_params = {}; my $form_params = {}; - my $_header_accept = 'application/json, application/xml'; - if ($_header_accept ne '') { + # '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; } - my @_header_content_type = (); - $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + #my @_header_content_type = (); + #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); # header params @@ -496,12 +510,14 @@ sub new { my $header_params = {}; my $form_params = {}; - my $_header_accept = 'application/json, application/xml'; - if ($_header_accept ne '') { + # '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; } - my @_header_content_type = ('multipart/form-data',); - $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + #my @_header_content_type = ('multipart/form-data',); + #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('multipart/form-data', ); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm index bb361d05a43d..0d7a2ca7c376 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm @@ -81,12 +81,14 @@ sub new { my $header_params = {}; my $form_params = {}; - my $_header_accept = 'application/json, application/xml'; - if ($_header_accept ne '') { + # '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; } - my @_header_content_type = (); - $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + #my @_header_content_type = (); + #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); @@ -132,12 +134,14 @@ sub new { my $header_params = {}; my $form_params = {}; - my $_header_accept = 'application/json, application/xml'; - if ($_header_accept ne '') { + # '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; } - my @_header_content_type = (); - $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + #my @_header_content_type = (); + #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); @@ -191,12 +195,14 @@ sub new { my $header_params = {}; my $form_params = {}; - my $_header_accept = 'application/json, application/xml'; - if ($_header_accept ne '') { + # '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; } - my @_header_content_type = (); - $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + #my @_header_content_type = (); + #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); @@ -252,12 +258,14 @@ sub new { my $header_params = {}; my $form_params = {}; - my $_header_accept = 'application/json, application/xml'; - if ($_header_accept ne '') { + # '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; } - my @_header_content_type = (); - $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + #my @_header_content_type = (); + #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm index d3869b625550..59a71bdd1ee0 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm @@ -86,12 +86,14 @@ sub new { my $header_params = {}; my $form_params = {}; - my $_header_accept = 'application/json, application/xml'; - if ($_header_accept ne '') { + # '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; } - my @_header_content_type = (); - $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + #my @_header_content_type = (); + #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); @@ -137,12 +139,14 @@ sub new { my $header_params = {}; my $form_params = {}; - my $_header_accept = 'application/json, application/xml'; - if ($_header_accept ne '') { + # '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; } - my @_header_content_type = (); - $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + #my @_header_content_type = (); + #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); @@ -188,12 +192,14 @@ sub new { my $header_params = {}; my $form_params = {}; - my $_header_accept = 'application/json, application/xml'; - if ($_header_accept ne '') { + # '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; } - my @_header_content_type = (); - $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + #my @_header_content_type = (); + #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); @@ -240,12 +246,14 @@ sub new { my $header_params = {}; my $form_params = {}; - my $_header_accept = 'application/json, application/xml'; - if ($_header_accept ne '') { + # '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; } - my @_header_content_type = (); - $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + #my @_header_content_type = (); + #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); # query params if ( exists $args{'username'}) { @@ -296,12 +304,14 @@ sub new { my $header_params = {}; my $form_params = {}; - my $_header_accept = 'application/json, application/xml'; - if ($_header_accept ne '') { + # '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; } - my @_header_content_type = (); - $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + #my @_header_content_type = (); + #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); @@ -349,12 +359,14 @@ sub new { my $header_params = {}; my $form_params = {}; - my $_header_accept = 'application/json, application/xml'; - if ($_header_accept ne '') { + # '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; } - my @_header_content_type = (); - $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + #my @_header_content_type = (); + #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); @@ -411,12 +423,14 @@ sub new { my $header_params = {}; my $form_params = {}; - my $_header_accept = 'application/json, application/xml'; - if ($_header_accept ne '') { + # '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; } - my @_header_content_type = (); - $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + #my @_header_content_type = (); + #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); @@ -472,12 +486,14 @@ sub new { my $header_params = {}; my $form_params = {}; - my $_header_accept = 'application/json, application/xml'; - if ($_header_accept ne '') { + # '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; } - my @_header_content_type = (); - $header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + #my @_header_content_type = (); + #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); diff --git a/samples/client/petstore/perl/t/01_pet_api.t b/samples/client/petstore/perl/t/01_pet_api.t index 02a10544c57a..7855254e6578 100644 --- a/samples/client/petstore/perl/t/01_pet_api.t +++ b/samples/client/petstore/perl/t/01_pet_api.t @@ -1,4 +1,4 @@ -use Test::More tests => 25; +use Test::More tests => 31; use Test::Exception; use lib 'lib'; @@ -12,6 +12,16 @@ 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'); From 7fc2f7485103eccb11bf7ddf3fe449f12b5870ea Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 18 May 2015 16:39:33 +0800 Subject: [PATCH 52/67] remove commented code --- .../src/main/resources/perl/api.mustache | 2 -- .../perl/lib/WWW/SwaggerClient/PetApi.pm | 16 ---------------- .../perl/lib/WWW/SwaggerClient/StoreApi.pm | 8 -------- .../perl/lib/WWW/SwaggerClient/UserApi.pm | 16 ---------------- 4 files changed, 42 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/perl/api.mustache b/modules/swagger-codegen/src/main/resources/perl/api.mustache index c88364ff7d72..131eb3a39347 100644 --- a/modules/swagger-codegen/src/main/resources/perl/api.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/api.mustache @@ -90,8 +90,6 @@ sub new { if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - #my @_header_content_type = ({{#consumes}}'{{mediaType}}'{{#hasMore}},{{/hasMore}}{{/consumes}}); - #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type({{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}); {{#queryParams}} # query params diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm index 7ee7dfce8747..57237a96974d 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm @@ -91,8 +91,6 @@ sub new { if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - #my @_header_content_type = ('application/json','application/xml',); - #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json', 'application/xml', ); @@ -144,8 +142,6 @@ sub new { if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - #my @_header_content_type = ('application/json','application/xml',); - #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json', 'application/xml', ); @@ -197,8 +193,6 @@ sub new { if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - #my @_header_content_type = (); - #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); # query params @@ -253,8 +247,6 @@ sub new { if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - #my @_header_content_type = (); - #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); # query params @@ -314,8 +306,6 @@ sub new { if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - #my @_header_content_type = (); - #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); @@ -379,8 +369,6 @@ sub new { if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - #my @_header_content_type = ('application/x-www-form-urlencoded',); - #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/x-www-form-urlencoded', ); @@ -450,8 +438,6 @@ sub new { if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - #my @_header_content_type = (); - #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); @@ -515,8 +501,6 @@ sub new { if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - #my @_header_content_type = ('multipart/form-data',); - #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('multipart/form-data', ); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm index 0d7a2ca7c376..d4261c6bbec4 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm @@ -86,8 +86,6 @@ sub new { if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - #my @_header_content_type = (); - #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); @@ -139,8 +137,6 @@ sub new { if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - #my @_header_content_type = (); - #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); @@ -200,8 +196,6 @@ sub new { if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - #my @_header_content_type = (); - #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); @@ -263,8 +257,6 @@ sub new { if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - #my @_header_content_type = (); - #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm index 59a71bdd1ee0..2e5889ba39e0 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm @@ -91,8 +91,6 @@ sub new { if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - #my @_header_content_type = (); - #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); @@ -144,8 +142,6 @@ sub new { if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - #my @_header_content_type = (); - #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); @@ -197,8 +193,6 @@ sub new { if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - #my @_header_content_type = (); - #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); @@ -251,8 +245,6 @@ sub new { if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - #my @_header_content_type = (); - #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); # query params @@ -309,8 +301,6 @@ sub new { if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - #my @_header_content_type = (); - #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); @@ -364,8 +354,6 @@ sub new { if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - #my @_header_content_type = (); - #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); @@ -428,8 +416,6 @@ sub new { if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - #my @_header_content_type = (); - #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); @@ -491,8 +477,6 @@ sub new { if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - #my @_header_content_type = (); - #$header_params->{'Content-Type'} = scalar(@_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); From db9ca1a485df92d4fa094c0f22c4813888c0e2cb Mon Sep 17 00:00:00 2001 From: xhh Date: Tue, 19 May 2015 15:42:29 +0800 Subject: [PATCH 53/67] Fix test of updatePetWithForm for Android Petstore sample --- .../test/java/io/swagger/petstore/test/PetApiTest.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) 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 +} From e717f74a0a022b48ebfa12667666c89e5323f2e5 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Tue, 19 May 2015 21:15:09 +0800 Subject: [PATCH 54/67] update readme with new generators --- README.md | 3 +++ 1 file changed, 3 insertions(+) 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 From 104bcc1f89a5b086e820fd9fec9f267136eefb6e Mon Sep 17 00:00:00 2001 From: xhh Date: Sun, 19 Apr 2015 00:35:58 +0800 Subject: [PATCH 55/67] Organize generated Ruby code into a module --- .../wordnik/swagger/codegen/CodegenModel.java | 4 +- .../swagger/codegen/DefaultCodegen.java | 1 + .../swagger/codegen/DefaultGenerator.java | 1 + .../codegen/languages/RubyClientCodegen.java | 75 +-- .../src/main/resources/ruby/api.mustache | 84 ++-- .../src/main/resources/ruby/model.mustache | 71 +-- .../ruby/swagger-client.gemspec.mustache | 8 +- .../resources/ruby/swagger-client.mustache | 29 +- .../src/main/resources/ruby/swagger.mustache | 134 +++-- .../ruby/swagger/configuration.mustache | 33 +- .../resources/ruby/swagger/request.mustache | 466 +++++++++--------- .../resources/ruby/swagger/response.mustache | 124 ++--- .../resources/ruby/swagger/version.mustache | 7 +- 13 files changed, 531 insertions(+), 506 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java index 169886da22e3..274b77b4e9dd 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java @@ -7,10 +7,10 @@ import java.util.*; public class CodegenModel { public String parent; - public String name, classname, description, classVarName, modelJson; + public String name, classname, importPath, description, classVarName, modelJson; public String defaultValue; public List vars = new ArrayList(); public Set imports = new HashSet(); public Boolean hasVars, emptyVars, hasMoreModels; public ExternalDocs externalDocs; -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index 6f51374c5363..3642e8de1b65 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -428,6 +428,7 @@ public class DefaultCodegen { m.name = name; m.description = escapeText(model.getDescription()); m.classname = toModelName(name); + m.importPath = toModelImport(name); m.classVarName = toVarName(name); m.modelJson = Json.pretty(model); m.externalDocs = model.getExternalDocs(); 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 175099732157..395f298eb07a 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++) { 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 99f56bf5d415..5fb8ee5eb8fb 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,15 +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")); - supportingFiles.add(new SupportingFile("base_object.mustache", "", "models/base_object.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 @@ -82,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 @@ -150,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); @@ -167,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) { @@ -186,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"; } @@ -196,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/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index 038a40f66ea4..ba38a8157b55 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -1,57 +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 = {}) - {{#allParams}}{{#required}} - # verify the required parameter '{{paramName}}' is set - raise "Missing the required parameter '{{paramName}}' when calling {{nickname}}" 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 = {} - # 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 + # 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 - # 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}} + # 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) - {{^bodyParam}}post_body = nil - {{/bodyParam}}{{#bodyParam}}post_body = Swagger::Request.object_to_http_body({{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}}) - {{/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}}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}} + {{#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/model.mustache b/modules/swagger-codegen/src/main/resources/ruby/model.mustache index 362664aa2b76..23e589b0862b 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/model.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/model.mustache @@ -1,41 +1,42 @@ require_relative 'base_object' -{{#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 - - # 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}} +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 - {{/vars}} - end -end + # 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 + 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 index c002e581b8b6..d23c4851b242 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger-client.gemspec.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger-client.gemspec.mustache @@ -1,10 +1,10 @@ # -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) -require "swagger/version" +require "{{gemName}}/swagger/version" Gem::Specification.new do |s| - s.name = "{{artifactId}}" - s.version = Swagger::VERSION + 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"] @@ -12,8 +12,6 @@ Gem::Specification.new do |s| 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' diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger-client.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger-client.mustache index b13f83b1dbcf..78d454388256 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger-client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger-client.mustache @@ -1,5 +1,26 @@ -require 'monkey' -require 'swagger' +# 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' -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 } +# Models +{{#models}} +{{#model}} +require '{{importPath}}' +{{/model}} +{{/models}} + +# APIs +{{#apiInfo}} +{{#apis}} +require '{{importPath}}' +{{/apis}} +{{/apiInfo}} + +module {{moduleName}} + # Initialize the default configuration + Swagger.configuration ||= Swagger::Configuration.new +end \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache index f393330b148a..750e6ac5155d 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache @@ -1,86 +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 + 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 4ec071b93d5e..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,263 +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 - # 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 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 641b7ccc7565..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, :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 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 - From 8dd7d3aacd69d50c42c417e8252ccb4aec36a193 Mon Sep 17 00:00:00 2001 From: xhh Date: Sun, 19 Apr 2015 00:41:39 +0800 Subject: [PATCH 56/67] Regenerate ruby petstore sample code --- samples/client/petstore/ruby/Gemfile.lock | 2 +- .../petstore/ruby/lib/swagger-client.rb | 27 +- .../ruby/lib/swagger-client/api/pet_api.rb | 323 ++++++++++++++++ .../ruby/lib/swagger-client/api/store_api.rb | 160 ++++++++ .../ruby/lib/swagger-client/api/user_api.rb | 352 ++++++++++++++++++ .../lib/swagger-client/models/category.rb | 35 ++ .../ruby/lib/swagger-client/models/order.rb | 55 +++ .../ruby/lib/swagger-client/models/pet.rb | 59 +++ .../ruby/lib/swagger-client/models/tag.rb | 35 ++ .../ruby/lib/swagger-client/models/user.rb | 65 ++++ .../ruby/lib/{ => swagger-client}/monkey.rb | 0 .../ruby/lib/swagger-client/swagger.rb | 77 ++++ .../swagger-client/swagger/configuration.rb | 19 + .../lib/swagger-client/swagger/request.rb | 205 ++++++++++ .../lib/swagger-client/swagger/response.rb | 70 ++++ .../lib/swagger-client/swagger/version.rb | 5 + .../ruby/lib/swagger/configuration.rb | 22 -- .../petstore/ruby/lib/swagger/version.rb | 4 - .../petstore/ruby/swagger-client.gemspec | 6 +- 19 files changed, 1486 insertions(+), 35 deletions(-) create mode 100644 samples/client/petstore/ruby/lib/swagger-client/api/pet_api.rb create mode 100644 samples/client/petstore/ruby/lib/swagger-client/api/store_api.rb create mode 100644 samples/client/petstore/ruby/lib/swagger-client/api/user_api.rb create mode 100644 samples/client/petstore/ruby/lib/swagger-client/models/category.rb create mode 100644 samples/client/petstore/ruby/lib/swagger-client/models/order.rb create mode 100644 samples/client/petstore/ruby/lib/swagger-client/models/pet.rb create mode 100644 samples/client/petstore/ruby/lib/swagger-client/models/tag.rb create mode 100644 samples/client/petstore/ruby/lib/swagger-client/models/user.rb rename samples/client/petstore/ruby/lib/{ => swagger-client}/monkey.rb (100%) create mode 100644 samples/client/petstore/ruby/lib/swagger-client/swagger.rb create mode 100644 samples/client/petstore/ruby/lib/swagger-client/swagger/configuration.rb create mode 100644 samples/client/petstore/ruby/lib/swagger-client/swagger/request.rb create mode 100644 samples/client/petstore/ruby/lib/swagger-client/swagger/response.rb create mode 100644 samples/client/petstore/ruby/lib/swagger-client/swagger/version.rb delete mode 100644 samples/client/petstore/ruby/lib/swagger/configuration.rb delete mode 100644 samples/client/petstore/ruby/lib/swagger/version.rb diff --git a/samples/client/petstore/ruby/Gemfile.lock b/samples/client/petstore/ruby/Gemfile.lock index 232facf4677c..028579303ecf 100644 --- a/samples/client/petstore/ruby/Gemfile.lock +++ b/samples/client/petstore/ruby/Gemfile.lock @@ -1,7 +1,7 @@ PATH remote: . specs: - swagger-client (4.06.08) + swagger-client (1.0.0) addressable (>= 2.2.4) json (>= 1.4.6) typhoeus (>= 0.2.1) diff --git a/samples/client/petstore/ruby/lib/swagger-client.rb b/samples/client/petstore/ruby/lib/swagger-client.rb index b13f83b1dbcf..05867456a689 100644 --- a/samples/client/petstore/ruby/lib/swagger-client.rb +++ b/samples/client/petstore/ruby/lib/swagger-client.rb @@ -1,5 +1,24 @@ -require 'monkey' -require 'swagger' +# 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' -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 } +# Models +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 \ No newline at end of file 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..25a1a8f8bf4e --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger-client/api/pet_api.rb @@ -0,0 +1,323 @@ +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 = {}) + # 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 +end \ No newline at end of file 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..40a0d63c7abc --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger-client/api/store_api.rb @@ -0,0 +1,160 @@ +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 = {}) + # 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 +end \ No newline at end of file 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..0df9d287199a --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger-client/api/user_api.rb @@ -0,0 +1,352 @@ +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 = {}) + # 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 +end \ No newline at end of file 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..87e41aad6fd1 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger-client/models/category.rb @@ -0,0 +1,35 @@ +module SwaggerClient + 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 +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..9adad6920ad9 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger-client/models/order.rb @@ -0,0 +1,55 @@ +module SwaggerClient + 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 +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..18e2be1dae08 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger-client/models/pet.rb @@ -0,0 +1,59 @@ +module SwaggerClient + 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 +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..41477ac73536 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger-client/models/tag.rb @@ -0,0 +1,35 @@ +module SwaggerClient + 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 +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..042d589726b5 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger-client/models/user.rb @@ -0,0 +1,65 @@ +module SwaggerClient + 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 +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..925382cf94e5 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger-client/swagger.rb @@ -0,0 +1,77 @@ +require 'logger' + +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 \ No newline at end of file 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..8a605784a3a0 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger-client/swagger/request.rb @@ -0,0 +1,205 @@ +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 + 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..b0870d2f2209 --- /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 + 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 \ No newline at end of file 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/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/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/swagger-client.gemspec b/samples/client/petstore/ruby/swagger-client.gemspec index bbff5f95f6bc..11434631fe9f 100644 --- a/samples/client/petstore/ruby/swagger-client.gemspec +++ b/samples/client/petstore/ruby/swagger-client.gemspec @@ -1,10 +1,10 @@ # -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) -require "swagger/version" +require "swagger-client/swagger/version" Gem::Specification.new do |s| s.name = "swagger-client" - s.version = Swagger::VERSION + s.version = SwaggerClient::Swagger::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Zeke Sikelianos", "Tony Tam"] s.email = ["zeke@wordnik.com", "tony@wordnik.com"] @@ -12,8 +12,6 @@ Gem::Specification.new do |s| 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' From 194e9e6f055efc914ec3d9f68c75f8cf2f16f201 Mon Sep 17 00:00:00 2001 From: xhh Date: Sun, 19 Apr 2015 00:42:55 +0800 Subject: [PATCH 57/67] Make petstore tests pass --- samples/client/petstore/ruby/spec/pet_spec.rb | 22 ++++----- .../client/petstore/ruby/spec/request_spec.rb | 48 +++++++++---------- .../petstore/ruby/spec/response_spec.rb | 6 +-- .../client/petstore/ruby/spec/spec_helper.rb | 12 ++--- .../client/petstore/ruby/spec/store_spec.rb | 2 +- .../client/petstore/ruby/spec/swagger_spec.rb | 28 +++++------ 6 files changed, 59 insertions(+), 59 deletions(-) diff --git a/samples/client/petstore/ruby/spec/pet_spec.rb b/samples/client/petstore/ruby/spec/pet_spec.rb index 90df1cd821b6..fce80afb3bc5 100644 --- a/samples/client/petstore/ruby/spec/pet_spec.rb +++ b/samples/client/petstore/ruby/spec/pet_spec.rb @@ -37,8 +37,8 @@ describe "Pet" do 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" @@ -46,17 +46,17 @@ describe "Pet" do 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 = 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" @@ -65,19 +65,19 @@ describe "Pet" do end it "should update a pet" do - pet = Pet.new({'id' => 10002, 'status' => 'sold'}) - PetApi.add_pet(:body => pet) + pet = SwaggerClient::Pet.new({'id' => 10002, 'status' => 'sold'}) + SwaggerClient::PetApi.add_pet(:body => pet) - fetched = PetApi.get_pet_by_id(10002) + 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) + 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 f29a0d2a62fb..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,7 +13,7 @@ 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 @@ -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 d247ba5cbec0..5e9b30c9a2e5 100644 --- a/samples/client/petstore/ruby/spec/spec_helper.rb +++ b/samples/client/petstore/ruby/spec/spec_helper.rb @@ -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,7 +47,7 @@ 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 category = Category.new('id' => 20002, 'name' => 'category test') tag = Tag.new('id' => 30002, 'name' => 'tag test') @@ -57,19 +57,19 @@ def prepare_pet 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 From 87904e8b69b471bd51ee4537dce72ef4d98587f5 Mon Sep 17 00:00:00 2001 From: xhh Date: Fri, 17 Apr 2015 09:33:49 +0800 Subject: [PATCH 58/67] Set version dynamically in ruby codegen Conflicts: modules/swagger-codegen/src/main/resources/ruby/swagger/version.mustache samples/client/petstore/ruby/lib/swagger/version.rb --- samples/client/petstore/ruby/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index 29a7ce844ce6..86b17e062364 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -11,14 +11,14 @@ 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 From b140f1f152425d2f9799888a19c8e49c9878cf4e Mon Sep 17 00:00:00 2001 From: xhh Date: Mon, 20 Apr 2015 10:12:02 +0800 Subject: [PATCH 59/67] Fix example code in README.md of Ruby petstore sample --- samples/client/petstore/ruby/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index 86b17e062364..a05c91317b60 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -42,7 +42,7 @@ ruby -Ilib script.rb ```ruby 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 ``` From fcf1327c1f5b04024224e1c4bba6a8e051ba6ac2 Mon Sep 17 00:00:00 2001 From: xhh Date: Mon, 20 Apr 2015 10:46:55 +0800 Subject: [PATCH 60/67] Rename swagger-client to swagger_client according to guides from rubygems: http://guides.rubygems.org/name-your-gem/ --- .../codegen/languages/RubyClientCodegen.java | 8 +++---- ...stache => swagger_client.gemspec.mustache} | 0 ...lient.mustache => swagger_client.mustache} | 0 samples/client/petstore/ruby/Gemfile.lock | 4 ++-- samples/client/petstore/ruby/README.md | 10 ++++---- .../petstore/ruby/lib/swagger-client.rb | 24 ------------------- .../petstore/ruby/lib/swagger_client.rb | 24 +++++++++++++++++++ .../api/pet_api.rb | 0 .../api/store_api.rb | 0 .../api/user_api.rb | 0 .../models/category.rb | 0 .../models/order.rb | 0 .../models/pet.rb | 0 .../models/tag.rb | 0 .../models/user.rb | 0 .../monkey.rb | 0 .../swagger.rb | 0 .../swagger/configuration.rb | 0 .../swagger/request.rb | 0 .../swagger/response.rb | 0 .../swagger/version.rb | 0 .../client/petstore/ruby/spec/spec_helper.rb | 2 +- ...-client.gemspec => swagger_client.gemspec} | 4 ++-- 23 files changed, 38 insertions(+), 38 deletions(-) rename modules/swagger-codegen/src/main/resources/ruby/{swagger-client.gemspec.mustache => swagger_client.gemspec.mustache} (100%) rename modules/swagger-codegen/src/main/resources/ruby/{swagger-client.mustache => swagger_client.mustache} (100%) delete mode 100644 samples/client/petstore/ruby/lib/swagger-client.rb create mode 100644 samples/client/petstore/ruby/lib/swagger_client.rb rename samples/client/petstore/ruby/lib/{swagger-client => swagger_client}/api/pet_api.rb (100%) rename samples/client/petstore/ruby/lib/{swagger-client => swagger_client}/api/store_api.rb (100%) rename samples/client/petstore/ruby/lib/{swagger-client => swagger_client}/api/user_api.rb (100%) rename samples/client/petstore/ruby/lib/{swagger-client => swagger_client}/models/category.rb (100%) rename samples/client/petstore/ruby/lib/{swagger-client => swagger_client}/models/order.rb (100%) rename samples/client/petstore/ruby/lib/{swagger-client => swagger_client}/models/pet.rb (100%) rename samples/client/petstore/ruby/lib/{swagger-client => swagger_client}/models/tag.rb (100%) rename samples/client/petstore/ruby/lib/{swagger-client => swagger_client}/models/user.rb (100%) rename samples/client/petstore/ruby/lib/{swagger-client => swagger_client}/monkey.rb (100%) rename samples/client/petstore/ruby/lib/{swagger-client => swagger_client}/swagger.rb (100%) rename samples/client/petstore/ruby/lib/{swagger-client => swagger_client}/swagger/configuration.rb (100%) rename samples/client/petstore/ruby/lib/{swagger-client => swagger_client}/swagger/request.rb (100%) rename samples/client/petstore/ruby/lib/{swagger-client => swagger_client}/swagger/response.rb (100%) rename samples/client/petstore/ruby/lib/{swagger-client => swagger_client}/swagger/version.rb (100%) rename samples/client/petstore/ruby/{swagger-client.gemspec => swagger_client.gemspec} (93%) 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 5fb8ee5eb8fb..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,7 +8,7 @@ import java.util.*; import java.io.File; public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String gemName = "swagger-client"; + protected String gemName = "swagger_client"; protected String moduleName = null; protected String libFolder = "lib"; @@ -25,7 +25,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { } /** - * Generate Ruby module name from the gem name, e.g. use "SwaggerClient" for "swagger-client". + * Generate Ruby module name from the gem name, e.g. use "SwaggerClient" for "swagger_client". */ public String generateModuleName() { return camelize(gemName.replaceAll("[^\\w]+", "_")); @@ -72,8 +72,8 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { 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("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")); 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 similarity index 100% rename from modules/swagger-codegen/src/main/resources/ruby/swagger-client.gemspec.mustache rename to modules/swagger-codegen/src/main/resources/ruby/swagger_client.gemspec.mustache diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger-client.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/ruby/swagger-client.mustache rename to modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache diff --git a/samples/client/petstore/ruby/Gemfile.lock b/samples/client/petstore/ruby/Gemfile.lock index 028579303ecf..c2f0a21b3fc1 100644 --- a/samples/client/petstore/ruby/Gemfile.lock +++ b/samples/client/petstore/ruby/Gemfile.lock @@ -1,7 +1,7 @@ PATH remote: . specs: - swagger-client (1.0.0) + swagger_client (1.0.0) addressable (>= 2.2.4) json (>= 1.4.6) typhoeus (>= 0.2.1) @@ -56,6 +56,6 @@ DEPENDENCIES autotest-growl autotest-rails-pure rspec (>= 2.5.0) - swagger-client! + swagger_client! vcr (>= 1.5.1) webmock (>= 1.6.2) diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index a05c91317b60..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-1.0.0.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', '~> 1.0.0' + 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,7 +40,7 @@ ruby -Ilib script.rb ## Configuration ```ruby -require 'swagger-client' +require 'swagger_client' SwaggerClient::Swagger.configure do |config| config.api_key = 'special-key' 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 05867456a689..000000000000 --- a/samples/client/petstore/ruby/lib/swagger-client.rb +++ /dev/null @@ -1,24 +0,0 @@ -# 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/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 \ No newline at end of file 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..33922da4c73f --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client.rb @@ -0,0 +1,24 @@ +# 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/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 \ No newline at end of file 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 similarity index 100% rename from samples/client/petstore/ruby/lib/swagger-client/api/pet_api.rb rename to samples/client/petstore/ruby/lib/swagger_client/api/pet_api.rb 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 similarity index 100% rename from samples/client/petstore/ruby/lib/swagger-client/api/store_api.rb rename to samples/client/petstore/ruby/lib/swagger_client/api/store_api.rb 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 similarity index 100% rename from samples/client/petstore/ruby/lib/swagger-client/api/user_api.rb rename to samples/client/petstore/ruby/lib/swagger_client/api/user_api.rb diff --git a/samples/client/petstore/ruby/lib/swagger-client/models/category.rb b/samples/client/petstore/ruby/lib/swagger_client/models/category.rb similarity index 100% rename from samples/client/petstore/ruby/lib/swagger-client/models/category.rb rename to samples/client/petstore/ruby/lib/swagger_client/models/category.rb diff --git a/samples/client/petstore/ruby/lib/swagger-client/models/order.rb b/samples/client/petstore/ruby/lib/swagger_client/models/order.rb similarity index 100% rename from samples/client/petstore/ruby/lib/swagger-client/models/order.rb rename to samples/client/petstore/ruby/lib/swagger_client/models/order.rb diff --git a/samples/client/petstore/ruby/lib/swagger-client/models/pet.rb b/samples/client/petstore/ruby/lib/swagger_client/models/pet.rb similarity index 100% rename from samples/client/petstore/ruby/lib/swagger-client/models/pet.rb rename to samples/client/petstore/ruby/lib/swagger_client/models/pet.rb diff --git a/samples/client/petstore/ruby/lib/swagger-client/models/tag.rb b/samples/client/petstore/ruby/lib/swagger_client/models/tag.rb similarity index 100% rename from samples/client/petstore/ruby/lib/swagger-client/models/tag.rb rename to samples/client/petstore/ruby/lib/swagger_client/models/tag.rb diff --git a/samples/client/petstore/ruby/lib/swagger-client/models/user.rb b/samples/client/petstore/ruby/lib/swagger_client/models/user.rb similarity index 100% rename from samples/client/petstore/ruby/lib/swagger-client/models/user.rb rename to samples/client/petstore/ruby/lib/swagger_client/models/user.rb diff --git a/samples/client/petstore/ruby/lib/swagger-client/monkey.rb b/samples/client/petstore/ruby/lib/swagger_client/monkey.rb similarity index 100% rename from samples/client/petstore/ruby/lib/swagger-client/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 similarity index 100% rename from samples/client/petstore/ruby/lib/swagger-client/swagger.rb rename to samples/client/petstore/ruby/lib/swagger_client/swagger.rb diff --git a/samples/client/petstore/ruby/lib/swagger-client/swagger/configuration.rb b/samples/client/petstore/ruby/lib/swagger_client/swagger/configuration.rb similarity index 100% rename from samples/client/petstore/ruby/lib/swagger-client/swagger/configuration.rb rename to samples/client/petstore/ruby/lib/swagger_client/swagger/configuration.rb diff --git a/samples/client/petstore/ruby/lib/swagger-client/swagger/request.rb b/samples/client/petstore/ruby/lib/swagger_client/swagger/request.rb similarity index 100% rename from samples/client/petstore/ruby/lib/swagger-client/swagger/request.rb rename to samples/client/petstore/ruby/lib/swagger_client/swagger/request.rb diff --git a/samples/client/petstore/ruby/lib/swagger-client/swagger/response.rb b/samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb similarity index 100% rename from samples/client/petstore/ruby/lib/swagger-client/swagger/response.rb rename to samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb diff --git a/samples/client/petstore/ruby/lib/swagger-client/swagger/version.rb b/samples/client/petstore/ruby/lib/swagger_client/swagger/version.rb similarity index 100% rename from samples/client/petstore/ruby/lib/swagger-client/swagger/version.rb rename to samples/client/petstore/ruby/lib/swagger_client/swagger/version.rb diff --git a/samples/client/petstore/ruby/spec/spec_helper.rb b/samples/client/petstore/ruby/spec/spec_helper.rb index 5e9b30c9a2e5..12d51679fc8a 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' diff --git a/samples/client/petstore/ruby/swagger-client.gemspec b/samples/client/petstore/ruby/swagger_client.gemspec similarity index 93% rename from samples/client/petstore/ruby/swagger-client.gemspec rename to samples/client/petstore/ruby/swagger_client.gemspec index 11434631fe9f..dc3cd8350bda 100644 --- a/samples/client/petstore/ruby/swagger-client.gemspec +++ b/samples/client/petstore/ruby/swagger_client.gemspec @@ -1,9 +1,9 @@ # -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) -require "swagger-client/swagger/version" +require "swagger_client/swagger/version" Gem::Specification.new do |s| - s.name = "swagger-client" + s.name = "swagger_client" s.version = SwaggerClient::Swagger::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Zeke Sikelianos", "Tony Tam"] From f766614b4d67f955e6a01ce5332a4140f02bfbd8 Mon Sep 17 00:00:00 2001 From: xhh Date: Mon, 18 May 2015 16:42:38 +0800 Subject: [PATCH 61/67] Clean old files generated --- samples/client/petstore/ruby/lib/pet_api.rb | 313 ------------------ samples/client/petstore/ruby/lib/store_api.rb | 154 --------- samples/client/petstore/ruby/lib/swagger.rb | 86 ----- .../petstore/ruby/lib/swagger/request.rb | 263 --------------- .../petstore/ruby/lib/swagger/response.rb | 70 ---- samples/client/petstore/ruby/lib/user_api.rb | 300 ----------------- .../petstore/ruby/models/base_object.rb | 83 ----- .../client/petstore/ruby/models/category.rb | 45 --- samples/client/petstore/ruby/models/order.rb | 77 ----- samples/client/petstore/ruby/models/pet.rb | 81 ----- samples/client/petstore/ruby/models/tag.rb | 45 --- samples/client/petstore/ruby/models/user.rb | 93 ------ 12 files changed, 1610 deletions(-) delete mode 100644 samples/client/petstore/ruby/lib/pet_api.rb delete mode 100644 samples/client/petstore/ruby/lib/store_api.rb delete mode 100644 samples/client/petstore/ruby/lib/swagger.rb delete mode 100644 samples/client/petstore/ruby/lib/swagger/request.rb delete mode 100644 samples/client/petstore/ruby/lib/swagger/response.rb delete mode 100644 samples/client/petstore/ruby/lib/user_api.rb delete mode 100644 samples/client/petstore/ruby/models/base_object.rb delete mode 100644 samples/client/petstore/ruby/models/category.rb delete mode 100644 samples/client/petstore/ruby/models/order.rb delete mode 100644 samples/client/petstore/ruby/models/pet.rb delete mode 100644 samples/client/petstore/ruby/models/tag.rb delete mode 100644 samples/client/petstore/ruby/models/user.rb 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 b15198588aad..000000000000 --- a/samples/client/petstore/ruby/lib/pet_api.rb +++ /dev/null @@ -1,313 +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 = {}) - - - # 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 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 c6d670cd8c04..000000000000 --- a/samples/client/petstore/ruby/lib/store_api.rb +++ /dev/null @@ -1,154 +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 = {}) - - - # 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 diff --git a/samples/client/petstore/ruby/lib/swagger.rb b/samples/client/petstore/ruby/lib/swagger.rb deleted file mode 100644 index f393330b148a..000000000000 --- a/samples/client/petstore/ruby/lib/swagger.rb +++ /dev/null @@ -1,86 +0,0 @@ -require 'monkey' -require 'swagger/configuration' -require 'swagger/request' -require 'swagger/response' -require 'swagger/version' -require 'logger' -require 'json' - -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 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 4ec071b93d5e..000000000000 --- a/samples/client/petstore/ruby/lib/swagger/request.rb +++ /dev/null @@ -1,263 +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 - - # 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 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 641b7ccc7565..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, :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 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 e7d0644d3204..000000000000 --- a/samples/client/petstore/ruby/lib/user_api.rb +++ /dev/null @@ -1,300 +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 = {}) - - - # 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 diff --git a/samples/client/petstore/ruby/models/base_object.rb b/samples/client/petstore/ruby/models/base_object.rb deleted file mode 100644 index ecad551c77b0..000000000000 --- a/samples/client/petstore/ruby/models/base_object.rb +++ /dev/null @@ -1,83 +0,0 @@ -# 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 = Object.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 diff --git a/samples/client/petstore/ruby/models/category.rb b/samples/client/petstore/ruby/models/category.rb deleted file mode 100644 index c1da69482e02..000000000000 --- a/samples/client/petstore/ruby/models/category.rb +++ /dev/null @@ -1,45 +0,0 @@ -require_relative 'base_object' - -# -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 diff --git a/samples/client/petstore/ruby/models/order.rb b/samples/client/petstore/ruby/models/order.rb deleted file mode 100644 index 6347167c860e..000000000000 --- a/samples/client/petstore/ruby/models/order.rb +++ /dev/null @@ -1,77 +0,0 @@ -require_relative 'base_object' - -# -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 diff --git a/samples/client/petstore/ruby/models/pet.rb b/samples/client/petstore/ruby/models/pet.rb deleted file mode 100644 index 9accf4d1c818..000000000000 --- a/samples/client/petstore/ruby/models/pet.rb +++ /dev/null @@ -1,81 +0,0 @@ -require_relative 'base_object' - -# -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 diff --git a/samples/client/petstore/ruby/models/tag.rb b/samples/client/petstore/ruby/models/tag.rb deleted file mode 100644 index 7eb332a32182..000000000000 --- a/samples/client/petstore/ruby/models/tag.rb +++ /dev/null @@ -1,45 +0,0 @@ -require_relative 'base_object' - -# -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 diff --git a/samples/client/petstore/ruby/models/user.rb b/samples/client/petstore/ruby/models/user.rb deleted file mode 100644 index 20420e1c69b7..000000000000 --- a/samples/client/petstore/ruby/models/user.rb +++ /dev/null @@ -1,93 +0,0 @@ -require_relative 'base_object' - -# -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 From 6eaaa5cc6962f2ba2d63bb138c7a121d741a49f6 Mon Sep 17 00:00:00 2001 From: xhh Date: Mon, 18 May 2015 16:44:10 +0800 Subject: [PATCH 62/67] Include base_object model into module structure --- .../main/resources/ruby/base_object.mustache | 146 +++++++++--------- .../src/main/resources/ruby/model.mustache | 2 - .../resources/ruby/swagger_client.mustache | 3 +- 3 files changed, 75 insertions(+), 76 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache index ecad551c77b0..c0e563a0bb72 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache @@ -1,83 +1,83 @@ -# base class containing fundamental method such as to_hash, build_from_hash and more -class BaseObject +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? + # 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 - 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) } ) + # 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 - #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 = Object.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 + # data not found in attributes(hash), not an issue as the data can be optional 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 + self end - 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 23e589b0862b..d0d4e7877564 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/model.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/model.mustache @@ -1,5 +1,3 @@ -require_relative 'base_object' - module {{moduleName}} {{#models}} # {{description}} {{#model}} class {{classname}} < BaseObject diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache index 78d454388256..89b4860a0438 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache @@ -7,6 +7,7 @@ require '{{gemName}}/swagger/response' require '{{gemName}}/swagger/version' # Models +require '{{modelPackage}}/base_object' {{#models}} {{#model}} require '{{importPath}}' @@ -23,4 +24,4 @@ require '{{importPath}}' module {{moduleName}} # Initialize the default configuration Swagger.configuration ||= Swagger::Configuration.new -end \ No newline at end of file +end From ab4975b7f1eb4f26e10eeae1ef0973078df93804 Mon Sep 17 00:00:00 2001 From: xhh Date: Mon, 18 May 2015 16:46:49 +0800 Subject: [PATCH 63/67] Regenerate petstore ruby sample --- .../petstore/ruby/lib/swagger_client.rb | 3 +- .../ruby/lib/swagger_client/api/pet_api.rb | 182 +++++++------- .../ruby/lib/swagger_client/api/store_api.rb | 92 ++++---- .../ruby/lib/swagger_client/api/user_api.rb | 222 +++++++----------- .../lib/swagger_client/models/base_object.rb | 83 +++++++ .../lib/swagger_client/models/category.rb | 51 ++-- .../ruby/lib/swagger_client/models/order.rb | 103 ++++---- .../ruby/lib/swagger_client/models/pet.rb | 83 ++++--- .../ruby/lib/swagger_client/models/tag.rb | 51 ++-- .../ruby/lib/swagger_client/models/user.rb | 129 ++++++---- .../ruby/lib/swagger_client/swagger.rb | 25 +- .../lib/swagger_client/swagger/request.rb | 98 ++++++-- .../lib/swagger_client/swagger/response.rb | 8 +- 13 files changed, 646 insertions(+), 484 deletions(-) create mode 100644 samples/client/petstore/ruby/lib/swagger_client/models/base_object.rb diff --git a/samples/client/petstore/ruby/lib/swagger_client.rb b/samples/client/petstore/ruby/lib/swagger_client.rb index 33922da4c73f..6d239185005c 100644 --- a/samples/client/petstore/ruby/lib/swagger_client.rb +++ b/samples/client/petstore/ruby/lib/swagger_client.rb @@ -7,6 +7,7 @@ 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' @@ -21,4 +22,4 @@ require 'swagger_client/api/store_api' module SwaggerClient # Initialize the default configuration Swagger.configuration ||= Swagger::Configuration.new -end \ No newline at end of file +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 index 25a1a8f8bf4e..6f2740b22e95 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/api/pet_api.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/api/pet_api.rb @@ -11,7 +11,7 @@ module SwaggerClient # @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') @@ -22,40 +22,23 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # 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 + 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 + 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 # @@ -63,7 +46,7 @@ module SwaggerClient # @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') @@ -74,40 +57,23 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # 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 + 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 + 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 @@ -115,7 +81,7 @@ module SwaggerClient # @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') @@ -127,21 +93,24 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + 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| Pet.new(response) } - end + 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. @@ -149,7 +118,7 @@ module SwaggerClient # @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') @@ -161,21 +130,24 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + 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| Pet.new(response) } - end + 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 @@ -183,8 +155,10 @@ module SwaggerClient # @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? + + # 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) @@ -195,21 +169,24 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + 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 - Pet.new(response) - end + obj = Pet.new() and obj.build_from_hash(response) + end # Updates a pet in the store with form data # @@ -219,8 +196,10 @@ module SwaggerClient # @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? + + # 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) @@ -231,11 +210,13 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -244,9 +225,10 @@ module SwaggerClient # 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 + Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end # Deletes a pet # @@ -255,8 +237,10 @@ module SwaggerClient # @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? + + # 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) @@ -267,11 +251,13 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + 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 @@ -279,9 +265,10 @@ module SwaggerClient # 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 + Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end # uploads an image # @@ -291,8 +278,10 @@ module SwaggerClient # @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? + + # 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) @@ -303,11 +292,13 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -316,8 +307,9 @@ module SwaggerClient # 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 + Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make end -end \ No newline at end of file + 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 index 40a0d63c7abc..37595c2147e1 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/api/store_api.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/api/store_api.rb @@ -10,7 +10,7 @@ module SwaggerClient # @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') @@ -21,21 +21,24 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + 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| map.new(response) } - end + response.map {|response| obj = map.new() and obj.build_from_hash(response) } + end # Place an order for a pet # @@ -43,7 +46,7 @@ module SwaggerClient # @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') @@ -54,41 +57,24 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # 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 + 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 - Order.new(response) - end + 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 @@ -96,8 +82,10 @@ module SwaggerClient # @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? + + # 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) @@ -108,21 +96,24 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + 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 - Order.new(response) - end + 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 @@ -130,8 +121,10 @@ module SwaggerClient # @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? + + # 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) @@ -142,19 +135,22 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + 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 + Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make end -end \ No newline at end of file + 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 index 0df9d287199a..12a45561e3f1 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/api/user_api.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/api/user_api.rb @@ -11,7 +11,7 @@ module SwaggerClient # @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') @@ -22,40 +22,23 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # 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 + 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 + 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 # @@ -63,7 +46,7 @@ module SwaggerClient # @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') @@ -74,40 +57,23 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # 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 + 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 + 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 # @@ -115,7 +81,7 @@ module SwaggerClient # @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') @@ -126,40 +92,23 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # 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 + 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 + 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 # @@ -168,7 +117,7 @@ module SwaggerClient # @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') @@ -181,28 +130,31 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + 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 - string.new(response) - end + 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 = {}) - # verify existence of params + # resource path path = "/user/logout".sub('{format}','json') @@ -213,20 +165,23 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + 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 + 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 # @@ -234,8 +189,10 @@ module SwaggerClient # @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? + + # 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) @@ -246,21 +203,24 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + 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 - User.new(response) - end + obj = User.new() and obj.build_from_hash(response) + end # Updated user # This can only be done by the logged in user. @@ -269,8 +229,10 @@ module SwaggerClient # @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? + + # 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) @@ -281,40 +243,23 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # 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 + 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 + 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. @@ -322,8 +267,10 @@ module SwaggerClient # @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? + + # 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) @@ -334,19 +281,22 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # 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'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + 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 + Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make end -end \ No newline at end of file + 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 index 87e41aad6fd1..fe195c7ac871 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/models/category.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/models/category.rb @@ -1,35 +1,44 @@ module SwaggerClient - class Category + # + class Category < BaseObject attr_accessor :id, :name - # :internal => :external + # attribute mapping from ruby-style variable name to JSON key def self.attribute_map { - :id => :'id', - :name => :'name' + + # + :'id' => :'id', + + # + :'name' => :'name' + + } + end + + # attribute type + def self.swagger_types + { + :'id' => :'int', + :'name' => :'string' } 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 + return if !attributes.is_a?(Hash) || attributes.empty? - def to_body - body = {} - self.class.attribute_map.each_pair do |key, value| - body[value] = self.send(key) unless self.send(key).nil? + # 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 - body + + 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 index 9adad6920ad9..3fe0282ed9b8 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/models/order.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/models/order.rb @@ -1,55 +1,76 @@ module SwaggerClient - class Order + # + class Order < BaseObject attr_accessor :id, :pet_id, :quantity, :ship_date, :status, :complete - # :internal => :external + # attribute mapping from ruby-style variable name to JSON key def self.attribute_map { - :id => :'id', - :pet_id => :'petId', - :quantity => :'quantity', - :ship_date => :'shipDate', - :status => :'status', - :complete => :'complete' + + # + :'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.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 + return if !attributes.is_a?(Hash) || attributes.empty? - def to_body - body = {} - self.class.attribute_map.each_pair do |key, value| - body[value] = self.send(key) unless self.send(key).nil? + # 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 - body + + 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 index 18e2be1dae08..32f95646c726 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/models/pet.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/models/pet.rb @@ -1,59 +1,80 @@ module SwaggerClient - class Pet + # + class Pet < BaseObject attr_accessor :id, :category, :name, :photo_urls, :tags, :status - # :internal => :external + # 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', - :status => :'status' + + # + :'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.empty? - # Morph attribute keys into undescored rubyish style + 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 self.class.attribute_map[:"id"] - @id = attributes["id"] + if attributes[:'id'] + @id = attributes[:'id'] end - if self.class.attribute_map[:"category"] - @category = attributes["category"] + if attributes[:'category'] + @category = attributes[:'category'] end - if self.class.attribute_map[:"name"] - @name = attributes["name"] + if attributes[:'name'] + @name = attributes[:'name'] end - if self.class.attribute_map[:"photo_urls"] - if (value = attributes["photoUrls"]).is_a?(Array) + if attributes[:'photoUrls'] + 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) } + if attributes[:'tags'] + if (value = attributes[:'tags']).is_a?(Array) + @tags = value end end - if self.class.attribute_map[:"status"] - @status = attributes["status"] + if attributes[:'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 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 index 41477ac73536..9c5cdde1af67 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/models/tag.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/models/tag.rb @@ -1,35 +1,44 @@ module SwaggerClient - class Tag + # + class Tag < BaseObject attr_accessor :id, :name - # :internal => :external + # attribute mapping from ruby-style variable name to JSON key def self.attribute_map { - :id => :'id', - :name => :'name' + + # + :'id' => :'id', + + # + :'name' => :'name' + + } + end + + # attribute type + def self.swagger_types + { + :'id' => :'int', + :'name' => :'string' } 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 + return if !attributes.is_a?(Hash) || attributes.empty? - def to_body - body = {} - self.class.attribute_map.each_pair do |key, value| - body[value] = self.send(key) unless self.send(key).nil? + # 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 - body + + 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 index 042d589726b5..2d723da54c44 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/models/user.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/models/user.rb @@ -1,65 +1,92 @@ module SwaggerClient - class User + # + class User < BaseObject attr_accessor :id, :username, :first_name, :last_name, :email, :password, :phone, :user_status - # :internal => :external + # 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 => :'userStatus' + + # + :'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.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 + return if !attributes.is_a?(Hash) || attributes.empty? - def to_body - body = {} - self.class.attribute_map.each_pair do |key, value| - body[value] = self.send(key) unless self.send(key).nil? + # 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 - body + + 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/swagger_client/swagger.rb b/samples/client/petstore/ruby/lib/swagger_client/swagger.rb index 925382cf94e5..278db36e4cad 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/swagger.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/swagger.rb @@ -1,16 +1,17 @@ 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 @@ -38,31 +39,31 @@ module SwaggerClient 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}", + :get, + "account/authenticate/{username}", :params => { - :username => Swagger.configuration.username, + :username => Swagger.configuration.username, :password => Swagger.configuration.password } ) - + response_body = request.response.body Swagger.configuration.auth_token = response_body['token'] end @@ -74,4 +75,4 @@ module SwaggerClient class ClientError < StandardError end -end \ No newline at end of file +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 index 8a605784a3a0..d5f266267dac 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/swagger/request.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/swagger/request.rb @@ -24,21 +24,21 @@ module SwaggerClient 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| @@ -47,20 +47,20 @@ module SwaggerClient end # Construct a base URL - def url(options = {}) + 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 @@ -83,18 +83,18 @@ module SwaggerClient # 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}" + 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) + def body=(value) if value.is_a?(Hash) value = value.inject({}) do |memo, (k,v)| memo[k.to_s.camelize(:lower).to_sym] = v @@ -103,9 +103,9 @@ module SwaggerClient end @body = value end - + # If body is an object, JSONify it before making the actual request. - # For form parameters, remove empty value + # For form parameters, remove empty value def outgoing_body # http form if @body.nil? && @form_params && !@form_params.empty? @@ -118,7 +118,7 @@ module SwaggerClient @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, @@ -133,17 +133,17 @@ module SwaggerClient 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 @@ -175,7 +175,7 @@ module SwaggerClient :body => self.outgoing_body, :headers => self.headers.stringify_keys, ) - + when :delete,:DELETE Typhoeus::Request.delete( self.url, @@ -185,21 +185,73 @@ module SwaggerClient end Response.new(response) end - + def response self.make end - + def response_code_pretty return unless @response.present? - @response.code.to_s + @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 index b0870d2f2209..538821bea691 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb @@ -17,7 +17,7 @@ module SwaggerClient def code raw.code end - + # Account for error messages that take different forms... def error_message body['message'] @@ -28,12 +28,12 @@ module SwaggerClient # If body is JSON, parse it # Otherwise return raw string def body - JSON.parse raw.body + JSON.parse(raw.body, :symbolize_names => true) rescue raw.body end - # `headers_hash` is a Typhoeus-specific extension of Hash, + # `headers_hash` is a Typhoeus-specific extension of Hash, # so simplify it back into a regular old Hash. def headers h = {} @@ -67,4 +67,4 @@ module SwaggerClient end end end -end \ No newline at end of file +end From 70c74d282f89249cdc617abf2399441b06d5b160 Mon Sep 17 00:00:00 2001 From: xhh Date: Mon, 18 May 2015 16:47:35 +0800 Subject: [PATCH 64/67] Fix tests --- samples/client/petstore/ruby/spec/pet_spec.rb | 24 +++++++++---------- .../client/petstore/ruby/spec/spec_helper.rb | 10 ++++---- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/samples/client/petstore/ruby/spec/pet_spec.rb b/samples/client/petstore/ruby/spec/pet_spec.rb index fce80afb3bc5..f66f33cf84c0 100644 --- a/samples/client/petstore/ruby/spec/pet_spec.rb +++ b/samples/client/petstore/ruby/spec/pet_spec.rb @@ -6,17 +6,17 @@ describe "Pet" do configure_swagger prepare_pet end - + describe "pet methods" do it "should construct a new pet object" do - tag1 = Tag.new({'id' => 1, 'name'=> 'tag1'}) - tag2 = Tag.new({'id' => 2, 'name'=> 'tag2'}) - category1 = Category.new({:id => 1, :name => 'category unknown'}) + 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 = Pet.new(pet_hash) + pet = SwaggerClient::Pet.new(pet_hash) # test new pet.name.should == "RUBY UNIT TESTING" pet.status.should == "pending" @@ -26,7 +26,7 @@ describe "Pet" do pet.category.name.should == 'category unknown' # test build_from_hash - pet2 = Pet.new + pet2 = SwaggerClient::Pet.new pet2.build_from_hash(pet.to_hash) pet.to_hash.should == pet2.to_hash @@ -49,7 +49,7 @@ describe "Pet" do 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 = SwaggerClient::PetApi.find_pets_by_status(:status => 'invalid-status') pets.length.should == 0 @@ -57,23 +57,23 @@ describe "Pet" do it "should find a pet by status" do pets = SwaggerClient::PetApi.find_pets_by_status(:status => "available,sold") - pets.map {|pet| - if(pet.status != 'available' && pet.status != '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 = 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 + it "should create a pet" do pet = SwaggerClient::Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING") SwaggerClient::PetApi.add_pet(:body => pet) diff --git a/samples/client/petstore/ruby/spec/spec_helper.rb b/samples/client/petstore/ruby/spec/spec_helper.rb index 12d51679fc8a..09012db29983 100644 --- a/samples/client/petstore/ruby/spec/spec_helper.rb +++ b/samples/client/petstore/ruby/spec/spec_helper.rb @@ -49,12 +49,12 @@ def prepare_pet # remove the pet SwaggerClient::PetApi.delete_pet(10002) # recreate the pet - category = Category.new('id' => 20002, 'name' => 'category test') - tag = Tag.new('id' => 30002, 'name' => 'tag test') - pet = Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING", 'photo_urls' => 'photo url', - 'category' => category, 'tags' => [tag], 'status' => 'pending') + 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') - PetApi.add_pet(:'body'=> pet) + SwaggerClient::PetApi.add_pet(:'body'=> pet) end # always delete and then re-create the store order From 792059f195fa0377c7561bf3ebae6e452089d33a Mon Sep 17 00:00:00 2001 From: xhh Date: Tue, 19 May 2015 11:12:49 +0800 Subject: [PATCH 65/67] Avoid warnings for ruby gem building --- .../ruby/swagger_client.gemspec.mustache | 21 ++++++++++--------- samples/client/petstore/ruby/Gemfile.lock | 20 +++++++++--------- .../petstore/ruby/swagger_client.gemspec | 21 ++++++++++--------- 3 files changed, 32 insertions(+), 30 deletions(-) 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 index d23c4851b242..9f84d88d4e12 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger_client.gemspec.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger_client.gemspec.mustache @@ -11,18 +11,19 @@ Gem::Specification.new do |s| 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_dependency 'typhoeus', '>=0.2.1' - s.add_dependency 'addressable', '>=2.2.4' - s.add_dependency 'json', '>=1.4.6' + 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', '>=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.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") diff --git a/samples/client/petstore/ruby/Gemfile.lock b/samples/client/petstore/ruby/Gemfile.lock index c2f0a21b3fc1..e9e03f10b779 100644 --- a/samples/client/petstore/ruby/Gemfile.lock +++ b/samples/client/petstore/ruby/Gemfile.lock @@ -2,9 +2,9 @@ PATH remote: . specs: swagger_client (1.0.0) - addressable (>= 2.2.4) - json (>= 1.4.6) - typhoeus (>= 0.2.1) + 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) + 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 (>= 1.5.1) - webmock (>= 1.6.2) + vcr (~> 2.9, >= 2.9.3) + webmock (~> 1.6, >= 1.6.2) diff --git a/samples/client/petstore/ruby/swagger_client.gemspec b/samples/client/petstore/ruby/swagger_client.gemspec index dc3cd8350bda..6ec2484e05c8 100644 --- a/samples/client/petstore/ruby/swagger_client.gemspec +++ b/samples/client/petstore/ruby/swagger_client.gemspec @@ -11,18 +11,19 @@ Gem::Specification.new do |s| 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_dependency 'typhoeus', '>=0.2.1' - s.add_dependency 'addressable', '>=2.2.4' - s.add_dependency 'json', '>=1.4.6' + 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', '>=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.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") From 312f1c6f25461a8c7b01e47625cf3d9313f383f3 Mon Sep 17 00:00:00 2001 From: xhh Date: Wed, 20 May 2015 09:23:02 +0800 Subject: [PATCH 66/67] Avoid the importPath field --- .../com/wordnik/swagger/codegen/CodegenModel.java | 2 +- .../com/wordnik/swagger/codegen/DefaultCodegen.java | 13 ++++++------- .../wordnik/swagger/codegen/DefaultGenerator.java | 1 + .../src/main/resources/ruby/swagger_client.mustache | 2 -- 4 files changed, 8 insertions(+), 10 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java index 274b77b4e9dd..bcd78fa3e042 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java @@ -7,7 +7,7 @@ import java.util.*; public class CodegenModel { public String parent; - public String name, classname, importPath, description, classVarName, modelJson; + public String name, classname, description, classVarName, modelJson; public String defaultValue; public List vars = new ArrayList(); public Set imports = new HashSet(); diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index 3642e8de1b65..2e79cdcdcc2f 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -61,7 +61,7 @@ public class DefaultCodegen { // override with any special handling of the entire swagger spec public void processSwagger(Swagger swagger) {} - + // override with any special text escaping logic public String escapeText(String input) { if(input != null) { @@ -428,7 +428,6 @@ public class DefaultCodegen { m.name = name; m.description = escapeText(model.getDescription()); m.classname = toModelName(name); - m.importPath = toModelImport(name); m.classVarName = toVarName(name); m.modelJson = Json.pretty(model); m.externalDocs = model.getExternalDocs(); @@ -503,18 +502,18 @@ public class DefaultCodegen { if(cp.isContainer != null) { String arrayImport = typeMapping.get("array"); if(arrayImport != null && - !languageSpecificPrimitives.contains(arrayImport) && + !languageSpecificPrimitives.contains(arrayImport) && !defaultIncludes.contains(arrayImport)) m.imports.add(arrayImport); } if(cp.complexType != null && - !languageSpecificPrimitives.contains(cp.complexType) && + !languageSpecificPrimitives.contains(cp.complexType) && !defaultIncludes.contains(cp.complexType)) m.imports.add(cp.complexType); if(cp.baseType != null && - !languageSpecificPrimitives.contains(cp.baseType) && + !languageSpecificPrimitives.contains(cp.baseType) && !defaultIncludes.contains(cp.baseType)) m.imports.add(cp.baseType); } @@ -842,7 +841,7 @@ public class DefaultCodegen { op.nickname = op.operationId; - if(op.allParams.size() > 0) + if(op.allParams.size() > 0) op.hasParams = true; op.externalDocs = operation.getExternalDocs(); @@ -1081,7 +1080,7 @@ public class DefaultCodegen { operations.put(tag, opList); } opList.add(co); - co.baseName = tag; + co.baseName = tag; } /* underscore and camelize are copied from Twitter elephant bird 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 395f298eb07a..7a522230c29d 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 @@ -428,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/resources/ruby/swagger_client.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache index 89b4860a0438..df675ddf26ea 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache @@ -9,9 +9,7 @@ require '{{gemName}}/swagger/version' # Models require '{{modelPackage}}/base_object' {{#models}} -{{#model}} require '{{importPath}}' -{{/model}} {{/models}} # APIs From 0fb191819620dbc7bebe2a7f3a35482a7b3740d3 Mon Sep 17 00:00:00 2001 From: xhh Date: Wed, 20 May 2015 10:13:29 +0800 Subject: [PATCH 67/67] Revert unnecessary changes on whitespace --- .../com/wordnik/swagger/codegen/CodegenModel.java | 2 +- .../com/wordnik/swagger/codegen/DefaultCodegen.java | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java index bcd78fa3e042..169886da22e3 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java @@ -13,4 +13,4 @@ public class CodegenModel { public Set imports = new HashSet(); public Boolean hasVars, emptyVars, hasMoreModels; public ExternalDocs externalDocs; -} +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index 2e79cdcdcc2f..6f51374c5363 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -61,7 +61,7 @@ public class DefaultCodegen { // override with any special handling of the entire swagger spec public void processSwagger(Swagger swagger) {} - + // override with any special text escaping logic public String escapeText(String input) { if(input != null) { @@ -502,18 +502,18 @@ public class DefaultCodegen { if(cp.isContainer != null) { String arrayImport = typeMapping.get("array"); if(arrayImport != null && - !languageSpecificPrimitives.contains(arrayImport) && + !languageSpecificPrimitives.contains(arrayImport) && !defaultIncludes.contains(arrayImport)) m.imports.add(arrayImport); } if(cp.complexType != null && - !languageSpecificPrimitives.contains(cp.complexType) && + !languageSpecificPrimitives.contains(cp.complexType) && !defaultIncludes.contains(cp.complexType)) m.imports.add(cp.complexType); if(cp.baseType != null && - !languageSpecificPrimitives.contains(cp.baseType) && + !languageSpecificPrimitives.contains(cp.baseType) && !defaultIncludes.contains(cp.baseType)) m.imports.add(cp.baseType); } @@ -841,7 +841,7 @@ public class DefaultCodegen { op.nickname = op.operationId; - if(op.allParams.size() > 0) + if(op.allParams.size() > 0) op.hasParams = true; op.externalDocs = operation.getExternalDocs(); @@ -1080,7 +1080,7 @@ public class DefaultCodegen { operations.put(tag, opList); } opList.add(co); - co.baseName = tag; + co.baseName = tag; } /* underscore and camelize are copied from Twitter elephant bird