From 7555dda2bfffacceb2746c1a0d94620f202a0d50 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Wed, 11 Mar 2015 01:37:39 +0800 Subject: [PATCH 1/6] add logic to handle all 2xx response code, bug fix for string response, bug fix for showing error message using serialize --- .../src/main/resources/php/Swagger.mustache | 7 +++++-- samples/client/petstore/php/Swagger.php | 10 ++++++++-- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/Swagger.mustache b/modules/swagger-codegen/src/main/resources/php/Swagger.mustache index d797bb53e9e..8aed52e2909 100644 --- a/modules/swagger-codegen/src/main/resources/php/Swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/php/Swagger.mustache @@ -129,11 +129,14 @@ class APIClient { if ($response_info['http_code'] == 0) { throw new Exception("TIMEOUT: api call to " . $url . " took more than 5s to return" ); - } else if ($response_info['http_code'] == 200) { + } 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 Exception("Unauthorized API request to " . $url . - ": ".json_decode($response)->message ); + ": ".serialize($response)); } else if ($response_info['http_code'] == 404) { $data = null; } else { diff --git a/samples/client/petstore/php/Swagger.php b/samples/client/petstore/php/Swagger.php index a7a18866345..8aed52e2909 100644 --- a/samples/client/petstore/php/Swagger.php +++ b/samples/client/petstore/php/Swagger.php @@ -107,6 +107,9 @@ class APIClient { 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); @@ -126,11 +129,14 @@ class APIClient { if ($response_info['http_code'] == 0) { throw new Exception("TIMEOUT: api call to " . $url . " took more than 5s to return" ); - } else if ($response_info['http_code'] == 200) { + } 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 Exception("Unauthorized API request to " . $url . - ": ".json_decode($response)->message ); + ": ".serialize($response)); } else if ($response_info['http_code'] == 404) { $data = null; } else { From a0dc2097eb2f6e947fc0e58e4c05163f814ff011 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Sat, 14 Mar 2015 23:48:05 +0800 Subject: [PATCH 2/6] update php api client to support datetime (iso8601) for parameters (header, path, url, form) --- .../src/main/resources/php/Swagger.mustache | 38 +++++++++-- .../src/main/resources/php/api.mustache | 2 +- samples/client/petstore/php/PetApi.php | 8 +-- samples/client/petstore/php/Swagger.php | 67 ++++++++++++++++--- 4 files changed, 94 insertions(+), 21 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/Swagger.mustache b/modules/swagger-codegen/src/main/resources/php/Swagger.mustache index d332cbc2e71..1247be83f3f 100644 --- a/modules/swagger-codegen/src/main/resources/php/Swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/php/Swagger.mustache @@ -178,7 +178,7 @@ class APIClient { * @return string the serialized object */ public static function toPathValue($value) { - return rawurlencode($value); + return rawurlencode(toString($value)); } /** @@ -193,20 +193,48 @@ class APIClient { if (is_array($object)) { return implode(',', $object); } else { - return $object; + return toString($object); } } /** - * Just pass through the header value for now. Placeholder in case we - * find out we need to do something with header values. + * 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 $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 * diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 7a36c9aa0a3..bdf66defcaf 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -63,7 +63,7 @@ class {{classname}} { }{{/pathParams}} {{#formParams}}// form params if (${{paramName}} !== null) { - $formParams['{{baseName}}'] = {{#isFile}}'@' . {{/isFile}}${{paramName}}; + $formParams['{{baseName}}'] = {{#isFile}}'@' . {{/isFile}}$this->apiClient->toFormValue(${{paramName}}); }{{/formParams}} {{#bodyParams}}// body params $body = null; diff --git a/samples/client/petstore/php/PetApi.php b/samples/client/petstore/php/PetApi.php index 8c7d74cb474..8993a609595 100644 --- a/samples/client/petstore/php/PetApi.php +++ b/samples/client/petstore/php/PetApi.php @@ -304,10 +304,10 @@ class PetApi { } // form params if ($name !== null) { - $formParams['name'] = $name; + $formParams['name'] = $this->apiClient->toFormValue($name); }// form params if ($status !== null) { - $formParams['status'] = $status; + $formParams['status'] = $this->apiClient->toFormValue($status); } @@ -408,10 +408,10 @@ class PetApi { } // form params if ($additionalMetadata !== null) { - $formParams['additionalMetadata'] = $additionalMetadata; + $formParams['additionalMetadata'] = $this->apiClient->toFormValue($additionalMetadata); }// form params if ($file !== null) { - $formParams['file'] = '@' . $file; + $formParams['file'] = '@' . $this->apiClient->toFormValue($file); } diff --git a/samples/client/petstore/php/Swagger.php b/samples/client/petstore/php/Swagger.php index b65add845c8..1247be83f3f 100644 --- a/samples/client/petstore/php/Swagger.php +++ b/samples/client/petstore/php/Swagger.php @@ -127,19 +127,19 @@ class APIClient { // Handle the response if ($response_info['http_code'] == 0) { - throw new Exception("TIMEOUT: api call to " . $url . - " took more than 5s to return" ); + 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) { $data = json_decode($response); } else if ($response_info['http_code'] == 401) { - throw new Exception("Unauthorized API request to " . $url . - ": ".json_decode($response)->message ); + throw new APIClientException("Unauthorized API request to " . $url . + ": " . json_decode($response)->message, 0, $response_info, $response); } else if ($response_info['http_code'] == 404) { $data = null; } else { - throw new Exception("Can't connect to the api: " . $url . + throw new APIClientException("Can't connect to the api: " . $url . " response code: " . - $response_info['http_code']); + $response_info['http_code'], 0, $response_info, $response); } return $data; } @@ -178,7 +178,7 @@ class APIClient { * @return string the serialized object */ public static function toPathValue($value) { - return rawurlencode($value); + return rawurlencode(toString($value)); } /** @@ -193,20 +193,48 @@ class APIClient { if (is_array($object)) { return implode(',', $object); } else { - return $object; + return toString($object); } } /** - * Just pass through the header value for now. Placeholder in case we - * find out we need to do something with header values. + * 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 $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 * @@ -257,3 +285,20 @@ class APIClient { } +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; + } +} From b8166f283a53bf2fffe35a03c5efd39be263e1db Mon Sep 17 00:00:00 2001 From: William Cheng Date: Sun, 15 Mar 2015 16:33:57 +0800 Subject: [PATCH 3/6] update php to support user agent --- .../src/main/resources/php/Swagger.mustache | 20 ++++++++++++++++++- samples/client/petstore/php/Swagger.php | 20 ++++++++++++++++++- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/Swagger.mustache b/modules/swagger-codegen/src/main/resources/php/Swagger.mustache index 1247be83f3f..03b73f5775a 100644 --- a/modules/swagger-codegen/src/main/resources/php/Swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/php/Swagger.mustache @@ -48,6 +48,18 @@ class APIClient { $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] */ @@ -58,7 +70,6 @@ class APIClient { $this->curl_timout = $seconds; } - /** * @param string $resourcePath path to method endpoint * @param string $method method to call @@ -121,6 +132,13 @@ class APIClient { } 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); diff --git a/samples/client/petstore/php/Swagger.php b/samples/client/petstore/php/Swagger.php index 1247be83f3f..03b73f5775a 100644 --- a/samples/client/petstore/php/Swagger.php +++ b/samples/client/petstore/php/Swagger.php @@ -48,6 +48,18 @@ class APIClient { $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] */ @@ -58,7 +70,6 @@ class APIClient { $this->curl_timout = $seconds; } - /** * @param string $resourcePath path to method endpoint * @param string $method method to call @@ -121,6 +132,13 @@ class APIClient { } 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); From 6bc8de1230342be471e70f62c5515e4881ee4ad6 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Sun, 15 Mar 2015 22:02:16 +0800 Subject: [PATCH 4/6] rebase on develop_2.0 --- .../src/main/resources/php/Swagger.mustache | 7 +++++-- samples/client/petstore/php/Swagger.php | 14 ++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/Swagger.mustache b/modules/swagger-codegen/src/main/resources/php/Swagger.mustache index 1247be83f3f..5c6ac134307 100644 --- a/modules/swagger-codegen/src/main/resources/php/Swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/php/Swagger.mustache @@ -129,11 +129,14 @@ class APIClient { 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) { + } 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 . - ": " . json_decode($response)->message, 0, $response_info, $response); + ": " . serialize($response), 0, $response_info, $response); } else if ($response_info['http_code'] == 404) { $data = null; } else { diff --git a/samples/client/petstore/php/Swagger.php b/samples/client/petstore/php/Swagger.php index 1247be83f3f..1d5e7dbda50 100644 --- a/samples/client/petstore/php/Swagger.php +++ b/samples/client/petstore/php/Swagger.php @@ -127,13 +127,27 @@ class APIClient { // Handle the response if ($response_info['http_code'] == 0) { +<<<<<<< HEAD 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) { +======= + throw new Exception("TIMEOUT: api call to " . $url . + " took more than 5s to return" ); + } else if ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { +>>>>>>> add logic to handle all 2xx response code, bug fix for string response, $data = json_decode($response); + if (json_last_error() > 0) { // if response is a string + $data = $response; + } } else if ($response_info['http_code'] == 401) { +<<<<<<< HEAD throw new APIClientException("Unauthorized API request to " . $url . ": " . json_decode($response)->message, 0, $response_info, $response); +======= + throw new Exception("Unauthorized API request to " . $url . + ": ".serialize($response)); +>>>>>>> add logic to handle all 2xx response code, bug fix for string response, } else if ($response_info['http_code'] == 404) { $data = null; } else { From bcdee4e03822d6356ed175fc61aa9706b966e267 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Sun, 15 Mar 2015 22:06:42 +0800 Subject: [PATCH 5/6] update php petstore sample code --- samples/client/petstore/php/Swagger.php | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/samples/client/petstore/php/Swagger.php b/samples/client/petstore/php/Swagger.php index 1d5e7dbda50..5c6ac134307 100644 --- a/samples/client/petstore/php/Swagger.php +++ b/samples/client/petstore/php/Swagger.php @@ -127,27 +127,16 @@ class APIClient { // Handle the response if ($response_info['http_code'] == 0) { -<<<<<<< HEAD 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) { -======= - throw new Exception("TIMEOUT: api call to " . $url . - " took more than 5s to return" ); } else if ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { ->>>>>>> add logic to handle all 2xx response code, bug fix for string response, $data = json_decode($response); if (json_last_error() > 0) { // if response is a string $data = $response; } } else if ($response_info['http_code'] == 401) { -<<<<<<< HEAD throw new APIClientException("Unauthorized API request to " . $url . - ": " . json_decode($response)->message, 0, $response_info, $response); -======= - throw new Exception("Unauthorized API request to " . $url . - ": ".serialize($response)); ->>>>>>> add logic to handle all 2xx response code, bug fix for string response, + ": " . serialize($response), 0, $response_info, $response); } else if ($response_info['http_code'] == 404) { $data = null; } else { From e9227ad7e5cd723d3432cda32fcf3745d8a3f735 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Mon, 16 Mar 2015 18:47:22 +0800 Subject: [PATCH 6/6] add ruby codegen, update sample (petstore) for ruby --- bin/ruby-petstore.sh | 36 ++ .../codegen/languages/RubyClientCodegen.java | 120 ++++++ .../com.wordnik.swagger.codegen.CodegenConfig | 1 + .../src/main/resources/ruby/model.mustache | 17 +- samples/client/petstore/ruby/lib/PetApi.rb | 359 ++++++++++++++++ samples/client/petstore/ruby/lib/StoreApi.rb | 176 ++++++++ samples/client/petstore/ruby/lib/UserApi.rb | 384 ++++++++++++++++++ samples/client/petstore/ruby/lib/monkey.rb | 2 +- samples/client/petstore/ruby/lib/swagger.rb | 2 +- .../ruby/lib/swagger/configuration.rb | 2 +- .../petstore/ruby/lib/swagger/request.rb | 2 +- .../petstore/ruby/lib/swagger/response.rb | 2 +- .../petstore/ruby/lib/swagger/version.rb | 1 - .../client/petstore/ruby/models/Category.rb | 20 +- samples/client/petstore/ruby/models/Order.rb | 64 ++- samples/client/petstore/ruby/models/Pet.rb | 70 ++-- samples/client/petstore/ruby/models/Tag.rb | 20 +- samples/client/petstore/ruby/models/User.rb | 88 ++-- .../petstore/ruby/swagger/configuration.rb | 22 + .../client/petstore/ruby/swagger/request.rb | 199 +++++++++ .../client/petstore/ruby/swagger/response.rb | 70 ++++ .../client/petstore/ruby/swagger/version.rb | 4 + 22 files changed, 1561 insertions(+), 100 deletions(-) create mode 100755 bin/ruby-petstore.sh create mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/RubyClientCodegen.java create mode 100644 samples/client/petstore/ruby/lib/PetApi.rb create mode 100644 samples/client/petstore/ruby/lib/StoreApi.rb create mode 100644 samples/client/petstore/ruby/lib/UserApi.rb create mode 100644 samples/client/petstore/ruby/swagger/configuration.rb create mode 100644 samples/client/petstore/ruby/swagger/request.rb create mode 100644 samples/client/petstore/ruby/swagger/response.rb create mode 100644 samples/client/petstore/ruby/swagger/version.rb diff --git a/bin/ruby-petstore.sh b/bin/ruby-petstore.sh new file mode 100755 index 00000000000..bd7c30496bf --- /dev/null +++ b/bin/ruby-petstore.sh @@ -0,0 +1,36 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +root=./modules/swagger-codegen-distribution/pom.xml + +# gets version of swagger-codegen +version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') + +executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.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="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l ruby -o samples/client/petstore/ruby" + +java $JAVA_OPTS -jar $executable $ags 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 new file mode 100644 index 00000000000..ee65073be1b --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/RubyClientCodegen.java @@ -0,0 +1,120 @@ +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 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"; + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "ruby"; + } + + public String getHelp() { + return "Generates a Ruby client library."; + } + + public RubyClientCodegen() { + super(); + modelPackage = "models"; + apiPackage = "lib"; + outputFolder = "generated-code/ruby"; + modelTemplateFiles.put("model.mustache", ".rb"); + apiTemplateFiles.put("api.mustache", ".rb"); + templateDir = "ruby"; + + typeMapping.clear(); + languageSpecificPrimitives.clear(); + + reservedWords = new HashSet ( + Arrays.asList( + "int") + ); + + 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", "", "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")); + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + "/" + apiPackage().replace('.', File.separatorChar); + } + + public String modelFileFolder() { + return outputFolder + "/" + 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"; + } +} 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 bc7554b95f0..8aa08f9599d 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 @@ -11,4 +11,5 @@ com.wordnik.swagger.codegen.languages.StaticHtmlGenerator com.wordnik.swagger.codegen.languages.SwaggerGenerator com.wordnik.swagger.codegen.languages.TizenClientCodegen com.wordnik.swagger.codegen.languages.PhpClientCodegen +com.wordnik.swagger.codegen.languages.RubyClientCodegen com.wordnik.swagger.codegen.languages.PythonClientCodegen diff --git a/modules/swagger-codegen/src/main/resources/ruby/model.mustache b/modules/swagger-codegen/src/main/resources/ruby/model.mustache index c587f12cb49..ef3b2fe48f9 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/model.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/model.mustache @@ -7,9 +7,8 @@ class {{classname}} def self.attribute_map { {{#vars}} - :{{{name}}} => :{{{baseName}}}{{#hasMore}}, - {{/hasMore}} - {{/vars}}{{newline}} + :{{{name}}} => :{{{baseName}}}{{#hasMore}},{{/hasMore}} + {{/vars}} } end @@ -19,14 +18,14 @@ class {{classname}} {{#vars}} if self.class.attribute_map[:"{{{name}}}"] {{#isContainer}} - if (value = attributes["{{{baseName}}}"]).is_a?(Array) - @{{{name}}} = value{{#complexType}}.map{ |v| {{complexType}}.new(v) }{{/complexType}}{{newline}} - end + if (value = attributes["{{{baseName}}}"]).is_a?(Array) + @{{{name}}} = value{{#complexType}}.map{ |v| {{complexType}}.new(v) }{{/complexType}}{{newline}} + end {{/isContainer}}{{^isContainer}} - @{{{name}}} = attributes["{{{baseName}}}"] - {{/isContainer}} + @{{{name}}} = attributes["{{{baseName}}}"] + {{/isContainer}} end - {{/vars}}{{newline}} + {{/vars}} end def to_body diff --git a/samples/client/petstore/ruby/lib/PetApi.rb b/samples/client/petstore/ruby/lib/PetApi.rb new file mode 100644 index 00000000000..41b4f4122c2 --- /dev/null +++ b/samples/client/petstore/ruby/lib/PetApi.rb @@ -0,0 +1,359 @@ +require "uri" + +class PetApi + basePath = "http://petstore.swagger.io/v2" + # apiInvoker = APIInvoker + + def self.escapeString(string) + URI.encode(string.to_s) + end + + + def self.updatePet (body, opts={}) + query_param_keys = [] + + + + # set default values and merge with input + options = { + + :body => body + + }.merge(opts) + + #resource path + path = "/pet".sub('{format}','json') + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + + headers = nil + + + post_body = nil + + if body != nil + if body.is_a?(Array) + array = Array.new + body.each do |item| + if item.respond_to?("to_body".to_sym) + array.push item.to_body + else + array.push item + end + end + post_body = array + + else + if body.respond_to?("to_body".to_sym) + post_body = body.to_body + else + post_body = body + end + end + end + + + + + Swagger::Request.new(:PUT, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make + + + end + + + def self.addPet (body, opts={}) + query_param_keys = [] + + + + # set default values and merge with input + options = { + + :body => body + + }.merge(opts) + + #resource path + path = "/pet".sub('{format}','json') + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + + headers = nil + + + post_body = nil + + if body != nil + if body.is_a?(Array) + array = Array.new + body.each do |item| + if item.respond_to?("to_body".to_sym) + array.push item.to_body + else + array.push item + end + end + post_body = array + + else + if body.respond_to?("to_body".to_sym) + post_body = body.to_body + else + post_body = body + end + end + end + + + + + Swagger::Request.new(:POST, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make + + + end + + + def self.findPetsByStatus (status, opts={}) + query_param_keys = [:status] + + + + # set default values and merge with input + options = { + + :status => status + + }.merge(opts) + + #resource path + path = "/pet/findByStatus".sub('{format}','json') + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + + headers = nil + + + post_body = nil + + + + response = Swagger::Request.new(:GET, path, {:params=>queryopts,:headers=>headers, :body=>post_body }).make.body + + response.map {|response| Pet.new(response) } + + + + end + + + def self.findPetsByTags (tags, opts={}) + query_param_keys = [:tags] + + + + # set default values and merge with input + options = { + + :tags => tags + + }.merge(opts) + + #resource path + path = "/pet/findByTags".sub('{format}','json') + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + + headers = nil + + + post_body = nil + + + + response = Swagger::Request.new(:GET, path, {:params=>queryopts,:headers=>headers, :body=>post_body }).make.body + + response.map {|response| Pet.new(response) } + + + + end + + + def self.getPetById (petId, opts={}) + query_param_keys = [] + + + + # set default values and merge with input + options = { + + :petId => petId + + }.merge(opts) + + #resource path + path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', escapeString(petId)) + + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + + headers = nil + + + post_body = nil + + + + response = Swagger::Request.new(:GET, path, {:params=>queryopts,:headers=>headers, :body=>post_body }).make.body + Pet.new(response) + + + + end + + + def self.updatePetWithForm (petId,name,status, opts={}) + query_param_keys = [] + + + + # set default values and merge with input + options = { + + :petId => petId, + + + :name => name, + + + :status => status + + }.merge(opts) + + #resource path + path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', escapeString(petId)) + + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + + headers = nil + + + post_body = nil + + + + + Swagger::Request.new(:POST, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make + + + end + + + def self.deletePet (api_key,petId, opts={}) + query_param_keys = [] + + + + # set default values and merge with input + options = { + + :api_key => api_key, + + + :petId => petId + + }.merge(opts) + + #resource path + path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', escapeString(petId)) + + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + headers = { + api_key: api_key, + } + + + + post_body = nil + + + + + Swagger::Request.new(:DELETE, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make + + + end + + + def self.uploadFile (petId,additionalMetadata,file, opts={}) + query_param_keys = [] + + + + # set default values and merge with input + options = { + + :petId => petId, + + + :additionalMetadata => additionalMetadata, + + + :file => file + + }.merge(opts) + + #resource path + path = "/pet/{petId}/uploadImage".sub('{format}','json').sub('{' + 'petId' + '}', escapeString(petId)) + + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + + headers = nil + + + post_body = nil + + + + + Swagger::Request.new(:POST, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make + + + end + +end diff --git a/samples/client/petstore/ruby/lib/StoreApi.rb b/samples/client/petstore/ruby/lib/StoreApi.rb new file mode 100644 index 00000000000..b5d33010cc9 --- /dev/null +++ b/samples/client/petstore/ruby/lib/StoreApi.rb @@ -0,0 +1,176 @@ +require "uri" + +class StoreApi + basePath = "http://petstore.swagger.io/v2" + # apiInvoker = APIInvoker + + def self.escapeString(string) + URI.encode(string.to_s) + end + + + def self.getInventory ( opts={}) + query_param_keys = [] + + + + # set default values and merge with input + options = { + + }.merge(opts) + + #resource path + path = "/store/inventory".sub('{format}','json') + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + + headers = nil + + + post_body = nil + + + + response = Swagger::Request.new(:GET, path, {:params=>queryopts,:headers=>headers, :body=>post_body }).make.body + + response.map {|response| map.new(response) } + + + + end + + + def self.placeOrder (body, opts={}) + query_param_keys = [] + + + + # set default values and merge with input + options = { + + :body => body + + }.merge(opts) + + #resource path + path = "/store/order".sub('{format}','json') + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + + headers = nil + + + post_body = nil + + if body != nil + if body.is_a?(Array) + array = Array.new + body.each do |item| + if item.respond_to?("to_body".to_sym) + array.push item.to_body + else + array.push item + end + end + post_body = array + + else + if body.respond_to?("to_body".to_sym) + post_body = body.to_body + else + post_body = body + end + end + end + + + + response = Swagger::Request.new(:POST, path, {:params=>queryopts,:headers=>headers, :body=>post_body }).make.body + Order.new(response) + + + + end + + + def self.getOrderById (orderId, opts={}) + query_param_keys = [] + + + + # set default values and merge with input + options = { + + :orderId => orderId + + }.merge(opts) + + #resource path + path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', escapeString(orderId)) + + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + + headers = nil + + + post_body = nil + + + + response = Swagger::Request.new(:GET, path, {:params=>queryopts,:headers=>headers, :body=>post_body }).make.body + Order.new(response) + + + + end + + + def self.deleteOrder (orderId, opts={}) + query_param_keys = [] + + + + # set default values and merge with input + options = { + + :orderId => orderId + + }.merge(opts) + + #resource path + path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', escapeString(orderId)) + + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + + headers = nil + + + post_body = nil + + + + + Swagger::Request.new(:DELETE, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make + + + end + +end diff --git a/samples/client/petstore/ruby/lib/UserApi.rb b/samples/client/petstore/ruby/lib/UserApi.rb new file mode 100644 index 00000000000..40051e7c9fc --- /dev/null +++ b/samples/client/petstore/ruby/lib/UserApi.rb @@ -0,0 +1,384 @@ +require "uri" + +class UserApi + basePath = "http://petstore.swagger.io/v2" + # apiInvoker = APIInvoker + + def self.escapeString(string) + URI.encode(string.to_s) + end + + + def self.createUser (body, opts={}) + query_param_keys = [] + + + + # set default values and merge with input + options = { + + :body => body + + }.merge(opts) + + #resource path + path = "/user".sub('{format}','json') + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + + headers = nil + + + post_body = nil + + if body != nil + if body.is_a?(Array) + array = Array.new + body.each do |item| + if item.respond_to?("to_body".to_sym) + array.push item.to_body + else + array.push item + end + end + post_body = array + + else + if body.respond_to?("to_body".to_sym) + post_body = body.to_body + else + post_body = body + end + end + end + + + + + Swagger::Request.new(:POST, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make + + + end + + + def self.createUsersWithArrayInput (body, opts={}) + query_param_keys = [] + + + + # set default values and merge with input + options = { + + :body => body + + }.merge(opts) + + #resource path + path = "/user/createWithArray".sub('{format}','json') + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + + headers = nil + + + post_body = nil + + if body != nil + if body.is_a?(Array) + array = Array.new + body.each do |item| + if item.respond_to?("to_body".to_sym) + array.push item.to_body + else + array.push item + end + end + post_body = array + + else + if body.respond_to?("to_body".to_sym) + post_body = body.to_body + else + post_body = body + end + end + end + + + + + Swagger::Request.new(:POST, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make + + + end + + + def self.createUsersWithListInput (body, opts={}) + query_param_keys = [] + + + + # set default values and merge with input + options = { + + :body => body + + }.merge(opts) + + #resource path + path = "/user/createWithList".sub('{format}','json') + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + + headers = nil + + + post_body = nil + + if body != nil + if body.is_a?(Array) + array = Array.new + body.each do |item| + if item.respond_to?("to_body".to_sym) + array.push item.to_body + else + array.push item + end + end + post_body = array + + else + if body.respond_to?("to_body".to_sym) + post_body = body.to_body + else + post_body = body + end + end + end + + + + + Swagger::Request.new(:POST, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make + + + end + + + def self.loginUser (username,password, opts={}) + query_param_keys = [:username,:password] + + + + # set default values and merge with input + options = { + + :username => username, + + + :password => password + + }.merge(opts) + + #resource path + path = "/user/login".sub('{format}','json') + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + + headers = nil + + + post_body = nil + + + + response = Swagger::Request.new(:GET, path, {:params=>queryopts,:headers=>headers, :body=>post_body }).make.body + string.new(response) + + + + end + + + def self.logoutUser ( opts={}) + query_param_keys = [] + + + + # set default values and merge with input + options = { + + }.merge(opts) + + #resource path + path = "/user/logout".sub('{format}','json') + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + + headers = nil + + + post_body = nil + + + + + Swagger::Request.new(:GET, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make + + + end + + + def self.getUserByName (username, opts={}) + query_param_keys = [] + + + + # set default values and merge with input + options = { + + :username => username + + }.merge(opts) + + #resource path + path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', escapeString(username)) + + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + + headers = nil + + + post_body = nil + + + + response = Swagger::Request.new(:GET, path, {:params=>queryopts,:headers=>headers, :body=>post_body }).make.body + User.new(response) + + + + end + + + def self.updateUser (username,body, opts={}) + query_param_keys = [] + + + + # set default values and merge with input + options = { + + :username => username, + + + :body => body + + }.merge(opts) + + #resource path + path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', escapeString(username)) + + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + + headers = nil + + + post_body = nil + + if body != nil + if body.is_a?(Array) + array = Array.new + body.each do |item| + if item.respond_to?("to_body".to_sym) + array.push item.to_body + else + array.push item + end + end + post_body = array + + else + if body.respond_to?("to_body".to_sym) + post_body = body.to_body + else + post_body = body + end + end + end + + + + + Swagger::Request.new(:PUT, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make + + + end + + + def self.deleteUser (username, opts={}) + query_param_keys = [] + + + + # set default values and merge with input + options = { + + :username => username + + }.merge(opts) + + #resource path + path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', escapeString(username)) + + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + + headers = nil + + + post_body = nil + + + + + Swagger::Request.new(:DELETE, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make + + + end + +end diff --git a/samples/client/petstore/ruby/lib/monkey.rb b/samples/client/petstore/ruby/lib/monkey.rb index 54cd22170e7..28932890af9 100644 --- a/samples/client/petstore/ruby/lib/monkey.rb +++ b/samples/client/petstore/ruby/lib/monkey.rb @@ -87,4 +87,4 @@ end end -# end +# end \ No newline at end of file diff --git a/samples/client/petstore/ruby/lib/swagger.rb b/samples/client/petstore/ruby/lib/swagger.rb index de48af3a33c..1cc3ea456c2 100644 --- a/samples/client/petstore/ruby/lib/swagger.rb +++ b/samples/client/petstore/ruby/lib/swagger.rb @@ -81,4 +81,4 @@ class ServerError < StandardError end class ClientError < StandardError -end +end \ No newline at end of file diff --git a/samples/client/petstore/ruby/lib/swagger/configuration.rb b/samples/client/petstore/ruby/lib/swagger/configuration.rb index 905ff261c29..c0b3c46268c 100644 --- a/samples/client/petstore/ruby/lib/swagger/configuration.rb +++ b/samples/client/petstore/ruby/lib/swagger/configuration.rb @@ -19,4 +19,4 @@ module Swagger end -end +end \ No newline at end of file diff --git a/samples/client/petstore/ruby/lib/swagger/request.rb b/samples/client/petstore/ruby/lib/swagger/request.rb index a38c4643a41..7836cb0bf03 100644 --- a/samples/client/petstore/ruby/lib/swagger/request.rb +++ b/samples/client/petstore/ruby/lib/swagger/request.rb @@ -196,4 +196,4 @@ module Swagger end end -end +end \ No newline at end of file diff --git a/samples/client/petstore/ruby/lib/swagger/response.rb b/samples/client/petstore/ruby/lib/swagger/response.rb index a42cf99d4d8..02a1a458eb4 100644 --- a/samples/client/petstore/ruby/lib/swagger/response.rb +++ b/samples/client/petstore/ruby/lib/swagger/response.rb @@ -67,4 +67,4 @@ module Swagger end end -end +end \ No newline at end of file diff --git a/samples/client/petstore/ruby/lib/swagger/version.rb b/samples/client/petstore/ruby/lib/swagger/version.rb index dfd2ddad203..39357c0ed6d 100644 --- a/samples/client/petstore/ruby/lib/swagger/version.rb +++ b/samples/client/petstore/ruby/lib/swagger/version.rb @@ -2,4 +2,3 @@ module Swagger VERSION = "4.06.08" end - diff --git a/samples/client/petstore/ruby/models/Category.rb b/samples/client/petstore/ruby/models/Category.rb index 54bd6a5245b..0f15c43a70a 100644 --- a/samples/client/petstore/ruby/models/Category.rb +++ b/samples/client/petstore/ruby/models/Category.rb @@ -1,26 +1,33 @@ + 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 + + if self.class.attribute_map[:"name"] + + @name = attributes["name"] + end - end def to_body @@ -31,4 +38,3 @@ class Category body end end - diff --git a/samples/client/petstore/ruby/models/Order.rb b/samples/client/petstore/ruby/models/Order.rb index 81bc6d5a4dc..45a0864cfcc 100644 --- a/samples/client/petstore/ruby/models/Order.rb +++ b/samples/client/petstore/ruby/models/Order.rb @@ -1,38 +1,65 @@ -class Order - attr_accessor :id, :pet_id, :quantity, :status, :ship_date +class Order + attr_accessor :id, :petId, :quantity, :shipDate, :status, :complete # :internal => :external def self.attribute_map { + :id => :id, - :pet_id => :petId, + + :petId => :petId, + :quantity => :quantity, + + :shipDate => :shipDate, + :status => :status, - :ship_date => :shipDate - + + :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[:"status"] - @status = attributes["status"] - end - if self.class.attribute_map[:"ship_date"] - @ship_date = attributes["shipDate"] + + end + + if self.class.attribute_map[:"petId"] + + @petId = attributes["petId"] + + end + + if self.class.attribute_map[:"quantity"] + + @quantity = attributes["quantity"] + + end + + if self.class.attribute_map[:"shipDate"] + + @shipDate = 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 @@ -43,4 +70,3 @@ class Order body end end - diff --git a/samples/client/petstore/ruby/models/Pet.rb b/samples/client/petstore/ruby/models/Pet.rb index f4b3eb2e4c8..f67067e6f91 100644 --- a/samples/client/petstore/ruby/models/Pet.rb +++ b/samples/client/petstore/ruby/models/Pet.rb @@ -1,44 +1,69 @@ -class Pet - attr_accessor :id, :category, :name, :photo_urls, :tags, :status +class Pet + attr_accessor :id, :category, :name, :photoUrls, :tags, :status # :internal => :external def self.attribute_map { + :id => :id, + :category => :category, + :name => :name, - :photo_urls => :photoUrls, + + :photoUrls => :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 = valueend - 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 + + 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[:"photoUrls"] + + if (value = attributes["photoUrls"]).is_a?(Array) + @photoUrls = 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 @@ -49,4 +74,3 @@ class Pet body end end - diff --git a/samples/client/petstore/ruby/models/Tag.rb b/samples/client/petstore/ruby/models/Tag.rb index abe4929a3d1..9a9193b8e82 100644 --- a/samples/client/petstore/ruby/models/Tag.rb +++ b/samples/client/petstore/ruby/models/Tag.rb @@ -1,26 +1,33 @@ + 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 + + if self.class.attribute_map[:"name"] + + @name = attributes["name"] + end - end def to_body @@ -31,4 +38,3 @@ class Tag body end end - diff --git a/samples/client/petstore/ruby/models/User.rb b/samples/client/petstore/ruby/models/User.rb index a6c2f052965..b7981a2bc41 100644 --- a/samples/client/petstore/ruby/models/User.rb +++ b/samples/client/petstore/ruby/models/User.rb @@ -1,50 +1,81 @@ -class User - attr_accessor :id, :first_name, :username, :last_name, :email, :password, :phone, :user_status +class User + attr_accessor :id, :username, :firstName, :lastName, :email, :password, :phone, :userStatus # :internal => :external def self.attribute_map { + :id => :id, - :first_name => :firstName, + :username => :username, - :last_name => :lastName, + + :firstName => :firstName, + + :lastName => :lastName, + :email => :email, + :password => :password, + :phone => :phone, - :user_status => :userStatus - + + :userStatus => :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[:"first_name"] - @first_name = attributes["firstName"] - end - if self.class.attribute_map[:"username"] - @username = attributes["username"] - 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 + + if self.class.attribute_map[:"username"] + + @username = attributes["username"] + + end + + if self.class.attribute_map[:"firstName"] + + @firstName = attributes["firstName"] + + end + + if self.class.attribute_map[:"lastName"] + + @lastName = 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[:"userStatus"] + + @userStatus = attributes["userStatus"] + end - end def to_body @@ -55,4 +86,3 @@ class User body end end - diff --git a/samples/client/petstore/ruby/swagger/configuration.rb b/samples/client/petstore/ruby/swagger/configuration.rb new file mode 100644 index 00000000000..c0b3c46268c --- /dev/null +++ b/samples/client/petstore/ruby/swagger/configuration.rb @@ -0,0 +1,22 @@ +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 + + # Defaults go in here.. + def initialize + @format = 'json' + @scheme = 'http' + @host = 'api.wordnik.com' + @base_path = '/v4' + @user_agent = "ruby-#{Swagger::VERSION}" + @inject_format = true + @force_ending_format = false + @camelize_params = true + end + + end + +end \ No newline at end of file diff --git a/samples/client/petstore/ruby/swagger/request.rb b/samples/client/petstore/ruby/swagger/request.rb new file mode 100644 index 00000000000..7836cb0bf03 --- /dev/null +++ b/samples/client/petstore/ruby/swagger/request.rb @@ -0,0 +1,199 @@ +module Swagger + + class Request + require 'uri' + require 'addressable/uri' + require 'typhoeus' + require "swagger/version" + + attr_accessor :host, :path, :format, :params, :body, :http_method, :headers + + + # 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 + } + + # 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 + + # Fill in the path params + self.params.each_pair do |key, value| + p = p.gsub("{#{key}}", value.to_s) + end + + # 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. + # + def outgoing_body + body.is_a?(String) ? body : body.to_json + 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 + 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 :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 \ No newline at end of file diff --git a/samples/client/petstore/ruby/swagger/response.rb b/samples/client/petstore/ruby/swagger/response.rb new file mode 100644 index 00000000000..02a1a458eb4 --- /dev/null +++ b/samples/client/petstore/ruby/swagger/response.rb @@ -0,0 +1,70 @@ +module Swagger + + class Response + require 'json' + + attr_accessor :raw + + def initialize(raw) + self.raw = raw + + case self.code + when 500..510 then raise(ServerError, self.error_message) + when 299..426 then raise(ClientError, self.error_message) + end + end + + def code + raw.code + end + + # Account for error messages that take different forms... + def error_message + body['message'] + rescue + body + end + + # If body is JSON, parse it + # Otherwise return raw string + def body + JSON.parse raw.body + rescue + raw.body + end + + # `headers_hash` is a Typhoeus-specific extension of Hash, + # so simplify it back into a regular old Hash. + def headers + h = {} + raw.headers_hash.each {|k,v| h[k] = v } + h + end + + # Extract the response format from the header hash + # e.g. {'Content-Type' => 'application/json'} + def format + headers['Content-Type'].split("/").last.downcase + end + + def json? + format == 'json' + end + + def xml? + format == 'xml' + end + + def pretty_body + return unless body.present? + case format + when 'json' then JSON.pretty_generate(body).gsub(/\n/, '
') + end + end + + def pretty_headers + JSON.pretty_generate(headers).gsub(/\n/, '
') + end + + end +end \ No newline at end of file diff --git a/samples/client/petstore/ruby/swagger/version.rb b/samples/client/petstore/ruby/swagger/version.rb new file mode 100644 index 00000000000..39357c0ed6d --- /dev/null +++ b/samples/client/petstore/ruby/swagger/version.rb @@ -0,0 +1,4 @@ +module Swagger + VERSION = "4.06.08" +end +